Exemple #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
Exemple #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
Exemple #3
0
 def delCreds(self,credsId):
     if credsId[0] == '#':
         credsId = credsId[1:]
     creds = Creds.find(credsId)
     if creds == None:
         print("Specified creds not found")
         return False
     return creds.delete()
Exemple #4
0
 def editCreds(self,credsId):
     if credsId[0] == '#':
         credsId = credsId[1:]
     creds = Creds.find(credsId)
     if creds == None:
         print("Specified creds not found")
         return
     creds.edit()
Exemple #5
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
Exemple #6
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]))
Exemple #7
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
Exemple #8
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
Exemple #9
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]))
Exemple #10
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)))
Exemple #11
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)
Exemple #12
0
 async def getKeyToCreds(self, keyfile, basePath=".ssh"):
     if basePath != ".":
         keyfile = os.path.join(basePath, keyfile)
     from baboossh.params import Extensions
     keysFolder = os.path.join(self.wspaceFolder, "keys")
     filename = str(self.connection.getEndpoint()).replace(
         ":", "-") + "_" + str(
             self.connection.getUser()) + "_" + keyfile.replace("/", "_")
     filepath = os.path.join(keysFolder, filename)
     try:
         await asyncssh.scp((self.socket, keyfile), filepath)
     except Exception as e:
         print(e)
         return None
     subprocess.run(["chmod", "600", filepath])
     p = subprocess.run(["sha1sum", filepath], stdout=subprocess.PIPE)
     output = p.stdout.decode("utf-8")
     output = output.split(" ", 1)[0]
     if output in self.keysHash.keys():
         if filepath != self.keysHash[output]:
             os.remove(filepath)
         return None
     valid, haspass = Extensions.getAuthMethod("privkey").checkKeyfile(
         filepath)
     if valid:
         self.keysHash[output] = filepath
         c = {"passphrase": "", "keypath": filepath, "haspass": haspass}
         cred = Creds("privkey", json.dumps(c))
         if not self.connection.inScope():
             cred.unscope()
         if cred.getId() is None:
             cred.setFound(self.connection.getEndpoint())
             cred.save()
             self.newCreds.append(cred)
         return cred
     else:
         os.remove(filepath)
     return None
Exemple #13
0
    def __init__(self, socket, connection, wspaceFolder):
        self.socket = socket
        self.connection = connection
        self.wspaceFolder = wspaceFolder
        self.newCreds = []
        self.newUsers = []
        self.newEndpoints = []
        self.newConnections = []

        self.keysHash = {}
        for c in Creds.findAll():
            if c.credsType != "privkey":
                continue
            path = c.obj.keypath
            p = subprocess.run(["sha1sum", path], stdout=subprocess.PIPE)
            out = p.stdout.decode("utf-8")
            h = out.split(" ", 1)[0]
            self.keysHash[h] = path
Exemple #14
0
    def __init__(self, connection, wspaceFolder):
        self.connection = connection
        self.wspaceFolder = wspaceFolder
        self.newCreds = []
        self.newUsers = []
        self.newEndpoints = []

        self.keysHash = {}
        for c in Creds.find_all():
            if c.creds_type != "privkey":
                continue
            path = c.obj.keypath
            p = subprocess.run(["sha1sum", path], stdout=subprocess.PIPE)
            out = p.stdout.decode("utf-8")
            h = out.split(" ", 1)[0]
            self.keysHash[h] = path

        self.sftp = SFTPClient.from_transport(self.connection.transport)
Exemple #15
0
 def getKeyToCreds(self, keyfile, basePath=".ssh"):
     if basePath != ".":
         keyfile = os.path.join(basePath, keyfile)
     from baboossh.extensions import Extensions
     keysFolder = os.path.join(self.wspaceFolder, "keys")
     filename = str(self.connection.endpoint).replace(":", "-") + "_" + str(
         self.connection.user) + "_" + keyfile.replace("/", "_")
     filepath = os.path.join(keysFolder, filename)
     try:
         self.sftp.get(keyfile, filepath)
     except Exception as e:
         print(e)
         return None
     subprocess.run(["chmod", "600", filepath])
     p = subprocess.run(["sha1sum", filepath], stdout=subprocess.PIPE)
     output = p.stdout.decode("utf-8")
     output = output.split(" ", 1)[0]
     if output in self.keysHash.keys():
         if filepath != self.keysHash[output]:
             os.remove(filepath)
         return None
     valid, haspass = Extensions.auths["privkey"].checkKeyfile(filepath)
     if valid:
         self.keysHash[output] = filepath
         c = {"passphrase": "", "keypath": filepath, "haspass": haspass}
         cred = Creds("privkey", json.dumps(c))
         if not self.connection.scope:
             cred.scope = False
         if cred.id is None:
             cred.found = self.connection.endpoint
             cred.save()
             self.newCreds.append(cred)
         return cred
     else:
         os.remove(filepath)
     return None
Exemple #16
0
 def getFoundCreds(self,endpoint):
     return Creds.findByFound(endpoint)
Exemple #17
0
 def getBaseObjects(self,scope=None):
     return Endpoint.findAll(scope=scope) + Creds.findAll(scope=scope) + User.findAll(scope=scope) + Host.findAll(scope=scope)
Exemple #18
0
 def getCreds(self,scope=None):
     return Creds.findAll(scope=scope)
Exemple #19
0
 def addCreds(self,credsType,stmt):
     credsContent = Extensions.getAuthMethod(credsType).fromStatement(stmt)
     newCreds = Creds(credsType,credsContent)
     newCreds.save()
     return newCreds.getId()