def check_auth_publickey(self, username, key): pubkey = key.get_base64() addr = self.sock_addr[0] if username == "sshproxy-IPC": try: hostkey_file = get_config('sshproxy').get('hostkey_file') hostkey = paramiko.DSSKey(filename=hostkey_file).get_base64() auth_keys_file = get_config('sipc')['authorized_keys'] if os.path.isfile(auth_keys_file): authorized_keys = open(auth_keys_file).readlines() else: authorized_keys = [] authorized_keys.append(hostkey) if not len([k for k in authorized_keys if pubkey in k]): log.error("ATTENTION: unauthorized attempt to connect " "on IPC channel from %s@%s" % (username, addr)) return paramiko.AUTH_FAILED except: log.exception("SIPC: exception in check_auth_pubkey") return paramiko.AUTH_FAILED self.username = username return paramiko.AUTH_SUCCESSFUL log.error("ATTENTION: unauthorized attempt to connect " "on IPC channel from %s@%s" % (username, addr)) return paramiko.AUTH_FAILED
def _sock_accept(self): if self.sock_type == socket.AF_UNIX and self.sock_addr[0] == '\x00': return IPCServer._sock_accept(self) real_sock, address = self.sock.accept() log.info("IPC: Accepting new secure client %s", address) host_key = paramiko.DSSKey(filename="/etc/sshproxy/id_dsa") transport = paramiko.Transport(real_sock) transport.load_server_moduli() transport.add_server_key(host_key) # start the server interface negotiation_ev = threading.Event() transport.start_server(negotiation_ev, SSHServer(self.sock_addr)) while not negotiation_ev.isSet(): negotiation_ev.wait(0.5) if not transport.is_active(): log.error("SIPC: SSH negotiation failed") raise 'SSH negotiation failed' sock = transport.accept(5) self.real_sock = real_sock self.transport = transport return sock, address
def __init__(self, hostname, port, username, private_ssh_key_filename): self.hostname = hostname self.port = port self.username = username #print "Created TestingNode with hostname %s, port %i, username %s" % (hostname, port, username) # read private key from file to get access to the node if True: # Always use RSA for now self.private_ssh_key = paramiko.RSAKey( filename=private_ssh_key_filename) else: self.private_ssh_key = paramiko.DSSKey( filename=private_ssh_key_filename) self.global_lock_file = "/tmp/cloudtest_lock" system_random = random.SystemRandom() self.global_build_path = "/tmp/cloudtest_build_" + str( system_random.randint(10000000, 99999999)) self.global_bench_path = "/tmp/cloudtest_bench_" + str( system_random.randint(10000000, 99999999)) self.global_test_path = "/tmp/cloudtest_test_" + str( system_random.randint(10000000, 99999999)) #print "Installing build into %s\n" % self.global_build_path self.basedata_installed = False self.ssh_transport = None
def key(self): if self.keyfile is None: return None elif self.keytype == 'dsa': key = paramiko.DSSKey(filename=self.keyfile) elif self.keytype == 'rsa': key = paramiko.RSAKey(filename=self.keyfile) return key
def connect_ssh( ip, username, password=None, client=paramiko.SSHClient, key=None, timeout=15.0, ): ssh = client() ssh.set_log_channel('critical_only') ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if key: f = StringIO.StringIO(key) pkey = paramiko.DSSKey(file_obj=f) else: pkey = None try: ssh.connect( ip, username=username, password=password, pkey=pkey, timeout=timeout, ) except (paramiko.AuthenticationException, EOFError) as e: raise AuthError(str(e)) return ssh
def read_public_key_file(filename): data = open(filename, 'r').read() if data.startswith('ssh-dss '): # This is probably a public OpenSSH key import binascii import struct keystring = binascii.a2b_base64(data.split(' ')[1]) keyparts = [] while len(keystring) > 4: length = struct.unpack(">I", keystring[:4])[0] keyparts.append(keystring[4:4 + length]) keystring = keystring[4 + length:] if keyparts[0] == 'ssh-dss': tup = [ Crypto.Util.number.bytes_to_long(keyparts[x]) for x in (4, 3, 1, 2) ] pubk = Crypto.PublicKey.DSA.construct(tup) p = pubk.key.p q = pubk.key.q g = pubk.key.g y = pubk.key.y vals = (p, q, g, y) return paramiko.DSSKey(vals=vals) return None elif data.startswith('ssh-rsa '): key = Crypto.PublicKey.RSA.importKey(data) return paramiko.RSAKey(vals=(key.e, key.n)) else: return None
def get_user_auth_keys(self, username): """Parse the users's authorized_keys file if any to look for authorized keys""" if username in self.users_keys: return self.users_keys[username] self.users_keys[username] = [] userdir = os.path.expanduser("~" + username) if not userdir: return self.users_keys[username] keyfile = os.path.join(userdir, ".ssh/authorized_keys") if not keyfile or not os.path.exists(keyfile): return self.users_keys[username] with open(keyfile) as f: for line in f.readlines(): line = line.strip() if not line or line.startswith("#"): continue values = [x.strip() for x in line.split()] exp = None try: int(values[0]) # bits value? except ValueError: # Type 1 or type 2, type 1 is bits in second value options_ktype = values[0] try: int(values[1]) # bits value? except ValueError: # type 2 with options ktype = options_ktype data = values[1] else: # Type 1 no options. exp = int(values[1]) data = values[2] else: # Type 1 no options. exp = int(values[1]) data = values[2] # XXX For now skip type 1 keys if exp is not None: continue if data: import base64 if ktype == "ssh-rsa": key = ssh.RSAKey( data=base64.decodebytes(data.encode('ascii'))) elif ktype == "ssh-dss": key = ssh.DSSKey( data=base64.decodebytes(data.encode('ascii'))) else: key = None if key: self.users_keys[username].append(key) return self.users_keys[username]
def _get_auth_keys(user: str) -> typing.List[paramiko.PKey]: """ Returns a list of user's public keys :param user: user's email :return: a list of user's public keys """ authorized_keys = [] filename = "/{email_hash}/ssh/authorized_keys".format(email_hash=user["email_hash"]) for rawline in open(filename, 'r'): line = rawline.strip() if not line or line.startswith("#"): continue if line.startswith("ssh-rsa ") or line.startswith("ssh-dss "): # Get the key field try: d = " ".join(line.split(" ")[1:]).lstrip().split(" ")[0] except: # Parse error continue if line.startswith("ssh-rsa"): d = d.encode() k = paramiko.RSAKey(data=base64.decodestring(d)) else: d = d.encode() k = paramiko.DSSKey(data=base64.decodestring(d)) del d authorized_keys.append(k) return authorized_keys
def check_auth_publickey(self, username, key): """ PKI-based Authentication. """ # Get the singleton instance of the RBAC manager rm = rbacManager.getInstance() # Use RBAC manager to retrieve the User object from its login u = rm.getUserFromLogin(username) if u == None: # If user does not exist, authentication must fail: return paramiko.AUTH_FAILED else: # If user public key does not exist in the RBAC manager, authentication must fail: if u.publickey == "": return paramiko.AUTH_FAILED else: # Build the known manager public key object from the RBAC manager. if u.publickeytype == "rsa": manager_public_key = paramiko.RSAKey( data=base64.decodestring(u.publickey)) elif u.publickeytype == "dss": manager_public_key = paramiko.DSSKey( data=base64.decodestring(u.publickey)) else: return paramiko.AUTH_FAILED # Compare the known public key with the received one: if (key == manager_public_key): self.user = username return paramiko.AUTH_SUCCESSFUL else: return paramiko.AUTH_FAILED
def get_dss_key_from_string(dsskeystr=None, password=None): if hasattr(paramiko.DSSKey, 'write_private_key'): fd = StringIO.StringIO() fd.write(dsskeystr) fd.seek(0L) return paramiko.DSSKey(file_obj=fd, password=password) # if paramiko <= 1.6 else: return _get_dss_key_from_string(dsskeystr, password)
def from_string(cls, key_string): try: pkey = paramiko.RSAKey(file_obj=StringIO(key_string)) return pkey except paramiko.SSHException: try: pkey = paramiko.DSSKey(file_obj=StringIO(key_string)) return pkey except paramiko.SSHException: return None
def get_absences(): # Load properties and check that they are structurally OK props = utils.load_properties() try: assert props[ 'hourTrackingSystem'] != None, 'No hourTrackingSystem properties section' assert props['hourTrackingSystem'][ 'moduleName'] != None, 'Time tracking module name not set' assert props['hourTrackingSystem'][ 'host'] != None, 'Time tracking host not set' assert props['hourTrackingSystem'][ 'port'] != None, 'Time tracking server port not set' assert props['hourTrackingSystem'][ 'path'] != None, 'Time tracking file path not set' assert props['hourTrackingSystem'][ 'id'] != None, 'Time tracking user ID not set' assert props['hourTrackingSystem'][ 'pw'] != None, 'Time tracking password not set' assert props['hourTrackingSystem'][ 'hostKey'] != None, 'Time tracking hostKey not set' except Exception as ex: print("Properties file not complete:", repr(ex)) exit() absences = [] # For added security, the server's hostkey is verified against the one stored in properties bHostKey = str.encode(props['hourTrackingSystem']['hostKey']) hostKey = paramiko.DSSKey(data=decodebytes(bHostKey)) cnopts = pysftp.CnOpts() cnopts.hostkeys.add(props['hourTrackingSystem']['host'], 'ssh-rsa', hostKey) tempfile = '__temp.csv' with pysftp.Connection(host=props['hourTrackingSystem']['host'], username=props['hourTrackingSystem']['id'], password=props['hourTrackingSystem']['pw'], cnopts=cnopts) as sftp: sftp.get(props['hourTrackingSystem']['path'], tempfile) csvfile = open(tempfile, 'r') reader = csv.reader(csvfile, delimiter=';') for row in reader: external_id, start_date, end_date = row absence = { 'externalId': external_id, 'startDate': parse_date(start_date), 'endDate': parse_date(end_date) } absences.append(absence) os.remove(tempfile) return absences
def from_line(cls, line, lineno=None, filename=None): ''' Parses the given line of text to find the name(s) for the host, the type of key, and the key data. ''' if not line or not line.strip(): return None fields = line.strip().split(' ') if not fields or fields[0].startswith('#'): return None if fields[0].startswith('@'): marker = fields[0] fields = fields[1:] else: marker = None if len(fields) < 3: raise UnreadableKey('Invalid known_hosts line', line, lineno) names, keytype, key = fields[:3] names = names.split(',') # Decide what kind of key we're looking at and create an object # to hold it accordingly. key = key.encode('ascii') # SSH-2 Key format consists of 2 (text) fields # keytype, base64_blob try: if keytype == 'ssh-rsa': key = paramiko.RSAKey(data=base64.b64decode(key)) elif keytype == 'ssh-dss': key = paramiko.DSSKey(data=base64.b64decode(key)) elif keytype == 'ecdsa-sha2-nistp256': key = paramiko.ECDSAKey(data=base64.b64decode(key), validate_point=False) elif len(fields) > 3: # SSH-1 Key format consists of 3 integer fields # bits, exponent, modulus (RSA Only) try: bits = int(fields[1]) exponent = int(fields[2]) modulus = long(fields[3]) key = paramiko.RSAKey(vals=(exponent, modulus)) except ValueError: raise UnreadableKey('Invalid known_hosts line', line, lineno, filename) else: raise UnreadableKey('Invalid known_hosts line', line, lineno, filename) return cls(names, key, marker, lineno, filename) except Exception as e: raise UnreadableKey('Invalid known_hosts line (%s)' % e, line, lineno, filename)
def generate_cache(cacheFile, authCredFile, authKeyFile): import paramiko username = None password = None hostKey = None ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if len(authCredFile): try: fd = open(authCredFile, 'r') except: errMsg("generate_cache: failed to open auth credentials file") return False for line in fd.readlines(): name, value = line.strip().split(':') if name == "username": username = value elif name == "password": password = value fd.close() if len(authKeyFile) and not os.path.exists(authKeyFile): errMsg("generate_cache: key file specified does not exist") return False elif len(authKeyFile): try: if config.auth_key_type == 'dsa': hostKey = paramiko.DSSKey(filename=authKeyFile, password=password) else: hostKey = paramiko.RSAKey(filename=authKeyFile, password=password) except Exception, e: msg = str(e) if msg.count("encrypt"): errMsg("generate_cache: key specified is encrypted " + "(use --authcred): %s" % msg) elif msg.count("RSA private"): errMsg("generate_cache: key specified is type DSA " + "(use --authkeydsa): %s" % msg) else: errMsg(msg) return False # if no auth credentials are specified default to root for username if len(username) == 0: username = "******"
def sshAuthentication(self, clientsock): # setup logging paramiko.util.log_to_file(C.SYSLOG_FILE) # Check that SSH server parameters have been set: if (self.sshData == None): return clientsock, False, None else: # Load private key of the server filekey = self.sshData["hostKeyFile"] if (not filekey.startswith("/")): filekey = C.YENCAP_CONF_KEYS + "/" + filekey # Build a key object from the file path: if (self.sshData["hostKeyType"] == "dss"): priv_host_key = paramiko.DSSKey(filename=filekey) elif (self.sshData["hostKeyType"] == "rsa"): priv_host_key = paramiko.RSAKey(filename=filekey) try: event = threading.Event() # Create a new SSH session over an existing socket, or socket-like object. t = Transport(clientsock) # Add a host key to the list of keys used for server mode. t.add_server_key(priv_host_key) # paramiko.ServerInterface defines an interface for controlling the behavior of paramiko in server mode. server = SSHServerModule() # Negotiate a new SSH2 session as a server. t.start_server(event, server) while 1: event.wait(0.1) if not t.is_active(): return clientsock, False, None if event.isSet(): break # Return the next channel opened by the client over this transport, in server mode. channel = t.accept(20) if channel is None: return clientsock, False, None except Exception, e: LogManager.getInstance().logError("Caught exception: %s: %s" % (str(e.__class__), str(e))) traceback.print_exc() try: t.close() except: pass return clientsock, False, None
def handle(self): transport = paramiko.Transport(self.request) rsafile = self.server.cfg.get("ssh", "private_rsa") dsafile = self.server.cfg.get("ssh", "private_dsa") rsakey = paramiko.RSAKey(filename=rsafile) dsakey = paramiko.DSSKey(filename=dsafile) transport.add_server_key(rsakey) transport.add_server_key(dsakey) transport.local_version = self.server.cfg.get("ssh", "banner") transport.set_subsystem_handler('sftp', paramiko.SFTPServer, sftpServer.sftp_server) nw = network.network(self.client_address[0], self.server.cfg.get("wetland", "docker_addr")) nw.create() if self.server.myip: myip = self.server.myip else: myip = transport.sock.getsockname()[0] sServer = sshServer.ssh_server(transport=transport, network=nw, myip=myip, whitelist=self.server.whitelist, blacklist=self.server.blacklist) try: transport.start_server(server=sServer) except paramiko.SSHException: return except Exception as e: print e nw.delete() sServer.docker_trans.close() return try: while True: chann = transport.accept(60) # no channel left if not transport._channels.values(): break except Exception as e: print e finally: nw.delete() sServer.docker_trans.close()
def handle_tcp_ssh(socket, dsthost, dstport, persona): try: #(dsthost, dstport) = socket.server_address t = paramiko.Transport(socket) t.local_version = persona.get('banner') t.load_server_moduli( ) # It can be safely commented out if it does not work on your system rsafile = './resources/ssh/{}_rsa'.format(dsthost) if (os.path.exists(rsafile)): print('SSH loading', rsafile) t.add_server_key(paramiko.RSAKey(filename=rsafile)) else: print('SSH loading default rsa, missing:', rsafile) t.add_server_key(default_key_rsa) dssfile = 'resources/ssh/{}_dss'.format(dsthost) if (os.path.exists(dssfile)): print('SSH loading', dssfile) t.add_server_key(paramiko.DSSKey(filename=dssfile)) else: print('SSH loading default dss, missing:', dssfile) t.add_server_key(default_key_dss) server = Server(socket.getpeername()) try: t.start_server(server=server) except socket.timeout: print('Timeout') except paramiko.ssh_exception.SSHException as err: print('SSHException: ', err) except EOFError: print("Disconnected by peer.") t.join() except Exception: print(traceback.format_exc()) pass try: t.close() except: print('When closing socket', traceback.format_exc()) pass socket.close()
def __reginit__(self, client, addr, host_key_file): self.client = client self.client_addr = addr ipc_address = get_config('sshproxy').get('ipc_address', 'sshproxy-control') handler = IPCClientInterface(self) try: self.monitor = ipc.IPCClient(ipc_address, handler=handler) except: log.exception("Couldn't create IPC channel to monitor") raise self.host_key = paramiko.DSSKey(filename=host_key_file) #self.ip_addr, self.port = client.getsockname() self.event = threading.Event() self.args = [] self._remotes = {} self.exit_status = -1
class SFTP_wrapper: """ variable declarations """ _t = None _chan = None _sftp = None """ utility functions """ def __init__(self, hostname=None, username=None, password=None, port=22): self.hostname = hostname self.username = username self.password = password self.port = port ### method: charger la clef from the. ---------------------------- def __load_host_keys(): #if systeme == LINUX #filename = os.environ['HOME'] + '/.ssh/known_hosts' #if systeme == WINDOWS filename = os.environ['USERPROFILE'] + '\key' #ifdef windows keys = {} try: f = open(filename, 'r') except Exception, e: logging.warning('Unable to open host keys file (%s)' % filename) return for line in f: keylist = line.split(' ') if len(keylist) != 3: continue hostlist, keytype, key = keylist hosts = hostlist.split(',') for host in hosts: if not keys.has_key(host): keys[host] = {} if keytype == 'ssh-rsa': keys[host][keytype] = paramiko.RSAKey( data=base64.decodestring(key)) elif keytype == 'ssh-dss': keys[host][keytype] = paramiko.DSSKey( data=base64.decodestring(key)) f.close() return keys
def __init__(self, ip_address, ssh_port, ssh_username, ssh_password, ssh_host_key, ssh_pkey=None): ''' If used, ssh_pkey must be a string with the complete PEM file contents. ''' self.ssh = ssh.SSHClient() self.ip_address = ip_address ssh_port = int(ssh_port) if ssh_host_key == None: self.ssh.set_missing_host_key_policy(ssh.AutoAddPolicy()) else: split_key = ssh_host_key.split(' ') key_type = split_key[0] key_data = split_key[1] # Host keys are looked up by IP if the port is 22, but [IP]:port if # the port is anything else. if int(ssh_port) == 22: key_host_name = '%s' % (ip_address, ) else: key_host_name = '[%s]:%d' % (ip_address, ssh_port) if key_type == 'ssh-dss': self.ssh.get_host_keys().add( key_host_name, key_type, ssh.DSSKey(data=base64.b64decode(key_data))) else: # 'ssh-rsa' self.ssh.get_host_keys().add( key_host_name, key_type, ssh.RSAKey(data=base64.b64decode(key_data))) if ssh_pkey is not None: ssh_pkey = ssh.RSAKey.from_private_key(StringIO.StringIO(ssh_pkey)) self.ssh.connect(ip_address, ssh_port, ssh_username, ssh_password, pkey=ssh_pkey, timeout=60)
def handle(self): transport = paramiko.Transport(self.request) rsafile = self.server.cfg.get("ssh", "private_rsa") dsafile = self.server.cfg.get("ssh", "private_dsa") rsakey = paramiko.RSAKey(filename=rsafile) dsakey = paramiko.DSSKey(filename=dsafile) transport.add_server_key(rsakey) transport.add_server_key(dsakey) transport.local_version = self.server.cfg.get("ssh", "banner") transport.set_subsystem_handler('sftp', paramiko.SFTPServer, sftpServer.sftp_server) hacker_addr = transport.getpeername()[0] if hacker_addr not in self.server.sessions: uid = uuid.uuid4().get_hex() self.server.sessions[hacker_addr] = uid else: uid = self.server.sessions[hacker_addr] sServer = sshServer.ssh_server(transport=transport, whitelist=self.server.whitelist, blacklist=self.server.blacklist, sessionuid=uid) try: transport.start_server(server=sServer) except paramiko.SSHException: return except Exception as e: print e sServer.docker_trans.close() return try: while True: chann = transport.accept(60) # no channel left if not transport._channels.values(): break except Exception as e: print e finally: sServer.docker_trans.close()
def load_authorized_keys(self): pubkeys = [] for line in open(RemoteCommandServer.AUTHORIZED_KEYS_FILENAME): if not line.strip() or line.startswith('#'): continue kind, b64pubkey = line.split()[:2] if kind == 'ssh-dss': pubkeys.append( paramiko.DSSKey(data=base64.decodestring(b64pubkey))) elif kind == 'ssh-rsa': pubkeys.append( paramiko.RSAKey(data=base64.decodestring(b64pubkey))) else: raise ValueError('unknown key type - ' + kind) if len(pubkeys) == 0: raise ValueError("didn't find any public keys in " + RemoteCommandServer.AUTHORIZED_KEYS_FILENAME) return pubkeys
def test_4_dict_set(self): hostdict = paramiko.HostKeys('hostfile.temp') key = paramiko.RSAKey(data=base64.decodestring(keyblob)) key_dss = paramiko.DSSKey(data=base64.decodestring(keyblob_dss)) hostdict['secure.example.com'] = {'ssh-rsa': key, 'ssh-dss': key_dss} hostdict['fake.example.com'] = {} hostdict['fake.example.com']['ssh-rsa'] = key self.assertEquals(3, len(hostdict)) self.assertEquals(2, len(hostdict.values()[0])) self.assertEquals(1, len(hostdict.values()[1])) self.assertEquals(1, len(hostdict.values()[2])) fp = hexlify(hostdict['secure.example.com'] ['ssh-rsa'].get_fingerprint()).upper() self.assertEquals('7EC91BB336CB6D810B124B1353C32396', fp) fp = hexlify(hostdict['secure.example.com'] ['ssh-dss'].get_fingerprint()).upper() self.assertEquals('4478F0B9A23CC5182009FF755BC1D26C', fp)
def test_dict_set(self): hostdict = paramiko.HostKeys("hostfile.temp") key = paramiko.RSAKey(data=decodebytes(keyblob)) key_dss = paramiko.DSSKey(data=decodebytes(keyblob_dss)) hostdict["secure.example.com"] = {"ssh-rsa": key, "ssh-dss": key_dss} hostdict["fake.example.com"] = {} hostdict["fake.example.com"]["ssh-rsa"] = key self.assertEqual(3, len(hostdict)) self.assertEqual(2, len(list(hostdict.values())[0])) self.assertEqual(1, len(list(hostdict.values())[1])) self.assertEqual(1, len(list(hostdict.values())[2])) fp = hexlify(hostdict["secure.example.com"] ["ssh-rsa"].get_fingerprint()).upper() self.assertEqual(b"7EC91BB336CB6D810B124B1353C32396", fp) fp = hexlify(hostdict["secure.example.com"] ["ssh-dss"].get_fingerprint()).upper() self.assertEqual(b"4478F0B9A23CC5182009FF755BC1D26C", fp)
def __init__(self, client, connection_id, publisher, keyfile): self.transport = paramiko.Transport(client) key = None with open(keyfile) as f: header = f.readline() if header == "-----BEGIN DSA PRIVATE KEY-----\n": key = paramiko.DSSKey(filename=keyfile) elif header == "-----BEGIN RSA PRIVATE KEY-----\n": key = paramiko.RSAKey(filename=keyfile) if key is None: raise Exception("%s doesn't appear to be an SSH keyfile" % keyfile) self.transport.add_server_key(key) self.connection_id = connection_id self.publisher = publisher self.initialized = False self.watching_id = None
def read_host_keys(): rsakey = config['host-rsa-key'] if rsakey: try: config['loaded-host-rsa-key'] = paramiko.RSAKey(filename=rsakey) except Exception as e: logger.critical('Failed to load RSA host key: ' + str(e)) dsakey = config['host-dsa-key'] if dsakey: try: config['loaded-host-dsa-key'] = paramiko.DSSKey(filename=dsakey) except Exception as e: logger.critical('Failed to load DSA host key: ' + str(e)) if not ('loaded-host-rsa-key' in config or 'loaded-host-dsa-key' in config): logger.critical('Failed to load any host key') sys.exit(1)
def main(sock, dport, logger, config, **kwargs): ssh_config = munchify({'shell': config.get('shell', {}), **config.protocols.ssh}) transport = paramiko.Transport(sock) transport.local_version = 'SSH-2.0-%s' % ssh_config.get('banner', 'OpenSSH-7.8p1') for key, value in ssh_config.key.items(): if key == 'dsa': transport.add_server_key(paramiko.DSSKey(filename=value)) elif key == 'rsa': transport.add_server_key(paramiko.RSAKey(filename=value)) elif key == 'ecdsa': transport.add_server_key(paramiko.ECDSAKey(filename=value)) elif key == 'ed25519': transport.add_server_key(paramiko.Ed25519Key(filename=value)) server = Server(dport, transport, logger, ssh_config) transport.start_server(server=server) transport.join()
def generate_fingerprint(public_key): try: parts = public_key.split(' ') ssh_alg = parts[0] pub_data = parts[1].decode('base64') if ssh_alg == 'ssh-rsa': pkey = paramiko.RSAKey(data=pub_data) elif ssh_alg == 'ssh-dss': pkey = paramiko.DSSKey(data=pub_data) elif ssh_alg == 'ecdsa-sha2-nistp256': pkey = paramiko.ECDSAKey(data=pub_data, validate_point=False) else: raise exception.InvalidKeypair( reason=_('Unknown ssh key type %s') % ssh_alg) raw_fp = binascii.hexlify(pkey.get_fingerprint()) return ':'.join(a + b for a, b in zip(raw_fp[::2], raw_fp[1::2])) except (IndexError, UnicodeDecodeError, binascii.Error, paramiko.ssh_exception.SSHException): raise exception.InvalidKeypair( reason=_('failed to generate fingerprint'))
def _sock_connect(self, real_sock, sock_addr): if self.sock_type == socket.AF_UNIX and self.sock_addr[0] == '\x00': return IPCClient._sock_connect(self, real_sock, sock_addr) real_sock.connect(sock_addr) log.info("IPC: Connecting to secure server %s", sock_addr) transport = paramiko.Transport(real_sock) ev = threading.Event() transport.start_client(ev) while not ev.isSet(): ev.wait(0.5) if not transport.is_active(): log.error("SIPC: SSH negotiation failed") raise 'SSH negotiation failed' ev = threading.Event() key_file = get_config("sipc").get("key_file") if not os.path.isfile(key_file): key_file = get_config("sshproxy").get("hostkey_file") key = paramiko.DSSKey(filename=key_file) transport.auth_publickey('sshproxy-IPC', key, ev) while not ev.isSet(): ev.wait(0.5) if not transport.is_authenticated(): log.error("SIPC: SSH authentication failed") raise 'SSH authentication failed' sock = transport.open_channel('sshproxy-IPC') self.real_sock = real_sock self.transport = transport return sock
def _start_ssh(self, sock): self.ssh = paramiko.Transport(sock) if self.publicKeyType == 'rsa': agent_public_key = paramiko.RSAKey( data=base64.decodestring(self.publicKey)) elif self.publicKeyType == 'dss': agent_public_key = paramiko.DSSKey( data=base64.decodestring(self.publicKey)) else: agent_public_key = None if not self.privateKeyFile == '': if self.privateKeyType == "rsa": user_private_key = paramiko.RSAKey.from_private_key_file( self.privateKeyFile) # elif self.privateKeyType == "dss": else: user_private_key = paramiko.DSSKey.from_private_key_file( self.privateKeyFile) try: self.ssh.connect(hostkey=agent_public_key, username=self.username, pkey=user_private_key) except paramiko.AuthenticationException: raise StdoutError("Authentication failed.") else: try: self.ssh.connect(hostkey=agent_public_key, username=self.username, password=self.password) except paramiko.AuthenticationException: raise StdoutError("Authentication failed.") self.chan = self.ssh.open_session() self.chan.invoke_subsystem("netconf")