Exemplo n.º 1
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
Exemplo n.º 2
0
    def addEndpoint(self,ip,port):
        if not self.checkIsIP(ip):
            print("The address given isn't a valid IP")
            raise ValueError
        if not port.isdigit():
            print("The port given isn't a positive integer")
            raise ValueError

        newEndpoint = Endpoint(ip,port)
        newEndpoint.save()
Exemplo n.º 3
0
 def addPath(self,src,dst):
     if src.lower() != "local":
         if src not in self.getHostsNames():
             print("Not a known Host name.")
             return
         
         hosts = Host.findByName(src)
         if len(hosts) > 1:
             print("Several hosts corresponding. Add failed")
             return
         src = hosts[0]
         if src is None:
             print("The source Host provided doesn't exist in this workspace")
             return
     else:
         src = None
     try:
         dst = Endpoint.findByIpPort(dst)
     except:
         print("Please specify valid destination endpoint in the IP:PORT form")
     if dst is None:
         print("The destination endpoint provided doesn't exist in this workspace")
         return
     p = Path(src,dst)
     p.save()
     print("Path saved")
Exemplo n.º 4
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
Exemplo n.º 5
0
 def findAll(cls):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute('SELECT src,dst FROM paths'):
         ret.append(Path(Host.find(row[0]), Endpoint.find(row[1])))
     c.close()
     return ret
Exemplo n.º 6
0
 def findByDst(cls, dst):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute('SELECT src,dst FROM paths WHERE dst=?',
                          (dst.getId(), )):
         ret.append(Path(Host.find(row[0]), Endpoint.find(row[1])))
     c.close()
     return ret
Exemplo n.º 7
0
 def find(cls, pathId):
     c = dbConn.get().cursor()
     c.execute('''SELECT src,dst FROM paths WHERE id=?''', (pathId, ))
     row = c.fetchone()
     c.close()
     if row == None:
         return None
     return Path(Host.find(row[0]), Endpoint.find(row[1]))
Exemplo n.º 8
0
 def getEndpoints(self):
     from baboossh.endpoint import Endpoint
     endpoints = []
     c = dbConn.get().cursor()
     for row in c.execute('SELECT ip,port FROM endpoints WHERE host=?',
                          (self.id, )):
         endpoints.append(Endpoint(row[0], row[1]))
     c.close()
     return endpoints
Exemplo n.º 9
0
 def getPath(cls, src, dst):
     if src == None:
         srcId = 0
     else:
         srcId = src.getId()
     dstId = dst.getId()
     chainId = cls.easyPath(srcId, dstId)
     if len(chainId) == 0:
         return None
     chain = []
     for i in range(0, len(chainId) - 1):
         if chainId[i] == 0:
             srcHost = None
         else:
             srcEndpoint = Endpoint.find(chainId[i])
             srcHost = srcEndpoint.getHost()
         chain.append(Path(srcHost, Endpoint.find(chainId[i + 1])))
     return chain
Exemplo n.º 10
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
Exemplo n.º 11
0
 def findByUser(cls, user):
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute(
             'SELECT endpoint,cred FROM connections WHERE user=?',
         (user.getId(), )):
         ret.append(
             Connection(Endpoint.find(row[0]), user, Creds.find(row[1])))
     c.close()
     return ret
Exemplo n.º 12
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]))
Exemplo n.º 13
0
 def delEndpoint(self,endpoint):
     try:
         endpoint = Endpoint.findByIpPort(endpoint)
     except ValueError:
         print("Could not find endpoint.")
         return False
     if endpoint is None:
         print("Could not find endpoint.")
         return False
     return endpoint.delete()
Exemplo n.º 14
0
 def findBySrc(cls, src):
     if src == None:
         srcId = 0
     else:
         srcId = src.getId()
     ret = []
     c = dbConn.get().cursor()
     for row in c.execute('SELECT dst FROM paths WHERE src=?', (srcId, )):
         ret.append(Path(src, Endpoint.find(row[0])))
     c.close()
     return ret
Exemplo n.º 15
0
 def scanTarget(self,target,gateway=None):
     if not isinstance(target,Endpoint):
         target = Endpoint.findByIpPort(target)
     if gateway is not None:
         if gateway == "local":
             gateway = None
         else:
             gateway = Connection.fromTarget(gateway)
     else:
         gateway = "auto"
     working = target.scan(gateway=gateway)
     return working
Exemplo n.º 16
0
    def run(cls, stmt, workspace):
        nmapfile = getattr(stmt, 'nmapfile')
        fromHost = getattr(stmt, 'from', "Local")

        if fromHost is None:
            src = None
            print("No source host specified, using Local")
        elif fromHost == "Local":
            src = None
        else:
            hosts = Host.findByName(fromHost)
            if len(hosts) > 1:
                print("Several hosts corresponding.")
                return False
            elif len(hosts) == 0:
                print("No host corresponding.")
                return False
            src = hosts[0]
        try:
            report = NmapParser.parse_fromfile(nmapfile)
        except Exception as e:
            print("Failed to read source file: " + str(e))
            return False
        count = 0
        countNew = 0
        for host in report.hosts:
            for s in host.services:
                if s.service == "ssh":
                    count = count + 1
                    newEndpoint = Endpoint(host.address, s.port)
                    if newEndpoint.getId() is None:
                        countNew = countNew + 1
                    newEndpoint.save()
                    newPath = Path(src, newEndpoint)
                    newPath.save()
        print(
            str(count) + " endpoints found, " + str(countNew) +
            " new endpoints saved")
        return True
Exemplo n.º 17
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)))
Exemplo n.º 18
0
    def getAdjacencyList(cls):
        adj = {}
        adj[0] = []
        c = dbConn.get().cursor()
        for row in c.execute('SELECT dst FROM paths WHERE src=0'):
            adj[0].append(row[0])
        c.close()

        for endpoint in Endpoint.findAllWorking():
            adj[endpoint.getId()] = []
            c = dbConn.get().cursor()
            for row in c.execute('SELECT dst FROM paths WHERE src=?',
                                 (endpoint.getHost().getId(), )):
                adj[endpoint.getId()].append(row[0])
            c.close()
        return adj
Exemplo n.º 19
0
 def __init__(self, name):
     self.name = name
     self.id = None
     self.scope = True
     self.found = None
     c = dbConn.get().cursor()
     c.execute('SELECT id,scope,found FROM users WHERE username=?',
               (self.name, ))
     savedUser = c.fetchone()
     c.close()
     if savedUser is not None:
         self.id = savedUser[0]
         self.scope = savedUser[1] != 0
         if savedUser[2] is not None:
             from baboossh.endpoint import Endpoint
             self.found = Endpoint.find(savedUser[2])
Exemplo n.º 20
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)
Exemplo n.º 21
0
 def __init__(self, credsType, credsContent):
     self.credsType = credsType
     self.credsContent = credsContent
     self.obj = Extensions.getAuthMethod(credsType)(credsContent)
     self.id = None
     self.scope = True
     self.found = None
     c = dbConn.get().cursor()
     c.execute(
         'SELECT id,scope,found FROM creds WHERE type=? AND identifier=?',
         (self.credsType, self.obj.getIdentifier()))
     savedCreds = c.fetchone()
     c.close()
     if savedCreds is not None:
         self.id = savedCreds[0]
         self.scope = savedCreds[1] != 0
         if savedCreds[2] is not None:
             from baboossh.endpoint import Endpoint
             self.found = Endpoint.find(savedCreds[2])
Exemplo n.º 22
0
    def run(cls, stmt, workspace):
        nmapfile = getattr(stmt, 'nmapfile')
        from_host = getattr(stmt, 'from', "Local")

        if from_host is None:
            print("No source host specified, ignoring paths")
            distance = None
        elif from_host == "Local":
            src = None
            distance = 0
        else:
            host = Host.find_one(name=from_host)
            if host is None:
                print("No host corresponding.")
                return False
            src = host
            distance = src.distance + 1
        try:
            report = NmapParser.parse_fromfile(nmapfile)
        except Exception as e:
            print("Failed to read source file: " + str(e))
            return False
        count = 0
        count_new = 0
        for host in report.hosts:
            for s in host.services:
                if s.service == "ssh" and s.open():
                    count = count + 1
                    new_endpoint = Endpoint(host.address, s.port)
                    if new_endpoint.id is None:
                        count_new = count_new + 1
                    new_endpoint.save()
                    if distance is not None:
                        if new_endpoint.distance is None or new_endpoint.distance > distance:
                            new_endpoint.distance = distance
                            new_endpoint.save()
                        new_path = Path(src, new_endpoint)
                        new_path.save()
        print(
            str(count) + " endpoints found, " + str(count_new) +
            " new endpoints saved")
        return True
Exemplo n.º 23
0
    def findPath(self,dst):
        #DST is HOST
        #if dst in self.getHostsNames():
        #    hosts = Host.findByName(dst)
        #    if len(hosts) > 1:
        #        print("Several hosts corresponding. Please target endpoint.")
        #        return False
        #    dst = str(hosts[0].getClosestEndpoint())
        try:
            dst = Endpoint.findByIpPort(dst)
        except:
            print("Please specify a valid endpoint in the IP:PORT form")
            return
        if dst is None:
            print("The endpoint provided doesn't exist in this workspace")
            return
        if Path.hasDirectPath(dst):
            print("The destination should be reachable directly from the host.")
            return

        workingDirect = dst.scan(gateway=None,silent=True)
        if workingDirect:
            p = Path(None,dst)
            p.save()
            print("Could reach target directly, path added.")
            return

        for h in Path.getHostsOrderedClosest():
            e = h.getClosestEndpoint()
            gateway = Connection.findWorkingByEndpoint(e)
            working = dst.scan(gateway=gateway,silent=True)
            if working:
                p = Path(h,dst)
                p.save()
                print("Working with gw "+str(e)+" (host "+str(h)+")")
                return
        return
Exemplo n.º 24
0
 def getPathToDst(self,dst):
     if dst in self.getHostsNames():
         hosts = Host.findByName(dst)
         if len(hosts) > 1:
             print("Several hosts corresponding. Please target endpoint.")
             return False
         dst = str(hosts[0].getClosestEndpoint())
     try:
         dst = Endpoint.findByIpPort(dst)
     except:
         print("Please specify a valid endpoint in the IP:PORT form")
         return
     if dst is None:
         print("The endpoint provided doesn't exist in this workspace")
         return
     if Path.hasDirectPath(dst):
         print("The destination should be reachable from the host")
         return
     chain = Path.getPath(None,dst)
     if chain is None:
         print("No path could be found to the destination")
         return
     for path in chain:
         print(path)
Exemplo n.º 25
0
 def getFoundEndpoints(self,endpoint):
     return Endpoint.findByFound(endpoint)
Exemplo n.º 26
0
 def getBaseObjects(self,scope=None):
     return Endpoint.findAll(scope=scope) + Creds.findAll(scope=scope) + User.findAll(scope=scope) + Host.findAll(scope=scope)
Exemplo n.º 27
0
 def getEndpoints(self,scope=None):
     endpoints = []
     for endpoint in Endpoint.findAll(scope=scope):
         endpoints.append(endpoint)
     return endpoints
Exemplo n.º 28
0
    def hostnameToIP(self, hostname, port=None):
        endpoints = []
        #Check if hostname is IP or Hostname :
        try:
            ipobj = ipaddress.ip_address(hostname)
        except ValueError:
            chan = self.connection.transport.open_channel("session", timeout=3)
            ips = ""
            chan.exec_command("getent hosts " + hostname +
                              " | awk '{ print $1 }'")
            try:
                x = u(chan.recv(1024))
                while len(x) != 0:
                    ips = ips + x
                    x = u(chan.recv(1024))
            except socket.timeout:
                pass
            chan.close()

            ips = ips.splitlines()
            for ip in ips:
                ipobj = ipaddress.ip_address(ip)
                if ipobj.is_loopback:
                    continue
                endpoint = Endpoint(ip, port if port is not None else 22)
                if endpoint.id is None:
                    endpoint.found = self.connection.endpoint
                if not self.connection.scope:
                    endpoint.scope = False
                try:
                    path = Path(self.connection.endpoint.host, endpoint)
                except ValueError:
                    pass
                else:
                    endpoint.save()
                    path.save()
                    endpoints.append(endpoint)
        else:
            if ipobj.is_loopback:
                return []
            endpoint = Endpoint(hostname, port if port is not None else 22)
            if endpoint.id is None:
                endpoint.found = self.connection.endpoint
            if not self.connection.scope:
                endpoint.scope = False
            if endpoint.id is None:
                endpoint.save()
                self.newEndpoints.append(endpoint)
            try:
                path = Path(self.connection.endpoint.host, endpoint)
            except ValueError:
                pass
            else:
                path.save()
                endpoints.append(endpoint)
        return endpoints
Exemplo n.º 29
0
 async def hostnameToIP(self, hostname, port=None):
     endpoints = []
     #Check if hostname is IP or Hostname :
     try:
         ipobj = ipaddress.ip_address(hostname)
     except ValueError:
         res = await self.socket.run("getent hosts " + hostname +
                                     " | awk '{ print $1 }'")
         ips = res.stdout.splitlines()
         for ip in ips:
             ipobj = ipaddress.ip_address(ip)
             if ipobj.is_loopback:
                 continue
             endpoint = Endpoint(ip, port if port is not None else 22)
             if endpoint.getId() is None:
                 endpoint.setFound(self.connection.getEndpoint())
             if not self.connection.inScope():
                 endpoint.unscope()
             try:
                 path = Path(self.connection.getEndpoint().getHost(),
                             endpoint)
             except ValueError:
                 pass
             else:
                 endpoint.save()
                 path.save()
                 endpoints.append(endpoint)
     else:
         if ipobj.is_loopback:
             return []
         endpoint = Endpoint(hostname, port if port is not None else 22)
         if endpoint.getId() is None:
             endpoint.setFound(self.connection.getEndpoint())
         if not self.connection.inScope():
             endpoint.unscope()
         if endpoint.getId() is None:
             endpoint.save()
             self.newEndpoints.append(endpoint)
         try:
             path = Path(self.connection.getEndpoint().getHost(), endpoint)
         except ValueError:
             pass
         else:
             path.save()
             endpoints.append(endpoint)
     return endpoints