def __init__( self, hostname, user="******", port=22, connect_timeout=60, password="", # pylint: disable=too-many-arguments key_file=None, extra_ssh_options=""): self.key_file = key_file self.port = port self.extra_ssh_options = extra_ssh_options self.connect_timeout = connect_timeout self._use_rsync = None self.known_hosts_file = tempfile.mkstemp()[1] self._ssh_up_thread = None self._ssh_is_up = threading.Event() self._ssh_up_thread_termination = threading.Event() self.ssh_config = Config( overrides={ 'load_ssh_config': False, 'UserKnownHostsFile': self.known_hosts_file, 'ServerAliveInterval': 300, 'StrictHostKeyChecking': 'no' }) self.connect_config = { 'pkey': RSAKey(filename=os.path.expanduser(self.key_file)) } super(RemoteCmdRunner, self).__init__(hostname, user, password) self.start_ssh_up_thread()
def setup_test_server( self, client_options=None, server_options=None, connect_kwargs=None, ): host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) if client_options is not None: client_options(self.tc.get_security_options()) if server_options is not None: server_options(self.ts.get_security_options()) event = threading.Event() self.server = NullServer() self.assertTrue(not event.is_set()) self.ts.start_server(event, self.server) if connect_kwargs is None: connect_kwargs = dict( hostkey=public_host_key, username='******', password='******', ) self.tc.connect(**connect_kwargs) event.wait(1.0) self.assertTrue(event.is_set()) self.assertTrue(self.ts.is_active())
def test_simple(self): """ verify that we can establish an ssh link with ourselves across the loopback sockets. this is hardly "simple" but it's simpler than the later tests. :) """ host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() self.assertTrue(not event.is_set()) self.assertEqual(None, self.tc.get_username()) self.assertEqual(None, self.ts.get_username()) self.assertEqual(False, self.tc.is_authenticated()) self.assertEqual(False, self.ts.is_authenticated()) self.ts.start_server(event, server) self.tc.connect(hostkey=public_host_key, username='******', password='******') event.wait(1.0) self.assertTrue(event.is_set()) self.assertTrue(self.ts.is_active()) self.assertEqual('slowdive', self.tc.get_username()) self.assertEqual('slowdive', self.ts.get_username()) self.assertEqual(True, self.tc.is_authenticated()) self.assertEqual(True, self.ts.is_authenticated())
def test_salt_size(self): # Read an existing encrypted private key file_ = test_path('test_rsa_password.key') password = '******' newfile = file_ + '.new' newpassword = '******' key = RSAKey(filename=file_, password=password) # Write out a newly re-encrypted copy with a new password. # When the bug under test exists, this will ValueError. try: key.write_private_key_file(newfile, password=newpassword) # Verify the inner key data still matches (when no ValueError) key2 = RSAKey(filename=newfile, password=newpassword) self.assertEqual(key, key2) finally: os.remove(newfile)
def generate_key_pair( cls, filename: str, bits: int = 2048, passphrase: str = None, comment: str = None, ): """Generate RSA key pair. :param filename: name of private key file :param bits: length of RSA key :param passphrase: passphrase of the RSA key :param comment: comment for RSA key """ priv = RSAKey.generate(bits=bits) priv.write_private_key_file(filename, password=passphrase) pub = RSAKey(filename=filename, password=passphrase) logger.info(f"generated RSA key pair: {filename}") with open(f"{filename}.pub", "w") as f: f.write(f"{pub.get_name()} {pub.get_base64()}") if comment: f.write(f" {comment}") hash = u(hexlify(pub.get_fingerprint())) fingerprint = ":".join([hash[i:2 + i] for i in range(0, len(hash), 2)]) logger.info(f"fingerprint: {bits} {fingerprint} {filename}.pub (RSA)") return fingerprint
def test_4_special(self): """ verify that the client can demand odd handshake settings, and can renegotiate keys in mid-stream. """ host_key = RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = RSAKey(data=str(host_key)) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() self.assert_(not event.isSet()) self.ts.start_server(event, server) options = self.tc.get_security_options() options.ciphers = ('aes256-cbc', ) options.digests = ('hmac-md5-96', ) self.tc.connect(hostkey=public_host_key, username='******', password='******') event.wait(1.0) self.assert_(event.isSet()) self.assert_(self.ts.is_active()) self.assertEquals('aes256-cbc', self.tc.local_cipher) self.assertEquals('aes256-cbc', self.tc.remote_cipher) self.assertEquals(12, self.tc.packetizer.get_mac_size_out()) self.assertEquals(12, self.tc.packetizer.get_mac_size_in()) self.tc.send_ignore(1024) self.tc.renegotiate_keys() self.ts.send_ignore(1024)
def _add_keys_to_known_hosts(server_keys, host_keys_file): try: if not os.path.isfile(host_keys_file): host_keys = HostKeys() else: host_keys = HostKeys(filename=host_keys_file) for hostname, key_list in server_keys.items(): try: for key_tuple in key_list: key = RSAKey(data=base64.b64decode(key_tuple[0])) host_keys.add(hostname=hostname, key=key, keytype=key_tuple[1]) host_keys.add(hostname=hostname + ".*", key=key, keytype=key_tuple[1]) host_keys.add(hostname=socket.gethostbyname(hostname), key=key, keytype=key_tuple[1]) logging.info( "Adding keys to known hosts file '{0}' for host '{1}'". format(host_keys_file, hostname)) host_keys.save(filename=host_keys_file) except Exception as e: logging.error( "Failed adding keys to known hosts file for host '{0}', with exception: {1}" .format(hostname, e)) except Exception as e: logging.error( "Failed adding keys to known hosts file '{0}', with exception: {1}" .format(host_keys_file, e))
def test_L_handshake_timeout(self): """ verify that we can get a hanshake timeout. """ # Tweak client Transport instance's Packetizer instance so # its read_message() sleeps a bit. This helps prevent race conditions # where the client Transport's timeout timer thread doesn't even have # time to get scheduled before the main client thread finishes # handshaking with the server. # (Doing this on the server's transport *sounds* more 'correct' but # actually doesn't work nearly as well for whatever reason.) class SlowPacketizer(Packetizer): def read_message(self): time.sleep(1) return super(SlowPacketizer, self).read_message() # NOTE: prettttty sure since the replaced .packetizer Packetizer is now # no longer doing anything with its copy of the socket...everything'll # be fine. Even tho it's a bit squicky. self.tc.packetizer = SlowPacketizer(self.tc.sock) # Continue with regular test red tape. host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() self.assertTrue(not event.is_set()) self.tc.handshake_timeout = 0.000000000001 self.ts.start_server(event, server) self.assertRaises(EOFError, self.tc.connect, username='******', password='******')
def test_create_paramiko_ssh_client_with_valid_ssh_certificate(mocker): """" Given: - valid SSH certificate. When: - trying to connect to an SSH client. Then: - Ensure that creating SSH connection was successful. """ from RemoteAccessv2 import create_paramiko_ssh_client ssh_connect_mock = mocker.patch('paramiko.SSHClient.connect') valid_private_key = '1234\n1234' mocker.patch('paramiko.RSAKey.from_private_key', return_value=RSAKey(key=valid_private_key)) create_paramiko_ssh_client('host', 'user', None, set(), set(), private_key=valid_private_key) assert type(ssh_connect_mock.call_args.kwargs.get('pkey')) == RSAKey assert not ssh_connect_mock.call_args.kwargs.get('password')
def test_H_compression(self): """ verify that zlib compression is basically working. """ host_key = RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = RSAKey(data=str(host_key)) self.ts.add_server_key(host_key) self.ts.get_security_options().compression = ('zlib', ) self.tc.get_security_options().compression = ('zlib', ) event = threading.Event() server = NullServer() self.ts.start_server(event, server) self.tc.connect(hostkey=public_host_key, username='******', password='******') event.wait(1.0) self.assert_(event.isSet()) self.assert_(self.ts.is_active()) chan = self.tc.open_session() chan.exec_command('yes') schan = self.ts.accept(1.0) bytes = self.tc.packetizer._Packetizer__sent_bytes chan.send('x' * 1024) bytes2 = self.tc.packetizer._Packetizer__sent_bytes # tests show this is actually compressed to *52 bytes*! including packet overhead! nice!! :) self.assert_(bytes2 - bytes < 1024) self.assertEquals(52, bytes2 - bytes) chan.close() schan.close()
def test_9_interactive_auth(self): """ verify keyboard-interactive auth works. """ host_key = RSAKey.from_private_key_file('tests/test_rsa.key') public_host_key = RSAKey(data=str(host_key)) self.ts.add_server_key(host_key) event = threading.Event() server = NullServer() self.assert_(not event.isSet()) self.ts.start_server(event, server) self.tc.ultra_debug = True self.tc.connect(hostkey=public_host_key) def handler(title, instructions, prompts): self.got_title = title self.got_instructions = instructions self.got_prompts = prompts return ['cat'] remain = self.tc.auth_interactive('commie', handler) self.assertEquals(self.got_title, 'password') self.assertEquals(self.got_prompts, [('Password', False)]) self.assertEquals([], remain) event.wait(1.0) self.assert_(event.isSet()) self.assert_(self.ts.is_active())
def generate_ssh_key(key_name: str) -> str: """ Creates an SSH key pair for use as a read / write deployment key :param key_name: Name of the Repository to use :return: public key contents as a string """ user_dir = __get_ssh_key_dir() private_key_path = os.path.join(user_dir, key_name) pub_key_path = os.path.join(user_dir, key_name + '.pub') # check if this already exists if os.path.exists(pub_key_path): with open(pub_key_path, 'r') as pkp: pub_key = pkp.read() return pub_key private_key = RSAKey.generate(bits=2048) private_key.write_private_key_file(private_key_path, password=None) pub = RSAKey(filename=private_key_path, password=None) public_key_contents = f'{pub.get_name()} {pub.get_base64()} PAN_CNC' with open(pub_key_path, 'w') as pkp: pkp.write(public_key_contents) return public_key_contents
def key(self): """ :return: a subclass of PKey of the appropriate key type """ # Check if the key pair exists: at least a public or private part of # the key is required, as well as the key type. if not self.key_type: return None if not self.public_key and not self.private_key: return None public_key = None private_key = None if self.public_key: public_key = base64.b64decode(self.public_key) if self.private_key: private_key = StringIO(self.private_key) if self.key_type == 'ssh-dss': pkey = DSSKey(data=public_key, file_obj=private_key) elif self.key_type == 'ssh-rsa': pkey = RSAKey(data=public_key, file_obj=private_key) elif self.key_type.startswith('ecdsa'): pkey = ECDSAKey(data=public_key, file_obj=private_key) elif self.key_type == '*****@*****.**': pkey = RSACert(data=public_key, privkey_file_obj=private_key) else: raise ValidationError('Unsupported key type: ' + self.key_type) return pkey
def start_server(self): host_key = RSAKey.from_private_key_file(_support('test_rsa.key')) self.public_host_key = RSAKey(data=host_key.asbytes()) self.ts.add_server_key(host_key) self.event = threading.Event() self.server = NullServer() self.assertTrue(not self.event.is_set()) self.ts.start_server(self.event, self.server)
def compute_fingerprint(self): data = base64.b64decode(self.key) if self.key_type == "ssh-rsa": pkey = RSAKey(data=data) elif self.key_type == "ssh-dss": pkey = DSSKey(data=data) return ":".join(re.findall(r"..", hexlify(pkey.get_fingerprint())))
def getRsaKeyFile(filename, password=None): try: key = RSAKey(filename=filename, password=password) except IOError: print 'Generating new server RSA key.' key = RSAKey.generate(1024) key.write_private_key_file(filename, password=password) return key
def getRsaKeyFile(filename, password=None): try: key = RSAKey(filename=filename, password=password) except IOError: log.info('Generating new server RSA key and saving in file %r.' % filename) key = RSAKey.generate(1024) key.write_private_key_file(filename, password=password) return key
def test_6_compare_rsa(self): # verify that the private & public keys compare equal key = RSAKey.from_private_key_file(_support("test_rsa.key")) self.assertEqual(key, key) pub = RSAKey(data=key.asbytes()) self.assertTrue(key.can_sign()) self.assertTrue(not pub.can_sign()) self.assertEqual(key, pub)
def test_6_compare_rsa(self): # verify that the private & public keys compare equal key = RSAKey.from_private_key_file('tests/test_rsa.key') self.assertEquals(key, key) pub = RSAKey(data=str(key)) self.assert_(key.can_sign()) self.assert_(not pub.can_sign()) self.assertEquals(key, pub)
def start_server(self): host_key = RSAKey.from_private_key_file('tests/test_rsa.key') self.public_host_key = RSAKey(data=str(host_key)) self.ts.add_server_key(host_key) self.event = threading.Event() self.server = NullServer() self.assert_(not self.event.isSet()) self.ts.start_server(self.event, self.server)
def get_rsa_key_file(filename, password=None): try: key = RSAKey(filename=filename, password=password) except IOError: logger.info('RSA Key file not found, generating a new one: {}'.format(filename)) key = RSAKey.generate(1024) key.write_private_key_file(filename, password=password) return key
def _create_connection(self) -> Connection: return Connection( host=self.hostname, user=self.user, port=self.port, config=self.ssh_config, connect_timeout=self.connect_timeout, connect_kwargs={ 'pkey': RSAKey(filename=os.path.expanduser(self.key_file))} if self.key_file else None)
def __init__(self, options): logging.getLogger("telnetsrv.paramiko_ssh ").setLevel(logging.WARNING) logging.getLogger("paramiko").setLevel(logging.WARNING) # generate key rsa_key = RSA.generate(1024) priv_key_text = rsa_key.exportKey('PEM', pkcs=1) self.key = RSAKey(file_obj=StringIO.StringIO(priv_key_text)) super(SSH, self).__init__(options)
def get_rsakey_from_string(private_key_string, passphrase=None): ssh_logger.info("Load private key:\n" + private_key_string) rsa = RSA.importKey(private_key_string, passphrase=passphrase) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q key.u = rsa.u key.keydata = ['n', 'e', 'd', 'p', 'q', 'u'] return key
def gen_rsa_key(filename): private_key_obj = RSAKey.generate(bits=1024) private_key = private_key_obj.key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()).decode() private_key_obj.write_private_key_file('aft_container_host_key') public_key_obj = RSAKey(filename='aft_container_host_key') return private_key, public_key_obj
def create_client(self): private = RSAKey(filename=self.get_private_key_file()) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.load_host_keys(self.get_host_keys_file()) client.connect(self.server.host, pkey=private, look_for_keys=False, port=self.server.port, username=self.server.user) return client
def generate_key(): if not os.path.exists(keyfile): keydir = os.path.dirname(keyfile) if not os.path.exists(keydir): os.mkdir(keydir) prv = RSAKey.generate(bits=1024) prv.write_private_key_file(keyfile) pub = RSAKey(filename=keyfile) with open("%s.pub" % keyfile, 'w') as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) print("Made new Wharf SSH key")
def ConnectionHandle(client, priv): try: t = Transport(client) ip, port = client.getpeername() t.local_version = 'SSH-2.0-' + choice(self.random_servers) t.add_server_key(RSAKey(file_obj=StringIO(priv))) t.start_server(server=SSHHandle(ip, port)) chan = t.accept(1) if not chan is None: chan.close() except: pass
def test_8_sign_rsa(self): # verify that the rsa private key can sign and verify key = RSAKey.from_private_key_file(test_path('test_rsa.key')) msg = key.sign_ssh_data(b'ice weasels') self.assertTrue(type(msg) is Message) msg.rewind() self.assertEqual('ssh-rsa', msg.get_text()) sig = bytes().join([byte_chr(int(x, 16)) for x in SIGNED_RSA.split(':')]) self.assertEqual(sig, msg.get_binary()) msg.rewind() pub = RSAKey(data=key.asbytes()) self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg))
def test_sign_rsa(self): # verify that the rsa private key can sign and verify key = RSAKey.from_private_key_file(_support('test_rsa.key')) msg = key.sign_ssh_data(b'ice weasels') self.assertTrue(type(msg) is Message) msg.rewind() self.assertEqual(msg.get_text(), 'ssh-rsa') self.assertEqual(msg.get_binary(), unhexlify(SIGNED_RSA.replace(':', ''))) msg.rewind() pub = RSAKey(data=key.asbytes()) self.assertTrue(pub.verify_ssh_sig(b'ice weasels', msg))