-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathtest_connection.py
More file actions
2856 lines (2030 loc) · 94.6 KB
/
Copy pathtest_connection.py
File metadata and controls
2856 lines (2030 loc) · 94.6 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2016-2025 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
"""Unit tests for AsyncSSH connection API"""
import asyncio
from copy import copy
import os
from pathlib import Path
import socket
import sys
import unittest
from unittest.mock import patch
import asyncssh
from asyncssh.constants import MSG_IGNORE, MSG_DEBUG
from asyncssh.constants import MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT
from asyncssh.constants import MSG_KEXINIT, MSG_NEWKEYS
from asyncssh.constants import MSG_KEX_FIRST, MSG_KEX_LAST
from asyncssh.constants import MSG_USERAUTH_REQUEST, MSG_USERAUTH_SUCCESS
from asyncssh.constants import MSG_USERAUTH_FAILURE, MSG_USERAUTH_BANNER
from asyncssh.constants import MSG_USERAUTH_FIRST
from asyncssh.constants import MSG_GLOBAL_REQUEST
from asyncssh.constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_CONFIRMATION
from asyncssh.constants import MSG_CHANNEL_OPEN_FAILURE, MSG_CHANNEL_DATA
from asyncssh.compression import get_compression_algs
from asyncssh.crypto.cipher import GCMCipher
from asyncssh.encryption import get_encryption_algs
from asyncssh.kex import get_kex_algs
from asyncssh.kex_dh import MSG_KEX_ECDH_REPLY
from asyncssh.mac import _HMAC, _mac_handler, get_mac_algs
from asyncssh.packet import SSHPacket, Boolean, NameList, String, UInt32
from asyncssh.public_key import get_default_public_key_algs
from asyncssh.public_key import get_default_certificate_algs
from asyncssh.public_key import get_default_x509_certificate_algs
from .server import Server, ServerTestCase
from .util import asynctest, patch_extra_kex, patch_getaddrinfo
from .util import patch_getnameinfo, patch_gss
from .util import gss_available, nc_available, x509_available
class _CheckAlgsClientConnection(asyncssh.SSHClientConnection):
"""Test specification of encryption algorithms"""
def get_enc_algs(self):
"""Return the selected encryption algorithms"""
return self._enc_algs
def get_server_host_key_algs(self):
"""Return the selected server host key algorithms"""
return self._server_host_key_algs
class _SplitClientConnection(asyncssh.SSHClientConnection):
"""Test SSH messages being split into multiple packets"""
def data_received(self, data, datatype=None):
"""Handle incoming data on the connection"""
super().data_received(data[:3], datatype)
super().data_received(data[3:6], datatype)
super().data_received(data[6:9], datatype)
super().data_received(data[9:], datatype)
class _ReplayKexClientConnection(asyncssh.SSHClientConnection):
"""Test starting SSH key exchange while it is in progress"""
def replay_kex(self):
"""Replay last kexinit packet"""
self.send_packet(MSG_KEXINIT, self._client_kexinit[1:])
class _KeepaliveClientConnection(asyncssh.SSHClientConnection):
"""Test handling of keepalive requests on client"""
def _process_keepalive_at_openssh_dot_com_global_request(self, packet):
"""Process an incoming OpenSSH keepalive request"""
super()._process_keepalive_at_openssh_dot_com_global_request(packet)
self.disconnect(asyncssh.DISC_BY_APPLICATION, 'Keepalive')
class _KeepaliveClientConnectionFailure(asyncssh.SSHClientConnection):
"""Test handling of keepalive failures on client"""
def _process_keepalive_at_openssh_dot_com_global_request(self, packet):
"""Ignore an incoming OpenSSH keepalive request"""
class _KeepaliveServerConnection(asyncssh.SSHServerConnection):
"""Test handling of keepalive requests on server"""
def _process_keepalive_at_openssh_dot_com_global_request(self, packet):
"""Process an incoming OpenSSH keepalive request"""
super()._process_keepalive_at_openssh_dot_com_global_request(packet)
self.disconnect(asyncssh.DISC_BY_APPLICATION, 'Keepalive')
class _KeepaliveServerConnectionFailure(asyncssh.SSHServerConnection):
"""Test handling of keepalive failures on server"""
def _process_keepalive_at_openssh_dot_com_global_request(self, packet):
"""Ignore an incoming OpenSSH keepalive request"""
class _VersionedServerConnection(asyncssh.SSHServerConnection):
"""Test alternate SSH server version lines"""
def __init__(self, version, leading_text, newline, *args, **kwargs):
super().__init__(*args, **kwargs)
self._version = version
self._leading_text = leading_text
self._newline = newline
@classmethod
def create(cls, version=b'SSH-2.0-AsyncSSH_Test',
leading_text=b'', newline=b'\r\n'):
"""Return a connection factory which sends modified version lines"""
return (lambda *args, **kwargs: cls(version, leading_text,
newline, *args, **kwargs))
def _send_version(self):
"""Start the SSH handshake"""
self._server_version = self._version
self._extra.update(server_version=self._version.decode('ascii'))
self._send(self._leading_text + self._version + self._newline)
class _BadHostKeyServerConnection(asyncssh.SSHServerConnection):
"""Test returning invalid server host key"""
def get_server_host_key(self):
"""Return the chosen server host key"""
result = copy(super().get_server_host_key())
result.public_data = b'xxx'
return result
class _ExtInfoServerConnection(asyncssh.SSHServerConnection):
"""Test adding an unrecognized extension in extension info"""
def _send_ext_info(self):
"""Send extension information"""
self._extensions_to_send['xxx'] = b''
super()._send_ext_info()
class _BadSignatureServerConnection(asyncssh.SSHServerConnection):
"""Test returning a bad signature in host keys prove request"""
def _process_hostkeys_prove_00_at_openssh_dot_com_global_request(
self, packet):
"""Prove the server has private keys for all requested host keys"""
self._report_global_response(String(b''))
class _ProveFailedServerConnection(asyncssh.SSHServerConnection):
"""Test returning failure in host keys prove request"""
def _process_hostkeys_prove_00_at_openssh_dot_com_global_request(
self, packet):
"""Prove the server has private keys for all requested host keys"""
super()._process_hostkeys_prove_00_at_openssh_dot_com_global_request(
SSHPacket(String(b'')))
def _failing_get_mac(alg, key):
"""Replace HMAC class with FailingMAC"""
class _FailingMAC(_HMAC):
"""Test error in MAC validation"""
def verify(self, seq, packet, sig):
"""Verify the signature of a message"""
return super().verify(seq, packet + b'\xff', sig)
_, hash_size, args = _mac_handler[alg]
return _FailingMAC(key, hash_size, *args)
async def _slow_connect(*_args, **_kwargs):
"""Simulate a really slow connect that ends up timing out"""
await asyncio.sleep(5)
class _FailingGCMCipher(GCMCipher):
"""Test error in GCM tag verification"""
def verify_and_decrypt(self, header, data, mac):
"""Verify the signature of and decrypt a block of data"""
return super().verify_and_decrypt(header, data + b'\xff', mac)
class _ValidateHostKeyClient(asyncssh.SSHClient):
"""Test server host key/CA validation callbacks"""
def __init__(self, host_key=None, ca_key=None):
self._host_key = \
asyncssh.read_public_key(host_key) if host_key else None
self._ca_key = \
asyncssh.read_public_key(ca_key) if ca_key else None
def validate_host_public_key(self, host, addr, port, key):
"""Return whether key is an authorized key for this host"""
# pylint: disable=unused-argument
return key == self._host_key
def validate_host_ca_key(self, host, addr, port, key):
"""Return whether key is an authorized CA key for this host"""
# pylint: disable=unused-argument
return key == self._ca_key
class _PreAuthRequestClient(asyncssh.SSHClient):
"""Test sending a request prior to auth complete"""
def __init__(self):
self._conn = None
def connection_made(self, conn):
"""Save connection for use later"""
self._conn = conn
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'
class _InternalErrorClient(asyncssh.SSHClient):
"""Test of internal error exception handler"""
def connection_made(self, conn):
"""Raise an error when a new connection is opened"""
# pylint: disable=unused-argument
raise RuntimeError('Exception handler test')
class _ClientCleanupError(asyncssh.SSHClient):
"""Test of exception during client cleanup"""
def connection_lost(self, exc):
"""Raise an error when a client is cleaned up"""
# pylint: disable=unused-argument
raise RuntimeError('Exception in cleanup test')
class _TunnelServer(Server):
"""Allow forwarding to test server host key request tunneling"""
def connection_requested(self, dest_host, dest_port, orig_host, orig_port):
"""Handle a request to create a new connection"""
return True
class _AbortServer(Server):
"""Server for testing connection abort during auth"""
def begin_auth(self, username):
"""Abort the connection during auth"""
self._conn.abort()
return False
class _CloseDuringAuthServer(Server):
"""Server for testing connection close during long auth callback"""
def password_auth_supported(self):
"""Return that password auth is supported"""
return True
async def validate_password(self, username, password):
"""Delay validating password"""
# pylint: disable=unused-argument
await asyncio.sleep(1)
return False # pragma: no cover - closed before we get here
class _InternalErrorServer(Server):
"""Server for testing internal error during auth"""
def debug_msg_received(self, msg, lang, always_display):
"""Process a debug message"""
# pylint: disable=unused-argument
raise RuntimeError('Exception handler test')
class _InvalidAuthBannerServer(Server):
"""Server for testing invalid auth banner"""
def begin_auth(self, username):
"""Send an invalid auth banner"""
self._conn.send_auth_banner(b'\xff')
return False
class _AuthBannerRecordingClient(asyncssh.SSHClient):
"""Client which records auth banner"""
def __init__(self):
self.auth_banner = None
def auth_banner_received(self, msg, lang):
"""Record the client version reported in the auth banner"""
self.auth_banner = msg
class _VersionReportingServer(Server):
"""Server for testing custom client version"""
def begin_auth(self, username):
"""Report the client's version in the auth banner"""
version = self._conn.get_extra_info('client_version')
self._conn.send_auth_banner(version)
return False
@patch_gss
@patch('asyncssh.connection.SSHClientConnection', _CheckAlgsClientConnection)
class _TestConnection(ServerTestCase):
"""Unit tests for AsyncSSH connection API"""
# pylint: disable=too-many-public-methods
@classmethod
async def start_server(cls):
"""Start an SSH server to connect to"""
def acceptor(conn):
"""Acceptor for SSH connections"""
conn.logger.info('Acceptor called')
return (await cls.create_server(_TunnelServer, gss_host=(),
compression_algs='*',
encryption_algs='*',
kex_algs='*', mac_algs='*',
acceptor=acceptor))
async def get_server_host_key(self, **kwargs):
"""Get host key from the test server"""
return (await asyncssh.get_server_host_key(self._server_addr,
self._server_port,
**kwargs))
async def _check_version(self, *args, **kwargs):
"""Check alternate SSH server version lines"""
with patch('asyncssh.connection.SSHServerConnection',
_VersionedServerConnection.create(*args, **kwargs)):
async with self.connect():
pass
@asynctest
async def test_connect(self):
"""Test connecting with async context manager"""
async with self.connect() as conn:
pass
self.assertTrue(conn.is_closed())
@asynctest
async def test_connect_sock(self):
"""Test connecting using an already-connected socket"""
sock = socket.socket()
await self.loop.sock_connect(sock, (self._server_addr,
self._server_port))
async with asyncssh.connect(sock=sock):
pass
@unittest.skipUnless(nc_available, 'Netcat not available')
@asynctest
async def test_connect_non_tcp_sock(self):
"""Test connecting using an non-TCP socket"""
sock1, sock2 = socket.socketpair()
proc = await asyncio.create_subprocess_exec(
'nc', str(self._server_addr), str(self._server_port),
stdin=sock1, stdout=sock1, stderr=sock1)
async with asyncssh.connect(
self._server_addr, self._server_port, sock=sock2):
pass
await proc.wait()
sock1.close()
@asynctest
async def test_run_client(self):
"""Test running an SSH client on an already-connected socket"""
sock = socket.socket()
await self.loop.sock_connect(sock, (self._server_addr,
self._server_port))
async with self.run_client(sock):
pass
@asynctest
async def test_connect_encrypted_key(self):
"""Test connecting with encrypted client key and no passphrase"""
async with self.connect(client_keys='ckey_encrypted',
ignore_encrypted=True):
pass
with self.assertRaises(asyncssh.KeyImportError):
await self.connect(client_keys='ckey_encrypted')
with open('config', 'w') as f:
f.write('IdentityFile ckey_encrypted')
async with self.connect(config='config'):
pass
with self.assertRaises(asyncssh.KeyImportError):
await self.connect(config='config', ignore_encrypted=False)
@asynctest
async def test_connect_invalid_options_type(self):
"""Test connecting using options using incorrect type of options"""
options = asyncssh.SSHServerConnectionOptions()
with self.assertRaises(TypeError):
await self.connect(options=options)
@asynctest
async def test_connect_invalid_option_name(self):
"""Test connecting using incorrect option name"""
with self.assertRaises(TypeError):
await self.connect(xxx=1)
@asynctest
async def test_connect_failure(self):
"""Test failure connecting"""
with self.assertRaises(OSError):
await asyncssh.connect('\xff')
@asynctest
async def test_connect_failure_without_agent(self):
"""Test failure connecting with SSH agent disabled"""
with self.assertRaises(OSError):
await asyncssh.connect('\xff', agent_path=None)
@asynctest
async def test_connect_timeout_exceeded(self):
"""Test connect timeout exceeded"""
with self.assertRaises(asyncio.TimeoutError):
with patch('asyncio.BaseEventLoop.create_connection',
_slow_connect):
await asyncssh.connect('', connect_timeout=1)
@asynctest
async def test_connect_timeout_exceeded_string(self):
"""Test connect timeout exceeded with string value"""
with self.assertRaises(asyncio.TimeoutError):
with patch('asyncio.BaseEventLoop.create_connection',
_slow_connect):
await asyncssh.connect('', connect_timeout='0m1s')
@asynctest
async def test_connect_timeout_exceeded_tunnel(self):
"""Test connect timeout exceeded"""
with self.assertRaises(asyncio.TimeoutError):
with patch('asyncio.BaseEventLoop.create_connection',
_slow_connect):
await asyncssh.listen(server_host_keys=['skey'],
tunnel='', connect_timeout=1)
@asynctest
async def test_invalid_connect_timeout(self):
"""Test invalid connect timeout"""
with self.assertRaises(ValueError):
await self.connect(connect_timeout=-1)
@asynctest
async def test_connect_tcp_keepalive_off(self):
"""Test connecting with TCP keepalive disabled"""
async with self.connect(tcp_keepalive=False) as conn:
sock = conn.get_extra_info('socket')
self.assertEqual(bool(sock.getsockopt(socket.SOL_SOCKET,
socket.SO_KEEPALIVE)), False)
@asynctest
async def test_split_version(self):
"""Test version split across two packets"""
with patch('asyncssh.connection.SSHClientConnection',
_SplitClientConnection):
async with self.connect():
pass
@asynctest
async def test_version_1_99(self):
"""Test SSH server version 1.99"""
await self._check_version(b'SSH-1.99-Test')
@asynctest
async def test_banner_before_version(self):
"""Test banner lines before SSH server version"""
await self._check_version(leading_text=b'Banner 1\r\nBanner 2\r\n')
@asynctest
async def test_banner_line_too_long(self):
"""Test excessively long banner line"""
with self.assertRaises(asyncssh.ProtocolError):
await self._check_version(leading_text=8192*b'*' + b'\r\n')
@asynctest
async def test_too_many_banner_lines(self):
"""Test too many banner lines"""
with self.assertRaises(asyncssh.ProtocolError):
await self._check_version(leading_text=2048*b'Banner line\r\n')
@asynctest
async def test_version_without_cr(self):
"""Test SSH server version with LF instead of CRLF"""
await self._check_version(newline=b'\n')
@asynctest
async def test_version_line_too_long(self):
"""Test excessively long version line"""
with self.assertRaises(asyncssh.ProtocolError):
await self._check_version(newline=256*b'*' + b'\r\n')
@asynctest
async def test_unknown_version(self):
"""Test unknown SSH server version"""
with self.assertRaises(asyncssh.ProtocolNotSupported):
await self._check_version(b'SSH-1.0-Test')
@asynctest
async def test_no_server_host_keys(self):
"""Test starting a server with no host keys"""
with self.assertRaises(ValueError):
await asyncssh.create_server(Server, server_host_keys=[],
gss_host=None)
@asynctest
async def test_duplicate_type_server_host_keys(self):
"""Test starting a server with duplicate host key types"""
with self.assertRaises(ValueError):
await asyncssh.listen(server_host_keys=['skey', 'skey'])
@asynctest
async def test_reserved_server_host_keys(self):
"""Test reserved host keys with host key sending enabled"""
async with self.listen(server_host_keys=['skey', 'skey'],
send_server_host_keys=True):
pass
@asynctest
async def test_get_server_host_key(self):
"""Test retrieving a server host key"""
keylist = asyncssh.load_public_keys('skey.pub')
key = await self.get_server_host_key()
self.assertEqual(key, keylist[0])
@asynctest
async def test_get_server_host_key_tunnel(self):
"""Test retrieving a server host key while tunneling over SSH"""
keylist = asyncssh.load_public_keys('skey.pub')
async with self.connect() as conn:
key = await self.get_server_host_key(tunnel=conn)
self.assertEqual(key, keylist[0])
@asynctest
async def test_get_server_host_key_connect_failure(self):
"""Test failure connecting when retrieving a server host key"""
with self.assertRaises(OSError):
await asyncssh.get_server_host_key('\xff')
@unittest.skipUnless(nc_available, 'Netcat not available')
@asynctest
async def test_get_server_host_key_proxy(self):
"""Test retrieving a server host key using proxy command"""
keylist = asyncssh.load_public_keys('skey.pub')
proxy_command = ('nc', str(self._server_addr), str(self._server_port))
key = await self.get_server_host_key(proxy_command=proxy_command)
self.assertEqual(key, keylist[0])
@unittest.skipUnless(nc_available, 'Netcat not available')
@asynctest
async def test_get_server_host_key_proxy_failure(self):
"""Test failure retrieving a server host key using proxy command"""
# Leave out arguments to 'nc' to trigger a failure
proxy_command = 'nc'
with self.assertRaises((OSError, asyncssh.ConnectionLost)):
await self.connect(proxy_command=proxy_command)
@asynctest
async def test_known_hosts_not_present(self):
"""Test connecting with default known hosts file not present"""
try:
os.rename(os.path.join('.ssh', 'known_hosts'),
os.path.join('.ssh', 'known_hosts.save'))
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect()
finally:
os.rename(os.path.join('.ssh', 'known_hosts.save'),
os.path.join('.ssh', 'known_hosts'))
@unittest.skipIf(sys.platform == 'win32', 'skip chmod tests on Windows')
@asynctest
async def test_known_hosts_not_readable(self):
"""Test connecting with default known hosts file not readable"""
try:
os.chmod(os.path.join('.ssh', 'known_hosts'), 0)
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect()
finally:
os.chmod(os.path.join('.ssh', 'known_hosts'), 0o644)
@asynctest
async def test_known_hosts_none(self):
"""Test connecting with known hosts checking disabled"""
default_algs = get_default_x509_certificate_algs() + \
get_default_certificate_algs() + \
get_default_public_key_algs()
async with self.connect(known_hosts=None) as conn:
self.assertEqual(conn.get_server_host_key_algs(), default_algs)
@asynctest
async def test_known_hosts_none_in_config(self):
"""Test connecting with known hosts checking disabled in config file"""
with open('config', 'w') as f:
f.write('UserKnownHostsFile none')
async with self.connect(config='config'):
pass
@asynctest
async def test_known_hosts_none_without_x509(self):
"""Test connecting with known hosts checking and X.509 disabled"""
non_x509_algs = get_default_certificate_algs() + \
get_default_public_key_algs()
async with self.connect(known_hosts=None,
x509_trusted_certs=None) as conn:
self.assertEqual(conn.get_server_host_key_algs(), non_x509_algs)
@asynctest
async def test_known_hosts_multiple_keys(self):
"""Test connecting with multiple trusted known hosts keys"""
rsa_algs = [alg for alg in get_default_public_key_algs()
if b'rsa' in alg]
async with self.connect(x509_trusted_certs=None,
known_hosts=(['skey.pub', 'skey.pub'],
[], [])) as conn:
self.assertEqual(conn.get_server_host_key_algs(), rsa_algs)
@asynctest
async def test_known_hosts_ca(self):
"""Test connecting with a known hosts CA"""
async with self.connect(known_hosts=([], ['skey.pub'], [])) as conn:
self.assertEqual(conn.get_server_host_key_algs(),
get_default_x509_certificate_algs() +
get_default_certificate_algs())
@asynctest
async def test_known_hosts_bytes(self):
"""Test connecting with known hosts passed in as bytes"""
with open('skey.pub', 'rb') as f:
skey = f.read()
async with self.connect(known_hosts=([skey], [], [])):
pass
@asynctest
async def test_known_hosts_keylist_file(self):
"""Test connecting with known hosts passed as a keylist file"""
async with self.connect(known_hosts=('skey.pub', [], [])):
pass
@asynctest
async def test_known_hosts_sshkeys(self):
"""Test connecting with known hosts passed in as SSHKeys"""
keylist = asyncssh.load_public_keys('skey.pub')
async with self.connect(known_hosts=(keylist, [], [])) as conn:
self.assertEqual(conn.get_server_host_key(), keylist[0])
@asynctest
async def test_read_known_hosts(self):
"""Test connecting with known hosts object from read_known_hosts"""
known_hosts = asyncssh.read_known_hosts('~/.ssh/known_hosts')
async with self.connect(known_hosts=known_hosts):
pass
@asynctest
async def test_read_known_hosts_filelist(self):
"""Test connecting with known hosts from read_known_hosts file list"""
known_hosts = asyncssh.read_known_hosts(['~/.ssh/known_hosts'])
async with self.connect(known_hosts=known_hosts):
pass
@asynctest
async def test_import_known_hosts(self):
"""Test connecting with known hosts object from import_known_hosts"""
known_hosts_path = os.path.join('.ssh', 'known_hosts')
with open(known_hosts_path) as f:
known_hosts = asyncssh.import_known_hosts(f.read())
async with self.connect(known_hosts=known_hosts):
pass
@asynctest
async def test_validate_host_ca_callback(self):
"""Test callback to validate server CA key"""
def client_factory():
"""Return an SSHClient which can validate the sevrer CA key"""
return _ValidateHostKeyClient(ca_key='skey.pub')
conn, _ = await self.create_connection(client_factory,
known_hosts=([], [], []))
async with conn:
pass
@asynctest
async def test_untrusted_known_hosts_ca(self):
"""Test untrusted server CA key"""
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect(known_hosts=([], ['ckey.pub'], []))
@asynctest
async def test_untrusted_host_key_callback(self):
"""Test callback to validate server host key returning failure"""
def client_factory():
"""Return an SSHClient which can validate the sevrer host key"""
return _ValidateHostKeyClient(host_key='ckey.pub')
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.create_connection(client_factory,
known_hosts=([], [], []))
@asynctest
async def test_untrusted_host_ca_callback(self):
"""Test callback to validate server CA key returning failure"""
def client_factory():
"""Return an SSHClient which can validate the sevrer CA key"""
return _ValidateHostKeyClient(ca_key='ckey.pub')
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.create_connection(client_factory,
known_hosts=([], [], []))
@asynctest
async def test_revoked_known_hosts_key(self):
"""Test revoked server host key"""
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect(known_hosts=(['ckey.pub'], [], ['skey.pub']))
@asynctest
async def test_revoked_known_hosts_ca(self):
"""Test revoked server CA key"""
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect(known_hosts=([], ['ckey.pub'], ['skey.pub']))
@asynctest
async def test_empty_known_hosts(self):
"""Test empty known hosts list"""
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect(known_hosts=([], [], []))
@asynctest
async def test_invalid_server_host_key(self):
"""Test invalid server host key"""
with patch('asyncssh.connection.SSHServerConnection',
_BadHostKeyServerConnection):
with self.assertRaises(asyncssh.HostKeyNotVerifiable):
await self.connect()
@asynctest
async def test_changing_server_host_key(self):
"""Test changing server host key"""
self._server.update(server_host_keys=['skey_ecdsa'])
async with self.connect(known_hosts=None):
pass
self._server.update(server_host_keys=['skey'])
with self.assertRaises(asyncssh.KeyExchangeFailed):
await self.connect(known_hosts=(['skey_ecdsa.pub'], [], []))
@asynctest
async def test_kex_algs(self):
"""Test connecting with different key exchange algorithms"""
for kex in get_kex_algs():
kex = kex.decode('ascii')
if kex.startswith('gss-') and not gss_available: # pragma: no cover
continue
with self.subTest(kex_alg=kex):
async with self.connect(kex_algs=[kex], gss_host='1'):
pass
@asynctest
async def test_duplicate_encryption_algs(self):
"""Test connecting with a duplicated encryption algorithm"""
with patch('asyncssh.connection.SSHClientConnection',
_CheckAlgsClientConnection):
async with self.connect(
encryption_algs=['aes256-ctr', 'aes256-ctr']) as conn:
self.assertEqual(conn.get_enc_algs(), [b'aes256-ctr'])
@asynctest
async def test_leading_encryption_alg(self):
"""Test adding a new first encryption algorithm"""
with patch('asyncssh.connection.SSHClientConnection',
_CheckAlgsClientConnection):
async with self.connect(encryption_algs='^aes256-ctr') as conn:
self.assertEqual(conn.get_enc_algs()[0], b'aes256-ctr')
@asynctest
async def test_trailing_encryption_alg(self):
"""Test adding a new last encryption algorithm"""
with patch('asyncssh.connection.SSHClientConnection',
_CheckAlgsClientConnection):
async with self.connect(encryption_algs='+3des-cbc') as conn:
self.assertEqual(conn.get_enc_algs()[-1], b'3des-cbc')
@asynctest
async def test_removing_encryption_alg(self):
"""Test removing an encryption algorithm"""
with patch('asyncssh.connection.SSHClientConnection',
_CheckAlgsClientConnection):
async with self.connect(encryption_algs='-aes256-ctr') as conn:
self.assertTrue(b'aes256-ctr' not in conn.get_enc_algs())
@asynctest
async def test_empty_kex_algs(self):
"""Test connecting with an empty list of key exchange algorithms"""
with self.assertRaises(ValueError):
await self.connect(kex_algs=[])
@asynctest
async def test_invalid_kex_alg(self):
"""Test connecting with invalid key exchange algorithm"""
with self.assertRaises(ValueError):
await self.connect(kex_algs=['xxx'])
@asynctest
async def test_invalid_kex_alg_str(self):
"""Test connecting with invalid key exchange algorithm pattern"""
with self.assertRaises(ValueError):
await self.connect(kex_algs='diffie-hallman-group14-sha1,xxx')
@asynctest
async def test_invalid_kex_alg_config(self):
"""Test connecting with invalid key exchange algorithm config"""
with open('config', 'w') as f:
f.write('KexAlgorithms diffie-hellman-group14-sha1,xxx')
async with self.connect(config='config'):
pass
@asynctest
async def test_unsupported_kex_alg(self):
"""Test connecting with unsupported key exchange algorithm"""
def unsupported_kex_alg():
"""Patched version of get_kex_algs to test unsupported algorithm"""
return [b'fail'] + get_kex_algs()