Пример #1
0
    def setUpClass(cls):
        """Create public keys needed for test"""

        super().setUpClass()

        for keylist, imported_keylist in zip(cls.keylists[:3],
                                             cls.imported_keylists[:3]):
            for _ in range(3):
                key = asyncssh.generate_private_key('ssh-rsa')
                keylist.append(key.export_public_key().decode('ascii'))
                imported_keylist.append(key.convert_to_public())

        if x509_available: # pragma: no branch
            for keylist, imported_keylist in zip(cls.keylists[3:5],
                                                 cls.imported_keylists[3:5]):
                for _ in range(2):
                    key = asyncssh.generate_private_key('ssh-rsa')
                    cert = key.generate_x509_user_certificate(key, 'OU=user',
                                                              'OU=user')
                    keylist.append(
                        cert.export_certificate('openssh').decode('ascii'))
                    imported_keylist.append(cert)

            for keylist, imported_keylist in zip(cls.keylists[5:],
                                                 cls.imported_keylists[5:]):
                for name in ('OU=user', 'OU=revoked'):
                    keylist.append('x509v3-ssh-rsa subject=' + name + '\n')
                    imported_keylist.append(X509NamePattern(name))
Пример #2
0
    def setUpClass(cls):
        """Create public keys needed for test"""

        super().setUpClass()

        for keylist, imported_keylist in zip(cls.keylists[:3],
                                             cls.imported_keylists[:3]):
            for _ in range(3):
                key = asyncssh.generate_private_key('ssh-rsa')
                keylist.append(key.export_public_key().decode('ascii'))
                imported_keylist.append(key.convert_to_public())

        if x509_available:  # pragma: no branch
            for keylist, imported_keylist in zip(cls.keylists[3:5],
                                                 cls.imported_keylists[3:5]):
                for _ in range(2):
                    key = asyncssh.generate_private_key('ssh-rsa')
                    cert = key.generate_x509_user_certificate(
                        key, 'OU=user', 'OU=user')
                    keylist.append(
                        cert.export_certificate('openssh').decode('ascii'))
                    imported_keylist.append(cert)

            for keylist, imported_keylist in zip(cls.keylists[5:],
                                                 cls.imported_keylists[5:]):
                for name in ('OU=user', 'OU=revoked'):
                    keylist.append('x509v3-ssh-rsa subject=' + name + '\n')
                    imported_keylist.append(X509NamePattern(name))
Пример #3
0
    async def test_enroll_pin_invalid(self):
        """Test generating key while providing invalid PIN"""

        with sk_error('badpin'):
            with self.assertRaises(ValueError):
                asyncssh.generate_private_key('*****@*****.**',
                                              pin=b'123456')
Пример #4
0
def get_or_generate_server_key():
	if conf.NW_HOST_KEY:
		return conf.NW_HOST_KEY

	if not os.path.exists('server_id_ed25519'):
		asyncssh.generate_private_key('ssh-ed25519').write_private_key('server_id_ed25519')

	return open('server_id_ed25519', 'rb').read()
Пример #5
0
def generate_test_ssh_key():
    """ Generate test ssh key pairs """
    os.makedirs(SSH_KEY_PATH, exist_ok=True)
    sshkey = asyncssh.generate_private_key('ssh-rsa')
    sshkey.write_private_key(SSH_KEY)
    sshkey.write_public_key('{}.pub'.format(SSH_KEY))
    return sshkey
Пример #6
0
def ensure_key():
    file_name = ".debug_console_ssh_host_key"
    path = pathlib.Path(file_name)
    if not path.exists():
        rsa_key = asyncssh.generate_private_key("ssh-rsa")
        path.write_bytes(rsa_key.export_private_key())
    return str(path)
Пример #7
0
    def test_publickey_auth(self):
        """Unit test public key authentication"""

        ckey = asyncssh.generate_private_key('ssh-rsa')
        cert = ckey.generate_user_certificate(ckey, 'name')

        with self.subTest('Public key auth not available'):
            yield from self.check_auth(b'publickey', (False, None))

        with self.subTest('Untrusted key'):
            yield from self.check_auth(b'publickey', (False, None),
                                       client_key=ckey, public_key_auth=True)

        with self.subTest('Trusted key'):
            yield from self.check_auth(b'publickey', (True, None),
                                       client_key=ckey, public_key_auth=True,
                                       success=True)

        with self.subTest('Trusted certificate'):
            yield from self.check_auth(b'publickey', (True, None),
                                       client_key=ckey, client_cert=cert,
                                       public_key_auth=True, success=True)

        with self.subTest('Invalid PK_OK message'):
            with self.assertRaises(DisconnectError):
                yield from self.check_auth(b'publickey', (False, None),
                                           client_key=ckey,
                                           public_key_auth=True,
                                           override_pk_ok=True)
Пример #8
0
    async def start_server(cls):
        """Start an SSH server which supports security key authentication"""

        cls.addClassCleanup(unstub_sk, *stub_sk(cls._sk_devs))

        cls._privkey = asyncssh.generate_private_key(
            cls._sk_alg,
            resident=cls._sk_resident,
            touch_required=cls._sk_touch_required)

        if cls._sk_host:
            if cls._sk_cert:
                cert = cls._privkey.generate_host_certificate(
                    cls._privkey, 'localhost', principals=['127.0.0.1'])

                key = (cls._privkey, cert)
            else:
                key = cls._privkey

            return await cls.create_server(server_host_keys=[key])
        else:
            options = []

            if cls._sk_cert:
                options.append('cert-authority')

            if not cls._sk_auth_touch_required:
                options.append('no-touch-required')

            auth_keys = asyncssh.import_authorized_keys(
                ','.join(options) + (' ' if options else '') +
                cls._privkey.export_public_key().decode('utf-8'))

            return await cls.create_server(authorized_client_keys=auth_keys)
Пример #9
0
    async def test_enroll_with_pin(self):
        """Test generating key with a PIN"""

        key = asyncssh.generate_private_key('*****@*****.**',
                                            pin=b'123456')

        self.assertIsNotNone(key)
Пример #10
0
 def setup_class(cls):
     cls.username = "******"
     cls.public_key = "password"
     cls.port = get_random_port()
     id_rsa = asyncssh.generate_private_key("ssh-rsa")
     id_rsa.write_private_key("id_rsa")
     id_rsa.write_public_key("id_rsa.pub")
Пример #11
0
    async def start(self):
        """
        Asynchronously start the SSH server, and process connections.

        This server will listen on the configured host and port.
        """
        def server_factory():
            return NuttsshServer(self)

        algs = ('ecdsa-sha2-nistp256', 'ssh-ed25519', 'ssh-rsa')
        server_host_keys = []
        for i, keyfile in enumerate(config.HOST_KEY_FILE):
            try:
                with open(keyfile, 'r'):
                    server_host_keys.append(keyfile)
            except FileNotFoundError:
                logging.info(f"Generating host key: {algs[i]}")
                key = asyncssh.generate_private_key(algs[i])
                server_host_keys.append(key)
                open(keyfile, 'w').write(key.export_private_key().decode())
                open(f'{keyfile}.pub',
                     'w').write(key.export_public_key().decode())
                os.chmod(keyfile, 0o600)

        await asyncssh.listen(config.LISTEN_HOST,
                              config.LISTEN_PORT,
                              server_host_keys=server_host_keys,
                              server_factory=server_factory,
                              allow_pty=config.ALLOW_PTY)
Пример #12
0
    def test_publickey_auth(self):
        """Unit test public key authentication"""

        ckey = asyncssh.generate_private_key('ssh-rsa')
        cert = ckey.generate_user_certificate(ckey, 'name')

        with self.subTest('Public key auth not available'):
            yield from self.check_auth(b'publickey', (False, None))

        with self.subTest('Untrusted key'):
            yield from self.check_auth(b'publickey', (False, None),
                                       client_key=ckey, public_key_auth=True)

        with self.subTest('Trusted key'):
            yield from self.check_auth(b'publickey', (True, None),
                                       client_key=ckey, public_key_auth=True,
                                       success=True)

        with self.subTest('Trusted certificate'):
            yield from self.check_auth(b'publickey', (True, None),
                                       client_key=ckey, client_cert=cert,
                                       public_key_auth=True, success=True)

        with self.subTest('Invalid PK_OK message'):
            with self.assertRaises(asyncssh.ProtocolError):
                yield from self.check_auth(b'publickey', (False, None),
                                           client_key=ckey,
                                           public_key_auth=True,
                                           override_pk_ok=True)
Пример #13
0
    def test_errors(self):
        """Test getting error responses from SSH agent"""

        # pylint: disable=bad-whitespace

        key = asyncssh.generate_private_key('ssh-rsa')
        keypair = asyncssh.load_keypairs(key)[0]

        for response in (b'', String(b''), String(Byte(SSH_AGENT_FAILURE)),
                         String(b'\xff')):
            mock_agent = _Agent(response)
            yield from mock_agent.start('mock_agent')

            agent = yield from asyncssh.connect_agent('mock_agent')

            for request in (agent.get_keys(), agent.sign(b'xxx', b'test'),
                            agent.add_keys([key]),
                            agent.add_smartcard_keys('xxx'),
                            agent.remove_keys([keypair]),
                            agent.remove_smartcard_keys('xxx'),
                            agent.remove_all(), agent.lock('passphrase'),
                            agent.unlock('passphrase')):
                with self.assertRaises(ValueError):
                    yield from request

                agent.close()

            yield from mock_agent.stop()
Пример #14
0
    async def test_hostbased_auth(self):
        """Unit test host-based authentication"""

        hkey = asyncssh.generate_private_key('ssh-rsa')
        cert = hkey.generate_host_certificate(hkey, 'host')

        with self.subTest('Host-based auth not available'):
            await self.check_auth(b'hostbased', (False, None))

        with self.subTest('Untrusted key'):
            await self.check_auth(b'hostbased', (False, None),
                                  client_host_key=hkey,
                                  host_based_auth=True)

        with self.subTest('Trusted key'):
            await self.check_auth(b'hostbased', (True, None),
                                  client_host_key=hkey,
                                  host_based_auth=True,
                                  success=True)

        with self.subTest('Trusted certificate'):
            await self.check_auth(b'hostbased', (True, None),
                                  client_host_key=hkey,
                                  client_host_cert=cert,
                                  host_based_auth=True,
                                  success=True)
Пример #15
0
    def test_add_remove_keys(self, agent):
        """Test adding and removing keys"""

        yield from agent.add_keys()
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        key = asyncssh.generate_private_key('ssh-rsa')
        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)

        yield from agent.remove_keys(agent_keys)
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)

        yield from agent_keys[0].remove()
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        yield from agent.add_keys([key], lifetime=1)
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)
        yield from asyncio.sleep(2)

        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)
Пример #16
0
    def test_add_remove_keys(self, agent):
        """Test adding and removing keys"""

        yield from agent.add_keys()
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        key = asyncssh.generate_private_key('ssh-rsa')
        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)

        yield from agent.remove_keys(agent_keys)
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)

        yield from agent_keys[0].remove()
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)

        yield from agent.add_keys([key], lifetime=1)
        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 1)
        yield from asyncio.sleep(2)

        agent_keys = yield from agent.get_keys()
        self.assertEqual(len(agent_keys), 0)
Пример #17
0
    def test_unknown_key(self, agent):
        """Test failure when signing with an unknown key"""

        key = asyncssh.generate_private_key('ssh-rsa')

        with self.assertRaises(ValueError):
            yield from agent.sign(key.public_data, b'test')
Пример #18
0
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()
Пример #19
0
    async def test_errors(self):
        """Test getting error responses from SSH agent"""

        key = asyncssh.generate_private_key('ssh-rsa')
        keypair = asyncssh.load_keypairs(key)[0]

        for response in (None, b'', Byte(SSH_AGENT_FAILURE), b'\xff'):
            mock_agent = _Agent(response)
            await mock_agent.start('mock_agent')

            async with asyncssh.connect_agent('mock_agent') as agent:
                for request in (agent.get_keys(),
                                agent.sign(b'xxx', b'test'),
                                agent.add_keys([key]),
                                agent.add_smartcard_keys('xxx'),
                                agent.remove_keys([keypair]),
                                agent.remove_smartcard_keys('xxx'),
                                agent.remove_all(),
                                agent.lock('passphrase'),
                                agent.unlock('passphrase')):
                    async with agent:
                        with self.assertRaises(ValueError):
                            await request

            await mock_agent.stop()
Пример #20
0
    def test_hostbased_auth(self):
        """Unit test host-based authentication"""

        hkey = asyncssh.generate_private_key('ssh-rsa')
        cert = hkey.generate_host_certificate(hkey, 'host')

        with self.subTest('Host-based auth not available'):
            yield from self.check_auth(b'hostbased', (False, None))

        with self.subTest('Untrusted key'):
            yield from self.check_auth(b'hostbased', (False, None),
                                       client_host_key=hkey,
                                       host_based_auth=True)

        with self.subTest('Trusted key'):
            yield from self.check_auth(b'hostbased', (True, None),
                                       client_host_key=hkey,
                                       host_based_auth=True,
                                       success=True)

        with self.subTest('Trusted certificate'):
            yield from self.check_auth(b'hostbased', (True, None),
                                       client_host_key=hkey,
                                       client_host_cert=cert,
                                       host_based_auth=True, success=True)
Пример #21
0
    def post_init(self):
        if not self._listen_url.auth:
            raise ValueError("SSH username not specified")
        if ":" in self._listen_url.auth:
            username, password = self._listen_url.auth.split(":", 1)
        else:
            username = self._listen_url.auth
            password = None
        public_key_path = self._listen_url.params.get("public_key")
        private_key_path = self._listen_url.params.get("private_key")
        if not private_key_path:
            private_key_path = "skey"
            if not os.path.isfile(private_key_path):
                skey = asyncssh.generate_private_key("ssh-rsa")
                skey.write_private_key(private_key_path)
                skey.write_public_key(private_key_path + ".pub")
        private_key_path = os.path.abspath(private_key_path)
        if not os.path.isfile(private_key_path):
            raise ValueError("Private key file %s not exist" %
                             private_key_path)
        if public_key_path:
            public_key_path = os.path.abspath(public_key_path)
            if not os.path.isfile(public_key_path):
                raise ValueError("Public key file %s not exist" %
                                 public_key_path)

        MicroSSHServer.__init__(
            self,
            self._listen_url.address,
            [private_key_path],
            username,
            password,
            public_key_path,
        )
Пример #22
0
    def test_unknown_key(self, agent):
        """Test failure when signing with an unknown key"""

        key = asyncssh.generate_private_key('ssh-rsa')

        with self.assertRaises(ValueError):
            yield from agent.sign(key.public_data, b'test')
Пример #23
0
    def test_errors(self):
        """Test getting error responses from SSH agent"""

        # pylint: disable=bad-whitespace

        key = asyncssh.generate_private_key('ssh-rsa')
        keypair = asyncssh.load_keypairs(key)[0]

        for response in (b'', String(b''),
                         String(Byte(SSH_AGENT_FAILURE)), String(b'\xff')):
            mock_agent = _Agent(response)
            yield from mock_agent.start('mock_agent')

            agent = yield from asyncssh.connect_agent('mock_agent')

            for request in (agent.get_keys(),
                            agent.sign(b'xxx', b'test'),
                            agent.add_keys([key]),
                            agent.add_smartcard_keys('xxx'),
                            agent.remove_keys([keypair]),
                            agent.remove_smartcard_keys('xxx'),
                            agent.remove_all(),
                            agent.lock('passphrase'),
                            agent.unlock('passphrase')):
                with self.assertRaises(ValueError):
                    yield from request

                agent.close()

            yield from mock_agent.stop()
Пример #24
0
    def test_non_root_ca(self):
        """Test error on non-root X.509 CA"""

        key = asyncssh.generate_private_key('ssh-rsa')
        cert = key.generate_x509_user_certificate(key, 'CN=a', 'CN=b')
        data = 'cert-authority ' + cert.export_certificate().decode('ascii')

        with self.assertRaises(ValueError):
            asyncssh.import_authorized_keys(data)
Пример #25
0
    def __init__(self, alg, gss_host, peer):
        gss = GSSServer(gss_host) if gss_host else None
        super().__init__(alg, gss, peer, True)

        if gss_host and 'no_host_key' in gss_host:
            self._server_host_key = None
        else:
            priv_key = asyncssh.generate_private_key('ssh-rsa')
            self._server_host_key = SSHLocalKeyPair(priv_key)
Пример #26
0
async def generate_public_private_keypair(
    algo, key_size, exponent, passphrase, cipher, rounds, hash_name
):
    if algo == "ssh-rsa":
        _private_key = asyncssh.generate_private_key(
            algo, key_size=key_size, exponent=exponent
        )
    else:
        _private_key = asyncssh.generate_private_key(algo)
    private_key = _private_key.export_private_key(
        "openssh",
        passphrase=passphrase,
        cipher_name=cipher,
        hash_name=hash_name,
        rounds=rounds,
    )
    public_key = _private_key.export_public_key("openssh")
    return private_key, public_key.decode("utf-8")
Пример #27
0
    def setUpClass(cls):
        """Create public keys needed for test"""

        super().setUpClass()

        for _ in range(3):
            key = asyncssh.generate_private_key('ssh-rsa')
            cls.keylist.append(key.export_public_key().decode('ascii'))
            cls.imported_keylist.append(key.convert_to_public())
Пример #28
0
async def start_ssh_server(port, username, password=None, public_key=None):
    if not os.path.isfile("skey"):
        skey = asyncssh.generate_private_key("ssh-rsa")
        skey.write_private_key("skey")
        skey.write_public_key("skey.pub")
    ssh_server = ssh.MicroSSHServer(("127.0.0.1", port), ["skey"], username,
                                    password, public_key)
    await ssh_server.start()
    return ssh_server
Пример #29
0
    def __init__(self, alg, gss_host, peer):
        gss = GSSServer(gss_host) if gss_host else None
        super().__init__(alg, gss, peer, True)

        if gss_host and 'no_host_key' in gss_host:
            self._server_host_key = None
        else:
            priv_key = asyncssh.generate_private_key('ssh-rsa')
            self._server_host_key = SSHLocalKeyPair(priv_key)
Пример #30
0
    def setUpClass(cls):
        """Create public keys needed for test"""

        super().setUpClass()

        for _ in range(3):
            key = asyncssh.generate_private_key('ssh-rsa')
            cls.keylist.append(key.export_public_key().decode('ascii'))
            cls.imported_keylist.append(key.convert_to_public())
Пример #31
0
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
Пример #32
0
    def initialize(self, *args, **kwargs):
        self.load_config_file(self.config_file)
        self.init_logging()

        if self.host_key_path is None:
            # We'll generate a temporary key in-memory key for this run only
            self.ssh_host_key = asyncssh.generate_private_key('ssh-rsa')
            self.log.warn('No --host-key-path provided, generating an ephemeral host key')
        else:
            with open(self.host_key_path) as f:
                self.ssh_host_key = asyncssh.import_private_key(f.read())
            self.log.info(f'Loaded host key from {self.host_key_path}')
Пример #33
0
    def start(self):
        """Start RSA key exchange"""

        if self._conn.is_server():
            host_key = self._conn.get_server_host_key()
            self._host_key_data = host_key.public_data

            self._trans_key = asyncssh.generate_private_key(
                'ssh-rsa', self._key_size)
            self._trans_key_data = self._trans_key.public_data

            self.send_packet(MSG_KEXRSA_PUBKEY, String(self._host_key_data),
                             String(self._trans_key_data))
Пример #34
0
def genkey(path):
    if not path:
        path = "~/.ssh/pysshchat"
    key_path = os.path.expanduser(path)
    path = Path(key_path)

    if not path.is_file():
        Path(path.parent).mkdir(parents=True, exist_ok=True)
        key = asyncssh.generate_private_key("ssh-rsa")
        key.write_private_key(key_path)
        print("Generate host key")
        # print("Fingerprint MD5:" + fingerprint(key.get_ssh_public_key()))
    return key_path
Пример #35
0
    def start(self):
        """Start RSA key exchange"""

        if self._conn.is_server():
            host_key = self._conn.get_server_host_key()
            self._host_key_data = host_key.public_data

            self._trans_key = asyncssh.generate_private_key('ssh-rsa',
                                                            self._key_size)
            self._trans_key_data = self._trans_key.public_data

            self.send_packet(MSG_KEXRSA_PUBKEY, String(self._host_key_data),
                             String(self._trans_key_data))
Пример #36
0
    def test_reconnect(self, agent):
        """Test reconnecting to the agent after closing it"""

        key = asyncssh.generate_private_key('ssh-rsa')
        pubkey = key.convert_to_public()

        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        agent.close()

        for agent_key in agent_keys:
            sig = yield from agent_key.sign(b'test')
            self.assertTrue(pubkey.verify(b'test', sig))
Пример #37
0
    def test_reconnect(self, agent):
        """Test reconnecting to the agent after closing it"""

        key = asyncssh.generate_private_key('ssh-rsa')
        pubkey = key.convert_to_public()

        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()
        agent.close()

        for agent_key in agent_keys:
            sig = yield from agent_key.sign(b'test')
            self.assertTrue(pubkey.verify(b'test', sig))
Пример #38
0
    def _get_key(self, args):
        """Sets either random or user-provided ssh-rsa key.

        args:
            args (dict): Dict that should contain 'key_file' key.
        """
        if args.key_file is None:
            key = asyncssh.generate_private_key('ssh-rsa',
                                                'RandomKey',
                                                key_size=1024)
        else:
            with open(args.key_file, 'rb') as f:
                key = asyncssh.import_private_key(f.read())
        self.ssh_key = key
Пример #39
0
    async def test_set_certificate(self, agent):
        """Test setting certificate on an existing keypair"""

        key = asyncssh.generate_private_key('ssh-rsa')
        cert = key.generate_user_certificate(key, 'name')

        key2 = asyncssh.generate_private_key('ssh-rsa')
        cert2 = key.generate_user_certificate(key2, 'name')

        await agent.add_keys([key])
        agent_key = (await agent.get_keys())[0]

        agent_key.set_certificate(cert)
        self.assertEqual(agent_key.public_data, cert.public_data)

        with self.assertRaises(ValueError):
            asyncssh.load_keypairs([(agent_key, cert2)])

        agent_key = (await agent.get_keys())[0]
        agent_key = asyncssh.load_keypairs([(agent_key, cert)])[0]
        self.assertEqual(agent_key.public_data, cert.public_data)

        with self.assertRaises(ValueError):
            asyncssh.load_keypairs([(agent_key, cert2)])
Пример #40
0
    def setUpClass(cls):
        """Create public keys needed for test"""

        super().setUpClass()

        for i in range(3):
            key = asyncssh.generate_private_key('ssh-rsa')
            cls.keylist.append(key.export_public_key().decode('ascii'))
            cls.imported_keylist.append(key.convert_to_public())

            if x509_available: # pragma: no branch
                subject = 'CN=cert%s' % i
                cert = key.generate_x509_user_certificate(key, subject)
                cls.certlist.append(cert.export_certificate().decode('ascii'))
                cls.imported_certlist.append(cert)
Пример #41
0
    def test_confirm(self, agent):
        """Test confirmation of key"""

        key = asyncssh.generate_private_key('ssh-rsa')
        pubkey = key.convert_to_public()

        yield from agent.add_keys([key], confirm=True)
        agent_keys = yield from agent.get_keys()

        self.set_askpass(1)

        for agent_key in agent_keys:
            with self.assertRaises(ValueError):
                sig = yield from agent_key.sign(b'test')

        self.set_askpass(0)

        for agent_key in agent_keys:
            sig = yield from agent_key.sign(b'test')
            self.assertTrue(pubkey.verify(b'test', sig))
Пример #42
0
    def test_lock(self, agent):
        """Test lock and unlock"""

        key = asyncssh.generate_private_key('ssh-rsa')
        pubkey = key.convert_to_public()

        yield from agent.add_keys([key])
        agent_keys = yield from agent.get_keys()

        yield from agent.lock('passphrase')

        for agent_key in agent_keys:
            with self.assertRaises(ValueError):
                yield from agent_key.sign(b'test')

        yield from agent.unlock('passphrase')

        for agent_key in agent_keys:
            sig = yield from agent_key.sign(b'test')
            self.assertTrue(pubkey.verify(b'test', sig))
Пример #43
0
    def test_sign(self, agent):
        """Test signing a block of data using the agent"""

        algs = ['ssh-dss', 'ssh-rsa', 'ecdsa-sha2-nistp256']

        if ed25519_available: # pragma: no branch
            algs.append('ssh-ed25519')

        for alg_name in algs:
            key = asyncssh.generate_private_key(alg_name)
            pubkey = key.convert_to_public()
            cert = key.generate_user_certificate(key, 'name')

            yield from agent.add_keys([(key, cert)])
            agent_keys = yield from agent.get_keys()

            for agent_key in agent_keys:
                sig = yield from agent_key.sign(b'test')
                self.assertTrue(pubkey.verify(b'test', sig))

            yield from agent.remove_keys(agent_keys)
Пример #44
0
    def test_rsa_errors(self):
        """Unit test error conditions in RSA key exchange"""

        client_conn, server_conn = \
            _KexClientStub.make_pair(b'rsa2048-sha256')

        with self.subTest('Pubkey sent to server'):
            with self.assertRaises(asyncssh.ProtocolError):
                server_conn.simulate_rsa_pubkey(b'', b'')

        with self.subTest('Secret sent to client'):
            with self.assertRaises(asyncssh.ProtocolError):
                client_conn.simulate_rsa_secret(b'')

        with self.subTest('Done sent to server'):
            with self.assertRaises(asyncssh.ProtocolError):
                server_conn.simulate_rsa_done(b'')

        with self.subTest('Invalid transient public key'):
            with self.assertRaises(asyncssh.ProtocolError):
                client_conn.simulate_rsa_pubkey(b'', b'')

        with self.subTest('Invalid encrypted secret'):
            with self.assertRaises(asyncssh.KeyExchangeFailed):
                server_conn.start()
                server_conn.simulate_rsa_secret(b'')

        with self.subTest('Invalid signature'):
            with self.assertRaises(asyncssh.KeyExchangeFailed):
                host_key = server_conn.get_server_host_key()
                trans_key = asyncssh.generate_private_key('ssh-rsa', 2048)
                client_conn.simulate_rsa_pubkey(host_key.public_data,
                                                trans_key.public_data)
                client_conn.simulate_rsa_done(b'')

        client_conn.close()
        server_conn.close()
Пример #45
0
    def __init__(self, alg, peer):
        super().__init__(alg, peer, True)

        priv_key = asyncssh.generate_private_key('ssh-rsa')
        self._server_host_key = SSHLocalKeyPair(priv_key)
Пример #46
0
    def asyncSetUpClass(cls):
        """Set up keys, an SSH server, and an SSH agent for the tests to use"""

        # pylint: disable=too-many-statements

        ckey = asyncssh.generate_private_key('ssh-rsa')
        ckey.write_private_key('ckey')
        ckey.write_private_key('ckey_encrypted', passphrase='passphrase')
        ckey.write_public_key('ckey.pub')

        ckey_ecdsa = asyncssh.generate_private_key('ecdsa-sha2-nistp256')
        ckey_ecdsa.write_private_key('ckey_ecdsa')
        ckey_ecdsa.write_public_key('ckey_ecdsa.pub')

        ckey_cert = ckey.generate_user_certificate(ckey, 'name',
                                                   principals=['ckey'])
        ckey_cert.write_certificate('ckey-cert.pub')

        skey = asyncssh.generate_private_key('ssh-rsa')
        skey.write_private_key('skey')
        skey.write_public_key('skey.pub')

        skey_ecdsa = asyncssh.generate_private_key('ecdsa-sha2-nistp256')
        skey_ecdsa.write_private_key('skey_ecdsa')
        skey_ecdsa.write_public_key('skey_ecdsa.pub')

        skey_cert = skey.generate_host_certificate(skey, 'name',
                                                   principals=['127.0.0.1'])
        skey_cert.write_certificate('skey-cert.pub')

        exp_cert = skey.generate_host_certificate(skey, 'name',
                                                  valid_after='-2d',
                                                  valid_before='-1d')
        skey.write_private_key('exp_skey')
        exp_cert.write_certificate('exp_skey-cert.pub')

        if x509_available: # pragma: no branch
            ckey_x509_self = ckey_ecdsa.generate_x509_user_certificate(
                ckey_ecdsa, 'OU=name', principals=['ckey'])
            ckey_ecdsa.write_private_key('ckey_x509_self')
            ckey_x509_self.append_certificate('ckey_x509_self', 'pem')
            ckey_x509_self.write_certificate('ckey_x509_self.pem', 'pem')
            ckey_x509_self.write_certificate('ckey_x509_self.pub')

            skey_x509_self = skey_ecdsa.generate_x509_host_certificate(
                skey_ecdsa, 'OU=name', principals=['127.0.0.1'])
            skey_ecdsa.write_private_key('skey_x509_self')
            skey_x509_self.append_certificate('skey_x509_self', 'pem')
            skey_x509_self.write_certificate('skey_x509_self.pem', 'pem')

            root_ca_key = asyncssh.generate_private_key('ssh-rsa')
            root_ca_key.write_private_key('root_ca_key')

            root_ca_cert = root_ca_key.generate_x509_ca_certificate(
                root_ca_key, 'OU=RootCA', ca_path_len=1)
            root_ca_cert.write_certificate('root_ca_cert.pem', 'pem')
            root_ca_cert.write_certificate('root_ca_cert.pub')

            int_ca_key = asyncssh.generate_private_key('ssh-rsa')
            int_ca_key.write_private_key('int_ca_key')

            int_ca_cert = root_ca_key.generate_x509_ca_certificate(
                int_ca_key, 'OU=IntCA', 'OU=RootCA', ca_path_len=0)
            int_ca_cert.write_certificate('int_ca_cert.pem', 'pem')

            ckey_x509_chain = int_ca_key.generate_x509_user_certificate(
                ckey, 'OU=name', 'OU=IntCA', principals=['ckey'])
            ckey.write_private_key('ckey_x509_chain')
            ckey_x509_chain.append_certificate('ckey_x509_chain', 'pem')
            int_ca_cert.append_certificate('ckey_x509_chain', 'pem')
            ckey_x509_chain.write_certificate('ckey_x509_partial.pem', 'pem')

            skey_x509_chain = int_ca_key.generate_x509_host_certificate(
                skey, 'OU=name', 'OU=IntCA', principals=['127.0.0.1'])
            skey.write_private_key('skey_x509_chain')
            skey_x509_chain.append_certificate('skey_x509_chain', 'pem')
            int_ca_cert.append_certificate('skey_x509_chain', 'pem')

            root_hash = root_ca_cert.x509_cert.subject_hash

            os.mkdir('cert_path')
            shutil.copy('root_ca_cert.pem',
                        os.path.join('cert_path', root_hash + '.0'))

            # Intentional hash mismatch
            shutil.copy('int_ca_cert.pem',
                        os.path.join('cert_path', root_hash + '.1'))

        for f in ('ckey', 'ckey_ecdsa', 'skey', 'exp_skey', 'skey_ecdsa'):
            os.chmod(f, 0o600)

        os.mkdir('.ssh', 0o700)
        os.mkdir('.ssh/crt', 0o700)

        shutil.copy('ckey_ecdsa', os.path.join('.ssh', 'id_ecdsa'))
        shutil.copy('ckey_ecdsa.pub', os.path.join('.ssh', 'id_ecdsa.pub'))
        shutil.copy('ckey_encrypted', os.path.join('.ssh', 'id_rsa'))
        shutil.copy('ckey.pub', os.path.join('.ssh', 'id_rsa.pub'))

        with open('authorized_keys', 'w') as auth_keys:
            with open('ckey.pub') as ckey_pub:
                shutil.copyfileobj(ckey_pub, auth_keys)

            with open('ckey_ecdsa.pub') as ckey_ecdsa_pub:
                shutil.copyfileobj(ckey_ecdsa_pub, auth_keys)

            auth_keys.write('cert-authority,principals="ckey",'
                            'permitopen=:* ')

            with open('ckey.pub') as ckey_pub:
                shutil.copyfileobj(ckey_pub, auth_keys)

        if x509_available: # pragma: no branch
            with open('authorized_keys_x509', 'w') as auth_keys_x509:
                with open('ckey_x509_self.pub') as ckey_self_pub:
                    shutil.copyfileobj(ckey_self_pub, auth_keys_x509)

                auth_keys_x509.write('cert-authority,principals="ckey" ')

                with open('root_ca_cert.pub') as root_pub:
                    shutil.copyfileobj(root_pub, auth_keys_x509)

        cls._server = yield from cls.start_server()

        sock = cls._server.sockets[0]
        cls._server_addr = '127.0.0.1'
        cls._server_port = sock.getsockname()[1]

        host = '[%s]:%d,localhost ' % (cls._server_addr, cls._server_port)

        with open('known_hosts', 'w') as known_hosts:
            known_hosts.write(host)

            with open('skey.pub') as skey_pub:
                shutil.copyfileobj(skey_pub, known_hosts)

            known_hosts.write('@cert-authority ' + host)

            with open('skey.pub') as skey_pub:
                shutil.copyfileobj(skey_pub, known_hosts)

        shutil.copy('known_hosts', os.path.join('.ssh', 'known_hosts'))

        os.environ['LOGNAME'] = 'guest'
        os.environ['HOME'] = '.'

        if 'DISPLAY' in os.environ: # pragma: no cover
            del os.environ['DISPLAY']
        if 'SSH_ASKPASS' in os.environ: # pragma: no cover
            del os.environ['SSH_ASKPASS']
        if 'SSH_AUTH_SOCK' in os.environ: # pragma: no cover
            del os.environ['SSH_AUTH_SOCK']
        if 'XAUTHORITY' in os.environ: # pragma: no cover
            del os.environ['XAUTHORITY']

        try:
            output = run('ssh-agent -a agent 2>/dev/null')
        except subprocess.CalledProcessError: # pragma: no cover
            cls._agent_pid = None
        else:
            cls._agent_pid = int(output.splitlines()[2].split()[3][:-1])

            os.environ['SSH_AUTH_SOCK'] = 'agent'

            agent = yield from asyncssh.connect_agent()
            yield from agent.add_keys([ckey_ecdsa, (ckey, ckey_cert)])
            agent.close()

        with open('ssh-keysign', 'wb'):
            pass
Пример #47
0
    def asyncSetUpClass(cls):
        """Set up keys, an SSH server, and an SSH agent for the tests to use"""

        ckey_dsa = asyncssh.generate_private_key('ssh-dss')
        ckey_dsa.write_private_key('ckey_dsa')
        ckey_dsa.write_public_key('ckey_dsa.pub')

        ckey = asyncssh.generate_private_key('ssh-rsa')
        ckey.write_private_key('ckey')
        ckey.write_public_key('ckey.pub')

        ckey_cert = ckey.generate_user_certificate(ckey, 'name')
        ckey_cert.write_certificate('ckey-cert.pub')

        skey = asyncssh.generate_private_key('ssh-rsa')
        skey.write_private_key('skey')
        skey.write_public_key('skey.pub')

        skey_cert = skey.generate_host_certificate(skey, 'name')
        skey_cert.write_certificate('skey-cert.pub')

        exp_cert = skey.generate_host_certificate(skey, 'name',
                                                  valid_after='-2d',
                                                  valid_before='-1d')
        skey.write_private_key('exp_skey')
        exp_cert.write_certificate('exp_skey-cert.pub')

        run('chmod 600 ckey_dsa ckey skey exp_skey')

        run('mkdir .ssh')
        run('chmod 700 .ssh')
        run('cp ckey_dsa .ssh/id_dsa')
        run('cp ckey_dsa.pub .ssh/id_dsa.pub')
        run('cp ckey .ssh/id_rsa')
        run('cp ckey.pub .ssh/id_rsa.pub')

        run('printf "cert-authority,principals=\"ckey\" " > authorized_keys')
        run('cat ckey.pub >> authorized_keys')
        run('printf "permitopen=\":*\" " >> authorized_keys')
        run('cat ckey.pub >> authorized_keys')
        run('cat ckey_dsa.pub >> authorized_keys')

        cls._server = yield from cls.start_server()

        sock = cls._server.sockets[0]
        cls._server_addr, cls._server_port = sock.getsockname()[:2]

        run('printf "[%s]:%s " > .ssh/known_hosts' % (cls._server_addr,
                                                      cls._server_port))
        run('cat skey.pub >> .ssh/known_hosts')

        os.environ = {'LOGNAME': 'guest', 'HOME': '.'}

        try:
            output = run('ssh-agent -a agent 2>/dev/null')
        except subprocess.CalledProcessError: # pragma: no cover
            cls._agent_pid = None
        else:
            cls._agent_pid = int(output.splitlines()[2].split()[3][:-1])

            os.environ['SSH_AUTH_SOCK'] = 'agent'

            agent = yield from asyncssh.connect_agent()
            yield from agent.add_keys([ckey_dsa, (ckey, ckey_cert)])
            agent.close()