def test_key(self): """Check key import and export""" for keytype in self.keytypes: with self.subTest(keytype=keytype): self.make_keypair('priv', 'pub', keytype) self.make_keypair('privca', 'pubca', keytype) run('chmod 600 priv privca') if self.base_format == 'openssh': run('cp -p pub sshpub') else: run('ssh-keygen -i -f pub -m %s > sshpub' % self.base_format) self.privkey = read_private_key('priv') self.pubkey = read_public_key('pub') self.privca = read_private_key('privca') self.pubca = read_public_key('pubca') self.check_encode_errors() self.check_decode_errors() self.check_sshkey_base_errors() self.check_sign_and_verify() if 'pkcs1' in self.private_formats: self.check_pkcs1_private() if 'pkcs1' in self.public_formats: self.check_pkcs1_public() if 'pkcs8' in self.private_formats: self.check_pkcs8_private() if 'pkcs8' in self.public_formats: self.check_pkcs8_public() if 'openssh' in self.private_formats: # pragma: no branch self.check_openssh_private() if 'openssh' in self.public_formats: # pragma: no branch self.check_openssh_public() if 'rfc4716' in self.public_formats: # pragma: no branch self.check_rfc4716_public() for cert_type in (CERT_TYPE_USER, CERT_TYPE_HOST): for version in self.cert_versions: for fmt in ('openssh', 'rfc4716'): with self.subTest(cert_type=cert_type, version=version, fmt=fmt): self.check_certificate(cert_type, version, fmt) self.check_certificate_errors(cert_type)
def test_key(self): """Check key import and export""" for keytype in self.keytypes: with self.subTest(keytype=keytype): self.make_keypair('priv', 'pub', keytype) self.make_keypair('privca', 'pubca', keytype) run('chmod 600 priv privca') if self.base_format == 'openssh': run('cp -p pub sshpub') else: run('ssh-keygen -i -f pub -m %s > sshpub' % self.base_format) self.privkey = read_private_key('priv') self.pubkey = read_public_key('pub') self.privca = read_private_key('privca') self.pubca = read_public_key('pubca') self.check_encode_errors() self.check_decode_errors() self.check_sshkey_base_errors() self.check_sign_and_verify() if 'pkcs1' in self.private_formats: self.check_pkcs1_private() if 'pkcs1' in self.public_formats and _pkcs1_public_supported: self.check_pkcs1_public() if 'pkcs8' in self.private_formats: self.check_pkcs8_private() if 'pkcs8' in self.public_formats: self.check_pkcs8_public() if 'openssh' in self.private_formats: # pragma: no branch self.check_openssh_private() if 'openssh' in self.public_formats: # pragma: no branch self.check_openssh_public() if 'rfc4716' in self.public_formats: # pragma: no branch self.check_rfc4716_public() for cert_type in (CERT_TYPE_USER, CERT_TYPE_HOST): for fmt in ('openssh', 'rfc4716'): with self.subTest(cert_type=cert_type, fmt=fmt): self.check_certificate(cert_type, fmt) self.check_certificate_errors(cert_type)
def test_disallowed_address(self): """Test disallowed address in certificate""" ckey = asyncssh.read_private_key('ckey') skey = asyncssh.read_private_key('skey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, skey, ckey, ['ckey'], options={'source-address': String('0.0.0.0')}) with self.assertRaises(asyncssh.DisconnectError): yield from self.connect(username='******', client_keys=[(skey, cert)])
def test_ec_explicit(self): """Test EC certificate with explcit parameters""" with self.subTest('Import EC key with explicit parameters'): run('openssl ecparam -out priv -noout -genkey -name secp256r1 ' '-param_enc explicit') read_private_key('priv') with self.subTest('Import EC key with unknown explicit parameters'): run('openssl ecparam -out priv -noout -genkey -name secp112r1 ' '-param_enc explicit') with self.assertRaises(KeyImportError): read_private_key('priv')
def test_expired_cert(self): """Test expired certificate""" ckey = asyncssh.read_private_key('ckey') skey = asyncssh.read_private_key('skey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, skey, ckey, ['ckey'], valid_before=1) with self.assertRaises(asyncssh.DisconnectError): yield from self.connect(username='******', client_keys=[(skey, cert)])
def check_private(self, passphrase=None): """Check for a private key match""" newkey = read_private_key('new', passphrase) self.assertEqual(newkey, self.privkey) self.assertEqual(hash(newkey), hash(self.privkey)) if passphrase: with self.assertRaises((KeyEncryptionError, KeyImportError)): read_private_key('new', 'xxx') else: run('cat new new > list') keylist = read_private_key_list('list', passphrase) self.assertEqual(keylist[0], newkey) self.assertEqual(keylist[1], newkey)
def test_ec_explicit(self): """Test EC certificate with explcit parameters""" for curve in ('secp256r1', 'secp384r1', 'secp521r1'): with self.subTest('Import EC key with explicit parameters', curve=curve): run('openssl ecparam -out priv -noout -genkey -name %s ' '-param_enc explicit' % curve) read_private_key('priv') with self.subTest('Import EC key with unknown explicit parameters'): run('openssl ecparam -out priv -noout -genkey -name secp112r1 ' '-param_enc explicit') with self.assertRaises(KeyImportError): read_private_key('priv')
def test_allowed_address(self): """Test allowed address in certificate""" ckey = asyncssh.read_private_key('ckey') skey = asyncssh.read_private_key('skey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, skey, ckey, ['ckey'], options={'source-address': String('0.0.0.0/0,::/0')}) with (yield from self.connect(username='******', client_keys=[(skey, cert)])) as conn: pass yield from conn.wait_closed()
async def remote_random_port(self): """Select unoccupied port on the remote host and return it. If this fails for some reason return `None`.""" username = self.get_remote_user(self.user.name) kf = self.ssh_keyfile.format(username=username) cf = kf + "-cert.pub" k = asyncssh.read_private_key(kf) c = asyncssh.read_certificate(cf) # this needs to be done against remote_host, first time we're calling up async with asyncssh.connect(self.remote_host, username=username, client_keys=[(k, c)], known_hosts=None) as conn: result = await conn.run(self.remote_port_command) stdout = result.stdout stderr = result.stderr retcode = result.exit_status if stdout != b"": ip, port = stdout.split() port = int(port) self.log.debug("ip={} port={}".format(ip, port)) else: ip, port = None, None self.log.error("Failed to get a remote port") self.log.error("STDERR={}".format(stderr)) self.log.debug("EXITSTATUS={}".format(retcode)) return (ip, port)
async def setup(spawner): username = spawner.user.name remote_host = "corijupyter.nersc.gov" keyfile = "/certs/{username}.key".format( username=username) # NEED to have in NERSCSpawner now certfile = keyfile + "-cert.pub" k = asyncssh.read_private_key(keyfile) c = asyncssh.read_certificate(certfile) try: async with asyncssh.connect(remote_host, username=username, client_keys=[(k, c)], known_hosts=None) as conn: result = await conn.run("myquota -c $HOME") retcode = result.exit_status except: spawner.log.warning( f"Problem connecting to {remote_host} to check quota oh well") retcode = 0 if retcode: from jinja2 import Markup e = web.HTTPError(507, reason="Insufficient Storage") e.jupyterhub_message = Markup( "<br>Your home directory is over quota! " + "Try moving or archiving and deleting some files from there, " + "then come back and try again.<br>") raise e
async def start_server(cls): """Start an SSH server which supports security key authentication""" cls.addClassCleanup(unstub_pkcs11, *stub_pkcs11(cls._pkcs11_tokens)) pubkeys = get_pkcs11_public_keys() certs = get_pkcs11_certs() cls._certs_available = bool(certs) for cert in certs: cert.append_certificate('auth_keys') for key in pubkeys: key.append_public_key('auth_keys') if pubkeys: ca_key = asyncssh.read_private_key('ckey') cert = ca_key.generate_user_certificate(pubkeys[0], 'name', principals=['ckey']) with open('auth_keys', 'a') as auth_keys: auth_keys.write('cert-authority ') ca_key.append_public_key('auth_keys') cert.write_certificate('pkcs11_cert.pub') auth_keys = 'auth_keys' if cls._pkcs11_tokens else () return await cls.create_server(authorized_client_keys=auth_keys, x509_trusted_certs=certs)
async def run_server(loop: asyncio.AbstractEventLoop, logger: logging.Logger, port=22): config_dir = "config" host_key: Optional[SSHKey] = None if not os.path.isdir(config_dir): os.mkdir(config_dir) host_key_file = os.path.join(config_dir, "host_key") if os.path.isfile(host_key_file): logger.info("Loading host key (%s)...", host_key_file) host_key = asyncssh.read_private_key(host_key_file) else: logger.info("Generating host key (%s)...", host_key_file) host_key = asyncssh.generate_private_key("ssh-rsa", key_size=1024) host_key.write_private_key(host_key_file) host_key.write_public_key("%s.pub" % host_key_file) assert host_key def server_factory(): return HoneypotServer(logger) logger.info("Running Honeypot on port %s", port) process_factory = functools.partial(handle_client, logger) server: asyncio.AbstractServer = await asyncssh.create_server(server_factory, port=port, server_host_keys=[host_key], process_factory=process_factory) async with server: await server.wait_closed()
def test_key(self): tmpdir = tempfile.TemporaryDirectory() os.chdir(tmpdir.name) for keytype in self.keytypes: with self.subTest(keytype=keytype): self.make_keypair(keytype) run('chmod 600 priv pub') self.key = read_private_key('priv') self.sshpub = self.key.encode_ssh_public() if 'pkcs1' in self.formats: self.check_pkcs1() if 'pkcs8' in self.formats: self.check_pkcs8() if 'openssh' in self.formats: self.check_openssh() if 'rfc4716' in self.formats: self.check_rfc4716() tmpdir.cleanup()
def get_keys(self): if not self.keys: try: self.keys = [asyncssh.read_private_key(os.path.expanduser(f)) for f in self.key_files if os.path.exists(os.path.expanduser(f))] except BaseException: return () return self.keys
def load_private_key(f, pwd): try: k = asyncssh.read_private_key(f, pwd) if k and pwd: log.debug(f"Decrypted with {pwd} - {f}") return k except Exception as ex: log.debug(f"{str(ex)} - {f}") return None
def test_client_key_sshkey(self): """Test client key passed in as an SSHKey""" ckey = asyncssh.read_private_key('ckey') with (yield from self.connect(username='******', client_keys=[ckey])) as conn: pass yield from conn.wait_closed()
def get_private_key(): key_filename = relative(config.PRIVATE_KEY) if not exists(key_filename): private_key = asyncssh.generate_private_key('ssh-rsa') private_key.write_private_key(key_filename) else: private_key = asyncssh.read_private_key(key_filename) return private_key
def test_forwarding_not_allowed(self): """Test an X11 request from a non-authorized user""" ckey = asyncssh.read_private_key("ckey") cert = ckey.generate_user_certificate(ckey, "name", principals=["ckey"], permit_x11_forwarding=False) with (yield from self.connect(username="******", client_keys=[(ckey, cert)])) as conn: with self.assertRaises(asyncssh.ChannelOpenError): yield from _create_x11_process(conn, "connect l") yield from conn.wait_closed()
def test_untrusted_ca(self): """Test untrusted CA""" skey = asyncssh.read_private_key('skey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, skey, skey, ['skey']) with self.assertRaises(ValueError): yield from self.connect(username='******', client_keys=[('ckey', cert)])
async def get_connection(self): if self.conn is None: config = self.config key = asyncssh.read_private_key(config['identityfile']) self.conn = await asyncssh.connect( config['hostname'], username=config['user'], port=int(config['port']), known_hosts=None, client_keys=(key,)) return self.conn
async def test_unix_connection_not_permitted(self): """Test permission denied in opening a remote UNIX connection""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-port-forwarding': ''}) async with self.connect(username='******', client_keys=[(ckey, cert)]) as conn: with self.assertRaises(asyncssh.ChannelOpenError): await conn.open_unix_connection('/echo')
async def test_forward_remote_path_not_permitted(self): """Test permission denied in forwarding a remote UNIX domain path""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-port-forwarding': ''}) async with self.connect(username='******', client_keys=[(ckey, cert)], agent_path=None) as conn: with self.assertRaises(asyncssh.ChannelListenError): await conn.forward_remote_path('', 'local')
async def test_forced_exec(self): """Test execution of a forced remote command""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], options={'force-command': String('echo')}) async with self.connect(username='******', client_keys=[(ckey, cert)]) as conn: await self._check_session(conn)
async def test_forwarding_not_allowed(self): """Test an X11 request from a non-authorized user""" ckey = asyncssh.read_private_key('ckey') cert = ckey.generate_user_certificate(ckey, 'name', principals=['ckey'], permit_x11_forwarding=False) async with self.connect(username='******', client_keys=[(ckey, cert)]) as conn: with self.assertRaises(asyncssh.ChannelOpenError): await _create_x11_process(conn, 'connect l')
def test_cert_principals(self): """Test certificate principals check""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey']) with (yield from self.connect(username='******', client_keys=[(ckey, cert)])) as conn: pass yield from conn.wait_closed()
def test_forced_exec(self): """Test execution of a forced remote command""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], options={'force-command': String('echo')}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)])) as conn: yield from self._check_session(conn) yield from conn.wait_closed()
def test_unix_connection_not_permitted(self): """Test permission denied in opening a remote UNIX connection""" ckey = asyncssh.read_private_key("ckey") cert = make_certificate( "*****@*****.**", CERT_TYPE_USER, ckey, ckey, ["ckey"], extensions={"no-port-forwarding": ""} ) with (yield from self.connect(username="******", client_keys=[(ckey, cert)])) as conn: with self.assertRaises(asyncssh.ChannelOpenError): yield from conn.open_unix_connection("/echo") yield from conn.wait_closed()
async def start_ssh_remote_forward_session(self): env = super(CloudSSHSpawner, self).get_env() env["JUPYTERHUB_API_URL"] = self.hub_api_url env["JUPYTERHUB_ACTIVITY_URL"] = self.hub_activity_url env["JUPYTERHUB_HOST"] = self.hub_public_host env["PATH"] = self.path kf = self.ssh_keyfile.format(username=self.user.name) cf = kf + "-cert.pub" k = asyncssh.read_private_key(kf) c = asyncssh.read_certificate(cf) # ssh -v -fNT -R 8081:multiplespawner.workers.vcn.oraclevcn.com:8081 -R 8000:127.0.0.1:8000 [email protected] -i ~/.corc/ssh/ras6_id_rsa self.log.debug("ssh remote forward target: {}".format( self.hub_public_host)) # -R remote_port,local_host:local_port -R remote_port,local_host:local_port remote_user@remoteip -i path_to_rsa_key ssh_backtunnel_command = "ssh -fNT -R {}:{}:{} -R {}:{}:{} {}@{} -i {}".format( self.hub_api_port, self.hub_api_interface, self.hub_api_port, self.hub.port, self.hub.ip, self.hub.port, self.user.name, self.remote_host, self.ssh_forward_credentials_paths["private_key_file"], ) username = self.get_remote_user(self.user.name) bash_script_str = "#!/bin/bash\n" bash_script_str += ( "%s < /dev/null >> .{}_ssh_remote_forward.log 2>&1 & pid=$!\n". format(self.user.name) % ssh_backtunnel_command) run_script = "/tmp/{}_ssh_remote_forward_run.sh".format(self.user.name) with open(run_script, "w") as f: f.write(bash_script_str) if not os.path.isfile(run_script): raise Exception("The file " + run_script + "was not created.") else: with open(run_script, "r") as f: self.log.debug(run_script + " was written as:\n" + f.read()) # Set the executable permission if not chmod(run_script, 0o755): raise Exception( "Failed to set executable permissions on: {}".format( run_script)) launched = await self.launch_detach_process(run_script) if not launched: raise Exception("Failed to execute: {}".format(run_script)) return True
async def test_pty_disallowed_by_cert(self): """Test rejection of pty request by certificate""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-pty': ''}) async with self.connect(username='******', client_keys=[(ckey, cert)]) as conn: with self.assertRaises(asyncssh.ChannelOpenError): await _create_session(conn, 'term', term_type='ansi')
def test_pty_disallowed_by_cert(self): """Test rejection of pty request by certificate""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-pty': ''}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)])) as conn: with self.assertRaises(asyncssh.ChannelOpenError): yield from _create_session(conn, 'term', term_type='ansi') yield from conn.wait_closed()
async def test_forward_remote_port_not_permitted(self): """Test permission denied in forwarding of a remote port""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-port-forwarding': ''}) async with self.connect(username='******', client_keys=[(ckey, cert)]) as conn: listener = await conn.forward_remote_port('', 0, '', 0) self.assertIsNone(listener)
def test_connection_not_permitted(self): """Test permission denied in opening a remote connection""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-port-forwarding': ''}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)])) as conn: with self.assertRaises(asyncssh.ChannelOpenError): yield from conn.open_connection('', 7) yield from conn.wait_closed()
def test_forward_remote_path_not_permitted(self): """Test permission denied in forwarding a remote UNIX domain path""" ckey = asyncssh.read_private_key("ckey") cert = make_certificate( "*****@*****.**", CERT_TYPE_USER, ckey, ckey, ["ckey"], extensions={"no-port-forwarding": ""} ) with (yield from self.connect(username="******", client_keys=[(ckey, cert)])) as conn: listener = yield from conn.forward_remote_path("", "local") self.assertIsNone(listener) yield from conn.wait_closed()
async def exec_notebook(self, command): """TBD""" env = super(CloudSSHSpawner, self).get_env() env["JUPYTERHUB_API_URL"] = self.hub_api_url env["JUPYTERHUB_ACTIVITY_URL"] = self.hub_activity_url env["PATH"] = self.path username = self.get_remote_user(self.user.name) kf = self.ssh_keyfile.format(username=username) cf = kf + "-cert.pub" k = asyncssh.read_private_key(kf) c = asyncssh.read_certificate(cf) bash_script_str = "#!/bin/bash\n" for item in env.items(): # item is a (key, value) tuple # command = ('export %s=%s;' % item) + command bash_script_str += "export %s=%s\n" % item bash_script_str += "unset XDG_RUNTIME_DIR\n" bash_script_str += "touch .jupyter.log\n" bash_script_str += "chmod 600 .jupyter.log\n" bash_script_str += "%s < /dev/null >> .jupyter.log 2>&1 & pid=$!\n" % command bash_script_str += "echo $pid\n" run_script = "/tmp/{}_run.sh".format(self.user.name) with open(run_script, "w") as f: f.write(bash_script_str) if not os.path.isfile(run_script): raise Exception("The file " + run_script + "was not created.") else: with open(run_script, "r") as f: self.log.debug(run_script + " was written as:\n" + f.read()) async with asyncssh.connect(self.remote_host, username=username, client_keys=[(k, c)], known_hosts=None) as conn: result = await conn.run("bash -s", stdin=run_script) stdout = result.stdout _ = result.stderr retcode = result.exit_status self.log.debug("exec_notebook status={}".format(retcode)) if stdout != b"": pid = int(stdout) else: return -1 return pid
def test_forward_remote_path_not_permitted(self): """Test permission denied in forwarding a remote UNIX domain path""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-port-forwarding': ''}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)])) as conn: listener = yield from conn.forward_remote_path('', 'local') self.assertIsNone(listener) yield from conn.wait_closed()
async def start(self): ssh_endpoint = self.get_config('app.contact.tunnel.ssh.socket') addr, port = ssh_endpoint.split(':') host_key_filename = self.get_config('app.contact.tunnel.ssh.host_key_file') host_key_filepath = os.path.join('conf', 'ssh_keys', host_key_filename) host_key_passphrase = self.get_config('app.contact.tunnel.ssh.host_key_passphrase') try: host_key = asyncssh.read_private_key(host_key_filepath, passphrase=host_key_passphrase) except Exception as e: self.log.warning('Generating temporary SSH private key. Was unable to use provided SSH private key: %s' % e) host_key = asyncssh.generate_private_key('ssh-rsa', comment='temporary key') try: await asyncssh.create_server(self.server_factory, addr, int(port), server_host_keys=[host_key]) except Exception as e: self.log.error('Error starting SSH server: %s' % e)
def load_all_keys(): key_files = glob.glob( os.path.join(os.path.dirname(__file__), '..') + "/keys/*") user_key_files = [ os.path.expanduser(file_) for file_ in [ '~/.ssh/id_ed25519', '~/.ssh/id_ecdsa', '~/.ssh/id_rsa', '~/.ssh/id_dsa' ] ] keys = [] for file_ in key_files + user_key_files: try: keys.append(asyncssh.read_private_key(file_)) except Exception: pass return keys
def test_pty_disallowed(self): """Test rejection of pty request""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-pty': ''}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)], agent_forwarding=True)) as conn: with self.assertRaises(asyncssh.ChannelOpenError): yield from _create_session(conn, 'term', term_type='ansi') yield from conn.wait_closed()
async def exec_notebook(self, command): """TBD""" env = self.user_env() username = self.get_remote_user(self.user.name) kf = self.ssh_keyfile.format(username=username) cf = kf + "-cert.pub" k = asyncssh.read_private_key(kf) c = asyncssh.read_certificate(cf) bash_script_str = "#!/bin/bash\n" for item in env.items(): # item is a (key, value) tuple # command = ('export %s=%s;' % item) + command bash_script_str += 'export %s=%s\n' % item bash_script_str += 'unset XDG_RUNTIME_DIR\n' bash_script_str += '%s < /dev/null >> jupyter.log 2>&1 & pid=$!\n' % command bash_script_str += 'echo $pid\n' run_script = "/tmp/{}_run.sh".format(self.user.name) with open(run_script, "w") as f: f.write(bash_script_str) if not os.path.isfile(run_script): raise Exception("The file " + run_script + "was not created.") else: with open(run_script, "r") as f: self.log.debug(run_script + " was written as:\n" + f.read()) async with asyncssh.connect(self.remote_host, username=username, client_keys=[(k, c)], known_hosts=None) as conn: result = await conn.run("bash -s", stdin=run_script) stdout = result.stdout stderr = result.stderr retcode = result.exit_status self.log.debug("exec_notebook status={}".format(retcode)) if stdout != b'': pid = int(stdout) else: return -1 return pid
async def test_agent_forwarding_failure(self): """Test failure of SSH agent forwarding""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-agent-forwarding': ''}) async with self.connect(username='******', client_keys=[(ckey, cert)], agent_forwarding=True) as conn: chan, session = await _create_session(conn, 'agent') await chan.wait_closed() self.assertEqual(session.exit_status, 1)
def test_agent_forwarding_failure(self): """Test failure of SSH agent forwarding""" ckey = asyncssh.read_private_key('ckey') cert = make_certificate('*****@*****.**', CERT_TYPE_USER, ckey, ckey, ['ckey'], extensions={'no-agent-forwarding': ''}) with (yield from self.connect(username='******', client_keys=[(ckey, cert)], agent_forwarding=True)) as conn: chan, session = yield from _create_session(conn, 'agent') yield from chan.wait_closed() self.assertEqual(session.exit_status, 1) yield from conn.wait_closed()
def test_key(self): tmpdir = tempfile.TemporaryDirectory() os.chdir(tmpdir.name) for keytype in self.keytypes: with self.subTest(keytype=keytype): self.make_private(keytype) run('openssl %s -pubout -in priv -out pub' % self.keyclass) run('chmod 600 priv pub') with self.subTest('Import PKCS#1 PEM private'): self.key = read_private_key('priv') self.sshpub = self.key.encode_ssh_public() self.assertTrue(self.sshpub) with self.subTest('Export PKCS#1 PEM private'): self.export_pkcs1_private('pem') with self.subTest('Import PKCS#1 DER private'): self.import_pkcs1_private('der') with self.subTest('Export PKCS#1 DER private'): self.export_pkcs1_private('der') for cipher in pkcs1_ciphers: with self.subTest('Import PKCS#1 PEM private (%s)' % cipher): self.import_pkcs1_private('pem', cipher) with self.subTest('Export PKCS#1 PEM private (%s)' % cipher): self.export_pkcs1_private('pem', cipher) with self.subTest('Import PKCS#8 PEM private'): self.import_pkcs8_private('pem') with self.subTest('Export PKCS#8 PEM private'): self.export_pkcs8_private('pem') with self.subTest('Import PKCS#8 DER private'): self.import_pkcs8_private('der') with self.subTest('Export PKCS#8 DER private'): self.export_pkcs8_private('der') for cipher, hash, pbe_version, args in pkcs8_ciphers: with self.subTest('Import PKCS#8 PEM private ' '(%s-%s-v%s)' % (cipher, hash, pbe_version)): self.import_pkcs8_private('pem', cipher, args) with self.subTest('Export PKCS#8 PEM private ' '(%s-%s-v%s)' % (cipher, hash, pbe_version)): self.export_pkcs8_private('pem', cipher, hash, pbe_version) with self.subTest('Import PKCS#8 DER private ' '(%s-%s-v%s)' % (cipher, hash, pbe_version)): self.import_pkcs8_private('der', cipher, args) with self.subTest('Export PKCS#8 DER private ' '(%s-%s-v%s)' % (cipher, hash, pbe_version)): self.export_pkcs8_private('der', cipher, hash, pbe_version) with self.subTest('Import PKCS#8 PEM public'): self.import_pkcs8_public('pem') with self.subTest('Export PKCS#8 PEM public'): self.export_pkcs8_public('pem') with self.subTest('Import PKCS#8 DER public'): self.import_pkcs8_public('der') with self.subTest('Export PKCS#8 DER public'): self.export_pkcs8_public('der') with self.subTest('Import OpenSSH public'): self.import_openssh_public() with self.subTest('Export OpenSSH public'): self.export_openssh_public() with self.subTest('Import RFC4716 public'): self.import_rfc4716_public() with self.subTest('Export RFC4716 public'): self.export_rfc4716_public() tmpdir.cleanup()
def check_private(self, passphrase): newkey = read_private_key('new', passphrase) self.assertEqual(newkey.encode_ssh_public(), self.sshpub)