-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathconnection.py
More file actions
9952 lines (7847 loc) · 407 KB
/
Copy pathconnection.py
File metadata and controls
9952 lines (7847 loc) · 407 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) 2013-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
"""SSH connection handlers"""
import asyncio
import functools
import getpass
import inspect
import io
import ipaddress
import os
import shlex
import socket
import sys
import tempfile
import time
from collections import OrderedDict
from functools import partial
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Any, AnyStr, Awaitable, Callable, Dict
from typing import Generic, List, Mapping, Optional, Sequence, Set, Tuple
from typing import Type, TypeVar, Union, cast
from typing_extensions import Protocol, Self
from .agent import SSHAgentClient, SSHAgentListener
from .auth import Auth, ClientAuth, KbdIntChallenge, KbdIntPrompts
from .auth import KbdIntResponse, PasswordChangeResponse
from .auth import get_supported_client_auth_methods, lookup_client_auth
from .auth import get_supported_server_auth_methods, lookup_server_auth
from .auth_keys import SSHAuthorizedKeys, read_authorized_keys
from .channel import SSHChannel, SSHClientChannel, SSHServerChannel
from .channel import SSHTCPChannel, SSHUNIXChannel, SSHTunTapChannel
from .channel import SSHX11Channel, SSHAgentChannel
from .client import SSHClient
from .compression import Compressor, Decompressor, get_compression_algs
from .compression import get_default_compression_algs, get_compression_params
from .compression import get_compressor, get_decompressor
from .config import ConfigPaths, SSHConfig, SSHClientConfig, SSHServerConfig
from .constants import DEFAULT_LANG, DEFAULT_PORT
from .constants import DISC_BY_APPLICATION
from .constants import EXTENDED_DATA_STDERR
from .constants import MSG_DISCONNECT, MSG_IGNORE, MSG_UNIMPLEMENTED, MSG_DEBUG
from .constants import MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT, MSG_EXT_INFO
from .constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_OPEN_CONFIRMATION
from .constants import MSG_CHANNEL_OPEN_FAILURE
from .constants import MSG_CHANNEL_FIRST, MSG_CHANNEL_LAST
from .constants import MSG_KEXINIT, MSG_NEWKEYS, MSG_KEX_FIRST, MSG_KEX_LAST
from .constants import MSG_USERAUTH_REQUEST, MSG_USERAUTH_FAILURE
from .constants import MSG_USERAUTH_SUCCESS, MSG_USERAUTH_BANNER
from .constants import MSG_USERAUTH_FIRST, MSG_USERAUTH_LAST
from .constants import MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS
from .constants import MSG_REQUEST_FAILURE
from .constants import OPEN_ADMINISTRATIVELY_PROHIBITED, OPEN_CONNECT_FAILED
from .constants import OPEN_UNKNOWN_CHANNEL_TYPE
from .encryption import Encryption, get_encryption_algs
from .encryption import get_default_encryption_algs
from .encryption import encryption_needs_mac
from .encryption import get_encryption_params, get_encryption
from .forward import SSHForwarder
from .gss import GSSBase, GSSClient, GSSServer, GSSError
from .kex import Kex, get_kex_algs, get_default_kex_algs
from .kex import expand_kex_algs, get_kex
from .keysign import KeySignPath, SSHKeySignKeyPair
from .keysign import find_keysign, get_keysign_keys
from .known_hosts import KnownHostsArg, match_known_hosts
from .listener import ListenKey, SSHListener
from .listener import SSHTCPClientListener, SSHUNIXClientListener
from .listener import TCPListenerFactory, UNIXListenerFactory
from .listener import create_tcp_forward_listener, create_unix_forward_listener
from .listener import create_socks_listener
from .logging import SSHLogger, logger
from .mac import get_mac_algs, get_default_mac_algs
from .misc import BytesOrStr, BytesOrStrDict, DefTuple, Env, EnvSeq, FilePath
from .misc import HostPort, IPNetwork, MaybeAwait, OptExcInfo, Options, SockAddr
from .misc import ChannelListenError, ChannelOpenError, CompressionError
from .misc import DisconnectError, ConnectionLost, HostKeyNotVerifiable
from .misc import KeyExchangeFailed, IllegalUserName, MACError
from .misc import PasswordChangeRequired, PermissionDenied, ProtocolError
from .misc import ProtocolNotSupported, ServiceNotAvailable
from .misc import TermModesArg, TermSizeArg
from .misc import async_context_manager, construct_disc_error, encode_env
from .misc import get_symbol_names, ip_address, lookup_env, map_handler_name
from .misc import parse_byte_count, parse_time_interval, split_args
from .packet import Boolean, Byte, NameList, String, UInt32, PacketDecodeError
from .packet import SSHPacket, SSHPacketHandler, SSHPacketLogger
from .pattern import WildcardPattern, WildcardPatternList
from .pkcs11 import load_pkcs11_keys
from .process import PIPE, ProcessSource, ProcessTarget
from .process import SSHServerProcessFactory, SSHCompletedProcess
from .process import SSHClientProcess, SSHServerProcess
from .public_key import CERT_TYPE_HOST, CERT_TYPE_USER, KeyImportError
from .public_key import CertListArg, IdentityListArg, KeyListArg, SigningKey
from .public_key import KeyPairListArg, X509CertPurposes, SSHKey, SSHKeyPair
from .public_key import SSHCertificate, SSHOpenSSHCertificate
from .public_key import SSHX509Certificate, SSHX509CertificateChain
from .public_key import decode_ssh_public_key, decode_ssh_certificate
from .public_key import get_public_key_algs, get_default_public_key_algs
from .public_key import get_certificate_algs, get_default_certificate_algs
from .public_key import get_x509_certificate_algs
from .public_key import get_default_x509_certificate_algs
from .public_key import load_keypairs, load_default_keypairs
from .public_key import load_public_keys, load_default_host_public_keys
from .public_key import load_certificates
from .public_key import load_identities, load_default_identities
from .saslprep import saslprep, SASLPrepError
from .server import SSHServer
from .session import DataType, SSHClientSession, SSHServerSession
from .session import SSHTCPSession, SSHUNIXSession, SSHTunTapSession
from .session import SSHClientSessionFactory, SSHTCPSessionFactory
from .session import SSHUNIXSessionFactory, SSHTunTapSessionFactory
from .sftp import MIN_SFTP_VERSION, SFTPClient, SFTPServer
from .sftp import start_sftp_client
from .stream import SSHReader, SSHWriter, SFTPServerFactory
from .stream import SSHSocketSessionFactory, SSHServerSessionFactory
from .stream import SSHClientStreamSession, SSHServerStreamSession
from .stream import SSHTCPStreamSession, SSHUNIXStreamSession
from .stream import SSHTunTapStreamSession
from .subprocess import SSHSubprocessTransport, SSHSubprocessProtocol
from .subprocess import SubprocessFactory, SSHSubprocessWritePipe
from .tuntap import SSH_TUN_MODE_POINTTOPOINT, SSH_TUN_MODE_ETHERNET
from .tuntap import SSH_TUN_UNIT_ANY, create_tuntap
from .version import __version__
from .x11 import SSHX11ClientForwarder
from .x11 import SSHX11ClientListener, SSHX11ServerListener
from .x11 import create_x11_client_listener, create_x11_server_listener
if TYPE_CHECKING:
# pylint: disable=unused-import
from .crypto import X509NamePattern
_ClientFactory = Callable[[], SSHClient]
_ServerFactory = Callable[[], SSHServer]
_ProtocolFactory = Union[_ClientFactory, _ServerFactory]
_Conn = TypeVar('_Conn', bound='SSHConnection')
_Options = TypeVar('_Options', bound='SSHConnectionOptions')
_ServerHostKeysHandler = Optional[Callable[[List[SSHKey], List[SSHKey],
List[SSHKey], List[SSHKey]],
MaybeAwait[None]]]
class _TunnelProtocol(Protocol):
"""Base protocol for connections to tunnel SSH over"""
def close(self) -> None:
"""Close this tunnel"""
async def wait_closed(self):
"""Wait for this tunnel to close"""
class _TunnelConnectorProtocol(_TunnelProtocol, Protocol):
"""Protocol to open a connection to tunnel an SSH connection over"""
async def create_connection(
self, session_factory: SSHTCPSessionFactory[bytes],
remote_host: str, remote_port: int) -> \
Tuple[SSHTCPChannel[bytes], SSHTCPSession[bytes]]:
"""Create an outbound tunnel connection"""
class _TunnelListenerProtocol(_TunnelProtocol, Protocol):
"""Protocol to open a listener to tunnel SSH connections over"""
async def create_server(self, session_factory: TCPListenerFactory,
listen_host: str, listen_port: int) -> SSHListener:
"""Create an inbound tunnel listener"""
_AcceptHandler = Optional[Callable[['SSHConnection'], MaybeAwait[None]]]
_ErrorHandler = Optional[Callable[['SSHConnection',
Optional[Exception]], None]]
_OpenHandler = Callable[[SSHPacket], Tuple[SSHClientChannel, SSHClientSession]]
_PacketHandler = Callable[[SSHPacket], None]
_AlgsArg = DefTuple[Union[str, Sequence[str]]]
_AuthArg = DefTuple[bool]
_AuthKeysArg = DefTuple[Union[None, str, List[str], SSHAuthorizedKeys]]
_ClientHostKey = Union[SSHKeyPair, SSHKeySignKeyPair]
_ClientKeysArg = Union[KeyListArg, KeyPairListArg]
_CNAMEArg = DefTuple[Union[Sequence[str], Sequence[Tuple[str, str]]]]
_GlobalRequest = Tuple[Optional[_PacketHandler], SSHPacket, bool]
_GlobalRequestResult = Tuple[int, SSHPacket]
_KeyOrCertOptions = Mapping[str, object]
_ListenerArg = Union[bool, SSHListener]
_ProxyCommand = Optional[Union[str, Sequence[str]]]
_RequestPTY = Union[bool, str]
_TCPServerHandlerFactory = Callable[[str, int], SSHSocketSessionFactory]
_UNIXServerHandlerFactory = Callable[[], SSHSocketSessionFactory]
_TunnelConnector = Union[None, str, _TunnelConnectorProtocol]
_TunnelListener = Union[None, str, _TunnelListenerProtocol]
_VersionArg = DefTuple[BytesOrStr]
SSHAcceptHandler = Callable[[str, int], MaybeAwait[bool]]
# SSH service names
_USERAUTH_SERVICE = b'ssh-userauth'
_CONNECTION_SERVICE = b'ssh-connection'
# Max banner and version line length and count
_MAX_BANNER_LINES = 1024
_MAX_BANNER_LINE_LEN = 8192
_MAX_VERSION_LINE_LEN = 255
# Max allowed username length
_MAX_USERNAME_LEN = 1024
# Default rekey parameters
_DEFAULT_REKEY_BYTES = 1 << 30 # 1 GiB
_DEFAULT_REKEY_SECONDS = 3600 # 1 hour
# Default login timeout
_DEFAULT_LOGIN_TIMEOUT = 120 # 2 minutes
# Default keepalive interval and count max
_DEFAULT_KEEPALIVE_INTERVAL = 0 # disabled by default
_DEFAULT_KEEPALIVE_COUNT_MAX = 3
# Default channel parameters
_DEFAULT_WINDOW = 2*1024*1024 # 2 MiB
_DEFAULT_MAX_PKTSIZE = 32768 # 32 kiB
# Default line editor parameters
_DEFAULT_LINE_HISTORY = 1000 # 1000 lines
_DEFAULT_MAX_LINE_LENGTH = 1024 # 1024 characters
async def _canonicalize_host(loop: asyncio.AbstractEventLoop,
options: 'SSHConnectionOptions') -> Optional[str]:
"""Canonicalize a host name"""
host = options.orig_host
if not options.canonicalize_hostname or not options.canonical_domains:
logger.info('Host canonicalization disabled')
return None
if host.count('.') > options.canonicalize_max_dots:
logger.info('Host canonicalization skipped due to max dots')
return None
try:
ipaddress.ip_address(host)
except ValueError:
pass
else:
logger.info('Hostname canonicalization skipped on IP address')
return None
logger.debug1('Beginning hostname canonicalization')
for domain in options.canonical_domains:
logger.debug1(' Checking domain %s', domain)
canon_host = f'{host}.{domain}'
try:
addrinfo = await loop.getaddrinfo(
canon_host, 0, flags=socket.AI_CANONNAME)
except socket.gaierror:
continue
cname = addrinfo[0][3]
if cname and cname != canon_host:
logger.debug1(' Checking CNAME rules for hostname %s '
'with CNAME %s', canon_host, cname)
for patterns in options.canonicalize_permitted_cnames:
host_pat, cname_pat = map(WildcardPatternList, patterns)
if host_pat.matches(canon_host) and cname_pat.matches(cname):
logger.info('Hostname canonicalization to CNAME '
'applied: %s -> %s', options.host, cname)
return cname
logger.info('Hostname canonicalization applied: %s -> %s',
options.host, canon_host)
return canon_host
if not options.canonicalize_fallback_local:
logger.info('Hostname canonicalization failed (fallback disabled)')
raise OSError(f'Unable to canonicalize hostname "{host}"')
logger.info('Hostname canonicalization failed, using local resolver')
return None
async def _open_proxy(
loop: asyncio.AbstractEventLoop, command: Sequence[str],
conn_factory: Callable[[], _Conn]) -> _Conn:
"""Open a tunnel running a proxy command"""
class _ProxyCommandTunnel(asyncio.SubprocessProtocol):
"""SSH proxy command tunnel"""
def __init__(self) -> None:
super().__init__()
self._transport: Optional[asyncio.SubprocessTransport] = None
self._stdin: Optional[asyncio.WriteTransport] = None
self._conn = conn_factory()
self._close_event = asyncio.Event()
def get_extra_info(self, name: str, default: Any = None) -> Any:
"""Return extra information associated with this tunnel"""
assert self._transport is not None
return self._transport.get_extra_info(name, default)
def get_conn(self) -> _Conn:
"""Return the connection associated with this tunnel"""
return self._conn
def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""Handle startup of the subprocess"""
self._transport = cast(asyncio.SubprocessTransport, transport)
self._stdin = cast(asyncio.WriteTransport,
self._transport.get_pipe_transport(0))
self._conn.connection_made(cast(asyncio.BaseTransport, self))
def pipe_data_received(self, fd: int, data: bytes) -> None:
"""Handle data received from this tunnel"""
# pylint: disable=unused-argument
self._conn.data_received(data)
def pipe_connection_lost(self, fd: int,
exc: Optional[Exception]) -> None:
"""Handle when this tunnel is closed"""
# pylint: disable=unused-argument
self._conn.connection_lost(exc)
def process_exited(self):
"""Called when the child process has exited"""
self._close_event.set()
def write(self, data: bytes) -> None:
"""Write data to this tunnel"""
assert self._stdin is not None
self._stdin.write(data)
def abort(self) -> None:
"""Forcibly close this tunnel"""
self.close()
def close(self) -> None:
"""Close this tunnel"""
if self._transport: # pragma: no cover
self._transport.close()
self._transport = None
async def wait_closed(self):
"""Wait for this subprocess to exit"""
await self._close_event.wait()
_, tunnel = await loop.subprocess_exec(_ProxyCommandTunnel, *command,
start_new_session=True)
conn = cast(_Conn, cast(_ProxyCommandTunnel, tunnel).get_conn())
conn.set_tunnel(tunnel)
return conn
async def _open_tunnel(tunnels: object, options: _Options,
config: DefTuple[ConfigPaths]) -> \
Optional['SSHClientConnection']:
"""Parse and open connection to tunnel over"""
username: DefTuple[str]
port: DefTuple[int]
if isinstance(tunnels, str):
conn: Optional[SSHClientConnection] = None
for tunnel in tunnels.split(','):
if '@' in tunnel:
username, host = tunnel.rsplit('@', 1)
else:
username, host = (), tunnel
if ':' in host:
host, port_str = host.rsplit(':', 1)
port = int(port_str)
else:
port = ()
last_conn = conn
conn = await connect(host, port, username=username,
passphrase=options.passphrase,
tunnel=conn or (), config=config)
conn.set_tunnel(last_conn)
if options.canonicalize_hostname != 'always':
options.canonicalize_hostname = False
return conn
else:
return None
async def _connect(options: _Options, config: DefTuple[ConfigPaths],
loop: asyncio.AbstractEventLoop, flags: int,
sock: Optional[socket.socket],
conn_factory: Callable[[], _Conn], msg: str) -> _Conn:
"""Make outbound TCP or SSH tunneled connection"""
options.waiter = loop.create_future()
canon_host = await _canonicalize_host(loop, options)
host = canon_host if canon_host else options.orig_host
canonical = bool(canon_host)
final = options.config.has_match_final()
if canonical or final:
options.update(host=host, reload=True, canonical=canonical, final=final)
host = options.host
port = options.port
tunnel = options.tunnel
family = options.family
local_addr = options.local_addr
proxy_command = options.proxy_command
free_conn = True
new_tunnel = await _open_tunnel(tunnel, options, config)
tunnel: _TunnelConnectorProtocol
try:
if sock:
logger.info('%s already-connected socket', msg)
_, session = await loop.create_connection(conn_factory, sock=sock)
conn = cast(_Conn, session)
elif new_tunnel:
new_tunnel.logger.info('%s %s via %s', msg, (host, port), tunnel)
# pylint: disable=broad-except
try:
_, tunnel_session = await new_tunnel.create_connection(
cast(SSHTCPSessionFactory[bytes], conn_factory),
host, port)
except Exception:
new_tunnel.close()
await new_tunnel.wait_closed()
raise
else:
conn = cast(_Conn, tunnel_session)
conn.set_tunnel(new_tunnel)
elif tunnel:
tunnel_logger = getattr(tunnel, 'logger', logger)
tunnel_logger.info('%s %s via SSH tunnel', msg, (host, port))
_, tunnel_session = await tunnel.create_connection(
cast(SSHTCPSessionFactory[bytes], conn_factory),
host, port)
conn = cast(_Conn, tunnel_session)
elif proxy_command:
conn = await _open_proxy(loop, proxy_command, conn_factory)
else:
logger.info('%s %s', msg, (host, port))
_, session = await loop.create_connection(
conn_factory, host, port, family=family,
flags=flags, local_addr=local_addr)
conn = cast(_Conn, session)
except asyncio.CancelledError:
options.waiter.cancel()
raise
conn.set_extra_info(host=host, port=port)
try:
await options.waiter
free_conn = False
return conn
finally:
if free_conn:
conn.abort()
await conn.wait_closed()
async def _listen(options: _Options, config: DefTuple[ConfigPaths],
loop: asyncio.AbstractEventLoop, flags: int,
backlog: int, sock: Optional[socket.socket],
reuse_address: Optional[bool], reuse_port: Optional[bool],
conn_factory: Callable[[], _Conn],
msg: str) -> 'SSHAcceptor':
"""Make inbound TCP or SSH tunneled listener"""
def tunnel_factory(_orig_host: str, _orig_port: int) -> SSHTCPSession:
"""Ignore original host and port"""
return cast(SSHTCPSession, conn_factory())
host = options.host
port = options.port
tunnel = options.tunnel
family = options.family
new_tunnel = await _open_tunnel(tunnel, options, config)
tunnel: _TunnelListenerProtocol
if sock:
logger.info('%s already-connected socket', msg)
server: asyncio.AbstractServer = await loop.create_server(
conn_factory, sock=sock, backlog=backlog,
reuse_address=reuse_address, reuse_port=reuse_port)
elif new_tunnel:
new_tunnel.logger.info('%s %s via %s', msg, (host, port), tunnel)
# pylint: disable=broad-except
try:
tunnel_server = await new_tunnel.create_server(
tunnel_factory, host, port)
except Exception:
new_tunnel.close()
await new_tunnel.wait_closed()
raise
else:
tunnel_server.set_tunnel(new_tunnel)
server = cast(asyncio.AbstractServer, tunnel_server)
elif tunnel:
tunnel_logger = getattr(tunnel, 'logger', logger)
tunnel_logger.info('%s %s via SSH tunnel', msg, (host, port))
tunnel_server = await tunnel.create_server(tunnel_factory, host, port)
server = cast(asyncio.AbstractServer, tunnel_server)
else:
logger.info('%s %s', msg, (host, port))
server = await loop.create_server(
conn_factory, host, port, family=family, flags=flags,
backlog=backlog, reuse_address=reuse_address,
reuse_port=reuse_port)
return SSHAcceptor(server, options)
def _validate_version(version: DefTuple[BytesOrStr]) -> bytes:
"""Validate requested SSH version"""
if version == ():
version = b'AsyncSSH_' + __version__.encode('ascii')
else:
if isinstance(version, str):
version = version.encode('ascii')
else:
assert isinstance(version, bytes)
# Version including 'SSH-2.0-' and CRLF must be 255 chars or less
if len(version) > 245:
raise ValueError('Version string is too long')
for b in version:
if b < 0x20 or b > 0x7e:
raise ValueError('Version string must be printable ASCII')
return version
def _expand_algs(alg_type: str, algs: str,
possible_algs: List[bytes],
default_algs: List[bytes],
strict_match: bool) -> Sequence[bytes]:
"""Expand the set of allowed algorithms"""
if algs[:1] in '^+-':
prefix = algs[:1]
algs = algs[1:]
else:
prefix = ''
matched: List[bytes] = []
for pat in algs.split(','):
pattern = WildcardPattern(pat)
matches = [alg for alg in possible_algs
if pattern.matches(alg.decode('ascii'))]
if not matches and strict_match:
raise ValueError(f'"{pat}" matches no valid {alg_type} algorithms')
matched.extend(matches)
if prefix == '^':
return matched + default_algs
elif prefix == '+':
return default_algs + matched
elif prefix == '-':
return [alg for alg in default_algs if alg not in matched]
else:
return matched
def _select_algs(alg_type: str, algs: _AlgsArg, config_algs: _AlgsArg,
possible_algs: List[bytes], default_algs: List[bytes],
none_value: Optional[bytes] = None,
allow_empty: bool = False) -> Sequence[bytes]:
"""Select a set of allowed algorithms"""
if algs == ():
algs = config_algs
strict_match = False
else:
strict_match = True
if algs in ((), 'default'):
return default_algs
elif algs:
if isinstance(algs, str):
expanded_algs = _expand_algs(alg_type, algs, possible_algs,
default_algs, strict_match)
else:
expanded_algs = [alg.encode('ascii') for alg in algs]
result: List[bytes] = []
for alg in expanded_algs:
if alg not in possible_algs:
raise ValueError(f'{alg.decode("ascii")} is not a valid '
f'{alg_type} algorithm')
if alg not in result:
result.append(alg)
return result
elif none_value:
return [none_value]
elif allow_empty:
return []
else:
raise ValueError(f'No {alg_type} algorithms selected')
def _select_host_key_algs(algs: _AlgsArg, config_algs: _AlgsArg,
default_algs: List[bytes]) -> Sequence[bytes]:
"""Select a set of allowed host key algorithms"""
possible_algs = (get_x509_certificate_algs() + get_certificate_algs() +
get_public_key_algs())
return _select_algs('host key', algs, config_algs,
possible_algs, default_algs)
def _validate_algs(config: SSHConfig, kex_algs_arg: _AlgsArg,
enc_algs_arg: _AlgsArg, mac_algs_arg: _AlgsArg,
cmp_algs_arg: _AlgsArg, sig_algs_arg: _AlgsArg,
allow_x509: bool) -> \
Tuple[Sequence[bytes], Sequence[bytes], Sequence[bytes],
Sequence[bytes], Sequence[bytes]]:
"""Validate requested algorithms"""
kex_algs = _select_algs('key exchange', kex_algs_arg,
cast(_AlgsArg, config.get('KexAlgorithms', ())),
get_kex_algs(), get_default_kex_algs())
enc_algs = _select_algs('encryption', enc_algs_arg,
cast(_AlgsArg, config.get('Ciphers', ())),
get_encryption_algs(),
get_default_encryption_algs())
mac_algs = _select_algs('MAC', mac_algs_arg,
cast(_AlgsArg, config.get('MACs', ())),
get_mac_algs(), get_default_mac_algs(), None, True)
cmp_algs = _select_algs('compression', cmp_algs_arg,
cast(_AlgsArg, config.get_compression_algs()),
get_compression_algs(),
get_default_compression_algs(), b'none')
allowed_sig_algs = get_x509_certificate_algs() if allow_x509 else []
allowed_sig_algs = allowed_sig_algs + get_public_key_algs()
default_sig_algs = get_default_x509_certificate_algs() if allow_x509 else []
default_sig_algs = allowed_sig_algs + get_default_public_key_algs()
sig_algs = _select_algs('signature', sig_algs_arg,
cast(_AlgsArg,
config.get('CASignatureAlgorithms', ())),
allowed_sig_algs, default_sig_algs)
return kex_algs, enc_algs, mac_algs, cmp_algs, sig_algs
class SSHAcceptor:
"""SSH acceptor
This class in a wrapper around an :class:`asyncio.Server` listener
which provides the ability to update the the set of SSH client or
server connection options associated with that listener. This is
accomplished by calling the :meth:`update` method, which takes the
same keyword arguments as the :class:`SSHClientConnectionOptions`
and :class:`SSHServerConnectionOptions` classes.
In addition, this class supports all of the methods supported by
:class:`asyncio.Server` to control accepting of new connections.
"""
def __init__(self, server: asyncio.AbstractServer,
options: 'SSHConnectionOptions'):
self._server = server
self._options = options
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, _exc_type: Optional[Type[BaseException]],
_exc_value: Optional[BaseException],
_traceback: Optional[TracebackType]) -> bool:
self.close()
await self.wait_closed()
return False
def __getattr__(self, name: str) -> Any:
return getattr(self._server, name)
def get_addresses(self) -> List[Tuple]:
"""Return socket addresses being listened on
This method returns the socket addresses being listened on.
It returns tuples of the form returned by
:meth:`socket.getsockname`. If the listener was created
using a hostname, the host's resolved IPs will be returned.
If the requested listening port was `0`, the selected
listening ports will be returned.
:returns: A list of socket addresses being listened on
"""
if hasattr(self._server, 'get_addresses'):
return self._server.get_addresses()
else:
return [sock.getsockname() for sock in self.sockets]
def get_port(self) -> int:
"""Return the port number being listened on
This method returns the port number being listened on.
If it is listening on multiple sockets with different port
numbers, this function will return `0`. In that case,
:meth:`get_addresses` can be used to retrieve the full
list of listening addresses and ports.
:returns: The port number being listened on, if there's only one
"""
if hasattr(self._server, 'get_port'):
return self._server.get_port()
else:
ports = {addr[1] for addr in self.get_addresses()}
return ports.pop() if len(ports) == 1 else 0
def close(self) -> None:
"""Stop listening for new connections
This method can be called to stop listening for new
SSH connections. Existing connections will remain open.
"""
self._server.close()
async def wait_closed(self) -> None:
"""Wait for this listener to close
This method is a coroutine which waits for this
listener to be closed.
"""
await self._server.wait_closed()
def update(self, **kwargs: object) -> None:
"""Update options on an SSH listener
Acceptors started by :func:`listen` support options defined
in :class:`SSHServerConnectionOptions`. Acceptors started
by :func:`listen_reverse` support options defined in
:class:`SSHClientConnectionOptions`.
Changes apply only to SSH client/server connections accepted
after the change is made. Previously accepted connections
will continue to use the options set when they were accepted.
"""
self._options.update(**kwargs)
class SSHConnection(SSHPacketHandler, asyncio.Protocol):
"""Parent class for SSH connections"""
_handler_names = get_symbol_names(globals(), 'MSG_')
next_conn = 0 # Next connection number, for logging
@staticmethod
def _get_next_conn() -> int:
"""Return the next available connection number (for logging)"""
next_conn = SSHConnection.next_conn
SSHConnection.next_conn += 1
return next_conn
def __init__(self, loop: asyncio.AbstractEventLoop,
options: 'SSHConnectionOptions',
acceptor: _AcceptHandler, error_handler: _ErrorHandler,
wait: Optional[str], server: bool):
self._loop = loop
self._options = options
self._protocol_factory = options.protocol_factory
self._acceptor = acceptor
self._error_handler = error_handler
self._server = server
self._wait = wait
self._waiter = options.waiter if wait else None
self._transport: Optional[asyncio.Transport] = None
self._local_addr = ''
self._local_port = 0
self._peer_host = ''
self._peer_addr = ''
self._peer_port = 0
self._tcp_keepalive = options.tcp_keepalive
self._utf8_decode_errors = options.utf8_decode_errors
self._owner: Optional[Union[SSHClient, SSHServer]] = None
self._extra: Dict[str, object] = {}
self._inpbuf = b''
self._packet = b''
self._pktlen = 0
self._banner_lines = 0
self._version = options.version
self._client_version = b''
self._server_version = b''
self._client_kexinit = b''
self._server_kexinit = b''
self._session_id = b''
self._send_seq = 0
self._send_encryption: Optional[Encryption] = None
self._send_enchdrlen = 5
self._send_blocksize = 8
self._compressor: Optional[Compressor] = None
self._compress_after_auth = False
self._deferred_packets: List[Tuple[int, Sequence[bytes]]] = []
self._recv_handler = self._recv_version
self._recv_seq = 0
self._recv_encryption: Optional[Encryption] = None
self._recv_blocksize = 8
self._recv_macsize = 0
self._decompressor: Optional[Decompressor] = None
self._decompress_after_auth = False
self._next_recv_encryption: Optional[Encryption] = None
self._next_recv_blocksize = 0
self._next_recv_macsize = 0
self._next_decompressor: Optional[Decompressor] = None
self._next_decompress_after_auth = False
self._trusted_host_keys: Optional[Set[SSHKey]] = set()
self._trusted_host_key_algs: List[bytes] = []
self._trusted_ca_keys: Optional[Set[SSHKey]] = set()
self._revoked_host_keys: Set[SSHKey] = set()
self._x509_trusted_certs = options.x509_trusted_certs
self._x509_trusted_cert_paths = options.x509_trusted_cert_paths
self._x509_revoked_certs: Set[SSHX509Certificate] = set()
self._x509_trusted_subjects: Sequence['X509NamePattern'] = []
self._x509_revoked_subjects: Sequence['X509NamePattern'] = []
self._x509_purposes = options.x509_purposes
self._kex_algs = options.kex_algs
self._enc_algs = options.encryption_algs
self._mac_algs = options.mac_algs
self._cmp_algs = options.compression_algs
self._sig_algs = options.signature_algs
self._host_based_auth = options.host_based_auth
self._public_key_auth = options.public_key_auth
self._kbdint_auth = options.kbdint_auth
self._password_auth = options.password_auth
self._kex: Optional[Kex] = None
self._kexinit_sent = False
self._kex_complete = False
self._ignore_first_kex = False
self._strict_kex = False
self._gss: Optional[GSSBase] = None
self._gss_kex = False
self._gss_auth = False
self._gss_kex_auth = False
self._gss_mic_auth = False
self._preferred_auth: Optional[Sequence[bytes]] = None
self._rekey_bytes = options.rekey_bytes
self._rekey_seconds = options.rekey_seconds
self._rekey_bytes_sent = 0
self._rekey_time = 0.
self._keepalive_count = 0
self._keepalive_count_max = options.keepalive_count_max
self._keepalive_interval = options.keepalive_interval
self._keepalive_timer: Optional[asyncio.TimerHandle] = None
self._tunnel: Optional[_TunnelProtocol] = None
self._enc_alg_cs = b''
self._enc_alg_sc = b''
self._mac_alg_cs = b''
self._mac_alg_sc = b''
self._cmp_alg_cs = b''
self._cmp_alg_sc = b''
self._can_send_ext_info = False
self._extensions_to_send: 'OrderedDict[bytes, bytes]' = OrderedDict()
self._can_recv_ext_info = False
self._server_sig_algs: Set[bytes] = set()