File: server.py

package info (click to toggle)
python-asyncssh 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,464 kB
  • sloc: python: 40,306; makefile: 11
file content (357 lines) | stat: -rw-r--r-- 13,445 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# Copyright (c) 2016-2024 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
#     http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
#    GNU General Public License, Version 2.0, or any later versions of
#    that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
#     Ron Frederick - initial implementation, API, and documentation

"""SSH server used for unit tests"""

import asyncio
import os
import shutil
import signal
import socket
import subprocess
import sys

import asyncssh
from asyncssh.misc import async_context_manager

from .util import AsyncTestCase, all_tasks, current_task, get_test_key
from .util import run, x509_available


class Server(asyncssh.SSHServer):
    """Unit test SSH server"""

    def __init__(self):
        self._conn = None

    def connection_made(self, conn):
        """Record connection object for later use"""

        self._conn = conn

    def begin_auth(self, username):
        """Handle client authentication request"""

        return username != 'guest'


class ServerTestCase(AsyncTestCase):
    """Unit test class which starts an SSH server and agent"""

    _server = None
    _server_addr = ''
    _server_port = 0
    _agent_pid = None

    @classmethod
    @async_context_manager
    async def listen(cls, *, server_factory=(), options=None, **kwargs):
        """Create an SSH server for the tests to use"""

        if server_factory == ():
            server_factory = Server

        options = asyncssh.SSHServerConnectionOptions(
            options=options, server_factory=server_factory,
            gss_host=None, server_host_keys=['skey'])

        return await asyncssh.listen(port=0, family=socket.AF_INET,
                                     options=options, **kwargs)

    @classmethod
    @async_context_manager
    async def listen_reverse(cls, *, options=None, **kwargs):
        """Create a reverse SSH server for the tests to use"""

        options = asyncssh.SSHClientConnectionOptions(
            options=options, gss_host=None,
            known_hosts=(['skey.pub'], [], []))

        return await asyncssh.listen_reverse(port=0, family=socket.AF_INET,
                                             options=options, **kwargs)


    @classmethod
    async def create_server(cls, server_factory=(), **kwargs):
        """Create an SSH server for the tests to use"""

        return await cls.listen(server_factory=server_factory, **kwargs)

    @classmethod
    async def start_server(cls):
        """Start an SSH server for the tests to use"""

        return NotImplemented # pragma: no cover

    # Pylint doesn't like mixed case method names, but this was chosen to
    # match the convention used in the unittest module.

    # pylint: disable=invalid-name

    @classmethod
    async def asyncSetUpClass(cls):
        """Set up keys, an SSH server, and an SSH agent for the tests to use"""

        # pylint: disable=too-many-statements

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

        ckey_ecdsa = get_test_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 = get_test_key('ssh-rsa', 1)
        skey.write_private_key('skey')
        skey.write_public_key('skey.pub')

        skey_ecdsa = get_test_key('ecdsa-sha2-nistp256', 1)
        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', 'localhost'])
        skey_cert.write_certificate('skey-cert.pub')

        skey_ecdsa_cert = skey_ecdsa.generate_host_certificate(
            skey_ecdsa, 'name', principals=['127.0.0.1', 'localhost'])
        skey_ecdsa_cert.write_certificate('skey_ecdsa-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 = get_test_key('ssh-rsa', 2)
            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 = get_test_key('ssh-rsa', 3)
            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(os.path.join('.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'))
        shutil.copy('ckey-cert.pub', os.path.join('.ssh', 'id_rsa-cert.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)

            shutil.copy('skey_x509_self.pem',
                        os.path.join('.ssh', 'ca-bundle.crt'))

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

        cls._server = await cls.start_server()

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

        host = f'[{cls._server_addr}]:{cls._server_port},localhost '

        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 * ')

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

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

        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']

        if sys.platform != 'win32':
            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'

                async with asyncssh.connect_agent() as agent:
                    await agent.add_keys([ckey_ecdsa, (ckey, ckey_cert)])
        else: # pragma: no cover
            cls._agent_pid = None

        with open('ssh-keysign', 'wb'):
            pass

    @classmethod
    async def asyncTearDownClass(cls):
        """Shut down test server and agent"""

        cls._server.close()
        await cls._server.wait_closed()

        tasks = all_tasks()
        tasks.remove(current_task())

        await asyncio.gather(*tasks, return_exceptions=True)

        if cls._agent_pid: # pragma: no branch
            os.kill(cls._agent_pid, signal.SIGTERM)

    # pylint: enable=invalid-name

    def agent_available(self):
        """Return whether SSH agent is available"""

        return bool(self._agent_pid)

    @async_context_manager
    async def connect(self, host=(), port=(), gss_host=None,
                      options=None, **kwargs):
        """Open a connection to the test server"""

        return await asyncssh.connect(host or self._server_addr,
                                      port or self._server_port,
                                      gss_host=gss_host, options=options,
                                      **kwargs)

    @async_context_manager
    async def connect_reverse(self, options=None, gss_host=None, **kwargs):
        """Create a connection to the test server"""

        options = asyncssh.SSHServerConnectionOptions(options,
                                                      server_factory=Server,
                                                      server_host_keys=['skey'],
                                                      gss_host=gss_host)

        return await asyncssh.connect_reverse(self._server_addr,
                                              self._server_port,
                                              options=options, **kwargs)

    @async_context_manager
    async def run_client(self, sock, config=(), options=None, **kwargs):
        """Run an SSH client on an already-connected socket"""

        return await asyncssh.run_client(sock, config, options, **kwargs)

    @async_context_manager
    async def run_server(self, sock, config=(), options=None, **kwargs):
        """Run an SSH server on an already-connected socket"""

        options = asyncssh.SSHServerConnectionOptions(options,
                                                      server_factory=Server,
                                                      server_host_keys=['skey'])

        return await asyncssh.run_server(sock, config, options, **kwargs)

    async def create_connection(self, client_factory, **kwargs):
        """Create a connection to the test server"""

        conn = await self.connect(client_factory=client_factory, **kwargs)

        return conn, conn.get_owner()