Beispiel #1
0
 def identifyObject(self,target):
     if target[0] == "#":
         credsId = target[1:]
     else:
         credsId = target
     creds = Creds.find(credsId)
     if creds is not None:
         return creds
     user = User.findByUsername(target)
     if user is not None:
         return user
     try:
         dst = Endpoint.findByIpPort(target)
         if dst is not None:
             return dst
     except:
         pass
     hosts = Host.findByName(target)
     if len(hosts) > 1:
         print("Multiple hosts matching, use endpoints")
         return None
     if len(hosts) == 1:
         return hosts[0]
     print("Could not identify object.")
     return None
Beispiel #2
0
 def fromTarget(cls, arg):
     if '@' in arg and ':' in arg:
         auth, sep, endpoint = arg.partition('@')
         endpoint = Endpoint.findByIpPort(endpoint)
         if endpoint is None:
             raise ValueError("Supplied endpoint isn't in workspace")
         user, sep, cred = auth.partition(":")
         if sep == "":
             raise ValueError("No credentials supplied")
         user = User.findByUsername(user)
         if user is None:
             raise ValueError("Supplied user isn't in workspace")
         if cred[0] == "#":
             cred = cred[1:]
         cred = Creds.find(cred)
         if cred is None:
             raise ValueError("Supplied credentials aren't in workspace")
         return Connection(endpoint, user, cred)
     else:
         if ':' not in arg:
             arg = arg + ':22'
         endpoint = Endpoint.findByIpPort(arg)
         if endpoint is None:
             raise ValueError("Supplied endpoint isn't in workspace")
         connection = endpoint.getConnection()
         if connection == None:
             raise ValueError("No working connection for supplied endpoint")
         return connection
     return None
Beispiel #3
0
 def findAllWorkingByEndpoint(cls, endpoint):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute(
             'SELECT user,cred FROM connections WHERE working=1 AND endpoint=? ORDER BY root ASC',
         (endpoint.getId(), )):
         ret.append(
             Connection(endpoint, User.find(row[0]), Creds.find(row[1])))
     c.close()
     return ret
Beispiel #4
0
 def findWorkingByEndpoint(cls, endpoint):
     c = dbConn.get().cursor()
     c.execute(
         'SELECT user,cred FROM connections WHERE working=1 AND endpoint=? ORDER BY root ASC',
         (endpoint.getId(), ))
     row = c.fetchone()
     c.close()
     if row is None:
         return None
     return Connection(endpoint, User.find(row[0]), Creds.find(row[1]))
Beispiel #5
0
 def findByCreds(cls, creds):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute(
             'SELECT endpoint,user FROM connections WHERE cred=?',
         (creds.getId(), )):
         ret.append(
             Connection(Endpoint.find(row[0]), User.find(row[1]), creds))
     c.close()
     return ret
Beispiel #6
0
 def findByEndpoint(cls, endpoint):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute(
             'SELECT user,cred FROM connections WHERE endpoint=?',
         (endpoint.getId(), )):
         ret.append(
             Connection(endpoint, User.find(row[0]), Creds.find(row[1])))
     c.close()
     return ret
Beispiel #7
0
 def find(cls, connectionId):
     c = dbConn.get().cursor()
     c.execute('SELECT endpoint,user,cred FROM connections WHERE id=?',
               (connectionId, ))
     row = c.fetchone()
     c.close()
     if row is None:
         return None
     return Connection(Endpoint.find(row[0]), User.find(row[1]),
                       Creds.find(row[2]))
Beispiel #8
0
    def gatherFromHistory(self, historyFile):
        lootFolder = os.path.join(self.wspaceFolder, "loot")
        filename = str(self.connection.endpoint).replace(":", "-") + "_" + str(
            self.connection.user) + "_" + historyFile.replace("/", "_")
        filepath = os.path.join(lootFolder, filename)
        try:
            self.sftp.get(historyFile, filepath)
        except Exception as e:
            print(e)
            return None
        with open(filepath, "r", errors="ignore") as dledFile:
            data = dledFile.read()
        lines = data.splitlines()
        for line in lines:
            if re.search(r'^ *ssh ', line):
                option = ""
                words = line.split()
                host = False
                port = None
                user = None
                identity = None

                for i in range(1, len(words)):
                    if option != "":
                        if option == "identity":
                            identity = words[i]
                            if identity[:2] == '~/':
                                identity = identity[2:]
                        elif option == "port":
                            port = words[i]
                        option = ""
                    elif words[i][0] == "-":
                        if words[i] == "-i":
                            option = "identity"
                        elif words[i] == "-p":
                            option = "port"
                        else:
                            option = words[i]
                    elif not host:
                        if '@' in words[i]:
                            user, hostname = words[i].split("@", 1)
                        else:
                            hostname = words[i]
                        host = True
                if not host:
                    continue
                endpoints = self.hostnameToIP(hostname, port)
                if user is not None:
                    user = User(user)
                    if not self.connection.scope:
                        user.scope = False
                    if user.id is None:
                        user.found = self.connection.endpoint
                        user.save()
                        self.newUsers.append(user)
                if identity is not None:
                    identity = self.getKeyToCreds(identity, ".")
Beispiel #9
0
 def setOption(self,option,value):
     if option == 'connection':
         if value is None:
             self.options['endpoint'] = None
             self.options['user'] = None
             self.options['creds'] = None
             for option in ['endpoint','user','creds']:
                 print(option+" => "+str(self.getOption(option)))
             return 
         if '@' not in value or ':' not in value:
             return
         connection = Connection.fromTarget(value)
         if connection == None:
             return
         self.options['endpoint'] = connection.getEndpoint()
         self.options['user'] = connection.getUser()
         self.options['creds'] = connection.getCred()
         for option in ['endpoint','user','creds']:
             print(option+" => "+str(self.getOption(option)))
         return 
     if not option in list(self.options.keys()):
         raise ValueError(option+" isn't a valid option.")
     if value != None:
         value = value.strip()
         if option == "endpoint":
             endpoint = Endpoint.findByIpPort(value)
             if endpoint is None:
                 raise ValueError
             value = endpoint
         elif option == "user":
             user = User.findByUsername(value)
             if user is None:
                 raise ValueError
             value = user
         elif option == "creds":
             if value[0] == '#':
                 credId = value[1:]
             else:
                 credId = value
             creds = Creds.find(credId)
             if creds is None:
                 raise ValueError
             value = creds
         elif option == "payload":
             value = Extensions.getPayload(value)
         self.options[option] = value
     else:
         self.options[option] = None
     print(option+" => "+str(self.getOption(option)))
Beispiel #10
0
 def parseOptionsTarget(self):
     user = self.getOption("user")
     if user is None:
         users = self.getUsers(scope=True)
     else:
         users = [User.find(user.getId())]
     endpoint = self.getOption("endpoint")
     if endpoint is None:
         endpoints = self.getEndpoints(scope=True)
     else:
         endpoints = [Endpoint.find(endpoint.getId())]
     cred = self.getOption("creds")
     if cred is None:
         creds = self.getCreds(scope=True)
     else:
         creds = [Creds.find(cred.getId())]
     return (endpoints,users,creds)
Beispiel #11
0
 def getUsers(self,scope=None):
     return User.findAll(scope=scope)
Beispiel #12
0
 def delUser(self,name):
     user = User.findByUsername(name)
     if user is None:
         print("Could not find user.")
         return False
     return user.delete()
Beispiel #13
0
 def addUser(self,name):
     newUser = User(name)
     newUser.save()
Beispiel #14
0
 async def gatherFromConfig(self):
     lootFolder = os.path.join(self.wspaceFolder, "loot")
     filename = str(self.connection.getEndpoint()).replace(
         ":", "-") + "_" + str(self.connection.getUser()) + "_.ssh_config"
     filepath = os.path.join(lootFolder, filename)
     try:
         await asyncssh.scp((self.socket, ".ssh/config"), filepath)
     except Exception as e:
         return None
     with open(filepath, 'r', errors='replace') as f:
         data = f.read()
     lines = data.split('\n')
     curHost = None
     for line in lines:
         if line == '':
             continue
         if line[:5].lower() == "Host ".lower():
             if curHost != None and curHost["name"] != "*":
                 if "host" in curHost.keys():
                     host = curHost["host"]
                 else:
                     host = curHost["name"]
                 if "port" in curHost.keys():
                     port = curHost["port"]
                 else:
                     port = None
                 endpoints = await self.hostnameToIP(host, port)
                 user = None
                 identity = None
                 if "user" in curHost.keys():
                     user = User(curHost["user"])
                     if not self.connection.inScope():
                         user.unscope()
                     if user.getId() is None:
                         user.setFound(self.connection.getEndpoint())
                         user.save()
                         self.newUsers.append(user)
                 if "identity" in curHost.keys():
                     identity = await self.getKeyToCreds(
                         curHost["identity"], ".")
                 if user is not None and identity is not None:
                     for endpoint in endpoints:
                         conn = Connection(endpoint, user, identity)
                         conn.save()
                         self.newConnections.append(conn)
             curHost = {}
             curHost["name"] = line.split()[1]
         else:
             [key, val] = line.strip().split(' ', 1)
             key = key.lower()
             if key == "user":
                 curHost['user'] = val
             elif key == "port":
                 curHost['port'] = val
             elif key == "hostname":
                 curHost['host'] = val
             elif key == "identityfile":
                 if val[:2] == '~/':
                     val = val[2:]
                 curHost['identity'] = val
     if curHost != None and curHost["name"] != "*":
         print("Not None")
         if "host" in curHost.keys():
             host = curHost["host"]
         else:
             host = curHost["name"]
         if "port" in curHost.keys():
             port = curHost["port"]
         else:
             port = None
         endpoints = await self.hostnameToIP(host, port)
         user = None
         identity = None
         if "user" in curHost.keys():
             user = User(curHost["user"])
             if not self.connection.inScope():
                 user.unscope()
             if user.getId() is None:
                 user.setFound(self.connection.getEndpoint())
                 self.newUsers.append(user)
                 user.save()
         if "identity" in curHost.keys():
             identity = await self.getKeyToCreds(curHost["identity"], ".")
         if user is not None and identity is not None:
             for endpoint in endpoints:
                 conn = Connection(endpoint, user, identity)
                 conn.save()
                 self.newConnections.append(conn)
     print("End")
Beispiel #15
0
 def getBaseObjects(self,scope=None):
     return Endpoint.findAll(scope=scope) + Creds.findAll(scope=scope) + User.findAll(scope=scope) + Host.findAll(scope=scope)
Beispiel #16
0
 def getFoundUsers(self,endpoint):
     return User.findByFound(endpoint)
Beispiel #17
0
    def gatherFromConfig(self):
        lootFolder = os.path.join(self.wspaceFolder, "loot")
        filename = str(self.connection.endpoint).replace(":", "-") + "_" + str(
            self.connection.user) + "_.ssh_config"
        filepath = os.path.join(lootFolder, filename)

        try:
            self.sftp.get(".ssh/config", filepath)
        except Exception as e:
            return None

        with open(filepath, 'r', errors='replace') as f:
            data = f.read()
        lines = data.split('\n')
        curHost = None
        for line in lines:
            if line == '':
                continue
            if line[:5].lower() == "Host ".lower():
                if curHost != None and curHost["name"] != "*":
                    if "host" in curHost.keys():
                        host = curHost["host"]
                    else:
                        host = curHost["name"]
                    if "port" in curHost.keys():
                        port = curHost["port"]
                    else:
                        port = None
                    endpoints = self.hostnameToIP(host, port)
                    user = None
                    identity = None
                    if "user" in curHost.keys():
                        user = User(curHost["user"])
                        if not self.connection.scope:
                            user.scope = False
                        if user.id is None:
                            user.found = self.connection.endpoint
                            user.save()
                            self.newUsers.append(user)
                    if "identity" in curHost.keys():
                        identity = self.getKeyToCreds(curHost["identity"], ".")
                curHost = {}
                curHost["name"] = line.split()[1]
            else:
                [key, val] = line.strip().split(' ', 1)
                key = key.lower()
                if key == "user":
                    curHost['user'] = val
                elif key == "port":
                    curHost['port'] = val
                elif key == "hostname":
                    curHost['host'] = val
                elif key == "identityfile":
                    if val[:2] == '~/':
                        val = val[2:]
                    curHost['identity'] = val
        if curHost != None and curHost["name"] != "*":
            if "host" in curHost.keys():
                host = curHost["host"]
            else:
                host = curHost["name"]
            if "port" in curHost.keys():
                port = curHost["port"]
            else:
                port = None
            endpoints = self.hostnameToIP(host, port)
            user = None
            identity = None
            if "user" in curHost.keys():
                user = User(curHost["user"])
                if not self.connection.scope:
                    user.scope = False
                if user.id is None:
                    user.found = self.connection.endpoint
                    self.newUsers.append(user)
                    user.save()
            if "identity" in curHost.keys():
                identity = self.getKeyToCreds(curHost["identity"], ".")