Ejemplo n.º 1
0
    def _get_userauth_request_packet(self, method, args):
        """Get packet data for a user authentication request"""

        # pylint: disable=no-self-use

        return b''.join((String('user'), String('service'),
                         String(method)) + args)
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
    def check_sign_and_verify(self):
        """Check key signing and verification"""

        with self.subTest('Sign/verify test'):
            pubkey = read_public_key('pub')
            data = os.urandom(8)

            sig = self.privkey.sign(data)
            with self.subTest('Good signature'):
                self.assertTrue(pubkey.verify(data, sig))

            badsig = bytearray(sig)
            badsig[-1] ^= 0xff
            badsig = bytes(badsig)
            with self.subTest('Bad signature'):
                self.assertFalse(pubkey.verify(data, badsig))

            with self.subTest('Empty signature'):
                self.assertFalse(
                    pubkey.verify(data,
                                  String(pubkey.algorithm) + String(b'')))

            badalg = String('xxx')
            with self.subTest('Bad algorithm'):
                self.assertFalse(pubkey.verify(data, badalg))

            with self.subTest('Sign with public key'):
                with self.assertRaises(ValueError):
                    pubkey.sign(data)
Ejemplo n.º 4
0
    def test_unexpected_userauth_banner(self):
        """Test unexpected userauth banner"""

        conn = yield from self.connect()

        conn.send_packet(MSG_USERAUTH_BANNER, String(''), String(''))

        yield from conn.wait_closed()
Ejemplo n.º 5
0
    def test_invalid_username(self):
        """Test invalid username in userauth request"""

        conn = yield from self.connect()

        conn.send_packet(MSG_USERAUTH_REQUEST, String(b'\xff'),
                         String('ssh-connection'), String('none'))

        yield from conn.wait_closed()
Ejemplo n.º 6
0
    def test_invalid_userauth_service(self):
        """Test invalid service in userauth request"""

        conn = yield from self.connect()

        conn.send_packet(MSG_USERAUTH_REQUEST, String('guest'), String('xxx'),
                         String('none'))

        yield from conn.wait_closed()
Ejemplo n.º 7
0
    def send_userauth_request(self, method, *args, key=None):
        """Send a user authentication request"""

        packet = self._get_userauth_request_packet(method, args)

        if key:
            packet += String(key.sign(String('') + packet))

        self.send_packet(MSG_USERAUTH_REQUEST, packet)
Ejemplo n.º 8
0
    def test_invalid_channel_open_failure_number(self):
        """Test invalid channel number in open failure"""

        conn = yield from self.connect()

        conn.send_packet(MSG_CHANNEL_OPEN_FAILURE, UInt32(0xff), UInt32(0),
                         String(''), String(''))

        yield from conn.wait_closed()
Ejemplo n.º 9
0
    def test_invalid_channel_open_failure_language(self):
        """Test invalid language in channel open failure"""

        conn = yield from self.connect()

        conn.send_packet(MSG_CHANNEL_OPEN_FAILURE, UInt32(0), UInt32(0),
                         String(''), String(b'\xff'))

        yield from conn.wait_closed()
Ejemplo n.º 10
0
    def test_extra_userauth_request(self):
        """Test userauth request after auth is complete"""

        with (yield from self.connect()) as conn:
            conn.send_packet(MSG_USERAUTH_REQUEST, String('guest'),
                             String('ssh-connection'), String('none'))
            yield from asyncio.sleep(0.1)

        yield from conn.wait_closed()
Ejemplo n.º 11
0
    def send_userauth_request(self, method, *args, key=None):
        """Send a user authentication request"""

        packet = b''.join((Byte(MSG_USERAUTH_REQUEST), String('user'),
                           String(b'service'), String(method)) + args)

        if key:
            packet += String(key.sign(String('') + packet))

        self.send_packet(packet)
Ejemplo n.º 12
0
    def _send_request(self, request, *args, want_reply=False):
        """Send a channel request"""

        if request == b'exit-signal':
            if args[0] == String('invalid'):
                args = (String(b'\xff'), ) + args[1:]

            if args[3] == String('invalid'):
                args = args[:3] + (String(b'\xff'), )

        super()._send_request(request, *args, want_reply=want_reply)
Ejemplo n.º 13
0
    def _send_request(self, request, *args, want_reply=False):
        """Send a channel request"""

        if request == b'env' and args[1] == String('invalid'):
            args = args[:1] + (String(b'\xff'), )
        elif request == b'pty-req':
            if args[5][-6:-5] == Byte(PTY_OP_PARTIAL):
                args = args[:5] + (String(args[5][4:-5]), )
            elif args[5][-6:-5] == Byte(PTY_OP_NO_END):
                args = args[:5] + (String(args[5][4:-6]), )

        super()._send_request(request, *args, want_reply=want_reply)
Ejemplo n.º 14
0
    def test_invalid_service_request(self):
        """Test invalid service request"""

        conn = yield from self.connect()

        conn.send_packet(MSG_SERVICE_REQUEST, String('xxx'))

        yield from conn.wait_closed()
Ejemplo n.º 15
0
    async def test_get_sk_keys(self):
        """Test getting U2F security keys"""

        key = asyncssh.generate_private_key(
            '*****@*****.**')
        cert = key.generate_user_certificate(key, 'test')

        mock_agent = _Agent(Byte(SSH_AGENT_IDENTITIES_ANSWER) + UInt32(2) +
                            String(key.public_data) + String('') +
                            String(cert.public_data) + String(''))

        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            await agent.get_keys()

        await mock_agent.stop()
Ejemplo n.º 16
0
    def test_invalid_data_channel_number(self):
        """Test invalid channel number in channel data message"""

        conn = yield from self.connect()

        conn.send_packet(MSG_CHANNEL_DATA, UInt32(99), String(''))

        yield from conn.wait_closed()
Ejemplo n.º 17
0
    def test_invalid_service_accept(self):
        """Test invalid service accept"""

        conn = yield from self.connect()

        conn.send_packet(MSG_SERVICE_ACCEPT, String('xxx'))

        yield from conn.wait_closed()
Ejemplo n.º 18
0
    def test_unexpected_global_response(self):
        """Test unexpected global response"""

        conn = yield from self.connect()

        conn.send_packet(MSG_GLOBAL_REQUEST, String('xxx'), Boolean(True))

        yield from conn.wait_closed()
Ejemplo n.º 19
0
    def test_invalid_global_request(self):
        """Test invalid global request"""

        conn = yield from self.connect()

        conn.send_packet(MSG_GLOBAL_REQUEST, String(b'\xff'), Boolean(True))

        yield from conn.wait_closed()
Ejemplo n.º 20
0
    async def test_cancel_forward_remote_port_invalid_unicode(self):
        """Test canceling TCP/IP forwarding with invalid Unicode in host"""

        with patch('asyncssh.connection.SSHClientConnection', _ClientConn):
            async with self.connect() as conn:
                pkttype, _ = await conn.make_global_request(
                    b'cancel-tcpip-forward', String(b'\xff'), UInt32(0))

                self.assertEqual(pkttype, asyncssh.MSG_REQUEST_FAILURE)
Ejemplo n.º 21
0
    async def test_cancel_forward_remote_path_invalid_unicode(self):
        """Test canceling UNIX forwarding with invalid Unicode in path"""

        with patch('asyncssh.connection.SSHClientConnection', _ClientConn):
            async with self.connect() as conn:
                pkttype, _ = await conn.make_global_request(
                    b'*****@*****.**', String(b'\xff'))

                self.assertEqual(pkttype, asyncssh.MSG_REQUEST_FAILURE)
Ejemplo n.º 22
0
    def test_unknown_channel_type(self):
        """Test unknown channel open type"""

        conn = yield from self.connect()

        conn.send_packet(MSG_CHANNEL_OPEN, String('xxx'), UInt32(0), UInt32(0),
                         UInt32(0))

        yield from conn.wait_closed()
Ejemplo n.º 23
0
    def test_invalid_channel_open(self):
        """Test invalid channel open request"""

        conn = yield from self.connect()

        conn.send_packet(MSG_CHANNEL_OPEN, String(b'\xff'), UInt32(0),
                         UInt32(0), UInt32(0))

        yield from conn.wait_closed()
Ejemplo n.º 24
0
    def password_auth_requested(self):
        """Attempt to execute a command before authentication is complete"""

        # pylint: disable=protected-access
        self._conn._auth_complete = True

        self._conn.send_packet(MSG_GLOBAL_REQUEST, String(b'\xff'),
                               Boolean(True))
        return 'pw'
Ejemplo n.º 25
0
    async def test_add_remove_smartcard_keys(self):
        """Test adding and removing smart card keys"""

        mock_agent = _Agent(String(Byte(SSH_AGENT_SUCCESS)))
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            result = await agent.add_smartcard_keys('provider')
            self.assertIsNone(result)

        await mock_agent.stop()

        mock_agent = _Agent(String(Byte(SSH_AGENT_SUCCESS)))
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            result = await agent.remove_smartcard_keys('provider')
            self.assertIsNone(result)

        await mock_agent.stop()
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
    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)])
Ejemplo n.º 28
0
    def test_add_remove_smartcard_keys(self):
        """Test adding and removing smart card keys"""

        mock_agent = _Agent(String(Byte(SSH_AGENT_SUCCESS)))
        yield from mock_agent.start('mock_agent')
        agent = yield from asyncssh.connect_agent('mock_agent')

        result = yield from agent.add_smartcard_keys('provider')
        self.assertIsNone(result)

        agent.close()
        yield from mock_agent.stop()

        mock_agent = _Agent(String(Byte(SSH_AGENT_SUCCESS)))
        yield from mock_agent.start('mock_agent')
        agent = yield from asyncssh.connect_agent('mock_agent')

        result = yield from agent.remove_smartcard_keys('provider')
        self.assertIsNone(result)

        agent.close()
        yield from mock_agent.stop()
Ejemplo n.º 29
0
    async def test_query_extensions(self):
        """Test query of supported extensions"""

        mock_agent = _Agent(Byte(SSH_AGENT_SUCCESS) + String('xxx'))
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            extensions = await agent.query_extensions()
            self.assertEqual(extensions, ['xxx'])

        await mock_agent.stop()

        mock_agent = _Agent(Byte(SSH_AGENT_SUCCESS) + String(b'\xff'))
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            with self.assertRaises(ValueError):
                await agent.query_extensions()

        await mock_agent.stop()

        mock_agent = _Agent(Byte(SSH_AGENT_FAILURE))
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            extensions = await agent.query_extensions()
            self.assertEqual(extensions, [])

        await mock_agent.stop()

        mock_agent = _Agent(b'\xff')
        await mock_agent.start('mock_agent')

        async with asyncssh.connect_agent('mock_agent') as agent:
            with self.assertRaises(ValueError):
                await agent.query_extensions()

        await mock_agent.stop()
Ejemplo n.º 30
0
    def process_packet(self, data):
        """Process an incoming packet"""

        packet = SSHPacket(data)
        pkttype = packet.get_byte()

        if pkttype == MSG_USERAUTH_REQUEST:
            _ = packet.get_string()         # username
            _ = packet.get_string()         # service
            method = packet.get_string()

            if self._auth:
                self._auth.cancel()

            if self._override_gss_mech:
                self.send_packet(MSG_USERAUTH_GSSAPI_RESPONSE,
                                 String('mismatch'))
            elif self._override_pk_ok:
                self.send_packet(MSG_USERAUTH_PK_OK, String(''), String(''))
            else:
                self._auth = lookup_server_auth(self, 'user', method, packet)
        else:
            self._auth.process_packet(pkttype, None, packet)