
    mg                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZmZmZm Z  dd	lm!Z!m"Z"m#Z# dd
l$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl*m/Z/m0Z0 ddl*m1Z1m2Z2 ddl*m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z; ddl8m<Z<m=Z=m>Z> ddl8m?Z?m@Z@ ddlAmBZB ddlCmDZDmEZEmFZF ddlCmGZGmHZH ddlCmIZImJZJ ddlKmLZLmMZMmNZNmOZO ddlPmQZQmRZR ddlPmSZS ddlPmTZT ddlPmUZUmVZVmWZWmXZX ddlPmYZYmZZZm[Z[ ddlPm\Z\m]Z] dd lPm^Z^ dd!lPm_Z_m`Z` dd"lPmaZambZbmcZcmdZd dd#lPmeZemfZf dd$lPmgZgmhZh dd%lPmiZimjZj dd&lPmkZkmlZl dd'lPmmZm dd(lPmnZnmoZo dd)lPmpZp dd*lqmrZrmsZs dd+lqmtZt dd,lqmuZumvZv dd-lwmxZx dd.lymzZzm{Z{m|Z|m}Z} dd/l~mZmZmZ dd0l~mZmZ dd1lmZmZ dd2lmZmZ dd3lmZmZ dd4lmZmZ dd5lmZmZ dd6lmZmZ dd7lmZmZ dd8lmZ dd9lmZmZ dd:lmZmZ dd;lmZmZmZmZmZ dd<lmZmZmZmZmZ dd=lmZmZmZ dd>lmZmZmZ dd?lmZmZmZ dd@lmZmZmZ ddAlmZmZ ddBlmZmZ ddClmZmZ ddDlmZmZmZ ddElmZmZmZ ddFlmZmZmZmZmZmZ ddGlmZmZmZ ddHlmZ ddIlmZ ddJlmZmZmZ ddKlmZmZ ddLlmZmZ ddMlmZmZmZ ddNlmZmZmZmZ ddOlmZmZmZmZ ddPlmZmZ ddQlmZmZ ddRlmZmZ ddSlmZmZ ddTlmZmZ ddUlmZ ddVlmZ ddWlmZmZ ddXlmZmZ ddYlmZ ddZlmZmZ dd[lmZmZ dd\lmZ dd]lmZmZmZ dd^lmZmZmZ dd_lmZm Z  dd`lmZmZ ddalmZmZmZ ddblmZ ddclm	Z	m
Z
mZ dddlmZmZ ddelmZmZ ddflmZmZ ddglmZ ddhlmZmZ ddilmZmZ ddjlmZmZ ddklmZmZ ddllmZ ddmlm Z  ddnlm!Z!m"Z" ddolm#Z#m$Z$ er	ddpl%m&Z& eg eBf   Z'eg ef   Z(e"e'e(f   Z) e!dqdrs      Z* e!dtdus      Z+eeee   ee   ee   ee   ged   f      Z, G dv dwe%      Z- G dx dye-e%      Z. G dz d{e-e%      Z/eedrged   f      Z0eedree1   gdf      Z2eegee:ef   f   Z3eegdf   Z4ee"e5ee5   f      Z6ee7   Z8ee"de5ee5   e6f      Z9e"eef   Z:e"eef   Z;ee"ee5e5f   ee5   f      Z<eee5      Z=eee4   eƐe7f   Z>ee?ef   Z@ee5eAf   ZBe"e7ef   ZCee"e5ee5   f      ZDe"e7e5f   ZEee5e?gef   ZFeg ef   ZGe"de5e.f   ZHe"de5e/f   ZIee   ZJee5e?gee7   f   ZKd|ZLd}ZMd~ZNdZOdZPd~ZQdZRdZSdZTdZUdZVdZWdZXdZYd~ZZdej                  dee5   deg e*f   de*fdZ\deAdee   deeL   ded   fdZ]ddtdeeL   dej                  de?deej                     deg e*f   de5de*fdZ^ddtdeeL   dej                  de?de?deej                     de7de7deg e*f   de5ddfdZ_dee   de`fdZade5de5dee`   dee`   de7dee`   fdZb	 dde5de6de6dee`   dee`   dee`   dee`   fdZcde6de6dee`   dee`   fdZddeMde6de6de6de6de6de7deee`   ee`   ee`   ee`   ee`   f   fdZe G d d      Zf G d dreejJ                        Zg G d deg      Zh G d deg      Zi G d due      Zj G d dej      Zk G d dej      Zle	 	 ddej                  deeL   deek   deAdehf
d       Zme	 	 ddej                  deeL   deel   deAdeif
d       Zneddddddddddee?   deeH   dee?   de?dee   deej                     deeL   deek   deAdehfd       Zoe	 ddddddddddee?   deeH   dee?   de?dee   deej                     deeL   deel   deAdeifdÄ       Zpedddej                  dddddddddƜdee?   deeI   dee?   de?de?deej                     de7de7dǐe0dȐe2deeL   deel   deAdeffdɄ       Zredddej                  dddddddddƜdee?   deeI   dee?   de?de?deej                     de7de7dǐe0dȐe2deeL   deek   deAdeffdʄ       Zs	 ddːe'dee?   deAdeeheBf   fd̄Zte	 dd͐e(dee?   deAdeffd΄       Zu	 dddddddddddddϜdee?   deeH   deeD   dee?   de?dee   deej                     dee   dҐe6dӐe6deeL   deek   dee   fdԄZv	 dddddddddddddϜdee?   dee5   deeH   deeD   dee?   de?dee   deej                     dee   dҐe6dӐe6deeL   deek   dee5   fdքZwy)zSSH connection handlers    N)OrderedDict)partial)Path)TracebackType)TYPE_CHECKINGAnyAnyStr	AwaitableCallableDict)ListMappingOptionalSequenceSetTupleType)TypeVarUnioncast)ProtocolSelf   )SSHAgentClientSSHAgentListener)Auth
ClientAuthKbdIntChallengeKbdIntPrompts)KbdIntResponsePasswordChangeResponse)!get_supported_client_auth_methodslookup_client_auth)!get_supported_server_auth_methodslookup_server_auth)SSHAuthorizedKeysread_authorized_keys)
SSHChannelSSHClientChannelSSHServerChannel)SSHTCPChannelSSHUNIXChannelSSHTunTapChannel)SSHX11ChannelSSHAgentChannel)	SSHClient)
CompressorDecompressorget_compression_algs)get_default_compression_algsget_compression_params)get_compressorget_decompressor)ConfigPaths	SSHConfigSSHClientConfigSSHServerConfig)DEFAULT_LANGDEFAULT_PORT)DISC_BY_APPLICATION)EXTENDED_DATA_STDERR)MSG_DISCONNECT
MSG_IGNOREMSG_UNIMPLEMENTED	MSG_DEBUG)MSG_SERVICE_REQUESTMSG_SERVICE_ACCEPTMSG_EXT_INFO)MSG_CHANNEL_OPENMSG_CHANNEL_OPEN_CONFIRMATION)MSG_CHANNEL_OPEN_FAILURE)MSG_CHANNEL_FIRSTMSG_CHANNEL_LAST)MSG_KEXINITMSG_NEWKEYSMSG_KEX_FIRSTMSG_KEX_LAST)MSG_USERAUTH_REQUESTMSG_USERAUTH_FAILURE)MSG_USERAUTH_SUCCESSMSG_USERAUTH_BANNER)MSG_USERAUTH_FIRSTMSG_USERAUTH_LAST)MSG_GLOBAL_REQUESTMSG_REQUEST_SUCCESS)MSG_REQUEST_FAILURE) OPEN_ADMINISTRATIVELY_PROHIBITEDOPEN_CONNECT_FAILED)OPEN_UNKNOWN_CHANNEL_TYPE)
Encryptionget_encryption_algs)get_default_encryption_algs)get_encryption_paramsget_encryption)SSHForwarder)GSSBase	GSSClient	GSSServerGSSError)Kexget_kex_algsget_default_kex_algs)expand_kex_algsget_kex)KeySignPathSSHKeySignKeyPair)find_keysignget_keysign_keys)KnownHostsArgmatch_known_hosts)	ListenKeySSHListener)SSHTCPClientListenerSSHUNIXClientListener)TCPListenerFactoryUNIXListenerFactory)create_tcp_forward_listenercreate_unix_forward_listener)create_socks_listener)	SSHLoggerlogger)get_mac_algsget_default_mac_algs)
BytesOrStrBytesOrStrDictDefTupleFilePathHostPort)	IPNetwork
MaybeAwait
OptExcInfoOptionsSockAddr)ChannelListenErrorChannelOpenErrorCompressionError)DisconnectErrorConnectionLostHostKeyNotVerifiable)KeyExchangeFailedIllegalUserNameMACError)PasswordChangeRequiredPermissionDeniedProtocolError)ProtocolNotSupportedServiceNotAvailable)TermModesArgTermSizeArg)async_context_managerconstruct_disc_error)get_symbol_names
ip_addressmap_handler_name)parse_byte_countparse_time_interval
split_args)BooleanByteNameListStringUInt32PacketDecodeError)	SSHPacketSSHPacketHandlerSSHPacketLogger)WildcardPattern)load_pkcs11_keys)PIPEProcessSourceProcessTarget)SSHServerProcessFactorySSHCompletedProcess)SSHClientProcessSSHServerProcess)CERT_TYPE_HOSTCERT_TYPE_USERKeyImportError)CertListArgIdentityListArg
KeyListArg
SigningKey)KeyPairListArgX509CertPurposesSSHKey
SSHKeyPair)SSHCertificateSSHOpenSSHCertificate)SSHX509CertificateSSHX509CertificateChain)decode_ssh_public_keydecode_ssh_certificate)get_public_key_algsget_default_public_key_algs)get_certificate_algsget_default_certificate_algs)get_x509_certificate_algs)!get_default_x509_certificate_algs)load_keypairsload_default_keypairs)load_public_keysload_default_host_public_keys)load_certificates)load_identitiesload_default_identities)saslprepSASLPrepError)	SSHServer)DataTypeSSHClientSessionSSHServerSession)SSHTCPSessionSSHUNIXSessionSSHTunTapSession)SSHClientSessionFactorySSHTCPSessionFactory)SSHUNIXSessionFactorySSHTunTapSessionFactory)MIN_SFTP_VERSION
SFTPClient
SFTPServer)start_sftp_client)	SSHReader	SSHWriterSFTPServerFactory)SSHSocketSessionFactorySSHServerSessionFactory)SSHClientStreamSessionSSHServerStreamSession)SSHTCPStreamSessionSSHUNIXStreamSession)SSHTunTapStreamSession)SSHSubprocessTransportSSHSubprocessProtocol)SubprocessFactorySSHSubprocessWritePipe)SSH_TUN_MODE_POINTTOPOINTSSH_TUN_MODE_ETHERNET)SSH_TUN_UNIT_ANYcreate_tuntap)__version__)SSHX11ClientForwarder)SSHX11ClientListenerSSHX11ServerListener)create_x11_client_listenercreate_x11_server_listener)X509NamePattern_ConnSSHConnection)bound_OptionsSSHConnectionOptionsc                       e Zd ZdZddZy)_TunnelProtocolz0Base protocol for connections to tunnel SSH overNc                      yzClose this tunnelN selfs    3lib/python3.12/site-packages/asyncssh/connection.pyclosez_TunnelProtocol.close           returnN)__name__
__module____qualname____doc__r  r  r	  r  r   r      s
    : r	  r   c                   D    e Zd ZdZdee   dededee	e   e
e   f   fdZy)_TunnelConnectorProtocolz>Protocol to open a connection to tunnel an SSH connection oversession_factoryremote_hostremote_portr  c                    K   yw)z$Create an outbound tunnel connectionNr  )r  r  r  r  s       r  create_connectionz*_TunnelConnectorProtocol.create_connection           N)r  r  r  r  r   bytesstrintr   r+   r   r  r  r	  r  r  r     sE    H3#7#>33+.3 mE*M%,@@A3r	  r  c                   (    e Zd ZdZdedededefdZy)_TunnelListenerProtocolz:Protocol to open a listener to tunnel SSH connections overr  listen_hostlisten_portr  c                    K   yw)z!Create an inbound tunnel listenerNr  )r  r  r  r  s       r  create_serverz%_TunnelListenerProtocol.create_server   r  r  N)	r  r  r  r  ru   r  r  rr   r!  r  r	  r  r  r     s*    D03E 0),0;>0CN0r	  r  s   ssh-userauths   ssh-connectioni   i       i   @i  x      i    i   i  loopcommandconn_factoryr  c                    K    G fddt         j                        } | j                  |g|  d{   \  }}t        t        t        ||      j                               S 7 /w)z%Open a tunnel running a proxy commandc                        e Zd ZdZd fdZddededefdZdefdZ	d	e
j                  ddfd
ZdededdfdZdedee   ddfdZdeddfdZddZddZ xZS )(_open_proxy.<locals>._ProxyCommandTunnelzSSH proxy command tunnelr  Nc                     t         |           d | _        d | _                | _        t        j                         | _        y N)super__init__
_transport_stdin_connasyncioEvent_close_event)r  	__class__r'  s    r  r.  z1_open_proxy.<locals>._ProxyCommandTunnel.__init__  s3    GEIDO<@DK%DJ 'Dr	  namedefaultc                 V    | j                   J | j                   j                  ||      S )z4Return extra information associated with this tunnel)r/  get_extra_infor  r6  r7  s      r  r9  z7_open_proxy.<locals>._ProxyCommandTunnel.get_extra_info'  s+     ??...??11$@@r	  c                     | j                   S )z1Return the connection associated with this tunnel)r1  r  s    r  get_connz1_open_proxy.<locals>._ProxyCommandTunnel.get_conn-  s     ::r	  	transportc                    t        t        j                  |      | _        t        t        j                  | j                  j                  d            | _        | j                  j                  t        t        j                  |              y)z Handle startup of the subprocessr   N)
r   r2  SubprocessTransportr/  WriteTransportget_pipe_transportr0  r1  connection_madeBaseTransport)r  r=  s     r  rB  z8_open_proxy.<locals>._ProxyCommandTunnel.connection_made2  s^     #7#>#>	JDOw55#AA!DFDKJJ&&tG,A,A4'HIr	  fddatac                 :    | j                   j                  |       y)z%Handle data received from this tunnelN)r1  data_received)r  rD  rE  s      r  pipe_data_receivedz;_open_proxy.<locals>._ProxyCommandTunnel.pipe_data_received:  s    
 JJ$$T*r	  excc                 :    | j                   j                  |       y)z!Handle when this tunnel is closedN)r1  connection_lost)r  rD  rI  s      r  pipe_connection_lostz=_open_proxy.<locals>._ProxyCommandTunnel.pipe_connection_lostA  s     JJ&&s+r	  c                 V    | j                   J | j                   j                  |       y)zWrite data to this tunnelN)r0  writer  rE  s     r  rN  z._open_proxy.<locals>._ProxyCommandTunnel.writeI  s&     ;;***KKd#r	  c                 $    | j                          y)zForcibly close this tunnelN)r  r  s    r  abortz._open_proxy.<locals>._ProxyCommandTunnel.abortO  s     JJLr	  c                     | j                   r| j                   j                          | j                  j                          yr  )r/  r  r4  setr  s    r  r  z._open_proxy.<locals>._ProxyCommandTunnel.closeT  s-     %%'!!#r	  r
  r,  )r  r  r  r  r.  r  r   r9  r   r<  r2  rC  rB  r  r  rH  r   	ExceptionrL  rN  rQ  r  __classcell__)r5  r'  s   @r  _ProxyCommandTunnelr*    s    &	0	As 	AS 	AC 	A	e 	
	JW-B-B 	Jt 	J	+ 	+E 	+d 	+	,3 	,&.y&9	,>B	,	$e 	$ 	$	
	$r	  rV  N)r2  SubprocessProtocolsubprocess_execr   r   r<  )r%  r&  r'  rV  _tunnels     `   r  _open_proxyr[    s_     
>$g88 >$B +d**+>IIIIAvt/8AACDD Js   2A'A%0A'tunnels
passphraseconfigSSHClientConnectionc           	      F  K   t        | t              rd}| j                  d      D ]s  }d|v r|j                  dd      \  }}nd|}}d|v r!|j                  dd      \  }}t	        |      }nd}|}	t        ||||||       d{   }|j                  |	       u |S y7 w)z(Parse and open connection to tunnel overN,@r   r  :)usernamer]  rZ  r^  )
isinstancer  splitrsplitr  connect
set_tunnel)
r\  r]  r^  connrZ  rd  hostport_strport	last_conns
             r  _open_tunnelro  b  s      '3.2mmC(Ff}!'sA!6$!#V$d{!%S!!4h8}I th,6t(.0 0D OOI&! )$ 0s   BB!BB!optionsflagssockmsgc                   K   | j                   }| j                  }| j                  }	| j                  }
| j                  }| j
                  }d}|j                         | _        t        |	| j                  |       d{   }	 |rFt        j                  d|       |j                  ||       d{   \  }}t        t        |      }nG|rv|j                  j                  d|||f|	       	 |j                  t        t        t            |      ||       d{   \  }}t        t        |      }|j#                  |       n|	rjt+        |	dt              }|j                  d|||f       |	j                  t        t        t            |      ||       d{   \  }}t        t        |      }nc|rt-        |||       d{   }nKt        j                  d|||f       |j                  ||||
||	       d{   \  }}t        t        |      }	 | j                   d{    d
}||r)|j5                          |j)                          d{    S S 7 7 7 C# t$        $ r+ |j'                          |j)                          d{  7    w xY w7 7 7 # t.        j0                  $ r | j                  j3                           w xY w7 7 # |r*|j5                          |j)                          d{  7   w w xY ww)z,Make outbound TCP or SSH tunneled connectionTN%s already-connected socket)rr  %s %s via %sr{   %s %s via SSH tunnel%s %s)familyrq  
local_addrF)rk  rm  rZ  ry  rz  proxy_commandcreate_futurewaiterro  r]  r{   infor  r   r   r   r  ri  rT  r  wait_closedgetattrr[  r2  CancelledErrorcancelrQ  )rp  r^  r%  rq  rr  r'  rs  rk  rm  rZ  ry  rz  r{  	free_conn
new_tunnelrY  sessionrj  tunnel_sessiontunnel_loggers                       r  _connectr    s     <<D<<D^^F^^F##J))MI'')GN#FG,>,>GGJ+KK5s;#55l5NNJAww'D"">3tfM
,*4*F*F-e4lC$+  % !> E>2
+#FHf=M5sT4LI&,&>&>)%0,?d' !A~ ~.D$T=,GGDKKtTl3#55dD
  6  4 4JAw w'D
%nn	JJL""$$$ k H O%     " ,,...! H4
 !! 
 	 % JJL""$$$ s   A:L<I=L.J 0I1;J -+I II  A5J J*J  J8J 9J:J K !K"K )%LKLJ I ,J
JJJ J J /K

LK L&K?7K:8K??Lbacklogreuse_address
reuse_portSSHAcceptorc
           
        K   dt         dt        dt        ffd}
| j                  }| j                  }| j
                  }| j                  }t        || j                  |       d{   }|r6t        j                  d|	       |j                  ||||       d{   }n|rh|j                  j                  d|	||f|       	 |j                  |
||       d{   }|j                  |       t        t        j                  |      }n|r\t'        |d	t              }|j                  d
|	||f       |j                  |
||       d{   }t        t        j                  |      }n:t        j                  d|	||f       |j                  |||||||       d{   }t)        ||       S 7 K7 7 # t         $ r+ |j#                          |j%                          d{  7    w xY w7 7 Qw)z)Make inbound TCP or SSH tunneled listener
_orig_host
_orig_portr  c                 .    t        t                      S )zIgnore original host and port)r   r   )r  r  r'  s     r  tunnel_factoryz_listen.<locals>.tunnel_factory  s     M<>22r	  Nru  )rr  r  r  r  rv  r{   rw  rx  )ry  rq  r  r  r  )r  r  r   rk  rm  rZ  ry  ro  r]  r{   r~  r!  ri  r   r2  AbstractServerrT  r  r  r  r  )rp  r^  r%  rq  r  rr  r  r  r'  rs  r  rk  rm  rZ  ry  r  servertunnel_serverr  s           `          r  _listenr    s    33 3C 3M 3
 <<D<<D^^F^^F#FG,>,>GGJ 137/3/A/AtW'J 0B 0@ *@ 
~sT4L&I		A",":":d#, ,M $$Z0'00-@F	&913tE$22>4NNg,,m<GS4,/))$V5=! * # #
 vw''K H*@, 	((***	 O
#sz   A#G4&F1'5G4F4(G4F9 F7F9 !A*G4G0AG4 G2!G44G47F9 9,G-%G(&G--G42G4versionc                    | dk(  rdt        j                  d      z   } | S t        | t              r| j                  d      } nt        | t              sJ t        |       dkD  rt        d      | D ]  }|dk  s|dkD  st        d       | S )	zValidate requested SSH versionr  s	   AsyncSSH_ascii   zVersion string is too long    ~   z&Version string must be printable ASCII)r   encodere  r  r  len
ValueError)r  bs     r  _validate_versionr    s     "}!3!3G!<< N gs#nnW-Ggu--- w<#9::A4x1t8 !IJJ  Nr	  alg_typealgspossible_algsdefault_algsstrict_matchc           	         |dd dv r|dd }|dd }nd}g }|j                  d      D ]c  }t        |      }|D 	cg c]$  }	|j                  |	j                  d            r|	& }
}	|
s|rt	        d|d| d	      |j                  |
       e |d
k(  r||z   S |dk(  r||z   S |dk(  r|D 	cg c]	  }	|	|vs|	 c}	S |S c c}	w c c}	w )z$Expand the set of allowed algorithmsNr   z^+- ra  r  "z" matches no valid z algorithms^+-)rf  r   matchesdecoder  extend)r  r  r  r  r  prefixmatchedpatpatternalgr  s              r  _expand_algsr    s    BQx5bqABxGzz#!#&"/ <-3oocjj&9: - < <!8- . . 	w  }%%	3g%%	3+B|s'/A|BB!< Cs   )B>+	C5Cconfig_algs
none_valuec                 `   |dk(  r|}d}nd}|dv r|S |rt        |t              rt        | ||||      }n|D cg c]  }|j                  d       }}g }	|D ]<  }||vr t	        |j                  d      d| d      ||	vs,|	j                  |       > |	S |r|gS t	        d| z        c c}w )	z"Select a set of allowed algorithmsr  FT)r  r7  r  z is not a valid z
 algorithmzNo %s algorithms selected)re  r  r  r  r  r  append)
r  r  r  r  r  r  r  expanded_algsr  results
             r  _select_algsr  B  s    
 rz	dC (4)5|EM =AADSSZZ0DMA  C-' "%**W"5x"A B B & c" ! 	|4x?@@! Bs   B+c                 `    t               t               z   t               z   }t        d| |||      S )z+Select a set of allowed host key algorithmszhost key)r   r   r   r  )r  r  r  r  s       r  _select_host_key_algsr  g  s:     /03G3II(*+M 
D+%|5 5r	  kex_algs_argenc_algs_argmac_algs_argcmp_algs_argsig_algs_arg
allow_x509c                    t        d|t        t        | j                  dd            t	               t                     }t        d|t        t        | j                  dd            t               t                     }t        d|t        t        | j                  dd            t               t                     }	t        d|t        t        | j                               t               t               d	      }
|r
t               ng }|t               z   }|r
t               ng }|t               z   }t        d
|t        t        | j                  dd            ||      }|||	|
|fS )zValidate requested algorithmskey exchangeKexAlgorithmsr  
encryptionCiphersMACMACscompression   none	signatureCASignatureAlgorithms)r  r   _AlgsArggetrg   rh   r]   r^   r|   r}   r3   r4   r   r   r   r   )r^  r  r  r  r  r  r  kex_algsenc_algsmac_algscmp_algsallowed_sig_algsdefault_sig_algssig_algss                 r  _validate_algsr  r  sF    NL 6::or+JK(N,@,BDH L, 6::i+DE/179;H E< 6::fb+AB(N,@,BDH M< 6+F+F+HI028:GEH
 7A02b'*=*??>H8:b'*E*GGK !',CR!HJ,.>@H
 Xx8;;r	  c                       e Zd ZdZdej
                  ddfdZdefdZde	e
e      d	e	e   d
e	e   defdZdedefdZdee   fdZdefdZddZddZdeddfdZy)r  aJ  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.

    r  rp  r   c                      || _         || _        y r,  )_server_options)r  r  rp  s      r  r.  zSSHAcceptor.__init__  s    r	  r  c                    K   | S wr,  r  r  s    r  
__aenter__zSSHAcceptor.__aenter__  s        	_exc_type
_exc_value
_tracebackc                 `   K   | j                          | j                          d {    y7 w)NF)r  r  r  r  r  r  s       r  	__aexit__zSSHAcceptor.__aexit__  s+      	

    	!s   $.,.r6  c                 .    t        | j                  |      S r,  )r  r  )r  r6  s     r  __getattr__zSSHAcceptor.__getattr__  s    t||T**r	  c                     t        | j                  d      r| j                  j                         S | j                  D cg c]  }|j	                          c}S c c}w )a  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

        get_addresses)hasattrr  r  socketsgetsockname)r  rr  s     r  r  zSSHAcceptor.get_addresses  sJ     4<<1<<--//37<<@<4D$$&<@@@s   Ac                     t        | j                  d      r| j                  j                         S t        d | j	                         D              }t        |      dk(  r|j                         S dS )a  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

        get_portc              3   &   K   | ]	  }|d      yw)r   Nr  ).0addrs     r  	<genexpr>z'SSHAcceptor.get_port.<locals>.<genexpr>  s     A,@DQ,@   r   r   )r  r  r  rS  r  r  pop)r  portss     r  r  zSSHAcceptor.get_port  sY     4<<,<<((**AD,>,>,@AAE"%e*/599;8q8r	  Nc                 8    | j                   j                          y)zStop listening for new connections

           This method can be called to stop listening for new
           SSH connections. Existing connections will remain open.

        N)r  r  r  s    r  r  zSSHAcceptor.close  s     	r	  c                 T   K   | j                   j                          d{    y7 w)zWait for this listener to close

           This method is a coroutine which waits for this
           listener to be closed.

        N)r  r  r  s    r  r  zSSHAcceptor.wait_closed  s      ll&&(((s   (&(kwargsc                 :    | j                   j                  |       y)a  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.

        N)r  updater  r  s     r  r  zSSHAcceptor.update  s     	V$r	  r
  )r  r  r  r  r2  r  r.  r   r  r   r   BaseExceptionr   boolr  r  r   r  r   r   r  r  r  r  r  objectr  r  r	  r  r  r    s     w55  0 
$ $}2E)F $,]$;$,]$;@D+ + +AtE{ A&9# 9&)%v %$ %r	  c                   >
   e Zd ZdZ e e       d      ZdZede	fd       Z
dej                  ddd	ed
edee   defdZdefdZdeee      dee   dee   defdZedefd       Zdee   ddfdZddZddZddZ ddZ!ddZ"ddZ#ddZ$dee   ddfdZ%dee   d d!ddfd"Z&	 dd#e'd   dee   dd!fd$Z(defd%Z)defd&Z*d' Z+dee,e-e.f      fd(Z/de0fd)Z1d*ee2   ddfd+Z3d,e4d-ed.ed/ee	   ddf
d0Z5d-ed.ed/e	d1e6de7f
d2Z8d-ed1e9de7fd3Z:d-ed.ed/e	d4e0de7f
d5Z;d6ejx                  ddfd7Z=ddee   ddfd8Z>	 	 dd9ee?   d:ee   ddfd;Z@dd<ZAdd=e0d>eBddfd?ZCdd@ZDddAZEddBZFdCeGeH   de	fdDZIdEe	ddfdFZJdeKfdGZLddHZMdIedJeNe0   dKeNe0   de0fdLZOdePe0   fdMZQd=e0ddfdNZRddOZSdefdPZTdefdQZUdefdRZVddSdTe	dUe0dVeeW   ddfdWZXddXZYdYe	dZed[eddfd\ZZdd]Z[dd^Z\d_e0d`e0ddfdaZ]dbe0ddfdcZ^dde0dUe_e0def   de0fdfZ`dde0dUe0de0fdgZaddhdidTe	dUe0dVeeW   djeddf
dkZbddhdldde0dUe0dmeec   djeddf
dnZddoeddfdpZeddqZfdre	dEe	dse	dte	due0ddfdvZgdre	dYe	dZed[eddf
dwZhdxdydze0dUe0d{eddfd|Zidze0dUe0de_e	ejf   fd}Zkd~e,ee0f   ddfdZlddZmddZnde	de	dejddfdZode	de	dejddfdZpde	de	dejddfdZqde	de	dejddfdZrde	de	dejddfdZsde	de	dejddfdZtde	de	dejddfdZude	de	dejddfdZvde	de	dejddfdZwde	de	dejddfdZxdedde0dejddfdZyde	de	dejddfdZzde	de	dejddfdZ{de	de	dejddfdZ|de	de	dejddfdZ}dTe	de	dejddfdZ~de	de	dejddfdZde	de	dejddfdZde	de	dejddfdZdejddfdZi eeoeepeeqeereeseeteeueeveeweexeezee{ee|ee}ee~ee~eeeeeeiZddZddZddZefdYe	dZed[eddfdZddededefdZdeddfdZ	 	 dde,deef   dee	   ddfdZedxfded[ededdfdZddeefdee   dede	de	def
dZddeefdee   dede	de	def
dZeefde	de	defdZeefde	de	defdZeefde	de	defdZ	 	 dddeeddeeH   dede	dede	dee   dede	de	de_eeH   eeH   f   fdZddeeddeeH   dedee   dede	de	de_eeH   eeH   f   fdZdede	defdZdedefdZe	 ddede	dede	dee   defdĄ       ZedededefdƄ       Zde	dee	   defdɄZdeddfd˄ZdCeGeH   ddfd̄Zy)r   z Parent class for SSH connectionsMSG_r   r  c                  X    t         j                  } t         xj                  dz  c_        | S )z9Return the next available connection number (for logging)r   )r   	next_conn)r  s    r  _get_next_connzSSHConnection._get_next_conn
  s&     "++	1$r	  r%  rp  r   acceptorerror_handlerwaitr  c                 r	   || _         || _        |j                  | _        || _        || _        || _        || _        |r|j                  nd | _	        d | _
        d| _        d| _        d| _        d| _        d| _        |j                   | _        d | _        i | _        d| _        d| _        d| _        d| _        |j0                  | _        d| _        d| _        d| _        d| _        d| _        d| _        d | _         d| _!        d| _"        d | _#        d| _$        g | _%        | jL                  | _'        d| _(        d | _)        d| _*        d| _+        d | _,        d| _-        d | _.        d| _/        d| _0        d | _1        d| _2        tg               | _4        g | _5        tg               | _6        tg               | _7        |jp                  | _9        |jt                  | _;        tg               | _<        g | _=        g | _>        |j~                  | _@        |j                  | _B        |j                  | _D        |j                  | _F        |j                  | _H        |j                  | _J        |j                  | _L        |j                  | _N        |j                  | _P        |j                  | _R        d | _S        d| _T        d| _U        d| _V        d| _W        d | _X        d| _Y        d| _Z        d| _[        d| _\        d | _]        |j                  | __        |j                  | _a        d| _b        d| _c        d| _d        |j                  | _f        |j                  | _h        d | _i        d | _j        d| _k        d| _l        d| _m        d| _n        d| _o        d| _p        d| _q        t               | _s        d| _t        tg               | _u        d | _v        d | _w        d | _x        d| _y        d| _z        d| _{        dg| _|        d	| _}        d| _~        i | _        d| _        g | _        g | _        i | _        d | _        t        j                         | _        d | _        t        j                  d
| j                         z        | _        |  |j                  r@| j                   j                  |j                  | j                        | _        d| _        y d | _        d| _        y )Nr  r   r	        Fg        r  Tzconn=%d)context)_loopr  protocol_factory_protocol_factory	_acceptor_error_handlerr  _waitr}  _waiterr/  _local_addr_local_port
_peer_host
_peer_addr
_peer_porttcp_keepalive_tcp_keepalive_owner_extra_inpbuf_packet_pktlen_banner_linesr  _version_client_version_server_version_client_kexinit_server_kexinit_session_id	_send_seq_send_encryption_send_enchdrlen_send_blocksize_compressor_compress_after_auth_deferred_packets_recv_version_recv_handler	_recv_seq_recv_encryption_recv_blocksize_recv_macsize_decompressor_decompress_after_auth_next_recv_encryption_next_recv_blocksize_next_recv_macsize_next_decompressor_next_decompress_after_authrS  _trusted_host_keys_trusted_host_key_algs_trusted_ca_keys_revoked_host_keysx509_trusted_certs_x509_trusted_certsx509_trusted_cert_paths_x509_trusted_cert_paths_x509_revoked_certs_x509_trusted_subjects_x509_revoked_subjectsx509_purposes_x509_purposesr  	_kex_algsencryption_algs	_enc_algsr  	_mac_algscompression_algs	_cmp_algssignature_algs	_sig_algshost_based_auth_host_based_authpublic_key_auth_public_key_authkbdint_auth_kbdint_authpassword_auth_password_auth_kex_kexinit_sent_kex_complete_ignore_first_kex_strict_kex_gss_gss_kex	_gss_auth_gss_kex_auth_gss_mic_auth_preferred_authrekey_bytes_rekey_bytesrekey_seconds_rekey_seconds_rekey_bytes_sent_rekey_time_keepalive_countkeepalive_count_max_keepalive_count_maxkeepalive_interval_keepalive_interval_keepalive_timer_tunnel_enc_alg_cs_enc_alg_sc_mac_alg_cs_mac_alg_sc_cmp_alg_cs_cmp_alg_sc_can_send_ext_infor   _extensions_to_send_can_recv_ext_info_server_sig_algs_next_service_agent_auth_auth_in_progress_auth_complete_auth_final_auth_methods_auth_was_trivial	_username	_channels_next_recv_chan_global_request_queue_global_request_waiters_local_listeners_x11_listenerr2  r3  r4  _server_host_key_algsr{   	get_childr  _loggerlogin_timeout
call_later_login_timer_callback_login_timer_disable_trivial_auth)r  r%  rp  r  r  r  r  s          r  r.  zSSHConnection.__init__  s{    
!(!9!9!+
)-w~~47;%33=A)+""""6:  15$)!DF!//6: 59&+#;?"$%!"#:>+0(9<35#7:u/2u#*#=#= (/(G(G%<?E CE#CE#%33 )) 00 )) 11 // ' 7 7 ' 7 7#//%33#'	""!& '+	"":>#//%33!" !$+$?$?!#*#=#= ?C26"'@K "',/E.204%)
!&# %Y!%02 ;=";= 	$ ?A ;? 	 $MMO@D"''	(,(;(;(=1> ? 	   $

 5 5%%t'A'A!CD
 &+" !%D%*"r	  c                    K   | S w)z:Allow SSHConnection to be used as an async context managerr  r  s    r  r  zSSHConnection.__aenter__  s      r  r  r  r  c                    K   | j                   j                         s| j                          | j                          d{    y7 w)z?Wait for connection close when used as an async context managerNF)r  	is_closedr  r  r  s       r  r  zSSHConnection.__aexit__  s;     
 zz##%JJL    	!s   >A AAc                     | j                   S )z(A logger associated with this connection)r  r  s    r  r{   zSSHConnection.logger  s     ||r	  rI  Nc                 (   | j                          t        | j                  j                               D ]  }|j	                  |        t        | j
                  j                               D ]  }|j                           | j                  r-| j                  t        dt        d             | j                  r-| j                  r!| j                  j                          d| _        | j                  r | j                  | |       d| _        d| _        | j                  rf| j                   rZ| j                   j#                         s@|r| j                   j%                  |       n| j                   j'                  d       d| _        | j(                  r"| j(                  j+                  |       d| _        | j-                          | j.                  j1                          d| _        | j4                  r"| j4                  j                          d| _        yy)zClean up this connectionr   r	  N)_cancel_keepalive_timerlistr  valuesprocess_connection_closer  r  r  _process_global_responserX   r   rz  r  r  r  r  r  	cancelledset_exception
set_resultr  rK  _cancel_login_timerr4  rS  r  rm  )r  rI  chanlisteners       r  _cleanupzSSHConnection._cleanup  s    	$$&..01D))#. 2 T2299;<HNN = **))*=q*3C.: ** ::JJDJc*!DN"&D::$,,t||/E/E/G**3/''-DJ;;KK'',DK  "<<LL DL r	  c                 `    | j                   r"| j                   j                          d| _         yy)zCancel the login timerN)r  r  r  s    r  r  z!SSHConnection._cancel_login_timer  s,     $$& $D r	  c                 F    d| _         | j                  t        d             y)z;Close the connection if authentication hasn't completed yetNzLogin timeout expired)r  rK  r   r  s    r  r  z#SSHConnection._login_timer_callback  s      !^,CDEr	  c                 `    | j                   r"| j                   j                          d| _         yy)zCancel the keepalive timerN)rl  r  r  s    r  r  z%SSHConnection._cancel_keepalive_timer  s,       !!((*$(D! !r	  c                     | j                   r6| j                  j                  | j                   | j                        | _        yy)zSet the keepalive timerN)rk  r  r  _keepalive_timer_callbackrl  r  s    r  _set_keepalive_timerz"SSHConnection._set_keepalive_timer  s;     ##$(JJ$9$9(($*H*H%JD! $r	  c                 ^    | j                   r!| j                          | j                          yy)zReset the keepalive timerN)r|  r  r  r  s    r  _reset_keepalive_timerz$SSHConnection._reset_keepalive_timer  s*     ((*%%' r	  c                    K   | j                   j                  d       | j                  d       d{    | j                  r| j                   j                  d       d| _        y7 3w)zSend keepalive requestzSending keepalive requests   keepalive@openssh.comNzGot keepalive responser   )r{   debug1_make_global_requestrl  rg  r  s    r  _make_keepalive_requestz%SSHConnection._make_keepalive_request  sZ      	67''(@AAA  KK78 ! 	Bs   0A(A&4A(c                    | xj                   dz  c_         | j                   | j                  kD  r0| j                  t        | j	                         rdnddz                y| j                          | j                  | j                                y)zHandle keepalive checkr   ServerClientz not responding to keepaliveN)rg  ri  rK  r   	is_clientr  create_taskr  r  s    r  r  z'SSHConnection._keepalive_timer_callback&  sz     	"  4#<#<<  DNN,<(= > ?@ %%'T99;<r	  c                     | j                   sy| j                   j                          d| _         | j                  j                  | j                  |       y)z*Force this connection to close immediatelyN)r/  rQ  r  	call_soonr  r  rI  s     r  _force_closezSSHConnection._force_close3  s=     

T]]C0r	  task_loggertaskzasyncio.Task[None]c                 6   	 |j                          y# t        j                  $ r Y yt        $ rL}| j	                  |j
                  |j                  |j                         | j                  |       Y d}~yd}~wt        $ r | j                  |       Y yw xY w)z1Collect result of an async task, reporting errorsN)error_logger)r  r2  r  r   _send_disconnectcodereasonlangr  rT  internal_error)r  r  r  rI  s       r  
_reap_taskzSSHConnection._reap_task>  sy    
	:KKM%% 	 	#!!#((CJJAc"" 	:[9	:s     BBAA77BBcoroc                 z    t        j                  |      }|j                  t        | j                  |             |S )z<Create an asynchronous task which catches and reports errors)r2  ensure_futureadd_done_callbackr   r  )r  r  r  r  s       r  r  zSSHConnection.create_taskM  s2    
 $$T*wtDEr	  c                     | j                    S )z%Return if this is a client connectionr  r  s    r  r  zSSHConnection.is_clientV  s     <<r	  c                     | j                   S )z%Return if this is a server connectionr  r  s    r  	is_serverzSSHConnection.is_server[  s     ||r	  c                 6    | j                   j                         S )z'Return whether the connection is closed)r4  is_setr  s    r  r  zSSHConnection.is_closed`  s       ''))r	  c                     | j                   S )z<Return the SSHClient or SSHServer which owns this connection)r  r  s    r  	get_ownerzSSHConnection.get_ownere  s     {{r	  c                     dj                  t        | j                        t        | j                        t        | j                        t        | j
                        f      S )zReturn the bytes used in calculating unique connection hashes

           This methods returns a packetized version of the client and
           server version and kexinit strings which is needed to perform
           key exchange hashes.

        r	  )joinr   r   r!  r"  r#  r  s    r  get_hash_prefixzSSHConnection.get_hash_prefixj  sQ     xx 4 45 4 45 4 45 4 457 8 	8r	  rZ  c                     || _         y)z'Set tunnel used to open this connectionN)rm  )r  rZ  s     r  ri  zSSHConnection.set_tunnelx  s     r	  known_hostsrk  r  rm  c                    t        ||||      \  }}}}}	}
}| j                  J |D ][  }| j                  j                  |       |j                  | j                  vs7| j                  j                  |j                         ] t        |      | _        t        |      | _	        | j                  Tt        | j                        | _
        | j                  j                  |       t        |	      | _        |
| _        || _        yy)z7Determine the set of trusted host keys and certificatesN)rp   r9  add	algorithmr:  r  sig_algorithmsrS  r;  r<  r>  r  rA  rB  rC  )r  r  rk  r  rm  trusted_host_keystrusted_ca_keysrevoked_host_keystrusted_x509_certsrevoked_x509_certstrusted_x509_subjectsrevoked_x509_subjectskeys                r  _match_known_hostsz SSHConnection._match_known_hosts}  s     "+tT4@	9?,= 2!#8 &&222$C##'',}}D$?$??++2233E3EF	 % !$O 4"%&7"8##/'+D,D,D'ED$$$++,>?'*+='>D$*?D'*?D' 0r	  certc                 h   | j                   |j                  | j                  v rt        d      | j                  st        d      |j                  | j                   vr3| j                  j                  ||||j                        st        d      |j                  t        |       |j                  S )z$Validate an OpenSSH host certificatezHost CA key is revokedConnection closedzHost CA key is not trusted)	r;  signing_keyr<  r  r  validate_host_ca_keyvalidater   r  )r  rk  r  rm  r  s        r  "_validate_openssh_host_certificatez0SSHConnection._validate_openssh_host_certificate  s    
   ,4#:#:: !9::;; !455t'<'<<;;33D$484D4DF !=>>MM.$/xxr	  c                    | j                   r)t        fd| j                   D              rt        d      | j                  r)t        fd| j                  D              st        d      | j                  rd}| j                  J j                  | j                  | j                  | j                  | j                  |       j                  S )z"Validate an X.509 host certificatec              3   T   K   | ]  }|j                  j                         ! y wr,  r  subjectr  r  r  s     r  r  zFSSHConnection._validate_x509_host_certificate_chain.<locals>.<genexpr>  s'      @#> OODLL1#>   %(zX.509 subject name is revokedc              3   T   K   | ]  }|j                  j                         ! y wr,  r  r  s     r  r  zFSSHConnection._validate_x509_host_certificate_chain.<locals>.<genexpr>  s'      D'BG  5'Br  z!X.509 subject name is not trustedr  )host_principal)
rC  anyr  rB  r>  validate_chainr@  rA  rE  r  )r  rk  r  s     `r  %_validate_x509_host_certificate_chainz3SSHConnection._validate_x509_host_certificate_chain  s     '' @#'#>#>@ @<=='' D'+'B'BD D@AA
 &&D''333D44 99 44 //+/	 	 	1 xxr	  key_datac           	         	 t        |      }|j                  r | j                  |t        t        |            S | j                  |||t        t        |            S # t        $ r Y nw xY w	 t        |      }| j                  g|| j                  v rt        d      | j                  st        d      || j                  vr)| j                  j                  ||||      st        d      |S # t        $ r Y t        d      w xY w)z&Validate and return a trusted host keyzHost key is revokedr  zHost key is not trustedzUnable to decode host key)r   is_x509_chainr  r   r   r  r   r   r   r9  r<  r  r  validate_host_public_key)r  rk  r  rm  r  r  r  s          r  _validate_host_keyz SSHConnection._validate_host_key  s    
	I)(3D !!AA$6=? ? >>$d+@$&GI I  			'1C &&2$111$%:;;{{$%899d555{{;;D$<@#G$%>??J  	  455#	s#   A 	A'&A'+C+ +	D Dr=  c                 d   t        t        j                  |      | _        t        t        j                  |j                  d            }|rh|j                  t        j                  t        j                  | j                         |j                  t        j                  t        j                  d       t        t        |j                  d            }|r|dd \  | _        | _        t        t        |j                  d            }|r|dd \  | _        | _        | j#                         | _        	 | j'                          | j$                  j)                  |        | j+                          y# t,        $ r; | j.                  j1                  | j2                  t5        j6                                Y yw xY w)z Handle a newly opened connectionsocketr   socknameN   peername)r   r2  	Transportr/  r  r9  
setsockopt
SOL_SOCKETSO_KEEPALIVEr  IPPROTO_TCPTCP_NODELAYr   r  r  r  r  r  r  _connection_maderB  _send_versionrT  r  r  r  sysexc_info)r  r=  rr  r  r  s        r  rB  zSSHConnection.connection_made  sF    w00)<FMM9#;#;H#EFOOF--v/B/B //1OOF..0B0BAF)":"::"FG19"1.Dd.)":"::"FG/7|,DOT_,,.	F!!#KK''-  	FJJ  !4!4cllnE	Fs   /;E+ +AF/.F/c                 X    || j                   rt        d      }| j                  |       y)z"Handle the closing of a connectionNzConnection lost)r/  r   r  r  s     r  rK  zSSHConnection.connection_lost  s(     ;4?? !23C#r	  r  r  c                     |st        j                         }|s| j                  }|j                  d|       | j	                  t        t        |d                y)z-Handle a fatal error in connection processingzUncaught exception)r  r   N)r  r  r{   r  r  r   rT  )r  r  r  s      r  r  zSSHConnection.internal_error  sK     ||~H;;L08D$y(1+67r	  c                      y)z9Handle session start when opening tunneled SSH connectionNr  r  s    r  session_startedzSSHConnection.session_started&  r  r	  rE  datatypec                    | xj                   |z  c_         | j                          	 | j                   r1| j                         r 	 | j                   r| j                         ryyyy# t        $ rL}| j	                  |j
                  |j                  |j                         | j                  |       Y d}~yd}~wt        $ r | j                          Y yw xY w)z&Handle incoming data on the connectionN)r  r  r-  r   r  r  r  r  r  rT  r  )r  rE  r  rI  s       r  rG  zSSHConnection.data_received*  s    
 	##%	",,4#5#5#7 ,,4#5#5#7,#7, 	#!!#((CJJAc"" 	"!	"s   9A% %	C.AB55CCc                 &    | j                  d       y)z0Handle an incoming end of file on the connectionN)rK  r  s    r  eof_receivedzSSHConnection.eof_received>  s     	T"r	  c                      y)z9Handle a request from the transport to pause writing dataNr  r  s    r  pause_writingzSSHConnection.pause_writingC  r  r	  c                      y)z:Handle a request from the transport to resume writing dataNr  r  s    r  resume_writingzSSHConnection.resume_writingH  r  r	  r  c                 2   | j                   st        t        d      | j                  | j                  v r0| j                  dz   dz  | _        | j                  | j                  v r0| j                  }| j                  dz   dz  | _        || j                  |<   |S )z/Add a new channel, returning its channel numberzSSH connection closedr       )r/  r   rZ   r  r  )r  r  	recv_chans      r  add_channelzSSHConnection.add_channelM  s     "#6#:< < ""dnn4$($8$81$<
#JD  ""dnn4 ((	 $ 4 4q 8JF$(y!r	  r  c                     | j                   |= y)z4Remove the channel with the specified channel numberN)r  )r  r  s     r  remove_channelzSSHConnection.remove_channel]  s     NN9%r	  c                 6    | j                   J | j                   S )z6Return the GSS context associated with this connection)r[  r  s    r  get_gss_contextzSSHConnection.get_gss_contextb  s     yy$$$yyr	  c                 &    | j                   | _        y)z&Enable GSS key exchange authenticationN)r]  r^  r  s    r  enable_gss_kex_authz!SSHConnection.enable_gss_kex_authh  s     "^^r	  r  
local_algsremote_algsc           
          | j                         r||}}n||}}|D ]
  }||v s|c S  t        d|ddj                  |      j                  d      ddj                  |      j                  d            )zChoose a common algorithm from the client & server lists

           This method returns the earliest algorithm on the client's
           list which is supported by the server.

        zNo matching z algorithm found, sent    ,r  z and received )r  r   r  r  )r  r  r  r  client_algsserver_algsr  s          r  _choose_algzSSHConnection._choose_algm  s{     >>'1;K'2JKCk!
   tyy,33G<YY{#**7356 	6r	  c                 2    | j                         rddgS ddgS )z Return the extra kex algs to add
   ext-info-c   kex-strict-c-v00@openssh.com
   ext-info-s   kex-strict-s-v00@openssh.com)r  r  s    r  _get_extra_kex_algsz!SSHConnection._get_extra_kex_algs  s&     >>!#BCC!#BCCr	  c                 t    | j                   r	 | j                   j                  |       yy# t        $ r Y yw xY w)zSend data to the SSH connectionN)r/  rN  BrokenPipeErrorrO  s     r  _sendzSSHConnection._send  s;     ??%%d+  # s   + 	77c                 D   d| j                   z   }| j                  j                  d|       | j                         r)|| _        | j                  |j                  d             n(|| _        | j                  |j                  d             | j                  |dz          y)zStart the SSH handshake   SSH-2.0-zSending version %sr  client_versionserver_versions   
N)	r  r{   r  r  r   set_extra_infor  r!  r(  )r  r  s     r  r   zSSHConnection._send_version  s     -/9>>#*D w~~g/FG#*D w~~g/FG

7W$%r	  c                 <   | j                   j                  ddt              }|dk  r7t        | j                         t        k\  r| j	                  t        d             y| j                   d| }|j                  d      r|dd }| j                   |dz   d | _         |j                  d	      s!| j                         r|j                  d
      rt        |      t        kD  r| j	                  t        d             | j                         r)|| _        | j                  |j                  d             n(|| _        | j                  |j                  d             | j                  j!                  d|       | j#                          d| _        | j&                  | _        y| j                         rU|j                  d      sD| xj*                  dz  c_        | j*                  t,        kD  r| j	                  t        d             yy| j	                  t/        d             y)z(Receive and parse the remote SSH version   
r   zBanner line too longFN   r   r*  s	   SSH-1.99-zVersion too longr  r+  r-  zReceived version %sTs   SSH-zToo many banner lineszUnsupported SSH version)r  find_MAX_BANNER_LINE_LENr  r  r   endswith
startswithr  _MAX_VERSION_LINE_LENr  r   r/  r  r!  r{   r  _send_kexinitrW  _recv_pkthdrr-  r  _MAX_BANNER_LINESr   )r  idxr  s      r  r,  zSSHConnection._recv_version  s    llq*>?74<< $88!!-0F"GH,,t$E"crlG||CEF+{+!g&8&8&F7|33!!-0B"CD ~~'.$##7>>'3J#K'.$##7>>'3J#KKK4g> !%D!%!2!2D  ^^g&8&8&A!#!!$55!!-0G"HI  23LMNr	  c                    t        | j                        | j                  k  ry| j                  d| j                   | _        | j                  | j                  d | _        | j                  r:| j                  j                  | j                  | j                  d      \  | _        }n| j                  dd }t        j                  |d      | _	        | j                  | _        y)z&Receive and parse an SSH packet headerFN   bigT)r  r  r0  r  r/  decrypt_headerr.  r  
from_bytesr  _recv_packetr-  )r  pktlens     r  r:  zSSHConnection._recv_pkthdr  s     t||t333||$9T%9%9:||D$8$8$9:  %%44T^^59\\1F !DL& \\"1%F~~fe4!..r	  c                    d| j                   z   | j                  z   | j                  z
  }t        | j                        |k  ry| j
                  }| j                  d|| j                  z
   }| j                  || j                  z
  | }| j                  r6| j                  j                  || j                  |d|      }|st        d      | j                  dd |z   }| j                  |d | _        d| _        |d|d     }| j                  r@| j                  s| j                  s(| j                  j                  |      }|t        d      |}t        |      }|j!                         }	| }
d	}d	}t"        |	cxk  r	t$        k  r7n n4| j&                  r#| j(                  r
d
}d| _        n| j&                  }
nd}d}n| j*                  r*| j                  st,        |	cxk  r	t.        k  rn nd}d|	z  }nt0        |	cxk  r	t2        k  r!n n| j4                  r| j4                  }
npd}d}nk|	t$        kD  r| j                  sd}d}nQ|	t2        kD  r| j                  sd}d}n7t6        |	cxk  r	t8        k  r$n n!	 |j;                         }	 | j<                  |   }
|
jC                  |	|||       |so	 |
jE                  |	||      }|sY| j*                  r| j                  sd|	z  }n;| jJ                  jM                  d|	       | jO                  tP        tS        |             |rtG        |      |	t2        kD  rd| _*        | jV                  ra| jX                  | _-        | j
                  dk(  r| j                  stG        d      |	t\        k(  r| j*                  rd| _        y|dz   dz  | _        y# t>        $ r d}d|z  }Y #w xY w# t@        $ r d}d}Y 7w xY w# t@        $ r}tG        tI        |            dd}~ww xY w)z5Receive the remainder of an SSH packet and process itr>  FNzMAC verification failedr	  r   r   zDecompression failedr  zignored first kexzkex not in progresszKey exchange not in progresszstrict kex violationzAStrict key exchange violation: unexpected packet type %d receivedzauth not in progresszAuthentication not in progressz#invalid request before kex completez0Invalid request before key exchange was completez$invalid request before auth completez2Invalid request before authentication was completezinvalid channel numberz"Invalid channel number %d receivedzincomplete channel requestz#Incomplete channel request receivedzUnknown packet type %d receivedTr  %Sequence rollover before kex complete)/r  r1  r0  r  r  r.  r/  decrypt_packetr  r   r2  r|  r3  
decompressr   r   get_byterN   rO   rV  rY  rZ  rA   rC   rT   rU   rz  rJ   rK   
get_uint32r  KeyErrorr   log_received_packetprocess_packetr   r  r{   r  send_packetrB   r   r}  r/  r:  r-  rM   )r  remseqrestmacpacket_dataorig_payloadpayloadpacketpkttypehandlerskip_reason
exc_reasonr  	processedrI  s                   r  rB  zSSHConnection._recv_packet  s    $,,!3!33d6J6JJt||s"nn||3S!3!334ll3t111#6  //>>T\\4C1K 899,,qr*T1K||CD)"1k!n_54#6#6'+'B'B((33LAG&'=>>"G7#//#$(
G3|3yy))"5K-2D*"iiG3;
d&;&;g220K>@GHJ7?.??zz**4=
|#D,A,A?KKJ((1D1D@KMJ'=-==8"--/	
8"nnY7G 	##GS&+F8#227CH	 ##D,A,A"FHO"PJ KK&&'H'.0$$%6sD
++&&#D??!%!2!2D~~+D4I4I#$KLL+%$*:*:!"  #&'Z!7O   8":K",.7"8J8 % C:B
C  % 8#CH-478s<   -N4 >N $O N10N14OO	O+O&&O+)rW  rV  argsrW  c                   | j                   ri| j                  r]| j                  | j                  k\  s-| j                  r8t        j                         | j                  k\  r| j                          d| _	        |t        t        hv s	|t        kD  r| j                  r6|t        k(  r| j                  s| j                   r|t        kD  r*| j                   s| j                   j#                  ||f       y| j$                  r-|t&        t(        fvr| j+                  t&        t-        d             t/        |      dj1                  |      z   }| j2                  r@| j                   s| j4                  s(| j2                  j7                  |      }|t9        d      |}| j:                  t=        |      z    | j>                  z  }|dk  r|| j>                  z  }t/        |      |z   tA        jB                  |      z   }t=        |      }tE        |      }	| jF                  }
| j$                  r!| j$                  jI                  |
|	|      \  }}n|	|z   }d}| jK                  ||z          | jF                  dk(  r| j$                  sd| _#        tM        d      |tN        k(  r| jP                  rd| _#        n|
d	z   dz  | _#        | j                  r| xj                  |z  c_        |s| }|jS                  ||
|       y)
zSend an SSH packetTNr	  zCompression failedr>  r  r   rE  r   )*r|  rX  re  rb  rd  time	monotonicrf  r9  rW  rD   rE   rO   rS   r{  rU   r+  r  r&  rA   rF   rM  r   r   r  r)  r*  compressr   r'  r  r(  osurandomr   r%  encrypt_packetr(  r   rM   rZ  log_sent_packet)r  rV  rW  r[  rS  rT  padlenrU  rC  hdrrO  rQ  s               r  rM  zSSHConnection.send_packet^  s~    D$6$6''4+<+<<%%.."d&6&66 !%D-/ABB$d.@.@//,,0C0C,,T5H5H""))7D/:   WZ4N%NZ5G}sxx~5!4!4%)%>%>&&//=G&';<<"G''#g,67$:N:NNA:d***Ff'"**V*<<VVnnn  //>>sCPKFC6\FC

6C< >>Z'0E0EDN GHHk!d&6&6DN!Ag3DN""f,"Gl;r	  c                 d    | j                   }g | _         |D ]  \  }} | j                  |g|   y)z1Send packets deferred due to key exchange or authN)r+  rM  )r  deferred_packetsrV  r[  s       r  _send_deferred_packetsz$SSHConnection._send_deferred_packets  s;      11!#-MGTDW,t, .r	  r  r  r  c                     | j                   j                  d||       | j                  t        t	        |      t        |      t        |             y)zSend a disconnect packetzSending disconnect: %s (%d)N)r{   r~  rM  r@   r   r   )r  r  r  r  s       r  r  zSSHConnection._send_disconnect  s>     	6E	7r	  c                    d| _         d| _        | j                  r&t        j                         | j                  z   | _        | j                  r%| j                  J | j                  j                  }ng }t        | j                  |t        | j                              | j                         z   }| j                  xs dg}| j                  j                  d       | j                  j!                  d|       | j                  j!                  d|       | j                  j!                  d| j"                         | j                  j!                  d	| j$                         | j                  j!                  d
| j&                         t)        j*                  d      }t-        |      }t-        |      }t-        | j"                        }t-        | j$                        }t-        | j&                        }t-        g       }dj/                  t1        t2              |||||||||||t5        d      t7        d      f      }	| j9                         r|	| _        n|	| _        | j?                  t2        |	dd        y)zStart a key exchangeFr   Ns   nullzRequesting key exchange  Key exchange algs: %s  Host key algs: %sz  Encryption algs: %sz  MAC algs: %sz  Compression algs: %s   r	  r   ) rX  re  rd  r]  r^  rf  r\  r[  mechsri   rF  r  r  r%  r{   r  debug2rH  rI  rK  r`  ra  r   r  r   rL   r   r   r  r#  r"  rM  )
r  	gss_mechsr  host_key_algscookier  r  r  langsrU  s
             r  r9  zSSHConnection._send_kexinit  s    #!"#~~/$2E2EED==99(((		II"4>>9#'(B(B#CE++-. 22?wi454h?0-@2DNNC+T^^<3T^^DBH% /DNN+DNN+DNN+4,fh#Xx8#UE75>6!9N O >>#)D #)D fQRj1r	  c                 T   t        t        | j                              }| j                  j	                  d       | j                  j                         D ]<  \  }}|t        |      t        |      z   z  }| j                  j	                  d||       > | j                  t        |       y)zSend extension informationzSending extension info  %s: %sN)	r   r  ru  r{   ro  itemsr   rM  rF   )r  rU  r6  values       r  _send_ext_infozSSHConnection._send_ext_info  s     D4456343399;KD%fTlVE]22FKKz47 <
 	v.r	  khc           
      j   | j                   s
d}|| _         nd}t        | j                  | j                        \  }}}}}}	t        | j                  | j
                        \  }
}}}}}|dk(  r| j                  | _        |dk(  r| j                  | _        t        | j                        }t        | j                        }| j                  j                  d       | j                  j                  d| j                         | j                  j                  d| j                         | j                  j                  d| j                         | j                  j                  d       | j                  j                  d| j                         | j                  j                  d| j
                         | j                  j                  d| j                         | j                  J | j                  j                  ||d
| j                   |      }| j                  j                  ||d| j                   |      }| j                  j                  ||d| j                   |      }| j                  j                  ||d| j                   |
      }| j                  j                  ||d| j                   |      }| j                  j                  ||d| j                   |      }d	| _        t        | j                  ||| j                  ||	      }t        | j                  ||| j
                  ||      }| j                  t               d| j                   d<   | j#                         r|| _        |	rdnd| _        t)        d|      | _        t-        | j                        | _        || _        || _        t)        d|      | _        || _        t9        | j                        | _        || _        | j?                  | j                  jA                  d      | j                  jA                  d      | j                  jA                  d      | j                  jA                  d      | j
                  jA                  d      | j                  jA                  d             |r| jB                  dk(  r| jD                  r| jD                  jG                         s|| jD                  jI                  d	       d	| _!        y	djK                  | jL                        | j                   d<   || _        |rdnd| _        t)        d|      | _        t-        | j                        | _        || _        || _        t)        d|      | _        || _        t9        | j                        | _        || _        | j?                  | j                  jA                  d      | j
                  jA                  d      | j                  jA                  d      | j                  jA                  d      | j                  jA                  d      | j                  jA                  d             | jN                  r| jQ                          d| _'        d| _)        |r1| j#                         r| jU                  tV               ntV        | _,        | j[                          y	)z1Finish a key exchange and send a new keys messageTFr     Client to server:z    Encryption alg: %sz    MAC alg: %sz    Compression alg: %s  Server to client:N   A   B   C   D   E   Fr	  s   global-requests-okr   r  r	  r  )send_ciphersend_macsend_compressionrecv_cipherrecv_macrecv_compressionkexr     server-sig-algs).r$  r_   rn  rp  ro  rq  r5   rr  rs  r{   ro  rV  compute_keyr`   rM  rM   ru  r  r&  r'  maxr(  r6   r)  r*  r4  r5  r6  r7   r7  r8  r/  r  r  r  r  r  r  rM  rt  rx  rX  send_service_request_USERAUTH_SERVICErx  rh  )r  ry  rz  	first_kexenc_keysize_csenc_ivsize_csenc_blocksize_csmac_keysize_csmac_hashsize_csetm_csenc_keysize_scenc_ivsize_scenc_blocksize_scmac_keysize_scmac_hashsize_scetm_sccmp_after_auth_cscmp_after_auth_sciv_csiv_sc
enc_key_cs
enc_key_sc
mac_key_cs
mac_key_scnext_enc_csnext_enc_scs                             r  send_newkeyszSSHConnection.send_newkeys  s    I DI "$"2"2D4D4DE	0'7
 "$"2"2D4D4DE	0'7 Q#//DQ#//D243C3CD243C3CD013T5E5EF,d.>.>?4d6F6FG013T5E5EF,d.>.>?4d6F6FGyy$$$		%%aD$2B2B&35		%%aD$2B2B&35YY**1at7G7G+9;
YY**1at7G7G+9;
YY**1at7G7G+9;
YY**1at7G7G+9;
	$T%5%5z5%)%5%5z6K$T%5%5z5%)%5%5z6K 	%:=  !67>>$/D!(.1AD #&q*:#;D -d.>.>?D(9D%)4D&(+A/?(@D%&5D#&6t7G7G&HD#/@D, ,,33G<))009!%!1!1!8!8!A ,,33G<))009!%!1!1!8!8!A   C ::&4<< LL224LL++D1!%DJ 		$..) $$%78 %0D!(.1AD #&q*:#;D -d.>.>?D(9D%)4D&(+A/?(@D%&5D#&6t7G7G&HD#/@D, ,,33G<))009!%!1!1!8!8!A ,,33G<))009!%!1!1!8!8!A   C ""!&+D#!~~))*;<%6"##%r	  servicec                     | j                   j                  d|       || _        | j                  t        t        |             y)zSend a service requestzRequesting service %sN)r{   ro  rx  rM  rD   r   )r  r  s     r  r  z"SSHConnection.send_service_requestn  s6     	2G<$,fWo>r	  method.c                     dj                  t        t              t        | j                        t        t
              t        |      f|z         S )z1Get packet data for a user authentication requestr	  )r  r   rP   r   r  _CONNECTION_SERVICEr  r  r[  s      r  _get_userauth_request_packetz*SSHConnection._get_userauth_request_packetv  sH     xx23VDNN5K 34fVnFHLM N 	Nr	  c                 R    t        | j                        | j                  ||      z   S )z4Get signature data for a user authentication request)r   r$  r  r  s      r  get_userauth_request_dataz'SSHConnection.get_userauth_request_data}  s.     t''(11&$?@ 	Ar	  T)rW  trivialr  c                Z    | xj                   |z  c_          | j                  |g|d|i y)z!Send a user authentication packetrW  N)r  rM  )r  rV  rW  r  r[  s        r  send_userauth_packetz"SSHConnection.send_userauth_packet  s/    
 	')9499r	  )r  r  r  c                  K   | j                  ||      }|rt        | j                        |z   }t        |dd      }|r ||       d{   }nNt        |dd      r0| j                  j                  d|j                  |       d{   }n|j                  |      }|t        |      z  }| j                  t        |dd |       y7 }7 Bw)z"Send a user authentication request
sign_asyncNuse_executorFr   )r  )	r  r   r$  r  r  run_in_executorsignr  rP   )	r  r  r  r  r[  rU  rE  r  sigs	            r  send_userauth_requestz#SSHConnection.send_userauth_request  s     
 2264@$**+f4D \40  &t,,ne4 JJ66tSXXtLLhhtnfSk!F!!"6qr
*1 	" 	3 -Ls%   AC	C
<CC	AC	Cpartial_successc                     t        t        t        |             }| j                  j	                  d|xs d       d| _        | j                  t        t        |      t        |             y)z+Send a user authentication failure responseRemaining auth methods: %sNoneN)
r$   r   SSHServerConnectionr{   ro  rz  rM  rQ   r   r   )r  r  methodss      r  send_userauth_failurez#SSHConnection.send_userauth_failure  s\     4$d+- 	79JFK
-x/@ 1	3r	  c                 ,   | j                   j                  d| j                         | j                  t               d| _        d| _        d| _        d| _        | j                  | j                         | j                          | j                          | j                          | j                  r| j                  j                          | j                  rI| j                  |       }t!        j"                  |      r|J | j%                  |       d| _        d| _        | j(                  dk(  rI| j*                  r=| j*                  j-                         s#| j*                  j/                  d       d| _        yt1        t2        |       j5                          y)z+Send a user authentication success responseAuth for user %s succeededNFTrd  auth)r{   r~  r  rM  rR   rz  r{  r|  rx  r/  rh  r  r  r  auth_completedr  inspectisawaitabler  r  r  r  r  r  r   r  send_server_host_keysr  r  s     r  send_userauth_successz#SSHConnection.send_userauth_success  s;    	5t~~F-.
!&"!T^^4##%  "!!#;;KK&&(>>^^D)F""6*)))  (!DN"&D::DLLLL**,LL##D)DJ 	 $'==?r	  	send_chanrecv_windowrecv_pktsizeresult_argsc           	           | j                   t        t        |      t        |      t        |      t        |      g|  y)z Send a channel open confirmationN)rM  rH   r   )r  r  r  r  r  r  s         r  send_channel_open_confirmationz,SSHConnection.send_channel_open_confirmation  s=    
 	6y8I	*F;,?-	=0;	=r	  c           	      ~    | j                  t        t        |      t        |      t        |      t        |             y)zSend a channel open failureN)rM  rI   r   r   )r  r  r  r  r  s        r  send_channel_open_failurez'SSHConnection.send_channel_open_failure  s0     	16)3Dvf~vd|	Er	  F)
want_replyrequestr  c                Z     | j                   t        t        |      t        |      g|  y)zSend a global requestN)rM  rV   r   r   )r  r  r  r[  s       r  _send_global_requestz"SSHConnection._send_global_request  s-     	+VG_ ,	5/3	5r	  c                    K   | j                   st        t        d      fS | j                  j	                         }| j
                  j                  |        | j                  |g|ddi | d{   S 7 w)z/Send a global request and wait for the responser	  r  TN)r/  rX   r   r  r|  r  r  r  )r  r  r[  r}  s       r  r  z"SSHConnection._make_global_request  so      &	#66 JJ$$& 	 	$$++F3!!!'BDBTB||s   A.A70A51A7r  c                    | j                   j                  d      \  }}}|rD|r-|du rdnt        t        |      }| j	                  t
        |       n| j	                  t               | j                   r| j                          yy)z>Report back the response to a previously issued global requestr   Tr	  N)r  r  r   r  rM  rW   rX   _service_next_global_request)r  r  rY  r  responses        r  _report_global_responsez%SSHConnection._report_global_response  su      5599!<1j"(D.3d5&6I  !4h?  !45%%--/ &r	  c                 t    | j                   d   \  }}}t        |      r	 ||       y| j                  d       y)z)Process next item on global request queuer   FN)r  callabler  )r  rW  rU  rY  s       r  r  z*SSHConnection._service_next_global_request  s8     "77:GFO((/r	  c                     t         )&Handle the opening of a new connectionNotImplementedErrorr  s    r  r  zSSHConnection._connection_made  
     "!r	  _pkttype_pktidrU  c                    |j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }| j                  j                  d||       |t        k7  s| j                  rt        |||      }	nd}	| j                  |	       y# t        $ r t        d      dw xY w)zProcess a disconnect messageutf-8r  zInvalid disconnect messageNzReceived disconnect: %s (%d))rI  
get_string	check_endr  UnicodeDecodeErrorr   r{   r  r>   r  r   r  )
r  r  r  rU  r  reason_bytes
lang_bytesr  r  rI  s
             r  _process_disconnectz!SSHConnection._process_disconnect  s       "((*&&(
	H!((1F$$W-D 	964H&&$**';D&$'OCC# " 	H <=4G	Hs   "B8 8Cc                 b    d| j                   vr!|j                         }|j                          yy)zProcess an ignore messages   CiscoN)r!  r  r  r  r  r  rU  rY  s        r  _process_ignorezSSHConnection._process_ignore4  s1     4///!!#A 0r	  c                 D    |j                         }|j                          y)z)Process an unimplemented message responseN)rI  r  r  s        r  _process_unimplementedz$SSHConnection._process_unimplemented>  s     r	  c                    |j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }| j                  j                  d||rdnd       | j                  r| j                  j                  |||       yy# t        $ r t        d      dw xY w)zProcess a debug messager  r  zInvalid debug messageNzReceived debug message: %s%s (always display)r  )
get_booleanr  r  r  r  r   r{   r  r  debug_msg_received)	r  r  r  rU  always_display	msg_bytesr  rs  r  s	            r  _process_debugzSSHConnection._process_debugG  s      ++-%%'	&&(
	C""7+C$$W-D 	932@.b	J ;;KK**3nE  " 	C 78dB	Cs   "B0 0Cc                    |j                         }|j                          | j                         rt        d      | j                  st        d      || j
                  k7  rt        d      | j                  j                  d|       | j                  t        t        |             d| _        |t        k(  rd| _        d| _        | j                          yy)zProcess a service requestz#Unexpected service request receivedz,Service request received before kex completez%Unexpected service in service requestz Accepting request for service %sNTF)r  r  r  r   r/  rx  r   r{   ro  rM  rE   r   r  r{  rv  rh  r  r  r  rU  r  s        r  _process_service_requestz&SSHConnection._process_service_request\  s     ##%>> EFF$$ NOOd(((%&MNN=wG+VG_=!''%)D"&+D#'') (r	  c                    |j                         }|j                          | j                         rt        d      | j                  st        d      || j
                  k7  rt        d      | j                  j                  d|       d| _        |t        k(  rH| j                  j                  d| j                         d| _        t        d|       j                          yy)	z!Process a service accept responsez"Unexpected service accept receivedz+Service accept received before kex completez$Unexpected service in service acceptzRequest for service %s acceptedNBeginning auth for user %sTr_  )r  r  r  r   r/  rx  r   r{   ro  r  r~  r  r{  r   try_next_authr  s        r  _process_service_acceptz%SSHConnection._process_service_acceptw  s     ##%>> DEE$$ MNNd(((%&LMM<gF!''KK94>>J%)D" &-;;= (r	  c                    | j                   st        d      i }| j                  j                  d       |j	                         }t        |      D ]D  }|j                         }|j                         }|||<   | j                  j                  d||       F |j                          | j                         r0t        |j                  dd      j                  d            | _        yy)zProcess extension informationzUnexpected ext_info receivedzReceived extension inforu  r  r	  r  N)rv  r   r{   ro  rI  ranger  r  r  rS  r  rf  rw  )	r  r  r  rU  
extensionsnum_extensionsrY  r6  rw  s	            r  _process_ext_infozSSHConnection._process_ext_info  s     && >??)+
45**,~&A$$&D%%'E$JtKKz47 ' 	>>JNN#5s;AA$GH ! r	  c                 
   | j                   rt        d      |j                  d      }|j                         }|j                         }|j                         }|j                         }|j                         }	|j                         }
|j                         }|j                         }|j                         }|j                         }|j	                         }|j                         }|j                          | j                         r8|j                         | _	        | j                  sNd|v rd| _        d|v r?d| _        n7|j                         | _        | j                  sd|v rd| _        d|v rd| _        | j                  r&| j                  s| j                  dk7  rt        d	      | j                   rd
| _        n| j#                          | j$                  r| j$                  j'                          | j(                  r%| j$                  J | j$                  j*                  }ng }t-        | j.                  |t1        | j2                              }| j4                  j7                  d       | j4                  j9                  d|       | j4                  j9                  d|       | j4                  j9                  d       | j4                  j9                  d|       | j4                  j9                  d|	       | j4                  j9                  d|       | j4                  j9                  d       | j4                  j9                  d|       | j4                  j9                  d|
       | j4                  j9                  d|       | j;                  d||      }t=        | |      | _         |xr | j                   j>                  |d   k7  | _         | j                         r;tC        tD        |       jG                  |      s|jI                  d      stK        d      | j;                  d| jL                  |      | _'        | j;                  d| jL                  |      | _(        | j;                  d| jR                  |	      | _*        | j;                  d| jR                  |
      | _+        | j;                  d| jX                  |      | _-        | j;                  d| jX                  |      | _.        | j4                  j7                  d       | j4                  j9                  d| j                   j>                         | j                   j_                          y)zProcess a key exchange requestz Key exchange already in progressrm  r!  Tr"  r#  r$  r   z?Strict key exchange violation: KEXINIT was not the first packetFNzReceived key exchange requestrk  rl  r|  z    Encryption algs: %sz    MAC algs: %sz    Compression algs: %sr}  r  s   gss-z)Unable to find compatible server host keyr  r  r  zBeginning key exchangez  Key exchange alg: %s)0rV  r   	get_bytesget_namelistr  rI  r  r  get_consumed_payloadr"  r$  rt  rZ  r#  r/  r.  rW  r9  r[  resetr\  rn  ri   rF  r  r  r{   r  ro  r  rj   r  rY  r   r  choose_server_host_keyr7  r   rH  rn  ro  rI  rp  rq  rK  rr  rs  start)r  r  r  rU  rY  peer_kex_algspeer_host_key_algsenc_algs_csenc_algs_scmac_algs_csmac_algs_sccmp_algs_cscmp_algs_scfirst_kex_followsrp  r  kex_algs                    r  _process_kexinitzSSHConnection._process_kexinit  st    99 BCCR ++-#002))+))+))+))+))+))+!!"..0>>#)#>#>#@D ## M1.2D+2mC'+D$#)#>#>#@D ## M1.2D+2mC'+D$D$9$9!# !C D D !&D 99IIOO==99(((		II"4>>9#'(B(B#CE 	:;4mD02DE014kB-{;5{C014kB-{;5{C"">8]KD'*	"3 #J"&))"5"5q9I"I 	 >> ,d3JJ&(070B0B70K' ): ; ;  ++L$..,79++L$..,79  ++E4>>;O++E4>>;O++M4>>,79++M4>>,79 	343TYY5H5HI		r	  c                 P   |j                          | j                  rd| j                  | _        | j                  | _        | j
                  | _        | j                  | _        | j                  | _
        d| _        d| _        nt        d      | j                  j                  d       y)z4Process a new keys message, finishing a key exchangeNTzNew keys not negotiatedzCompleted key exchange)r  r4  r/  r5  r0  r6  r1  r7  r2  r8  r3  rv  r   r{   r  )r  r  r  rU  s       r  _process_newkeyszSSHConnection._process_newkeys	  s     	%%$($>$>D!#'#<#<D !%!8!8D!%!8!8D*.*J*JD')-D&&*D# 9::34r	  c                    |j                         }|j                         }|j                         }t        |      t        k\  rt        d      |t        k7  rt        d      	 t        |j                  d            }| j                         rt        d      | j                  r| j                  rt        d      y|| j                  k7  r&| j                   j#                  d|       || _        d}	nd}	| j%                  | j'                  |	||             y# t        t        f$ r}t        t        |            dd}~ww xY w)	z%Process a user authentication requestzUsername too longz"Unexpected service in auth requestr  NzUnexpected userauth requestr  TF)r  r  _MAX_USERNAME_LENr   r  r   r   r  r  r   r  r  r   r|  r}  r  r{   r~  r  _finish_userauth)
r  r  r  rU  username_bytesr  r  rd  rI  
begin_auths
             r  _process_userauth_requestz'SSHConnection._process_userauth_request,	  s-     **,##%""$~"33!"566))%&JKK	6 5 5g >?H >> =>>   #$ABB   4>>)  !=xH!)!
"
T22:vvNO' #M2 	6!#c(+5	6s   #D D?%D::D?r  c                 .  K   | j                   sy|rt        t        |       j                          d{    t        t        | j                         j                  | j                        }t        j                  |      rt        t        t           |       d{   }|s| j                          y| j                   sy| j                  r| j                  j                          t        t        t        |       | j                  ||      | _        y7 7 xw)z/Finish processing a user authentication requestN)r  r   r  reload_configr   r  r  r  r  r
   r  r  rz  r  r%   )r  r  r  rU  r  s        r  r  zSSHConnection._finish_userauthQ	  s      {{ *D1??AAA)T[[1<<T^^LF""6*#IdOV<<**,{{::JJ'-@$(G-1^^VVM
# B
 =s#   1DDA&DDA7DDc                 H   |j                         }|j                         }|j                          | j                  j	                  d|xs d       | j
                  dk(  rY| j                  rM| j                  j                         s3| j                  j                  d       t        |      | _
        d| _        y| j                  rG| j                  j	                  d| j                  xs d       | j                  D cg c]  }||v r|
 }}t        |      | _
        | j                         rh| j                  r\t        t        | j                        }|r|j!                          n|j#                          t        t$        |       j'                          yt)        d      c c}w )z.Process a user authentication failure responser  r  auth_methodsNzPreferred auth methods: %sz$Unexpected userauth failure response)r  r  r  r{   ro  r  r  r  r  r  r~  r`  r  rz  r   r   auth_succeededauth_failedr_  r  r   )r  r  r  rU  r#  r  r  r  s           r  _process_userauth_failurez'SSHConnection._process_userauth_failureo	  s`    **, ,,.7'16	3 ::'DLLLL**,LL##D)!%l!3DDJKK;#33=v? 261E1E 71Ev%5 #1EL 7 ",/>>


DJJ/D##%  " $d+99; FGG%7s   =Fc                    |j                          | j                         rT| j                  rGt        t        | j                        }| j
                  r| j                  rt        d      | j                  j                  d| j                         | j                  dk(  rQ| j                  rE| j                  j                         s+| j                  j                  d       dg| _        d| _        y|j!                          |j#                          d| _        d| _        d| _        d| _        | j*                  r| j*                  j-                          | j/                  | j                         | j1                          | j3                          | j5                          | j6                  r| j6                  j9                          | j:                  rI| j;                  |       }t=        j>                  |      r|J | jA                  |       d| _        d| _!        | j                  d	k(  rK| j                  r>| j                  j                         s#| j                  j                  d       d| _        yyyytE        d
      )z.Process a user authentication success responsezTrivial auth disabledr  r#  Nr  FTr  r  z$Unexpected userauth success response)#r  r  rz  r   r   r  r  r   r{   r~  r  r  r  r  r  r~  r$  r  r{  r|  rv  ry  r  r/  r  rh  r  r  r  r  r  r  r  r  r   )r  r  r  rU  r  r  s         r  _process_userauth_successz'SSHConnection._process_userauth_success	  s    	>>


DJJ/D%%$*D*D&'>??KK94>>Jzz^+..0''-&-Y"!
!KKMDJ%*D""&D&+D#{{!!#8$$&'')%%'{{**,~~-&&v.!---$$V,!%&*#zzV#..0''-!
 1 )5#
   FGGr	  c                    |j                         }|j                         }d| j                  v r#|j                         dk(  r|j                          |j	                          	 |j                  d      }|j                  d      }| j                  j                  d       | j                         r+t        t        | j                        j                  ||       yt        d      # t        $ r t        d      dw xY w)	z,Process a user authentication banner messages   cryptlib    r  r  zInvalid userauth bannerNzReceived authentication bannerzUnexpected userauth banner)r  r!  get_remaining_payloadrH  r  r  r  r   r{   r  r  r   r0   r  auth_banner_received)r  r  r  rU  r  r  rs  r  s           r  _process_userauth_bannerz&SSHConnection._process_userauth_banner	  s     %%'	&&(
 $...,,.%7OO	E""7+C$$W-D 	;<>>DKK(==c4H <== " 	E 9:D	Es   #"C& &C<c                    |j                         }|j                         }	 |j                  d      }dt        |      z   dz   }t        t        t           t        | |d            }|s| j                  j                  d|       | j                  j                  |||f       t        | j                        dk(  r| j                          yy# t        $ r t	        d      dw xY w)zProcess a global requestr  zInvalid global requestN	_process__global_requestz#Received unknown global request: %sr   )r  r  r  r  r   r   r   r   _PacketHandlerr  r{   r  r  r  r  r  )	r  r  r  rU  request_bytesr  r  r6  rW  s	            r  _process_global_requestz%SSHConnection._process_global_request	  s     ))+'')
	D#**73G -g669JJx/tT1JKKKDgN""))7FJ*GHt))*a/--/ 0 " 	D 89tC	Ds   C C"c                     | j                   r@| j                   j                  d      }|j                         s|j                  ||f       yyt	        d      )zProcess a global responser   zUnexpected global responseN)r  r  r  r  r   )r  rV  r  rU  r}  s        r  r  z&SSHConnection._process_global_response
  sU     ''1155a8F##%!!7F"34 &   <==r	  c                    |j                         }|j                         }|j                         }|j                         }d| j                  v r| j                  r|dz  }	 |j	                  d      }	 dt        |      z   dz   }	t        t        t           t        | |	d            }
t        |
      r  |
|      \  }}|j                  ||||       yt        t        d      # t
        $ r t        d      dw xY w# t        $ rc}| j                   j#                  d	||j$                         | j'                  ||j(                  |j$                  |j*                         Y d}~yd}~ww xY w)
zProcess a channel open request   dropbearr   r  zInvalid channel open requestNr/  _openzUnknown channel typez#Open failed for channel type %s: %s)r  rI  r   r)  r  r  r   r   r   r   _OpenHandlerr  r  process_openr   r[   r{   r  r  r  r  r  )r  r  r  rU  chantype_bytesr  send_windowsend_pktsizechantyper6  rW  r  r  rI  s                 r  _process_channel_openz#SSHConnection._process_channel_open
  sh     **,%%'	'')((* $...43C3CAL	J%,,W5H	A!1(!;;gED8L174t3LMG  'g!!)[".9 ''@'=? ? " 	J >?TI	J   	AKKD'5 **9chh+.::sxxA A		As,   !C! 3AC: C: !C7:	E&AE!!E&c                 r   |j                         }|j                         }|j                         }|j                         }d| j                  v r| j                  r|dz  }| j                  j	                  |      }|r|j                  ||||       y| j                  j                  d|       t        d      )z,Process a channel open confirmation responser6  r   z1Received open confirmation for unknown channel %dInvalid channel numberN)	rI  r!  r)  r  r  process_open_confirmationr{   r  r   )	r  r  r  rU  r  r  r;  r<  r  s	            r  "_process_channel_open_confirmationz0SSHConnection._process_channel_open_confirmation3
  s     %%'	%%'	'')((* $...43C3CAL~~!!),**9k+7A KK  ,-68   899r	  c                    |j                         }|j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }	| j                  j                  |      }
|
r|
j                  |||	       y| j                  j                  d|       t        d      # t        $ r t        d      dw xY w)z'Process a channel open failure responser  r  zInvalid channel open failureNz,Received open failure for unknown channel %dr@  )rI  r  r  r  r  r   r  r  process_open_failurer{   r  )r  r  r  rU  r  r  r  r  r  r  r  s              r  _process_channel_open_failurez+SSHConnection._process_channel_open_failureK
  s     %%'	  "((*&&(
	J!((1F$$W-D ~~!!),%%dFD9KK  ,-68   899 " 	J >?TI	Js   "C C"c                 |    |j                          | j                  j                  d       | j                  d       y)z-Process an incoming OpenSSH keepalive requestz"Received OpenSSH keepalive requestTN)r  r{   ro  r  r  rU  s     r  4_process_keepalive_at_openssh_dot_com_global_requestzBSSHConnection._process_keepalive_at_openssh_dot_com_global_requestd
  s1     	?@$$T*r	  c                 \    | j                   j                  d       | j                  d       y)a  Forcibly close the SSH connection

           This method closes the SSH connection immediately, without
           waiting for pending operations to complete and without sending
           an explicit SSH disconnect message. Buffered data waiting to be
           sent will be lost and no more data will be received. When the
           the connection is closed, :meth:`connection_lost()
           <SSHClient.connection_lost>` on the associated :class:`SSHClient`
           object will be called with the value `None`.

        zAborting connectionN)r{   r~  r  r  s    r  rQ  zSSHConnection.abort
  s%     	./$r	  c                 f    | j                   j                  d       | j                  t        d       y)zCleanly close the SSH connection

           This method calls :meth:`disconnect` with the reason set to
           indicate that the connection was closed explicitly by the
           application.

        zClosing connectionzDisconnected by applicationN)r{   r~  
disconnectr>   r  s    r  r  zSSHConnection.close
  s'     	-.+-JKr	  c                    K   | j                   r"| j                   j                          d{    | j                  j                          d{    y7 '7 w)zWait for this connection to close

           This method is a coroutine which can be called to block until
           this connection has finished closing.

        N)ry  r  r4  r  r  s    r  r  zSSHConnection.wait_closed
  sF      ;;++))+++$$&&& ,&s!   *AA!AAAAc                     t        | j                  j                               D ]  }|j                           | j	                  |||       | j                  d       y)aJ  Disconnect the SSH connection

           This method sends a disconnect message and closes the SSH
           connection after buffered data waiting to be written has been
           sent. No more data will be received. When the connection is
           fully closed, :meth:`connection_lost() <SSHClient.connection_lost>`
           on the associated :class:`SSHClient` or :class:`SSHServer` object
           will be called with the value `None`.

           :param code:
               The reason for the disconnect, from
               :ref:`disconnect reason codes <DisconnectReasons>`
           :param reason:
               A human readable reason for the disconnect
           :param lang:
               The language the reason is in
           :type code: `int`
           :type reason: `str`
           :type lang: `str`

        N)r  r  r  r  r  r  )r  r  r  r  r  s        r  rK  zSSHConnection.disconnect
  sK    0 ..01DJJL 2 	dFD1$r	  r6  r7  c                     | j                   j                  || j                  r | j                  j                  ||            S |      S )a
  Get additional information about the connection

           This method returns extra information about the connection once
           it is established. Supported values include everything supported
           by a socket transport plus:

             | username
             | client_version
             | server_version
             | send_cipher
             | send_mac
             | send_compression
             | recv_cipher
             | recv_mac
             | recv_compression

           See :meth:`get_extra_info() <asyncio.BaseTransport.get_extra_info>`
           in :class:`asyncio.BaseTransport` for more information.

           Additional information stored on the connection by calling
           :meth:`set_extra_info` can also be returned here.

        )r  r  r/  r9  r:  s      r  r9  zSSHConnection.get_extra_info
  sI    2 {{t"&//  $==dGL@ 	@7>@ 	@r	  r  c                 <     | j                   j                  di | y)ay  Store additional information associated with the connection

           This method allows extra information to be associated with the
           connection. The information to store should be passed in as
           keyword parameters and can later be returned by calling
           :meth:`get_extra_info` with one of the keywords as the name
           to retrieve.

        Nr  )r  r  r  s     r  r/  zSSHConnection.set_extra_info
  s     	$V$r	  interval	count_maxc                     |2t        |t              rt        |      }|dk  rt        d      || _        ||dk  rt        d      || _        | j                          y)a  Set keep-alive timer on this connection

           This method sets the parameters of the keepalive timer on the
           connection. If *interval* is set to a non-zero value,
           keep-alive requests will be sent whenever the connection is
           idle, and if a response is not received after *count_max*
           attempts, the connection is closed.

           :param interval: (optional)
               The time in seconds to wait before sending a keep-alive message
               if no data has been received. This defaults to 0, which
               disables sending these messages.
           :param count_max: (optional)
               The maximum number of keepalive messages which will be sent
               without getting a response before closing the connection.
               This defaults to 3, but only applies when *interval* is
               non-zero.
           :type interval: `int`, `float`, or `str`
           :type count_max: `int`

        Nr   %Keepalive interval cannot be negativez&Keepalive count max cannot be negative)re  r  r   r  rk  ri  r  )r  rP  rQ  s      r  set_keepalivezSSHConnection.set_keepalive
  sf    0 (C(.x8!| !HII'/D$ 1} !IJJ(1D%##%r	  rs  r  c                     | j                   j                  d||rdnd       | j                  t        t	        |      t        |      t        |             y)a  Send a debug message on this connection

           This method can be called to send a debug message to the
           other end of the connection.

           :param msg:
               The debug message to send
           :param lang:
               The language the message is in
           :param always_display:
               Whether or not to display the message
           :type msg: `str`
           :type lang: `str`
           :type always_display: `bool`

        zSending debug message: %s%sr  r  N)r{   r  rM  rC   r   r   )r  rs  r  r  s       r  
send_debugzSSHConnection.send_debug#  sJ    & 	8#2@.b	J 	GN$;fTl	4r	  strictencodingerrorswindowmax_pktsizec                 6    t        | | j                  ||||      S )aQ  Create an SSH TCP channel for a new direct TCP connection

           This method can be called by :meth:`connection_requested()
           <SSHServer.connection_requested>` to create an
           :class:`SSHTCPChannel` with the desired encoding, Unicode
           error handling strategy, window, and max packet size for
           a newly created SSH direct connection.

           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the
               connection. This defaults to `None`, allowing the
               application to send and receive raw bytes.
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHTCPChannel`

        )r+   r  r  rX  rY  rZ  r[  s        r  create_tcp_channelz SSHConnection.create_tcp_channel<  s#    @ T4::x#V[: 	:r	  c                 6    t        | | j                  ||||      S )ay  Create an SSH UNIX channel for a new direct UNIX domain connection

           This method can be called by :meth:`unix_connection_requested()
           <SSHServer.unix_connection_requested>` to create an
           :class:`SSHUNIXChannel` with the desired encoding, Unicode
           error handling strategy, window, and max packet size for
           a newly created SSH direct UNIX domain socket connection.

           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the
               connection. This defaults to `None`, allowing the
               application to send and receive raw bytes.
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHUNIXChannel`

        )r,   r  r]  s        r  create_unix_channelz!SSHConnection.create_unix_channel_  s#    @ dDJJ$fk; 	;r	  c                 6    t        | | j                  dd||      S )a  Create a channel to use for TUN/TAP forwarding

           This method can be called by :meth:`tun_requested()
           <SSHServer.tun_requested>` or :meth:`tap_requested()
           <SSHServer.tap_requested>` to create an :class:`SSHTunTapChannel`
           with the desired window and max packet size for a newly created
           TUN/TAP tunnel.

           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHTunTapChannel`

        NrW  )r-   r  r  rZ  r[  s      r  create_tuntap_channelz#SSHConnection.create_tuntap_channel  s"    ,  djj$ &5 	5r	  c                 6    t        | | j                  dd||      S )z2Create an SSH X11 channel to use in X11 forwardingNrW  )r.   r  rb  s      r  create_x11_channelz SSHConnection.create_x11_channel  s"    
 T4::tX#[2 	2r	  c                 6    t        | | j                  dd||      S )z6Create an SSH agent channel to use in agent forwardingNrW  )r/   r  rb  s      r  create_agent_channelz"SSHConnection.create_agent_channel  s"    
 tTZZx%{4 	4r	  rX  rY  rZ  r[  r  r  r  	orig_host	orig_portc                   K   t         w)z0Create an SSH direct or forwarded TCP connectionr  )
r  r  r  r  ri  rj  rX  rY  rZ  r[  s
             r  r  zSSHConnection.create_connection        "!   	remote_pathc                   K   t         w)z?Create an SSH direct or forwarded UNIX domain socket connectionr  )r  r  rn  rX  rY  rZ  r[  s          r  create_unix_connectionz$SSHConnection.create_unix_connection  rl  rm  	dest_host	dest_portc                 ,  K   	 | j                   j                  t        ||       d{   \  }}| j                  j	                  d||f       t        t        t        |            S 7 ># t
        $ r}t        t        t        |            dd}~ww xY ww)a)  Forward a tunneled TCP connection

           This method is a coroutine which can be returned by a
           `session_factory` to forward connections tunneled over
           SSH to the specified destination host and port.

           :param dest_host:
               The hostname or address to forward the connections to
           :param dest_port:
               The port number to forward the connections to
           :type dest_host: `str` or `None`
           :type dest_port: `int`

           :returns: :class:`asyncio.BaseProtocol`

        Nz!  Forwarding TCP connection to %s)
r  r  ra   r{   r~  OSErrorr   rZ   r  r   )r  rq  rr  rY  peerrI  s         r  forward_connectionz SSHConnection.forward_connection  s     &	L JJ889BIO OGAt KK@'35
 Dt455O
  	L"#6CAtK	Ls8   B$A) A'%A) B'A) )	B2BBB	dest_pathc                 &  K   	 | j                   j                  t        |       d{   \  }}| j                  j	                  d|       t        t        t        |            S 7 <# t
        $ r}t        t        t        |            dd}~ww xY ww)a  Forward a tunneled UNIX domain socket connection

           This method is a coroutine which can be returned by a
           `session_factory` to forward connections tunneled over
           SSH to the specified destination path.

           :param dest_path:
               The path to forward the connection to
           :type dest_path: `str`

           :returns: :class:`asyncio.BaseProtocol`

        Nz"  Forwarding UNIX connection to %s)
r  rp  ra   r{   r~  rt  r   rZ   r  r   )r  rw  rY  ru  rI  s        r  forward_unix_connectionz%SSHConnection.forward_unix_connection  s     	Ljj77iPP At KKA9M Dt455 Q  	L"#6CAtK	Ls8   B#A& A$#A& B$A& &	B/B		BBr  r  accept_handlerc                 ,   K   dt         t           dt        dt        dt        t
        t           t        t           f   f fd}||ffk(  r j                  j                  d||f       n! j                  j                  d||ff       	 t          j                  |||       d{   }|d
k(  r|j                         }d
k(  r|| j                  ||f<   |S 7 3# t        $ r"} j                  j                  d	|        d}~ww xY ww)a  Set up local port forwarding

           This method is a coroutine which attempts to set up port
           forwarding from a local listening port to a remote host and port
           via the SSH connection. If the request is successful, the
           return value is an :class:`SSHListener` object which can be used
           later to shut down the port forwarding.

           :param listen_host:
               The hostname or address on the local host to listen on
           :param listen_port:
               The port number on the local host to listen on
           :param dest_host:
               The hostname or address to forward the connections to
           :param dest_port:
               The port number to forward the connections to
           :param accept_handler:
               A `callable` or coroutine which takes arguments of the
               original host and port of the client and decides whether
               or not to allow connection forwarding, returning `True` to
               accept the connection and begin forwarding or `False` to
               reject and close it.
           :type listen_host: `str`
           :type listen_port: `int`
           :type dest_host: `str`
           :type dest_port: `int`
           :type accept_handler: `callable` or coroutine

           :returns: :class:`SSHListener`

           :raises: :exc:`OSError` if the listener can't be opened

        r  ri  rj  r  c                 2  K   rp ||      }t        j                  |      rt        t        t           |       d{   }|s1j
                  j                  d||ff       t        t        d      j                  | ||       d{   S 7 T7 w#Forward a local connection over SSHNz>Request for TCP forwarding from %s to %s denied by applicationzConnection forwarding denied)
r  r  r   r
   r  r{   r~  r   rY   r  )r  ri  rj  r  rz  rq  rr  r  s       r  tunnel_connectionz;SSHConnection.forward_local_port.<locals>.tunnel_connection  s      '	9=&&v.#'	$#@@FKK$$ &F&/%;&/%;=
 ++K+IK K 001:I1:IG G H AGs"   ;BBABBBBz"Creating local TCP forwarder on %s*Creating local TCP forwarder from %s to %sN'Failed to create local TCP listener: %sr   )r   r  r  r  r   r+   r   r{   r~  rw   r  rt  r  r  r  )	r  r  r  rq  rr  rz  r  r  rI  s	   `  ```   r  forward_local_portz SSHConnection.forward_local_port  s?    N	H!5e!<	H	H+.	H -.e0DDE	H 	H2 %)Y)??KKA);79 KKI);7'35	8tzz9J9D9DF FH !"++-K>#I:Bk;67!F  	KKH#N	s<   BDC& 0C$1C& 5/D$C& &	D/DDDlisten_pathc                 v   K   dt         t           dt        t        t           t        t           f   f fd} j
                  j                  d|       	 t          j                  ||       d{   }| j                  |<   |S 7 # t        $ r"} j
                  j                  d|        d}~ww xY ww)a  Set up local UNIX domain socket forwarding

           This method is a coroutine which attempts to set up UNIX domain
           socket forwarding from a local listening path to a remote path
           via the SSH connection. If the request is successful, the
           return value is an :class:`SSHListener` object which can be used
           later to shut down the UNIX domain socket forwarding.

           :param listen_path:
               The path on the local host to listen on
           :param dest_path:
               The path on the remote host to forward the connections to
           :type listen_path: `str`
           :type dest_path: `str`

           :returns: :class:`SSHListener`

           :raises: :exc:`OSError` if the listener can't be opened

        r  r  c                 D   K   j                  |        d{   S 7 w)r~  N)rp  )r  rw  r  s    r  r  z;SSHConnection.forward_local_path.<locals>.tunnel_connectionk  s/     
 44_5>@ @ @ @s     +Creating local UNIX forwarder from %s to %sN(Failed to create local UNIX listener: %s)r   r  r   r,   r   r{   r~  rx   r  rt  r  r  )r  r  rw  r  r  rI  s   ` `   r  forward_local_pathz SSHConnection.forward_local_pathS  s     0	@!6u!=	@./1FFG	@ 	F$i	1	9$

:K:EG GH .6k*G  	KKI3O	s<   AB9B 3B	4B 8B9	B 	B6B11B66B9modeunitc                 .   	 t        t        ||      \  }}|j                  d      }| j                  j	                  d|t
        k(  rdnd|       t        t        t        |      d|i      S # t        $ r}t        t        t        |            dd}~ww xY w)zSet up TUN/TAP forwarding	interfacez#  Forwarding layer %d traffic to %sr$  r  N)extra)r   ra   r9  r{   r~  r   rt  r   rZ   r  r   )r  r  r  r=  ru  r  rI  s          r  forward_tuntapzSSHConnection.forward_tuntap  s    	L+L$EOIt!00=IKKB"&*C"CQ&( Dt4#.	":< 	<  	L"#6CAtK	Ls   AA, ,	B5BB
listen_keyc                 <    | j                   j                  |d       y)z*Mark a local forwarding listener as closedN)r  r  )r  r  s     r  close_forward_listenerz$SSHConnection.close_forward_listener  s     	!!*d3r	  c                     t         )*Detach a session from a local X11 listenerr  r  r  s     r  detach_x11_listenerz!SSHConnection.detach_x11_listener  r  r	  r
  r,  NNr  r   )r  r  r  r  r   globals_handler_namesr  staticmethodr  r  r2  AbstractEventLoop_AcceptHandler_ErrorHandlerr   r  r  r.  r   r  r   r  r   r  propertyrz   r{   rT  r  r  r  r  r  r  r  r  r  r  r
   r  r  r  r  r   r0   r   r  r  r  r   ri  ro   r  r   r   r  r   r  r  rC  rB  rK  r   r  r  r   rG  r
  r  r  r(   r	   r  r  rb   r  r  r   r  r   r%  r(  r   r,  r:  rB  r   rM  rh  r  r9  rx  r  r  r   r  r  r  r   r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r&  r(  r-  r3  r  r>  rB  rE  rH  r@   rA   rB   rC   rD   rE   rF   rL   rM   rP   rQ   rR   rS   rV   rW   rX   rG   rH   rI   _packet_handlersrQ  r  r  r<   rK  r   r9  r/  floatrT  rV  _DEFAULT_WINDOW_DEFAULT_MAX_PKTSIZEr+   r^  r,   r`  r-   rc  r.   re  r/   rg  r   r   r  r   r   rp  ra   rv  ry  r   SSHAcceptHandlerrr   r  r  r  rq   r  r  r  r	  r  r   r     s   *%gi8NIC  `+W66 `+0`+)`+:G`+  }`+ /3`+D$ 
	$}2E)F 	$,]$;	$,]$;	@D	 	  
+ HY/ + D + Z%F)J(
"=	1 3 	1 	1:hy&9 :-:26:  8<	$ !))!4  4  
4 
*
8E)Y*>$?@ 
8 8/!: t 
@m @3 @!$@,4SM@>B@8#&.1',2*#:?E<#6s #6# #6S #6%*#6/5#6JF)>)> F4 F@8I#6 $  ?C;?8x
'; 8%-i%88DH8H"% "8 "t "(#
H
I

6 2 s  & & &
 ,
6C 6Xe_ 6!)%65:6.DT%[ D% D & .t .`d (sd sl :>C<3 C<u C<%o6C<BFC<J-7S 7# 7S 7T 7-2^/{&e {& {&$ {&z?E ?d ?N5 N+0+<NAFNA Ae A A CG-1:C : :&.&?:&*:6:: AE483% 3 3)1*)=3-13=A34
3T 
3d 
3%@N= = =47=GJ=5:=?C=E3 Ec E*-E58E=AE 165E 5% 5)-5:>5% */49#y.4I 0eD%K.@ 0T 00"
C  $-260 S  ).2s C '059Fs FC F(F-1F** *c *)2*7;*6> >S >(1>6:>:I# Is I"+I04I2i ic i!*i/3iV5 5c 5!*5/35(#P# #Ps #P*3#P8<#PJM Mu M'0M59M<(H# (Hs (H*3(H8<(HT6H# 6Hs 6H*36H8<6Hp> >c >)2>7;>80 0S 0(106:0,	> 	>S 	>)2	>7;	>#Ac #A3 #A&/#A48#AJ:3 : :3<:AE:0:c :3 :.7:<@:2+#+(,+(; 	(> 		
 	(@ 	(? 	(9 	(8 	(8 	(A 	(A 	(A 	(@" 	(?#$ 	(@%& 	(@'* 	(=+, 	&(J (E/4 "L'  , s  C   04 <@3 @ @ @:%s %t % AE15'&eD%,<&= '&!)#'&:>'&R 0<*/4c 4 4#'44842 <@)1)8.B!:8C= !:#&!:#&!: ),!: 	!:F =A*2*9/C!;HSM !;$'!;$'!; *-!; 	!;F 3B1E5C 5+.554 !032228E2 !034448G4 BD	" >B"/3	"#7#?	"	"+.	";>	" 	" .6c]	" 		" -0		"
 	" mF+]6-BBC	" <@"/3		"#8#@	"	"+3C=	" 	" -0	" 		"
 nV,nV.DDE	"6 6-065A6<6s 6| 62  :>X"X14XX'*X %%56X CNX Xt ,C ,,/,4?, ,\<3 <hsm < < 4 4t 4
"
6(: "t "r	  c            (       \
    e Zd ZU dZded<   eed<   ee   ed<   	 	 	 ddej                  ddd	e
d
edee   f
 fdZddZdee   ddf fdZdedefdZdedefdZdee   fdZdee   fdZddZdefdZdefdZdeee   eef   fdZdee   fdZ dee   fdZ!dededeeef   fdZ"dd Z#dd!Z$dee   fd"Z%d#ed$eded%e&dee'   f
d&Z(d'e)dee*e+f   fd(Z,d'e)dee-e   e.e   f   fd)Z/d*e)dee-e0e.   f   fd+Z1d,ed-e2ddfd.Z3d'e)dee4e5f   fd/Z6d'e)dee7e8f   fd0Z9d*e)dee4e0e5   f   fd1Z:d2eddfd3Z;d*e)dee<e=e>   f   fd4Z?d*e)dee4e=e@   f   fd5ZAd*e)ddfd6ZBd*e)ddfd7ZCd8eDeE   d9ee   d:ee   d;edeeee2f   f
d<ZFd8eGeE   ddfd=ZH	 dd>d>d>d>d>d>d>d>d>d>d>d>d>d>d>d?d@eIdAeJee      dBeJee      dCeJeK   dDeJeL   dEeJeMeef      dFeJee      dGeJeN   dHeJeO   dIeJeMe2ef      dJeJee      dKeJee      dLeJe   dMeJee      dNeJe   dOeJe2   dPeJe2   deeDePf   f$dQZQdReRdSeRdeeSeTeTf   fdTZUeVdeWeWeWeXj                  dUdUdVdReRdWeeE   dXeZdYe[dZe[d[e2d\ed]edSeRde\eE   fd^       Z]d>eXj                  deWeWeWdfd_e^dAeJee      d[e2dWeeE   dXeZdYe[dZe[dMee   dSeRdee_e`f   fd`ZadaddbdReRdceddeeb   dSeRdecf
deZd	 	 dddfeeefdgd@egeE   dhedie2djedke2dMee   dNedOe2dPe2dee-eE   e.eE   f   fdlZhdReRdSeRdeeTeSf   fdmZieVddfeeefdgd@ejeE   d,ed-e2dMee   dNedOe2dPe2dekfdn       ZleVdoemdReRdSeRdekfdp       Znddfeeefdgd@eoeE   dqedMee   dNedOe2dPe2dee4eE   e5eE   f   fdrZpdReRdSeRdeeTeSf   fdsZqeVddfeeefdgd@ereE   d2edMee   dNedOe2dPe2dekfdt       ZseVdoetdReRdSeRdekfdu       Zu	 ddvevdwedxeJe2   dSeRded ef   f
dyZweVddwedxeJe2   dSeRdd fdz       ZxeVddwedxeJe2   dSeRdd{fd|       ZyeVddwedxeJe2   dSeRdezfd}       Z{eV	 	 ddwedxeJe2   dSeRdezfd~       Z|	 deeefdd@e}dee2   dOe2dPe2dee7e8f   f
dZ~	 deeefdd@e}dee2   dOe2dPe2dee7e8f   f
dZdReRdSeRdeeTeSf   fdZdReRdSeRdeeTeSf   fdZeV	 dd,ed-e2dedee   dekf
d       ZeVd2edede2dekfd       ZeVd,ed-e2dede2dekf
d       ZeVd2ededekfd       ZeVd,ed-e2dedekfd       ZeVd2edede2dekfd       ZeVd,ed-e2dekfd       ZeV	 	 ddee2   dee2   de@fd       ZeV	 	 ddee2   dee2   de@fd       ZeVd>d>ddfefdCeJeK   dDeJeL   dee   defd       Z xZS )r_  a  SSH client connection

       This class represents an SSH client connection.

       Once authentication is successful on a connection, new client
       sessions can be opened by calling :meth:`create_session`.

       Direct TCP connections can be opened by calling
       :meth:`create_connection`.

       Remote listeners for forwarded TCP connections can be opened by
       calling :meth:`create_server`.

       Direct UNIX domain socket connections can be opened by calling
       :meth:`create_unix_connection`.

       Remote listeners for forwarded UNIX domain socket connections
       can be opened by calling :meth:`create_unix_server`.

       TCP port forwarding can be set up by calling :meth:`forward_local_port`
       or :meth:`forward_remote_port`.

       UNIX domain socket forwarding can be set up by calling
       :meth:`forward_local_path` or :meth:`forward_remote_path`.

       Mixed forwarding from a TCP port to a UNIX domain socket or
       vice-versa can be set up by calling :meth:`forward_local_port_to_path`,
       :meth:`forward_local_path_to_port`,
       :meth:`forward_remote_port_to_path`, or
       :meth:`forward_remote_path_to_port`.

    SSHClientConnectionOptionsr  r  r  Nr%  rp  r  r  r  c                    t         |   |||||d       |j                  | _        |j                  | _        |j                  | _        |j                  | _	        d | _
        d | _        |j                  | _        |j                  | _        |j                   | _        g | _        |j&                  rt)        |j&                        ng | _        d | _        |j.                  dk7  r/|j.                  D cg c]  }|j1                  d       c}| _        nt5               | _        |j6                  | _        |j:                  t=        |j:                        | _        |j@                  | _!        |jD                  | _#        tI        | j>                        | _%        |jL                  | _'        |jP                  | _)        tI        | jN                        | _*        |jV                  dk7  r|jV                  n|j                  }|rZ	 tY        ||jZ                  |j\                        | _/        |j`                  | _1        |jd                  | _3        | jf                  | _4        d| _6        i | _7        i | _8        y c c}w # tj        $ r Y &w xY w)NFr  r  r  )9r-  r.  rk  _hostrm  _portr  _known_hostshost_key_alias_host_key_aliasr  _server_host_keyserver_host_keys_handler_server_host_keys_handlerrd  r  password	_password_client_host_keysclient_keysr  _client_keys_saved_rsa_keypreferred_authr  r`  r"   disable_trivial_authr  
agent_pathr   ry  agent_identities_agent_identitiesagent_forward_path_agent_forward_pathr  _get_agent_keyspkcs11_provider_pkcs11_provider
pkcs11_pin_pkcs11_pin_get_pkcs11_keysgss_hostrc   	gss_storegss_delegate_credsr[  gss_kexr\  gss_authr]  r_  re   _kbdint_password_auth_remote_listeners_dynamic_remote_listeners)	r  r%  rp  r  r  r  r  r  r5  s	           r  r.  zSSHClientConnection.__init__  s>   
 	w-e 	 	- \\
\\
#//&55@D"26)0)I)I& )) ))79 *1)<)<D$$%" 	8<!!R'$+$:$:$<$: @FFMM'$:$:$<D  $E#FD %,%A%A")(););<DK!(!9!9#*#=#= #DKK0 ' 7 7"-- $T%:%: ;'.'7'72'=7##7<<%h0A0A&-&@&@B	 '!(!1!1%)^^" &+" =? 	 KM&I$<6  s   /I'8AI, ,	I87I8r  c           
      v   | j                   J | j                  s]| j                  r#| j                  | _        | j                  | _        n.| j                  d      }t        t        |      \  | _        | _        | j                  j                  rt        t        j                  | j                   j                  d            }t        t        | j                  j                  |j                         | j                  j                              | _        nB| j                  j                   r%t        | j                  j                         | _        ng | _        | j"                  d| _        d| _        n| j"                  sgt)        ddd      j+                         }|j-                         r5t/        j0                  |t.        j2                        rt5        |      | _        nd| _        | j                  t6        k7  r| j                  nd}| j9                  t        t:        | j"                        | j<                  xs | j                  | j                  |       g }| j                  j>                  dk7  r1| j@                  r| j@                  }| j&                  rtC               |z   }|stC               tE               z   }| jF                  %| jF                  s| jH                  rtK               |z   }tM        | j                  j>                  t        tN        t4           | j                  jP                  jS                  d	d
            |      | _*        | jV                  jY                  d| j                  | j                  f       | j                  jZ                  rIdj]                  d | j                  jZ                  D              }| jV                  jY                  d|       y| jV                  jY                  d| j^                  | j`                  f       | jV                  jY                  d| j                  | j                  f       y)r  Nremote_peernamer  ~.sshr  r	  r7  HostKeyAlgorithmsr  zConnected to SSH server at %s c              3   F   K   | ]  }t        j                  |        y wr,  shlexquoter  args     r  r  z7SSHClientConnection._connection_made.<locals>.<genexpr>P  "      %B%@ ;>U[[%5%@   !  Proxy command: %s  Local address: %s  Peer address: %s)1r/  r  r  r  r  r9  r   r   r  client_host_keysignr  r  rn   filenoclient_host_pubkeysr  client_host_keypairsr  r9  r;  r   
expanduseris_filer`  accessR_OKr  r=   r  ro   r  server_host_key_algsr:  r   r   r>  r@  r   r  r   r^  r  r  r{   r~  r{  r  r  r  )r  remote_peerrr  default_known_hostsrm  default_host_key_algsr{  s          r  r  z$SSHClientConnection._connection_made  sX    ***zz!__
!__
"112CD)-h)D&
DJ==,,66x@BD &**:114;;=11+3 &4D" ]]//%)$--*L*L%MD"%'D"$&*D#$(D!$$&*3+8'::D*, $ (//1		"5rww?(+,?(@D%(+D%!%|!;4::D##D8I8I$J$($8$8$FDJJ$(OOT; !#==--:**(,(C(C%$$025JJ & %,.1L1NN " ##/''4+H+H57:OO & &;MM..# 4 4 8 8#R!) *!	&#" 	8**djj1	3 ==&&HH %B%)]]%@%@%B BMKK2MBKK2"..0@0@ACKK1"oot?Ar	  rI  c                    | j                   r| j                   j                          | j                  rFt        | j                  j	                               D ]  }|j                           i | _        i | _        || j                  j                  d       n\t        |t              r%| j                  j                  t        |             n'| j                  j                  dt        |      z          t        | 1  |       y)zClean up this client connectionNr  zConnection failure: )ry  r  r  r  r  r  r{   r~  re  r   r  r-  r  )r  rI  tcp_listenerr5  s      r  r  zSSHClientConnection._cleanupZ  s     ;;KK!! $T%;%;%B%B%D E""$ !F &(D"-/D*;KK01^,KKSX&KK3c#h>?r	  keypairc                     | j                   rA|j                  D ]2  }|| j                  v s|| j                   v s!|j                  |        y |j                  d   | j                  v S )z>Choose signature algorithm to use for key-based authenticationTr3  )rw  r  rM  set_sig_algorithm)r  r  r  s      r  _choose_signature_algz)SSHClientConnection._choose_signature_algq  sc       --$..(SD4I4I-I--c2 .
 %%b)T^^;;r	  r  c                 .   	 | j                  | j                  xs | j                  | j                  | j                  |      }|| _        |S # t
        $ r@}| j                  }| j                  r|d| j                   z  }t        | d|       dd}~ww xY w)z)Validate and return the server's host keyz with alias z
 for host N)r  r  r  r  r  r  r   r  )r  r  host_keyrI  rk  s        r  validate_server_host_keyz,SSHClientConnection.validate_server_host_key|  s    
	K..$$2

X7H !)  	K::D##,t';';&<==&#j'?@dJ	Ks   A A 	B;BBc                     | j                   S )a*  Return the server host key used in the key exchange

           This method returns the server host key used to complete the
           key exchange with the server.

           If GSS key exchange is used, `None` is returned.

           :returns: An :class:`SSHKey` public key or `None`

        r  r  s    r  get_server_host_keyz'SSHClientConnection.get_server_host_key  s     $$$r	  c                 ^    | j                   D cg c]  }|j                  d       c}S c c}w )zReturn the server host key used in the key exchange

           This method returns the auth methods available to authenticate
           to the server.

           :returns: `list` of `str`

        r  )r~  r  r  r  s     r  get_server_auth_methodsz+SSHClientConnection.get_server_auth_methods  s-     6:5G5GH5G6g&5GHHHs   *c                    | j                   r!| j                   j                          d| _         | j                  rF| j                  j                  d      }t	        | |      | _         | j                   ry| j                  rF| j
                  j                  d| j                         | j                  t        d| j                   d| j                                y)z>Attempt client authentication using the next compatible methodNr   zAuth failed for user %szPermission denied for user z	 on host )rz  r  r~  r  r#   r{   r~  r  r  r   r  r  s     r  r  z!SSHClientConnection.try_next_auth  s     ::JJDJ  ''++A.F+D&9DJzz    	2DNNC*+H.2nn-=Y.2jj\,; < 	=r	  c                 ,    | j                   rd| _         yy)z>Return whether to allow GSS key exchange authentication or notFT)r^  r  s    r  gss_kex_auth_requestedz*SSHClientConnection.gss_kex_auth_requested       !&Dr	  c                 ,    | j                   rd| _         yy)z5Return whether to allow GSS MIC authentication or notFTr_  r  s    r  gss_mic_auth_requestedz*SSHClientConnection.gss_mic_auth_requested  r  r	  c                   K   | j                   sy	 | j                  r(| j                  }|j                  dz   |_        d| _        n	 | j                  j                  d      }|J | j                  |      r&|j                  dk(  r|j                  dk7  r|| _        n| j                  j                  }|Y| j                  d      }|rD| j                  j                  t        t        |      t        j                          d{   \  }}nd}| j                  j"                  r|d	d d
k7  r|d
z  }||| j                  j$                  fS # t        $ r d}Y w xY w7 Ww)z6Return a host key, host, and user to authenticate with)Nr  r     -cert-v01@openssh.comNr      ssh-rsa-cert-v01@openssh.com   ssh-rsar  r  r3  .)rO  r  sig_algorithmr  r  r  
IndexErrorr  r  client_hostr9  r  getnameinfor   r   r  NI_NUMERICSERVr  client_username)r  r  r  r  rY  s        r  host_based_auth_requestedz-SSHClientConnection.host_based_auth_requested  sg     $$ "")) # 1 14L L&*#0044Q7C
 ?"?))#.==$CC))Z7*-D'' * mm//**:6H'+zz'='=8,f.C.C(E "EQ ! ==,,RS1AS1H3KK!>!>>>; " C&"Es8   AEE
 !B"EEAE
EEEEc                   K   | j                   sy| j                  r[| j                  J 	 | j                  j                  | j                         d{   }t        |      | j                  dd d| _        | j                  rk| j                  J | j                  j                  dt        | j                  | j                         d{   }t        |      | j                  dd d| _        	 | j                  sj| j                  j                         }t!        j"                  |      rt%        t&        t(           |       d{   }|syt        t+        |            | _        | j,                  r(| j,                  }|j.                  dz   |_        d| _        n| j                  j3                  d      }| j5                  |      r'|j0                  dk(  r|j.                  dk7  r|| _        |S 7 # t        $ r Y w xY w7 67 w)z-Return a client key pair to authenticate withNr   Fr  r   r  )rQ  r  ry  get_keysr  r  r  r  r  r  r  r  r   r  r  public_key_auth_requestedr  r  r   r
   r   r   r  r  r  r  r  )r  
agent_keyspkcs11_keysr  r  s        r  r  z-SSHClientConnection.public_key_auth_requested  s     $$;;***#';;#7#78N8N#OO
(,Z(8!!"1% $)D   ((444 $

 : :&(=(=t?O?O!Q QK %)$5Dbq!$)D!$$>>@&&v.#'	.(A6#JJF %)v)>$?!  "")) # 1 14L L&*#''++A.))#.==$CC))Z7*-D'
Q ! P Q Ks[   (H(G0 G-G0 0AH
H A9HHB(H-G0 0	G=9H<G==HHc                 l  K   | j                   s| j                  sy| j                  | j                  }t        |      r% t	        t
        g t        t           f   |             }t        j                  |      r't	        t        t        t              |       d{   }nt	        t        t           |      }d| _        |S | j                  j                         }t        j                  |      r(t	        t        t        t              |       d{   }|S t	        t        t           |      }|S 7 7 !w)z&Return a password to authenticate withN)rU  r  r  r  r   r   r   r  r  r  r
   r  password_auth_requested)r  r  r  s      r  r  z+SSHClientConnection.password_auth_requestedC  s      ""4+E+E>>%&*nnH!F4Xc]): ;XFH""8,!%i&>!IIx8!DN  [[88:F""6*!%i&>!GG   v6 J Hs%   BD4D0A5D4D2 D42D4promptr  c                    K   | j                   j                  ||      }t        j                  |      rt	        t
        t           |       d{   }t	        t        |      S 7 w)z?Return a password to authenticate with and what to change it toN)r  password_change_requestedr  r  r   r
   r!   )r  r  r  r  s       r  r  z-SSHClientConnection.password_change_requested_  sU      66vtDv&	*@ A6JJF*F33 K   AA%A#A%c                 8    | j                   j                          y)z#Report a successful password changeN)r  password_changedr  s    r  r  z$SSHClientConnection.password_changedj  s     	$$&r	  c                 8    | j                   j                          y)zReport a failed password changeN)r  password_change_failedr  s    r  r  z*SSHClientConnection.password_change_failedo  s     	**,r	  c                 X  K   | j                   sy| j                  j                         }t        j                  |      r&t        t        t        t              |       d{   }|t        u r$| j                  | j                  s
d| _        d}nd}t        t        t           |      S 7 Gw)a&  Return the list of supported keyboard-interactive auth methods

           If keyboard-interactive auth is not supported in the client but
           a password was provided when the connection was opened, this
           will allow sending the password via keyboard-interactive auth.

        NTr  )rS  r  kbdint_auth_requestedr  r  r   r
   r   r  NotImplementedr  r  r  s     r  r  z)SSHClientConnection.kbdint_auth_requestedt  s        224v&	(3- 8&AAF^#~~)$2L2L-1*HSM6** Bs   AB* B(!AB*r6  instructionspromptsc                   K   | j                   r[|sg }|S t        |      dk(  rC|d   d   j                         }d|v sd|v r!| j                          d{   }||gnd}|S d}|S d}|S | j                  j                  ||||      }t        j                  |      r!t        t        t           |       d{   }|S t        t        |      }|S 7 {7 w)z9Return responses to a keyboard-interactive auth challenger   r   r  passcodeN)r  r  lowerr  r  kbdint_challenge_receivedr  r  r   r
   r    )	r  r6  r  r  r  r  r  r  r  s	            r  r!  z-SSHClientConnection.kbdint_challenge_received  s     
 %%57* ) W" A,,.':+?%)%A%A%CCH-5-AztH   $H     [[::4;?JF ""6*!%i&?!HH   7!  D Is%   ACCA"C7C8CCr  c                 "    t        t        d      )zmProcess an inbound session open request

           These requests are disallowed on an SSH client.

        z Session open forbidden on clientr   rY   r  r  s     r  _process_session_openz)SSHClientConnection._process_session_open  s     ?AC 	Cr	  c                 "    t        t        d      )z{Process an inbound direct TCP/IP channel open request

           These requests are disallowed on an SSH client.

        z&Direct TCP/IP open forbidden on clientr#  r$  s     r  _process_direct_tcpip_openz.SSHClientConnection._process_direct_tcpip_open  s     ?GI 	Ir	  rU  c                    |j                         }|j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }t        t        t           | j                  j                  ||f      xs | j                  j                  |            }|rU|j                  ||      \  }	}
| j                  j                  d||f       | j                  j                  d||f       |	|
fS t        t         d      # t        $ r t        d      dw xY w)z8Process an inbound forwarded TCP/IP channel open requestr  z-Invalid forwarded TCP/IP channel open requestNz'Accepted forwarded TCP connection on %s  Client address: %sNo such listener)r  rI  r  r  r  r   r   rs   r  r  r  r  process_connectionr{   r~  r   rZ   )r  rU  dest_host_bytesrr  orig_host_bytesrj  rq  ri  r  r  r  s              r  _process_forwarded_tcpip_openz1SSHClientConnection._process_forwarded_tcpip_open  sD    !++-%%'	 ++-%%'		:'..w7I'..w7I ,U3""&&	9'=> :**..y9; $77	9MMD'KKF'35KK3i5KL= "#68JKK) " 	: !/ 059:	:s   "D* *E r  r  c                 Z  K   | j                  dt        |      t        |             d{    | j                  j	                  d||f       | j
                  j                  ||f      }|r;| j                  j                  |      |k(  r| j                  |= | j
                  ||f= yy7 }w)zClose a remote TCP/IP listeners   cancel-tcpip-forwardNz Closed remote TCP listener on %s)r  r   r   r{   r~  r  r  r  )r  r  r  r  s       r  close_client_tcp_listenerz-SSHClientConnection.close_client_tcp_listener  s      ''#VK%8&:MO 	O 	O 	;%{3	5 ))--{K.HI--11+>(J22;?&&{K'?@	 	Os   )B+B)A>B+c                 "    t        t        d      )zProcess an inbound direct UNIX domain channel open request

           These requests are disallowed on an SSH client.

        z2Direct UNIX domain socket open forbidden on clientr#  r$  s     r  3_process_direct_streamlocal_at_openssh_dot_com_openzGSSHClientConnection._process_direct_streamlocal_at_openssh_dot_com_open  s     ? 56 	6r	  c                 "    t        t        d      )zmProcess an inbound TUN/TAP open request

           These requests are disallowed on an SSH client.

        z#TUN/TAP request forbidden on clientr#  r$  s     r  $_process_tun_at_openssh_dot_com_openz8SSHClientConnection._process_tun_at_openssh_dot_com_open  s     ?DF 	Fr	  c                    |j                         }|j                         }|j                          	 |j                  d      }t        t        t           | j                  j                  |            }|r3|j                         \  }}| j                  j                  d|       ||fS t        t        d      # t        $ r t	        d      dw xY w)z=Process an inbound forwarded UNIX domain channel open requestr  z2Invalid forwarded UNIX domain channel open requestNz%Accepted remote UNIX connection on %sr*  )r  r  r  r  r   r   rt   r  r  r  r+  r{   r~  r   rZ   )r  rU  dest_path_bytesrY  rw  r  r  r  s           r  6_process_forwarded_streamlocal_at_openssh_dot_com_openzJSSHClientConnection._process_forwarded_streamlocal_at_openssh_dot_com_open  s    
 !++-	:'..w7I
 -e4..229=? $779MD'KKDiP= "#68JKK " 	: !/ 059:	:s   B8 8Cr  c                    K   | j                  dt        |             d{    | j                  j                  d|       || j                  v r| j                  |= yy7 =w)z*Close a remote UNIX domain socket listeners&   cancel-streamlocal-forward@openssh.comNClosed UNIX listener on %s)r  r   r{   r~  r  )r  r  s     r  close_client_unix_listenerz.SSHClientConnection.close_client_unix_listener4  sk      ''5vk7JL 	L 	L 	5{C$000&&{3 1	Ls   A!A>A!c                    |j                         }|j                         }|j                          	 |j                  d      }| j                  rw| j                  j                  d       | j                  j                  d||f       | j                         }|j                  ||       || j                  j                         fS t        t        d      # t        $ r t        d      dw xY w)z+Process an inbound X11 channel open requestr  z*Invalid forwarded X11 channel open requestNzAccepted X11 connectionr)  zX11 forwarding disabled)r  rI  r  r  r  r   r  r{   r~  re  set_inbound_peer_namesrv  r   rZ   )r  rU  r-  rj  ri  r  s         r  _process_x11_openz%SSHClientConnection._process_x11_open?  s     !++-%%'		:'..w7I
 KK67KK3i5KL**,D''	9=++>>@@@"#6#<> > " 	: !/ 059:	:s   C C,c                     |j                          | j                  rF| j                  j                  d       | j	                         | j                  | j                        fS t        t        d      )z2Process an inbound auth agent channel open requestzAccepted SSH agent connectionzAuth agent forwarding disabled)r  r  r{   r~  r`  ry  r   rZ   rG  s     r  +_process_auth_agent_at_openssh_dot_com_openz?SSHClientConnection._process_auth_agent_at_openssh_dot_com_open[  so    
 	##KK<=,,.001I1IJL L ##6#CE Er	  c                 D    | j                  | j                  |             y)z+Process a list of accepted server host keysN)r  _finish_hostkeysrG  s     r  6_process_hostkeys_00_at_openssh_dot_com_global_requestzJSSHClientConnection._process_hostkeys_00_at_openssh_dot_com_global_requestk  s     	..v67r	  c                 f  K   | j                   s-| j                  j                  d       | j                  d       y| j                  -| j                  j                  d       | j                  d       yg }t        | j                        }g }g }g }|r	 |j                         }t        |      }|| j                  v r|j                  |       nM|| j                  v r#|j                  |       |j                  |       n|j                  |t        |      f       |r|r| j                  ddj                  d |D                     d{   \  }	}|	t         k(  r~t        d      t        | j"                        z   }
|D ]W  \  }}|j                         }|j%                  |
|z   |      r|j                  |       =| j                  j                  d	       Y n| j                  j                  d
       |j'                          | j                  j                  dt)        |       dt)        |       dt)        |       dt)        |       d	       | j                  ||||      }t+        j,                  |      r|J | d{    | j                  d       y# t        $ r Y w xY w7 _7 )w)z)Finish processing hostkeys global requestz,Ignoring server host key message: no handlerFNz.Server host key not verified: handler disableds   hostkeys-prove-00@openssh.comr	  c              3   &   K   | ]	  \  }}|  y wr,  r  )r  rY  key_strs      r  r  z7SSHClientConnection._finish_hostkeys.<locals>.<genexpr>  s     95ZQ5r  hostkeys-prove-00@openssh.comz!Server host key validation failedz$Server host key prove request failedzServer host key report: z added, z
 removed, z retained, z revokedT)r  r{   r  r  r9  r~  r  r  r   r<  r  remover   r   r  r  rW   r$  verifyr  r  r  r  )r  rU  addedremovedretainedrevokedprover  r  rV  r  rE  r  r  s                 r  rA  z$SSHClientConnection._finish_hostkeysq  s     --KKMN((/""*KKMN((/t../!,,.+H5$111NN3'D333OOC(NN3'LL#vh'7!89  $($=$=09599%; ;OGV -- ?@ 0 012 %*LC ++-Czz&7"2C8S)**+NO %* ""#IJ3CJ<xL>CM?+L>3 	4 //w08'C v&%%%LL$$T*G " ;: sP   BJ1BJ J1 -J1J,D7J1J/J1	J)%J1(J))J1/J1r  display	auth_pathsingle_connectionc                   K   |st         j                  j                  d      }|st        d      | j                  s$t        | j                  ||       d{   | _        | j                  j                  |||      S 7 &w)z'Attach a channel to a local X11 displayDISPLAYzX11 display not setN)r`  environr  r  r  r   r  attach)r  r  rN  rO  rP  s        r  attach_x11_listenerz'SSHClientConnection.attach_x11_listener  su      jjnnY/G233!!'A

GY(0 "0D !!(($8IJJ"0s   AB A>'B c                 d    | j                   r$| j                   j                  |      rd| _         yyy)r  Nr  detachr  s     r  r  z'SSHClientConnection.detach_x11_listener  3     !!((.%)" / r	  r  )	subsystemenvsend_envrequest_pty	term_type	term_size
term_modesx11_forwardingx11_displayx11_auth_pathx11_single_connectionrX  rY  rZ  r[  r  r&  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  c                  K   |dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j
                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|	dk(  r| j                   j                  }	|
dk(  r| j                   j                  }
|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                  }|dk(  r| j                   j                   }i }|rH|D ]C  }t#        |      |j%                  fdt&        j(                  j+                         D               E |rV	 t-        |t.              r|j%                  d |D               n,|j%                  t1        t2        t4        t4        f   |             |dk(  rd}n'|dk(  rt9        |xr |xs |       }n|rt9        |      }t;        | | j<                  ||||      }|j?                  ||||||||	xs i |
|||t9        | j@                               d{   }||fS # t6        $ r t7        d      dw xY w7 !w)	a  Create an SSH client session

           This method is a coroutine which can be called to create an SSH
           client session used to execute a command, start a subsystem
           such as sftp, or if no command or subsystem is specified run an
           interactive shell. Optional arguments allow terminal and
           environment information to be provided.

           By default, this class expects string data in its send and
           receive functions, which it encodes on the SSH connection in
           UTF-8 (ISO 10646) format. An optional encoding argument can
           be passed in to select a different encoding, or `None` can
           be passed in if the application wishes to send and receive
           raw bytes. When an encoding is set, an optional errors
           argument can be passed in to select what Unicode error
           handling strategy to use.

           Other optional arguments include the SSH receive window size and
           max packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHClientSession` object
               that will be created to handle activity on this session
           :param command: (optional)
               The remote command to execute. By default, an interactive
               shell is started if no command or subsystem is provided.
           :param subsystem: (optional)
               The name of a remote subsystem to start up.
           :param env: (optional)
               The  environment variables to set for this session. Keys and
               values passed in here will be converted to Unicode strings
               encoded as UTF-8 (ISO 10646) for transmission.

                   .. note:: Many SSH servers restrict which environment
                             variables a client is allowed to set. The
                             server's configuration may need to be edited
                             before environment variables can be
                             successfully set in the remote environment.
           :param send_env: (optional)
               A list of environment variable names to pull from
               `os.environ` and set for this session. Wildcards patterns
               using `'*'` and `'?'` are allowed, and all variables with
               matching names will be sent with whatever value is set
               in the local environment. If a variable is present in both
               env and send_env, the value from env will be used.
           :param request_pty: (optional)
               Whether or not to request a pseudo-terminal (PTY) for this
               session. This defaults to `True`, which means to request a
               PTY whenever the `term_type` is set. Other possible values
               include `False` to never request a PTY, `'force'` to always
               request a PTY even without `term_type` being set, or `'auto'`
               to request a TTY when `term_type` is set but only when
               starting an interactive shell.
           :param term_type: (optional)
               The terminal type to set for this session.
           :param term_size: (optional)
               The terminal width and height in characters and optionally
               the width and height in pixels.
           :param term_modes: (optional)
               POSIX terminal modes to set for this session, where keys are
               taken from :ref:`POSIX terminal modes <PTYModes>` with values
               defined in section 8 of :rfc:`RFC 4254 <4254#section-8>`.
           :param x11_forwarding: (optional)
               Whether or not to request X11 forwarding for this session,
               defaulting to `False`. If set to `True`, X11 forwarding will
               be requested and a failure will raise :exc:`ChannelOpenError`.
               It can also be set to `'ignore_failure'` to attempt X11
               forwarding but ignore failures.
           :param x11_display: (optional)
               The display that X11 connections should be forwarded to,
               defaulting to the value in the environment variable `DISPLAY`.
           :param x11_auth_path: (optional)
               The path to the Xauthority file to read X11 authentication
               data from, defaulting to the value in the environment variable
               `XAUTHORITY` or the file :file:`.Xauthority` in the user's
               home directory if that's not set.
           :param x11_single_connection: (optional)
               Whether or not to limit X11 forwarding to a single connection,
               defaulting to `False`.
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on this session.
           :param errors: (optional)
               The error handling strategy to apply on Unicode encode/decode
               errors.
           :param window: (optional)
               The receive window size for this session.
           :param max_pktsize: (optional)
               The maximum packet size for this session.
           :type session_factory: `callable`
           :type command: `str`
           :type subsystem: `str`
           :type env: `dict` with `str` keys and values
           :type send_env: `list` of `str`
           :type request_pty: `bool`, `'force'`, or `'auto'`
           :type term_type: `str`
           :type term_size: `tuple` of 2 or 4 `int` values
           :type term_modes: `dict` with `int` keys and values
           :type x11_forwarding: `bool` or `'ignore_failure'`
           :type x11_display: `str`
           :type x11_auth_path: `str`
           :type x11_single_connection: `bool`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHClientChannel` and :class:`SSHClientSession`

           :raises: :exc:`ChannelOpenError` if the session can't be opened

        r  c              3   N   K   | ]  \  }}j                  |      r||f  y wr,  )r  )r  r  rw  r  s      r  r  z5SSHClientConnection.create_session.<locals>.<genexpr>  s-      8>P
U")//#"6 !$U|>Ps   "%c              3   @   K   | ]  }|j                  d d        yw)=r   N)rf  )r  items     r  r  z5SSHClientConnection.create_session.<locals>.<genexpr>  s     #G34DJJsA$63s   zInvalid environment valueNforceTauto)!r  r&  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  r   r  r`  rS  rv  re  r  r   r   r  r  r  r)   r  creater  )r  r  r&  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  new_envr  r  r  r  s                         @r  create_sessionz"SSHClientConnection.create_session  s    D b=mm++G?//I"9--##Cr>}}--H"--33K?//I?//I11JR!]]99N"--33KB MM77M B&$(MM$G$G!r>}}--HR<]]))FR<]]))F"--33K"$)#. 8bjj>N>N>P 8 8  
 Hc4(NN#G3#GHNN4S(93#?@ '!KF"yG'2FY-GHKy/K"  djj(F &5 OWi$+[)Y$.$4"n$/$9$()A)A$BD D W}G  H !<=4GH8Ds,   G?K<AK! B K<K:K<!K77K<r[  r  c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      t        ||t              fS 7 /w)a  Open an SSH client session

           This method is a coroutine wrapper around :meth:`create_session`
           designed to provide a "high-level" stream interface for creating
           an SSH client session. Instead of taking a `session_factory`
           argument for constructing an object which will handle activity
           on the session via callbacks, it returns an :class:`SSHWriter`
           and two :class:`SSHReader` objects representing stdin, stdout,
           and stderr which can be used to perform I/O on the session. With
           the exception of `session_factory`, all of the arguments to
           :meth:`create_session` are supported and have the same meaning.

        N)rn  r   r   r   r?   r  r[  r  r  r  s        r  open_sessionz SSHClientConnection.open_session  si       2d11"5%)5-35 5g
 '4()GT*B'4)=>@ 	@5s   AA0AT)inputstdinstdoutstderrbufsizesend_eofrecv_eofrr  rs  rt  ru  rv  rw  rx  c                   K    | j                   t        g|i |	 d{   \  }
}|}|r#|
j                  |       |
j                          d}|j	                  ||||||       d{    |S 7 N7 w)a  Create a process on the remote system

           This method is a coroutine wrapper around :meth:`create_session`
           which can be used to execute a command, start a subsystem,
           or start an interactive shell, optionally redirecting stdin,
           stdout, and stderr to and from files or pipes attached to
           other local and remote processes.

           By default, the stdin, stdout, and stderr arguments default
           to the special value `PIPE` which means that they can be
           read and written interactively via stream objects which are
           members of the :class:`SSHClientProcess` object this method
           returns. If other file-like objects are provided as arguments,
           input or output will automatically be redirected to them. The
           special value `DEVNULL` can be used to provide no input or
           discard all output, and the special value `STDOUT` can be
           provided as `stderr` to send its output to the same stream
           as `stdout`.

           In addition to the arguments below, all arguments to
           :meth:`create_session` except for `session_factory` are
           supported and have the same meaning.

           :param input: (optional)
               Input data to feed to standard input of the remote process.
               If specified, this argument takes precedence over stdin.
               Data should be a `str` if encoding is set, or `bytes` if not.
           :param stdin: (optional)
               A filename, file-like object, file descriptor, socket, or
               :class:`SSHReader` to feed to standard input of the remote
               process, or `DEVNULL` to provide no input.
           :param stdout: (optional)
               A filename, file-like object, file descriptor, socket, or
               :class:`SSHWriter` to feed standard output of the remote
               process to, or `DEVNULL` to discard this output.
           :param stderr: (optional)
               A filename, file-like object, file descriptor, socket, or
               :class:`SSHWriter` to feed standard error of the remote
               process to, `DEVNULL` to discard this output, or `STDOUT`
               to feed standard error to the same place as stdout.
           :param bufsize: (optional)
               Buffer size to use when feeding data from a file to stdin
           :param send_eof:
               Whether or not to send EOF to the channel when EOF is
               received from stdin, defaulting to `True`. If set to `False`,
               the channel will remain open after EOF is received on stdin,
               and multiple sources can be redirected to the channel.
           :param recv_eof:
               Whether or not to send EOF to stdout and stderr when EOF is
               received from the channel, defaulting to `True`. If set to
               `False`, the redirect targets of stdout and stderr will remain
               open after EOF is received on the channel and can be used for
               multiple redirects.
           :type input: `str` or `bytes`
           :type bufsize: `int`
           :type send_eof: `bool`
           :type recv_eof: `bool`

           :returns: :class:`SSHClientProcess`

           :raises: :exc:`ChannelOpenError` if the channel can't be opened

        N)rn  r   rN  	write_eofredirect)r  rr  rs  rt  ru  rv  rw  rx  r[  r  r  process	new_stdins                r  create_processz"SSHClientConnection.create_process  s     R 2d11/#/'-/ /g .3	 JJuNNIy&&&(< 	< 	< /	<s"   A3A/AA3(A1)A31A3r  c	                 V  K   dt         ffd}
 | j                  |
|fd|i|	 d{   \  }}|}|rBt        t        |j	                  d            }|j                  |       |j                          d}|j                  ||||       d{    ||j                         fS 7 {7 w)a  Create a subprocess on the remote system

           This method is a coroutine wrapper around :meth:`create_session`
           which can be used to execute a command, start a subsystem,
           or start an interactive shell, optionally redirecting stdin,
           stdout, and stderr to and from files or pipes attached to
           other local and remote processes similar to :meth:`create_process`.
           However, instead of performing interactive I/O using
           :class:`SSHReader` and :class:`SSHWriter` objects, the caller
           provides a function which returns an object which conforms
           to the :class:`asyncio.SubprocessProtocol` and this call
           returns that and an :class:`SSHSubprocessTransport` object which
           conforms to :class:`asyncio.SubprocessTransport`.

           With the exception of the addition of `protocol_factory`, all
           of the arguments are the same as :meth:`create_process`.

           :param protocol_factory:
               A `callable` which returns an :class:`SSHSubprocessProtocol`
               object that will be created to handle activity on this
               session.
           :type protocol_factory: `callable`

           :returns: an :class:`SSHSubprocessTransport` and
                     :class:`SSHSubprocessProtocol`

           :raises: :exc:`ChannelOpenError` if the channel can't be opened

        r  c                      t               S )zReturn a subprocess transport)r   )r  s   r  transport_factoryz@SSHClientConnection.create_subprocess.<locals>.transport_factoryN  s     **:;;r	  rX  Nr   )	r   rn  r   r   rA  rN  rz  r{  get_protocol)r  r  r&  rv  rr  rs  rt  ru  rX  r  r  rY  r=  r}  
stdin_pipes    `             r  create_subprocessz%SSHClientConnection.create_subprocess&  s     P	<#9 	<
 1T001BG ;:B;39; ;9 .3	 4'::1=?JU#  "I  FFGDDD)00222!; 	Es"   &B)B%A$B)B'B)'B)F)checktimeoutr  r  c                z   K    | j                   |i | d{   }|j                  ||       d{   S 7 7 w)a  Run a command on the remote system and collect its output

           This method is a coroutine wrapper around :meth:`create_process`
           which can be used to run a process to completion when no
           interactivity is needed. All of the arguments to
           :meth:`create_process` can be passed in to provide input or
           redirect stdin, stdout, and stderr, but this method waits until
           the process exits and returns an :class:`SSHCompletedProcess`
           object with the exit status or signal information and the
           output to stdout and stderr (if not redirected).

           If the check argument is set to `True`, a non-zero exit status
           from the remote process will trigger the :exc:`ProcessError`
           exception to be raised.

           In addition to the argument below, all arguments to
           :meth:`create_process` are supported and have the same meaning.

           If a timeout is specified and it expires before the process
           exits, the :exc:`TimeoutError` exception will be raised. By
           default, no timeout is set and this call will wait indefinitely.

           :param check: (optional)
               Whether or not to raise :exc:`ProcessError` when a non-zero
               exit status is returned
           :param timeout:
               Amount of time in seconds to wait for process to exit or
               `None` to wait indefinitely
           :type check: `bool`
           :type timeout: `int`, `float`, or `None`

           :returns: :class:`SSHCompletedProcess`

           :raises: | :exc:`ChannelOpenError` if the session can't be opened
                    | :exc:`ProcessError` if checking non-zero exit status
                    | :exc:`TimeoutError` if the timeout expires before exit

        N)r~  r  )r  r  r  r[  r  r|  s         r  runzSSHClientConnection.runf  s@     T ,++T<V<<\\%111 =1s   ;7;9;;rW  rh  r  r  ri  rj  c                   K   | j                   j                  d||f       | j                   j                  d||f       | j                  ||||	      }
|
j                  |||||       d{   }|
|fS 7 w)a6
  Create an SSH TCP direct connection

           This method is a coroutine which can be called to request that
           the server open a new outbound TCP connection to the specified
           destination host and port. If the connection is successfully
           opened, a new SSH channel will be opened with data being handled
           by a :class:`SSHTCPSession` object created by `session_factory`.

           Optional arguments include the host and port of the original
           client opening the connection when performing TCP port forwarding.

           By default, this class expects data to be sent and received as
           raw bytes. However, an optional encoding argument can be passed
           in to select the encoding to use, allowing the application send
           and receive string data. When encoding is set, an optional errors
           argument can be passed in to select what Unicode error handling
           strategy to use.

           Other optional arguments include the SSH receive window size and
           max packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHTCPSession` object
               that will be created to handle activity on this session
           :param remote_host:
               The remote hostname or address to connect to
           :param remote_port:
               The remote port number to connect to
           :param orig_host: (optional)
               The hostname or address of the client requesting the connection
           :param orig_port: (optional)
               The port number of the client requesting the connection
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_host: `str`
           :type remote_port: `int`
           :type orig_host: `str`
           :type orig_port: `int`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHTCPChannel` and :class:`SSHTCPSession`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        z#Opening direct TCP connection to %sr)  N)r{   r~  r^  rh  r  r  r  r  ri  rj  rX  rY  rZ  r[  r  r  s               r  r  z%SSHClientConnection.create_connection  s     ~ 	>%{3	5/)Y1GH&&xM_k;%.	; ; W};   A)A6+A4,	A6c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)aM  Open an SSH TCP direct connection

           This method is a coroutine wrapper around :meth:`create_connection`
           designed to provide a "high-level" stream interface for creating
           an SSH TCP direct connection. Instead of taking a
           `session_factory` argument for constructing an object which will
           handle activity on the session via callbacks, it returns
           :class:`SSHReader` and :class:`SSHWriter` objects which can be
           used to perform I/O on the connection.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_connection` are supported and have the same
           meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        Nr  r   r   r   rp  s        r  open_connectionz#SSHClientConnection.open_connection  sV     , 5d442"&2*02 2g
 $'7D)AAA2   AA  Ac          
        K   |j                         }| j                  j                  d||f       | j                  dt	        |      t        |             d{   \  }}	|t        k(  r|dk(  r|	j                         }d}
n.t        |	j                               dk(  r|	j                          d}
|	j                          t        t           | |||||||      }|
r+| j                  j                  d|       || j                  |<   || j                  ||f<   |S |	j                          | j                  j                  d	       t!        d	      7 w)
ao  Create a remote SSH TCP listener

           This method is a coroutine which can be called to request that
           the server listen on the specified remote address and port for
           incoming TCP connections. If the request is successful, the
           return value is an :class:`SSHListener` object which can be
           used later to shut down the listener. If the request fails,
           `None` is returned.

           :param session_factory:
               A `callable` or coroutine which takes arguments of the
               original host and port of the client and decides whether
               to accept the connection or not, either returning an
               :class:`SSHTCPSession` object used to handle activity
               on that connection or raising :exc:`ChannelOpenError`
               to indicate that the connection should not be accepted
           :param listen_host:
               The hostname or address on the remote host to listen on
           :param listen_port:
               The port number on the remote host to listen on
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable` or coroutine
           :type listen_host: `str`
           :type listen_port: `int`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        z"Creating remote TCP listener on %ss   tcpip-forwardNr   Tr>  FzAssigning dynamic port %dz$Failed to create remote TCP listener)r   r{   r~  r  r   r   rW   rI  r  r+  r  rs   r	   r  r  r  r   )r  r  r  r  rX  rY  rZ  r[  rV  rU  dynamicr  s               r  r!  z!SSHClientConnection.create_server  sV    b "'')=%{3	5 !% 9 9f[16+3F!H H ))a$//1 v3356!;%%'+F3D/4?4<f4:KIH
 ""#>L>F..{;?GD"";#;<OKKEF$%KLLEHs   AEEC6Ehandler_factoryc                 |   K   dt         dt        dt        ffd} | j                  |g|i | d{   S 7 w)a=  Start a remote SSH TCP listener

           This method is a coroutine wrapper around :meth:`create_server`
           designed to provide a "high-level" stream interface for creating
           remote SSH TCP listeners. Instead of taking a `session_factory`
           argument for constructing an object which will handle activity on
           the session via callbacks, it takes a `handler_factory` which
           returns a `callable` or coroutine that will be passed
           :class:`SSHReader` and :class:`SSHWriter` objects which can be
           used to perform I/O on each new connection which arrives. Like
           :meth:`create_server`, `handler_factory` can also raise
           :exc:`ChannelOpenError` if the connection should not be accepted.

           With the exception of `handler_factory` replacing
           `session_factory`, all of the arguments to :meth:`create_server`
           are supported and have the same meaning here.

           :param handler_factory:
               A `callable` or coroutine which takes arguments of the
               original host and port of the client and decides whether to
               accept the connection or not, either returning a callback
               or coroutine used to handle activity on that connection
               or raising :exc:`ChannelOpenError` to indicate that the
               connection should not be accepted
           :type handler_factory: `callable` or coroutine

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        ri  rj  r  c                 (    t         | |            S )z#Return a TCP stream session handler)r   )ri  rj  r  s     r  r  z9SSHClientConnection.start_server.<locals>.session_factoryx  s     'y)'LMMr	  N)r  r  r   r!  r  r  r[  r  r  s    `   r  start_serverz SSHClientConnection.start_serverU  sY     F	Ns 	Ns 	N} 	N
 (T'' 9)-9179 9 	9 9s   2<:<rn  c                   K   | j                   j                  d|       | j                  ||||      }|j                  ||       d{   }||fS 7 w)a  Create an SSH UNIX domain socket direct connection

           This method is a coroutine which can be called to request that
           the server open a new outbound UNIX domain socket connection to
           the specified destination path. If the connection is successfully
           opened, a new SSH channel will be opened with data being handled
           by a :class:`SSHUNIXSession` object created by `session_factory`.

           By default, this class expects data to be sent and received as
           raw bytes. However, an optional encoding argument can be passed
           in to select the encoding to use, allowing the application to
           send and receive string data. When encoding is set, an optional
           errors argument can be passed in to select what Unicode error
           handling strategy to use.

           Other optional arguments include the SSH receive window size and
           max packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHUNIXSession` object
               that will be created to handle activity on this session
           :param remote_path:
               The remote path to connect to
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_path: `str`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHUNIXChannel` and :class:`SSHUNIXSession`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        z$Opening direct UNIX connection to %sN)r{   r~  r`  rh  	r  r  rn  rX  rY  rZ  r[  r  r  s	            r  rp  z*SSHClientConnection.create_unix_connection  sW     d 	?M''&&+N_kBBW} C   AAA		Ac                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)au  Open an SSH UNIX domain socket direct connection

           This method is a coroutine wrapper around
           :meth:`create_unix_connection` designed to provide a "high-level"
           stream interface for creating an SSH UNIX domain socket direct
           connection. Instead of taking a `session_factory` argument for
           constructing an object which will handle activity on the session
           via callbacks, it returns :class:`SSHReader` and :class:`SSHWriter`
           objects which can be used to perform I/O on the connection.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_unix_connection` are supported and have the same
           meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        Nrp  r   r   r   rp  s        r  open_unix_connectionz(SSHClientConnection.open_unix_connection  sY     . .$--.B ?/3?7=? ? 	g $'7D)AAA?r  c          	      b  K   | j                   j                  d|       | j                  dt        |             d{   \  }}|j	                          |t
        k(  r)t        t           | ||||||      }	|	| j                  |<   |	S | j                   j                  d       t        d      7 ow)a  Create a remote SSH UNIX domain socket listener

           This method is a coroutine which can be called to request that
           the server listen on the specified remote path for incoming UNIX
           domain socket connections. If the request is successful, the
           return value is an :class:`SSHListener` object which can be
           used later to shut down the listener. If the request fails,
           `None` is returned.

           :param session_factory:
               A `callable` or coroutine which decides whether to accept
               the connection or not, either returning an
               :class:`SSHUNIXSession` object used to handle activity
               on that connection or raising :exc:`ChannelOpenError`
               to indicate that the connection should not be accepted
           :param listen_path:
               The path on the remote host to listen on
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type listen_path: `str`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        z#Creating remote UNIX listener on %ss   streamlocal-forward@openssh.comNz%Failed to create remote UNIX listener)r{   r~  r  r   r  rW   rt   r	   r  r  r   )
r  r  r  rX  rY  rZ  r[  rV  rU  r  s
             r  create_unix_serverz&SSHClientConnection.create_unix_server  s     X 	>L $ 9 9.{0C!E E 	)),V4T?5@(5;V5@BH
 3;D"";/OKKFG$%LMMEs   ;B/B-A0B/c                 d   K   dt         ffd} | j                  |g|i | d{   S 7 w)aD  Start a remote SSH UNIX domain socket listener

           This method is a coroutine wrapper around :meth:`create_unix_server`
           designed to provide a "high-level" stream interface for creating
           remote SSH UNIX domain socket listeners. Instead of taking a
           `session_factory` argument for constructing an object which
           will handle activity on the session via callbacks, it takes a
           `handler_factory` which returns a `callable` or coroutine that
           will be passed :class:`SSHReader` and :class:`SSHWriter` objects
           which can be used to perform I/O on each new connection which
           arrives. Like :meth:`create_unix_server`, `handler_factory`
           can also raise :exc:`ChannelOpenError` if the connection should
           not be accepted.

           With the exception of `handler_factory` replacing
           `session_factory`, all of the arguments to
           :meth:`create_unix_server` are supported and have the same
           meaning here.

           :param handler_factory:
               A `callable` or coroutine which decides whether to accept
               the UNIX domain socket connection or not, either returning
               a callback or coroutine used to handle activity on that
               connection or raising :exc:`ChannelOpenError` to indicate
               that the connection should not be accepted
           :type handler_factory: `callable` or coroutine

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        r  c                  $    t                       S )z2Return a UNIX domain socket stream session handler)r   )r  s   r  r  z>SSHClientConnection.start_unix_server.<locals>.session_factory<  s     ((9::r	  N)r   r  r  s    `   r  start_unix_serverz%SSHClientConnection.start_unix_server  sH     J	;!5 	;
 -T,,_ >.2>6<> > 	> >s   &0.0client_factoryrk  rm  c                 >   K   t        |||fd| i| d{   S 7 w)a  Create a tunneled SSH client connection

           This method is a coroutine which can be called to open an
           SSH client connection to the requested host and port tunneled
           inside this already established connection. It takes all the
           same arguments as :func:`create_connection` but requests
           that the upstream SSH server open the connection rather than
           connecting directly.

        rZ  Nr  )r  r  rk  rm  r  s        r  create_ssh_connectionz)SSHClientConnection.create_ssh_connectionD  s6      (d ?/3?7=? ? 	@ ?s   c                 <   K   t        ||fd| i| d{   S 7 w)a  Make a tunneled SSH client connection

           This method is a coroutine which can be called to open an
           SSH client connection to the requested host and port tunneled
           inside this already established connection. It takes all the
           same arguments as :func:`connect` but requests that the upstream
           SSH server open the connection rather than connecting directly.

        rZ  N)rh  r  rk  rm  r  s       r  connect_sshzSSHClientConnection.connect_sshV  s%      T4??????   r  c                 <   K   t        ||fd| i| d{   S 7 w)a  Make a tunneled reverse direction SSH connection

           This method is a coroutine which can be called to open an
           SSH client connection to the requested host and port tunneled
           inside this already established connection. It takes all the
           same arguments as :func:`connect` but requests that the upstream
           SSH server open the connection rather than connecting directly.

        rZ  N)connect_reverser  s       r  connect_reverse_sshz'SSHClientConnection.connect_reverse_sshe  s2      %T4 / /'-/ / 	/ /r  c                 <   K   t        ||fd| i| d{   S 7 w)a  Create a tunneled SSH listener

           This method is a coroutine which can be called to open a remote
           SSH listener on the requested host and port tunneled inside this
           already established connection. It takes all the same arguments as
           :func:`listen` but requests that the upstream SSH server open the
           listener rather than listening directly via TCP/IP.

        rZ  Nlistenr  s       r  
listen_sshzSSHClientConnection.listen_sshu  s%      D$>t>v>>>>r  c                 <   K   t        ||fd| i| d{   S 7 w)a  Create a tunneled reverse direction SSH listener

           This method is a coroutine which can be called to open a remote
           SSH listener on the requested host and port tunneled inside this
           already established connection. It takes all the same arguments as
           :func:`listen_reverse` but requests that the upstream SSH server
           open the listener rather than listening directly via TCP/IP.

        rZ  N)listen_reverser  s       r  listen_reverse_sshz&SSHClientConnection.listen_reverse_ssh  s2      $D$ .t .&,. . 	. .r  rZ  r[  remote_unitc                   K   | j                   j                  d|dn
t        |             | j                  ||      }|j	                  |t
        |       d{   }||fS 7 w)a)  Create an SSH layer 3 tunnel

           This method is a coroutine which can be called to request that
           the server open a new outbound layer 3 tunnel to the specified
           remote TUN device. If the tunnel is successfully opened, a new
           SSH channel will be opened with data being handled by a
           :class:`SSHTunTapSession` object created by `session_factory`.

           Optional arguments include the SSH receive window size and max
           packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHUNIXSession` object
               that will be created to handle activity on this session
           :param remote_unit:
               The remote TUN device to connect to
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_unit: `int` or `None`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHTunTapChannel` and :class:`SSHTunTapSession`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        z(Opening layer 3 tunnel to remote unit %sNr  )r{   r~  r  rc  openr   r  r  r  rZ  r[  r  r  s          r  
create_tunzSSHClientConnection.create_tun  sn     H 	C"-"53{;K	M ))&+>		/3L"-/ / W}/   AA#A!	A#c                   K   | j                   j                  d|dn
t        |             | j                  ||      }|j	                  |t
        |       d{   }||fS 7 w)a)  Create an SSH layer 2 tunnel

           This method is a coroutine which can be called to request that
           the server open a new outbound layer 2 tunnel to the specified
           remote TAP device. If the tunnel is successfully opened, a new
           SSH channel will be opened with data being handled by a
           :class:`SSHTunTapSession` object created by `session_factory`.

           Optional arguments include the SSH receive window size and max
           packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHUNIXSession` object
               that will be created to handle activity on this session
           :param remote_unit:
               The remote TAP device to connect to
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_unit: `int` or `None`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHTunTapChannel` and :class:`SSHTunTapSession`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        z(Opening layer 2 tunnel to remote unit %sNr  )r{   r~  r  rc  r  r   r  s          r  
create_tapzSSHClientConnection.create_tap  sn     H 	C"-"53{;K	M ))&+>		/3H"-/ / W}/r  c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)a"  Open an SSH layer 3 tunnel

           This method is a coroutine wrapper around :meth:`create_tun`
           designed to provide a "high-level" stream interface for creating
           an SSH layer 3 tunnel. Instead of taking a `session_factory`
           argument for constructing an object which will handle activity
           on the session via callbacks, it returns :class:`SSHReader` and
           :class:`SSHWriter` objects which can be used to perform I/O on
           the tunnel.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_tun` are supported and have the same meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        N)r  r   r   r   rp  s        r  open_tunzSSHClientConnection.open_tun  T     * .doo.D ?/3?7=? ?g
 $'7D)AAA?r  c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)a"  Open an SSH layer 2 tunnel

           This method is a coroutine wrapper around :meth:`create_tap`
           designed to provide a "high-level" stream interface for creating
           an SSH layer 2 tunnel. Instead of taking a `session_factory`
           argument for constructing an object which will handle activity
           on the session via callbacks, it returns :class:`SSHReader` and
           :class:`SSHWriter` objects which can be used to perform I/O on
           the tunnel.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_tap` are supported and have the same meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

           :raises: :exc:`ChannelOpenError` if the connection can't be opened

        N)r  r   r   r   rp  s        r  open_tapzSSHClientConnection.open_tap  r  r  rw  rz  c                    K   dt         t           dt        dt        dt        t
        t           t        t           f   f fd} j                  j                  d||f       	 t          j                  |||       d{   }|d	k(  r|j                         }| j                  ||f<   |S 7 ,# t        $ r"} j                  j                  d|        d}~ww xY ww)
aF  Set up local TCP port forwarding to a remote UNIX domain socket

           This method is a coroutine which attempts to set up port
           forwarding from a local TCP listening port to a remote UNIX
           domain path via the SSH connection. If the request is successful,
           the return value is an :class:`SSHListener` object which can be
           used later to shut down the port forwarding.

           :param listen_host:
               The hostname or address on the local host to listen on
           :param listen_port:
               The port number on the local host to listen on
           :param dest_path:
               The path on the remote host to forward the connections to
           :param accept_handler:
               A `callable` or coroutine which takes arguments of the
               original host and port of the client and decides whether
               or not to allow connection forwarding, returning `True` to
               accept the connection and begin forwarding or `False` to
               reject and close it.
           :type listen_host: `str`
           :type listen_port: `int`
           :type dest_path: `str`
           :type accept_handler: `callable` or coroutine

           :returns: :class:`SSHListener`

           :raises: :exc:`OSError` if the listener can't be opened

        r  ri  rj  r  c                 (  K   rn ||      }t        j                  |      rt        t        t           |       d{   }|s/j
                  j                  d||f       t        t        d      j                  |        d{   S 7 O7 wr}  )
r  r  r   r
   r  r{   r~  r   rY   rp  )r  ri  rj  r  rz  rw  r  s       r  r  zISSHClientConnection.forward_local_port_to_path.<locals>.tunnel_connectionL  s      '	9=&&v.#'	$#@@FKK$$ &F&/%;YH ++K+IK K 55o6?A A B AAs"   ;BBA
B	B
BBr  Nr  r   )r   r  r  r  r   r,   r   r{   r~  rw   r  rt  r  r  r  )r  r  r  rw  rz  r  r  rI  s   `  ``   r  forward_local_port_to_pathz.SSHClientConnection.forward_local_port_to_path)  s     F	B!6u!=	B	B+.	B ./1FFG	B. 	E%{3Y	@	8tzz9J9D9DF FH !"++-K:Bk;67F  	KKH#N	s<   A"C!(B3 B1B3 	(C!1B3 3	C<CCC!rq  rr  c                 ~   K   dt         t           dt        t        t           t        t           f   f fd} j
                  j                  d|f       	 t          j                  ||       d{   }| j                  |<   |S 7 # t        $ r"} j
                  j                  d|        d}~ww xY ww)a  Set up local UNIX domain socket forwarding to a remote TCP port

           This method is a coroutine which attempts to set up UNIX domain
           socket forwarding from a local listening path to a remote host
           and port via the SSH connection. If the request is successful,
           the return value is an :class:`SSHListener` object which can
           be used later to shut down the UNIX domain socket forwarding.

           :param listen_path:
               The path on the local host to listen on
           :param dest_host:
               The hostname or address to forward the connections to
           :param dest_port:
               The port number to forward the connections to
           :type listen_path: `str`
           :type dest_host: `str`
           :type dest_port: `int`

           :returns: :class:`SSHListener`

           :raises: :exc:`OSError` if the listener can't be opened

        r  r  c                 J   K   j                  | dd       d{   S 7 w)r~  r  r   Nr  )r  rq  rr  r  s    r  r  zISSHClientConnection.forward_local_path_to_port.<locals>.tunnel_connection  s5     
 //092qB B B B   #!#r  Nr  )r   r  r   r+   r   r{   r~  rx   r  rt  r  r  )r  r  rq  rr  r  r  rI  s   ` ``   r  forward_local_path_to_portz.SSHClientConnection.forward_local_path_to_portv  s     8	B!5e!<	B-.e0DDE	B 	F$y)&<	>	9$

:K:EG GH .6k*G  	KKI3O	s<   AB=B 7B8B <B=B 	B:B55B::B=c                     K   dt         dt        dt        t           f fd} j                  j                  d||ff        j                  |||       d{   S 7 w)a2  Set up remote port forwarding

           This method is a coroutine which attempts to set up port
           forwarding from a remote listening port to a local host and port
           via the SSH connection. If the request is successful, the
           return value is an :class:`SSHListener` object which can be
           used later to shut down the port forwarding. If the request
           fails, `None` is returned.

           :param listen_host:
               The hostname or address on the remote host to listen on
           :param listen_port:
               The port number on the remote host to listen on
           :param dest_host:
               The hostname or address to forward connections to
           :param dest_port:
               The port number to forward connections to
           :type listen_host: `str`
           :type listen_port: `int`
           :type dest_host: `str`
           :type dest_port: `int`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        r  r  r  c                 R    t        t        t           j                              S z9Return an SSHTCPSession used to do remote port forwarding)r   r
   r   rv  )r  r  rq  rr  r  s     r  r  z@SSHClientConnection.forward_remote_port.<locals>.session_factory  s+     	-0//	9EG Gr	  +Creating remote TCP forwarder from %s to %sN)r  r  r
   r   r{   r~  r!  )r  r  r  rq  rr  r  s   `  `` r  forward_remote_portz'SSHClientConnection.forward_remote_port  sz     @	G 	G(+	G09-0H	G 	F%{3i5K	M ''(35 5 	5 5s   AA%A#A%c                     K   dt         t        t              f fd} j                  j	                  d|        j                  ||       d{   S 7 w)a?  Set up remote UNIX domain socket forwarding

           This method is a coroutine which attempts to set up UNIX domain
           socket forwarding from a remote listening path to a local path
           via the SSH connection. If the request is successful, the
           return value is an :class:`SSHListener` object which can be
           used later to shut down the port forwarding. If the request
           fails, `None` is returned.

           :param listen_path:
               The path on the remote host to listen on
           :param dest_path:
               The path on the local host to forward connections to
           :type listen_path: `str`
           :type dest_path: `str`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        r  c                  ^    t        t        t        t              j	                               S z:Return an SSHUNIXSession used to do remote path forwarding)r   r
   r   r  ry  )rw  r  s   r  r  z@SSHClientConnection.forward_remote_path.<locals>.session_factory  s.     	."7844Y?A Ar	  ,Creating remote UNIX forwarder from %s to %sN)r
   r   r  r{   r~  r  )r  r  rw  r  s   ` ` r  forward_remote_pathz'SSHClientConnection.forward_remote_path  sV     2	A>%+@!A 	A 	G$i	1 ,,_kJJJJs   AAAAc                     K   dt         dt        dt        t           f fd} j                  j                  d||f        j                  |||       d{   S 7 w)a  Set up remote TCP port forwarding to a local UNIX domain socket

           This method is a coroutine which attempts to set up port
           forwarding from a remote TCP listening port to a local UNIX
           domain socket path via the SSH connection. If the request is
           successful, the return value is an :class:`SSHListener` object
           which can be used later to shut down the port forwarding. If
           the request fails, `None` is returned.

           :param listen_host:
               The hostname or address on the remote host to listen on
           :param listen_port:
               The port number on the remote host to listen on
           :param dest_path:
               The path on the local host to forward connections to
           :type listen_host: `str`
           :type listen_port: `int`
           :type dest_path: `str`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        r  r  r  c                 P    t        t        t           j                              S r  )r   r
   r   ry  )r  r  rw  r  s     r  r  zHSSHClientConnection.forward_remote_port_to_path.<locals>.session_factory  s)     	.144Y?A Ar	  r  N)r  r  r
   r   r{   r~  r!  )r  r  r  rw  r  s   `  ` r  forward_remote_port_to_pathz/SSHClientConnection.forward_remote_port_to_path  st     :	A 	A(+	A09.0I	A 	F%{3Y	@ ''(35 5 	5 5s   AA!AA!c                     K   dt         t        t              f fd} j                  j	                  d|f        j                  ||       d{   S 7 w)a  Set up remote UNIX domain socket forwarding to a local TCP port

           This method is a coroutine which attempts to set up UNIX domain
           socket forwarding from a remote listening path to a local TCP
           host and port via the SSH connection. If the request is
           successful, the return value is an :class:`SSHListener` object
           which can be used later to shut down the port forwarding. If
           the request fails, `None` is returned.

           :param listen_path:
               The path on the remote host to listen on
           :param dest_host:
               The hostname or address to forward connections to
           :param dest_port:
               The port number to forward connections to
           :type listen_path: `str`
           :type dest_host: `str`
           :type dest_port: `int`

           :returns: :class:`SSHListener`

           :raises: :class:`ChannelListenError` if the listener can't be opened

        r  c                  `    t        t        t        t              j	                               S r  )r   r
   r   r  rv  )rq  rr  r  s   r  r  zHSSHClientConnection.forward_remote_path_to_port.<locals>.session_factoryA  s0     	-"67//	9EG Gr	  r  N)r
   r   r  r{   r~  r  )r  r  rq  rr  r  s   ` `` r  forward_remote_path_to_portz/SSHClientConnection.forward_remote_path_to_port$  s[     :	G=+?!@ 	G 	G$y)&<	> ,,_kJJJJs   AAAAc                    K   dt         t           dt        dt        dt        dt        dt        t
        t           t        t           f   f fd} j                  j                  d||f       	 t          j                  |||       d	{   }|dk(  r|j                         }| j                  ||f<   |S 7 ,# t        $ r"} j                  j                  d
|        d	}~ww xY ww)a  Set up local port forwarding via SOCKS

           This method is a coroutine which attempts to set up dynamic
           port forwarding via SOCKS on the specified local host and
           port. Each SOCKS request contains the destination host and
           port to connect to and triggers a request to tunnel traffic
           to the requested host and port via the SSH connection.

           If the request is successful, the return value is an
           :class:`SSHListener` object which can be used later to shut
           down the port forwarding.

           :param listen_host:
               The hostname or address on the local host to listen on
           :param listen_port:
               The port number on the local host to listen on
           :type listen_host: `str`
           :type listen_port: `int`

           :returns: :class:`SSHListener`

           :raises: :exc:`OSError` if the listener can't be opened

        r  rq  rr  ri  rj  r  c                 J   K   j                  | ||||       d{   S 7 w)z)Forward a local SOCKS connection over SSHNr  )r  rq  rr  ri  rj  r  s        r  tunnel_socksz7SSHClientConnection.forward_socks.<locals>.tunnel_socksh  s6      //099099F F F Fr  z$Creating local SOCKS forwarder on %sNz)Failed to create local SOCKS listener: %sr   )r   r  r  r  r   r+   r   r{   r~  ry   r  rt  r  r  r  )r  r  r  r  r  rI  s   `     r  forward_socksz!SSHClientConnection.forward_socksL  s    8	F0DU0K 	F*-	F:=	F*-	F:=	F mE*M%,@@A	F 	?%{3	5	243?3>M MH !"++-K:Bk;67M  	KKJCP	s<   A+C(/B: B8B: (C(8B: :	C%C  C%%C(
local_unitc                     K   dt         f fd} j                  ||       d{   \  }}t        t        |      S 7 w)a,  Set up layer 3 forwarding

           This method is a coroutine which attempts to set up layer 3
           packet forwarding between local and remote TUN devices. If the
           request is successful, the return value is an :class:`SSHForwarder`
           object which can be used later to shut down the forwarding.

           :param local_unit:
               The unit number of the local TUN device to use
           :param remote_unit:
               The unit number of the remote TUN device to use
           :type local_unit: `int` or `None`
           :type remote_unit: `int` or `None`

           :returns: :class:`SSHForwarder`

           :raises: | :exc:`OSError` if the local TUN device can't be opened
                    | :exc:`ChannelOpenError` if the SSH channel can't be opened

        r  c                  L    t        t        j                  t                     S )z8Return an SSHTunTapSession used to do layer 3 forwarding)r   r   r  r   r  r  s   r  r  z8SSHClientConnection.forward_tun.<locals>.session_factory  s)     (++,E,689 9r	  N)r   r  r   ra   r  r  r  r  rY  ru  s   ``    r  forward_tunzSSHClientConnection.forward_tun  s@     0	9!1 	9 EE4L$'' F   #A?Ac                     K   dt         f fd} j                  ||       d{   \  }}t        t        |      S 7 w)a,  Set up layer 2 forwarding

           This method is a coroutine which attempts to set up layer 2
           packet forwarding between local and remote TAP devices. If the
           request is successful, the return value is an :class:`SSHForwarder`
           object which can be used later to shut down the forwarding.

           :param local_unit:
               The unit number of the local TAP device to use
           :param remote_unit:
               The unit number of the remote TAP device to use
           :type local_unit: `int` or `None`
           :type remote_unit: `int` or `None`

           :returns: :class:`SSHForwarder`

           :raises: | :exc:`OSError` if the local TUN device can't be opened
                    | :exc:`ChannelOpenError` if the SSH channel can't be opened

        r  c                  L    t        t        j                  t                     S )z8Return an SSHTunTapSession used to do layer 2 forwarding)r   r   r  r   r  s   r  r  z8SSHClientConnection.forward_tap.<locals>.session_factory  s(     (++,A:NP Pr	  N)r   r  r   ra   r  s   ``    r  forward_tapzSSHClientConnection.forward_tap  sB     0	P!1 	P EE4L$'' Fr  r  path_encodingc           	         K   | j                  d||d       d{   \  }}}t        | | j                  |||||       d{   S 7 +7 w)a_	  Start an SFTP client

           This method is a coroutine which attempts to start a secure
           file transfer session. If it succeeds, it returns an
           :class:`SFTPClient` object which can be used to copy and
           access files on the remote host.

           An optional Unicode encoding can be specified for sending and
           receiving pathnames, defaulting to UTF-8 with strict error
           checking. If an encoding of `None` is specified, pathnames
           will be left as bytes rather than being converted to & from
           strings.

           :param env: (optional)
               The environment variables to set for this SFTP session. Keys
               and values passed in here will be converted to Unicode
               strings encoded as UTF-8 (ISO 10646) for transmission.

                   .. note:: Many SSH servers restrict which environment
                             variables a client is allowed to set. The
                             server's configuration may need to be edited
                             before environment variables can be
                             successfully set in the remote environment.
           :param send_env: (optional)
               A list of environment variable names to pull from
               `os.environ` and set for this SFTP session. Wildcards
               patterns using `'*'` and `'?'` are allowed, and all variables
               with matching names will be sent with whatever value is set
               in the local environment. If a variable is present in both
               env and send_env, the value from env will be used.
           :param path_encoding:
               The Unicode encoding to apply when sending and receiving
               remote pathnames
           :param path_errors:
               The error handling strategy to apply on encode/decode errors
           :param sftp_version: (optional)
               The maximum version of the SFTP protocol to support, currently
               either 3 or 4, defaulting to 3.
           :type env: `dict` with `str` keys and values
           :type send_env: `list` of `str`
           :type path_encoding: `str` or `None`
           :type path_errors: `str`
           :type sftp_version: `int`

           :returns: :class:`SFTPClient`

           :raises: :exc:`SFTPError` if the session can't be opened

        sftpN)rZ  r[  r\  rX  )rq  r   r  )	r  r[  r\  r  path_errorssftp_versionwriterreaderrY  s	            r  r   z%SSHClientConnection.start_sftp_client  sj     p #'"3"3f8;h=A #4 #C C 'tTZZ'4k'35 5 	5	C5s!   AA&AA	A	ANNNr
  )r  r  r  r  r,  r  )r  r  r  r  __annotations__r0   r   r   r2  r  r  r  r  r.  r  rT  r  _ClientHostKeyr  r  r  r   r  r  r   r  r  r  r  r   r	  r   r  r  r  r  r  r  r   r    r!  r   r*   r   r%  r+   r   r'  r   r.  r  r0  r,   r   r2  r-   r   r4  r7  r:  r.   r
   r   r=  ra   r?  rB  rA  r)   r	   rU  r(   r  r   r   _Env_SendEnvr   r   r   r   rn  r  r   r   rq  r   r   ioDEFAULT_BUFFER_SIZEr   r   r   r~  r   r   r   r  r  r   r  r  r  r   r  r  ru   rr   r!  _TCPServerHandlerFactoryr  r   rp  r  rv   r  _UNIXServerHandlerFactoryr  _ClientFactoryr  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   rU  r5  s   @r  r_  r_    s   B +*011 -104'+	AMW66 AM6AM)AM !.AM  }	AMFQAhHY/ D .	<^ 	< 	< 6 $%Xf%5 %
I# 
I=*  .?(>*C45.?`B*1E BHx} 8	4c 	4.1	46;CHo	4'
-
+Xc] +4+.69"'/'?>CY C"$445CI) I-&e(<<=I!LI !L-M!::;!LFA3 A58A=AA$6$6nn456F$F&(889FL#Lnj&@@AL6	4C 	4D 	4>	 >-+@!AAB>8E#Eni&==>E 8#8(,8B+Y B+4 B+HK.>v.F K+3C=K-5c]K 6:K %#$	K&*
6(: *t * ACcAC35<>GIBD@BBDIKDFFHEGAC5757:<!c4K c&.x}&=c(0#(?c #+4.c (0'9	c
 +35s3C*Dc )1#(?c )1(=c *2,)?c .6eCHo-Fc +38C=*Ac -5Xc],Cc 5=TNc (0'>c &.c]c &.c]c  +33-!c" "$445#cJ@ @& @)Y	12@2 7;485959,.,B,B.2TV& V$,V$4V$1V &3V &3	V
 '*V (,V ?CV (.V 3C62JV Vr DF/1/E/E:>7;8<8<:>=38I =3)1(3-)@=3),=3 (0'7=3 (5	=3
 )6=3 )6=3 +33-=3 +1=3 (*??@=3@ 6;-1,2v ,2d ,2#E?,2",2':,2` BDH >B"/3H#7#?HH+.H;>H H .6c]H 	H -0	H
 H mF+]6-BBCHTB6 BV B)Y&'B:  '+()3WM#5f#=WMWM+.WM smWM 58WM 	WM
 WM
 9DWM WMr (92J (9"((94:(9?J(9 (9X <@"/3	8#8#@88+3C=8 8 -08 	8
 nV,nV.DDE8tB B& B)Y&'B<  <@"/3	<N#6v#><N<N+3C=<N <N -0<N 	<N 9D	<N <N| *>#<*>*>%+*>0;*> *>Z FH@. @*-@5=c]@.4@ +Y67@$ @c @# @$*@/D@ @ /c /# /,2/7L/ / ?S ?Xc] ?#)?.9? ? 3579.S .'/}.+1.6A. .$ *.,@O3,#:,!#,:=, , &(889	,` *.,@O3,#:,!#,:=, , &(889	,\BF Bf B)Y&'B8BF Bf B)Y&'B8  :>J"J14JADJ$%56JBMJ JX 0C 0470470<G0 0d *5S *5/2*5?B*5-0*55@*5 *5X !KS !K-0!K5@!K !KF '5S '57:'558'5=H'5 '5R %KS %K58%K58%K=H%K %KN 5s 5),51<5 5n <@7; (HSM  ('/} (@L (  (D <@7;(HSM ('/}(@L( (B <>?A?F.6/?	=58D> =5*28*<=5/7}=5 EO	=5 =5r	  c                       e Zd ZU dZded<   eed<   ee   ed<   	 	 	 dndej                  ddd	e
d
edee   f
 fdZdee   ddf fdZdodZdodZdee   defdZdee   fdZdodZdefdZdefdZdedededefdZdefdZdedededed ed!edefd"Zded#edee   fd$Z ded#e!dee   fd%Z"dededee   fd&Z#dededee   fd'Z$defd(Z%deded ed!edef
d)Z&defd*Z'ded+edefd,Z(ded-ed.edefd/Z)defd0Z*ded1ed2ede+fd3Z,ded4e-de+fd5Z.d6e/de0e1e2f   fd7Z3d6e/de0e4e   e5e   f   fd8Z6d6e/ddfd9Z7d:ed;e8ddfd<Z9d6e/ddfd=Z:d6e/de0e;e   e<e   f   fd>Z=d6e/ddfd?Z>d@eddfdAZ?d6e/ddfdBZ@d6e/de0eAeBf   fdCZCd6e/ddfdDZDdEe1eE   dFedGedHe8dee   f
dIZFdEeGeE   ddfdJZHdefdKZIdee   fdLZJeKfd ed1eddfdMZLdNeMddfdOZNdpdPedQeOdeOfdRZPdSedefdTZQ	 dpdPedQeOdeOfdUZRdSedefdVZS	 	 	 dqdWee   dXedYe8dZe8de1f
d[ZT	 	 drdd\eUeVd]d^eWeE   d_ed`e8daedbe8dWee   dXedYe8dZe8de0e4eE   e5eE   f   fdcZXddeOdeeOde0eYeZf   fdfZ[dd\eUeVd]d^e\eE   dgedWee   dXedYe8dZe8de0e;eE   e<eE   f   fdhZ]ddeOdeeOde0eYeZf   fdiZ^	 dreUeVdjd^eWe   daedbe8dYe8dZe8de0e_e5e   f   fdkZ`eUeVdjd^e\e   dYe8dZe8de0eae<e   f   fdlZbde0eYe   eZe   f   fdmZc xZdS )sr  aF  SSH server connection

       This class represents an SSH server connection.

       During authentication, :meth:`send_auth_banner` can be called to
       send an authentication banner to the client.

       Once authenticated, :class:`SSHServer` objects wishing to create
       session objects with non-default channel properties can call
       :meth:`create_server_channel` from their :meth:`session_requested()
       <SSHServer.session_requested>` method and return a tuple of
       the :class:`SSHServerChannel` object returned from that and either
       an :class:`SSHServerSession` object or a coroutine which returns
       an :class:`SSHServerSession`.

       Similarly, :class:`SSHServer` objects wishing to create TCP
       connection objects with non-default channel properties can call
       :meth:`create_tcp_channel` from their :meth:`connection_requested()
       <SSHServer.connection_requested>` method and return a tuple of
       the :class:`SSHTCPChannel` object returned from that and either
       an :class:`SSHTCPSession` object or a coroutine which returns an
       :class:`SSHTCPSession`.

       :class:`SSHServer` objects wishing to create UNIX domain socket
       connection objects with non-default channel properties can call
       :meth:`create_unix_channel` from the :meth:`unix_connection_requested()
       <SSHServer.unix_connection_requested>` method and return a tuple of
       the :class:`SSHUNIXChannel` object returned from that and either
       an :class:`SSHUNIXSession` object or a coroutine which returns an
       :class:`SSHUNIXSession`.

    SSHServerConnectionOptionsr  r  r  Nr%  rp  r  r  r  c                    t         |   |||||d       || _        |j                  | _        |j
                  | _        t        |j                  j                               | _	        |j                  | _        |j                  | _        |j                  | _        |j                   | _        |j$                  | _        |j(                  | _        |j,                  | _        |j0                  | _        |j4                  | _        |j8                  | _        |j<                  | _        |j@                  | _!        |jD                  | _#        |jH                  | _%        |jL                  | _'        |jP                  | _)        |jT                  | _+        |jX                  | _-        |j\                  | _/        |j`                  | _1        |jd                  | _3        |jh                  rY	 tk        |jh                  |jl                        | _7        |jp                  | _9        |jt                  | _;        | jv                  | _<        d | _>        i | _?        d | _@        d| _A        d | _B        y # tz        $ r Y /w xY w)NTr  F)Cr-  r.  r  server_host_keys_server_host_keysall_server_host_keys_all_server_host_keysr  keysr  known_client_hosts_known_client_hoststrust_client_host_trust_client_hostauthorized_client_keys_authorized_client_keys	allow_pty
_allow_ptyline_editor_line_editor	line_echo
_line_echoline_history_line_historymax_line_length_max_line_lengthrdns_lookup_rdns_lookupra  _x11_forwardingrc  _x11_auth_pathagent_forwarding_agent_forwardingprocess_factory_process_factoryr  _session_factoryrX  	_encodingrY  _errorssftp_factory_sftp_factoryr  _sftp_version	allow_scp
_allow_scprZ  _windowr[  _max_pktsizer  rd   r  r[  r  r\  r  r]  r_  re   r  _key_options_cert_optionsr  _agent_listener)r  r%  rp  r  r  r  r5  s         r  r.  zSSHServerConnection.__init__0  s   
 	w-d 	 	,  !(!9!9%,%A%A"%)'*B*B*G*G*I%J"#*#=#= ")";";'.'E'E$!++#//!++$11 ' 7 7#//&55%33!(!9!9 ' 7 7 ' 7 7 ))~~$11$11!++~~#//%g&6&68I8IJ	 '!(!1!1%)^^" 7;/1:>%*";?  s   AI 	I"!I"rI  r  c                 ~    | j                   r!| j                   j                          d| _         t        |   |       y)zClean up this server connectionN)r&  r  r-  r  )r  rI  r5  s     r  r  zSSHServerConnection._cleanupc  s5       &&(#'D r	  c                    | j                   j                  d       | j                  j                  rIdj	                  d | j                  j                  D              }| j                   j                  d|       y| j                   j                  d| j
                  | j                  f       | j                   j                  d| j                  | j                  f       y)r  zAccepted SSH client connectionr  c              3   F   K   | ]  }t        j                  |        y wr,  r  r  s     r  r  z7SSHServerConnection._connection_made.<locals>.<genexpr>r  r  r  r  r  r  N)	r{   r~  r  r{  r  r  r  r  r  )r  r{  s     r  r  z$SSHServerConnection._connection_madel  s     	9:==&&HH %B%)]]%@%@%B BMKK2MBKK2"..0@0@ACKK1"oot?Ar	  c           	      4  K   | j                   rP| j                  j                  | j                  | j                  ft
        j                         d{   \  | _        }t        j                  | j                  d| j                  | j                  | j                  | j                  | j                         d{   }|| _
        |j                  | _        |j                   | _        |j$                  | _        |j(                  | _        |j,                  | _        |j0                  | _        |j4                  | _        |j8                  | _        |j<                  | _        |j@                  | _!        |jD                  | _#        |jH                  | _%        y7 A7 ۭw)z-Re-evaluate config with updated match optionsNT)rp  reloadaccept_addraccept_portrd  r  client_addr)&r  r  r  r  r  r  r  r  r  	constructr  r  r  r  rN  rO  rP  rQ  rR  rS  rT  rU  r  r  r  r	  ra  r  r  r  ra  rb  rc  rd  rh  ri  rj  rk  )r  rY  rp  s      r  r!  z!SSHServerConnection.reload_config{  sS     '+zz'='=$//2F4I4I(K "KDOQ 3<<MM$D<L<L((4>>T__ = F F
   ' 7 7 ' 7 7#//%33'.'E'E$!++&55!(!9!9#//%33$+$?$?!#*#=#= 1"KFs&   AFFA'F:F;CFFr  c                     |D ]H  }| j                   j                  |      }|s!||j                  k7  r|j                  |       || _         y y)zChoose the server host key to use

           Given a list of host key algorithms supported by the client,
           select the first compatible server host key we have and return
           whether or not we were able to find a match.

        TF)r  r  r  r  r  )r  r  r  r  s       r  r  z*SSHServerConnection.choose_server_host_key  sS     &C,,005G'+++--c2(/% & r	  c                     | j                   S )zReturn the chosen server host key

           This method returns a keypair object containing the
           chosen server host key and a corresponding public key
           or certificate.

        r  r  s    r  r  z'SSHServerConnection.get_server_host_key  s     $$$r	  c                    | j                   r_| j                  j                  d       | j                   j                         D cg c]  }t	        |       }} | j
                  dg|  y| j                  j                  d       yc c}w )z'Send list of available server host keyszSending server host keyss   hostkeys-00@openssh.comz!Sending server host keys disabledN)r   r{   r~  r  r   r  )r  r  r  s      r  r  z)SSHServerConnection.send_server_host_keys  sx     %%KK78+/+E+E+J+J+LM+LCF3K+LDM%D%%&@H4HKK@A Ns   Bc                 d    | j                   r$| j                  J | j                  j                  S y)z;Return whether GSS key exchange authentication is supportedF)r^  r[  completer  s    r  gss_kex_auth_supportedz*SSHServerConnection.gss_kex_auth_supported  s0     99(((99%%%r	  c                     | j                   S )z2Return whether GSS MIC authentication is supportedr  r  s    r  gss_mic_auth_supportedz*SSHServerConnection.gss_mic_auth_supported  s     !!!r	  rd  user_principalr  c                    K   | j                   j                  |||      }t        j                  |      rt	        t
        t           |       d{   }t	        t        |      S 7 w)zValidate the GSS principal name for the specified user

           Return whether the user principal acquired during GSS
           authentication is valid for the specified user.

        N)r  validate_gss_principalr  r  r   r
   r  )r  rd  r8  r  r  s        r  r:  z*SSHServerConnection.validate_gss_principal  sY      33Hn4BD v&	$88FD&!! 9   AA&A$A&c                     | j                   xr1 t        | j                        xs | j                  j	                         S )z<Return whether or not host based authentication is supported)rO  r  r  r  host_based_auth_supportedr  s    r  r=  z-SSHServerConnection.host_based_auth_supported  s:     %% :d../ 9668	;r	  r  r  r  rs  r  c                   K   |dd dk(  r|dd }| j                   r|}nt| j                  j                  t        t        | j                  d            t        j                         d{   \  }}||k7  r| j                  j                  d||       | j                  r(| j                  | j                  || j                  d       	 | j                  || j                  | j                  |      }	|	j#                  t%        | j&                        |z   |      s| j                  j!                  d       y| j(                  j+                  |||      }t-        j.                  |      rt        t0        t2           |       d{   }t        t2        |      S 7 ,# t        $ r&}
| j                  j!                  d|
       Y d}
~
yd}
~
ww xY w7 Iw)	zBValidate host based authentication for the specified host and userr3  Nr  r  z.Client host mismatch: received %s, resolved %szInvalid host key: %sFz!Invalid host-based auth signature)r  r  r  r   r   r9  r  r  r{   r~  r  r  r  r  r  r  r  rH  r   r$  r  validate_host_based_userr  r  r
   r  )r  rd  r  r  r  rs  r  resolved_hostrY  r  rI  r  s               r  validate_host_based_authz,SSHServerConnection.validate_host_based_auth  s     rss"%cr*K""'M%)ZZ%;%;Xt22:>?%%&'  'M1 +   "/0;]L ####D$<$<m$(OOT;	))-*.//8EC zz&!1!12S8)DKKBC55h6EG v&	$88FD&!!; '  	KK5s;	 9sJ   A'G)F*AG(F 0BG G
G	G!G=GGGr  c                 p  K   d}| j                   rH| j                   j                  |j                  | j                  | j                  |j
                  d      }|_| j                  j                  ||j                        }t        j                  |      rt        t        t           |       d{   }|syi }|| _        | j                  d      rd}	 |j                  t        |       t        t"        t$           |j&                  j)                  d            }|r*t+        | j                        t-        fd|D              sy|j&                  | _        |j0                  j3                  | j                  dd	      xr | j5                  dd	              |j0                  S 7 # t         $ r Y yw xY ww)
z=Validate an OpenSSH client certificate for the specified userNT)ca
principalsr  zsource-addressc              3   &   K   | ]  }|v  
 y wr,  r  )r  networkips     r  r  zDSSHServerConnection._validate_openssh_certificate.<locals>.<genexpr>:  s     F4ErW}4Es   no-touch-requiredF)r  r  r  r  r  rD  r  validate_ca_keyr  r  r   r
   r  r$  get_key_optionr   r  r   r   rp  r  r   r  r%  r  set_touch_requiredget_certificate_option)r  rd  r  rp  r  allowed_addressesrG  s         @r  _validate_openssh_certificatez1SSHServerConnection._validate_openssh_certificate  s    
 04''22;;  $//T < ;G ?[[004;K;KLF""6*#IdOV<<G#|,H	MM.(3 !)!4!%!1!12B!CEDOO,BF4EFF!\\##$$%8%@ I,,-@%HJ	K xx= =  		s7   B.F61F%2#F6F' ,B:F6'	F30F62F33F6c                   K   | j                   sy| j                   j                  || j                  | j                        \  }}|y|| _        | j                  d      rd}| j                  J t        | j                        }|r||gz  }	 |j                  || j                  t               | j                  |       |j                  S # t        $ r Y yw xY ww)z;Validate an X.509 client certificate for the specified userNrD  r  )r8  )r  validate_x509r  r  r$  rJ  r>  r  r  r@  rS  rE  r  r  )r  rd  r  rp  trusted_certtrusted_certss         r   _validate_x509_certificate_chainz4SSHServerConnection._validate_x509_certificate_chainE  s     
 ++ ((66doot8 	 ?#|,H''333T556l^+M	t/L/L #t':':/7   9 xx  		s*   B
C2C ?C	CCCCc                    K   	 t        |      }|j                  r(| j                  |t	        t
        |             d{   S | j                  |t	        t        |             d{   S # t        $ r Y yw xY w7 ;7 w)z4Validate a client certificate for the specified userN)r   r   r  rS  r   r   rN  r   )r  rd  r  r  s       r  _validate_client_certificatez0SSHServerConnection._validate_client_certificateh  s     	)(3D >>$6=? ? ? ;;$4d;= = =  		?=sC   A>A+ /A>A:'A>&A<'A>+	A74A>6A77A><A>c                   K   	 t        |      }d}| j                  r1| j                  j                  || j                  | j
                        }|U| j                  j                  ||      }t        j                  |      rt        t        t           |       d{   }|syi }|| _        |j                  | j                  dd              |S # t        $ r Y yw xY w7 Cw)z3Validate a client public key for the specified userNrH  F)r   r   r  r  r  r  r  validate_public_keyr  r  r   r
   r  r$  rK  rJ  )r  rd  r  r  rp  r  s         r  _validate_client_public_keyz/SSHServerConnection._validate_client_public_keyx  s     	'1C 04''22;;T__doo7G ?[[44XsCF""6*#IdOV<<G###$7??	A 
3  		 =s4   C!C BC!C4C!	CC!CC!c                     | j                   xr1 t        | j                        xs | j                  j	                         S )z<Return whether or not public key authentication is supported)rQ  r  r  r  public_key_auth_supportedr  s    r  rZ  z-SSHServerConnection.public_key_auth_supported  s:     %% :d223 9668	;r	  c                    K   | j                  ||       d{   xs | j                  ||       d{   }|y|r(|j                  t        | j                        |z   |      S y7 N7 4w)a  Validate the public key or certificate for the specified user

           This method validates that the public key or certificate provided
           is allowed for the specified user. If msg and signature are
           provided, the key is used to also validate the message signature.
           It returns `True` when the key is allowed and the signature (if
           present) is valid. Otherwise, it returns `False`.

        NFT)rU  rX  rH  r   r$  )r  rd  r  rs  r  r  s         r  rW  z'SSHServerConnection.validate_public_key  st      77(KK L66xJJ 	 ;::fT%5%56<iHH LJs   A+A'A+A)3A+)A+c                 R    | j                   xr | j                  j                         S )z:Return whether or not password authentication is supported)rU  r  password_auth_supportedr  s    r  r]  z+SSHServerConnection.password_auth_supported  s"     ""Lt{{'J'J'LLr	  r  c                    K   | j                   j                  ||      }t        j                  |      rt	        t
        t           |       d{   }t	        t        |      S 7 w)z.Return whether password is valid for this userN)r  validate_passwordr  r  r   r
   r  )r  rd  r  r  s       r  r_  z%SSHServerConnection.validate_password  sQ      ..xBv&	$88FD&!! 9r  old_passwordnew_passwordc                    K   | j                   j                  |||      }t        j                  |      rt	        t
        t           |       d{   }t	        t        |      S 7 w)z+Handle a password change request for a userN)r  change_passwordr  r  r   r
   r  )r  rd  r`  ra  r  s        r  rc  z#SSHServerConnection.change_password  sX      ,,X|-9; v&	$88FD&!! 9r;  c                     | j                   xr | j                  j                         }|du ry|t        u r"| j                  j	                         rd| _        yy)zQReturn whether or not keyboard-interactive authentication
           is supportedTF)rS  r  kbdint_auth_supportedr  r]  r  r  s     r  re  z)SSHServerConnection.kbdint_auth_supported  sQ     ""Jt{{'H'H'JT>&kk113)-D&r	  r  
submethodsc                   K   | j                   rddt        df}|S | j                  j                  |||      }t	        j
                  |      r!t        t        t           |       d{   }|S t        t        |      }|S 7 w)z,Return a keyboard-interactive auth challenger  ))z	Password:FN)	r  r<   r  get_kbdint_challenger  r  r   r
   r   )r  rd  r  rf  	challenger  s         r  rh  z(SSHServerConnection.get_kbdint_challenge  s      %%*,b,*A*CI  [[55h6@BF ""6*"&y'A6"JJ	  !&9		 Ks   A%B'B (B	responsesc                   K   | j                   rvt        |      dk7  ry	 | j                  j                  ||d         }t	        j
                  |      r t        t        t           |       d{   }nt        t        |      }|S | j                  j                  ||      }t	        j
                  |      r!t        t        t           |       d{   }|S t        t        |      }|S 7 {# t        $ r d}Y |S w xY w7 ,w)zRReturn whether the keyboard-interactive response is valid
           for this userr   Fr   N)r  r  r  r_  r  r  r   r
   r  r   validate_kbdint_responser   )r  rd  rj  	pw_resultnext_challenger  s         r  rl  z,SSHServerConnection.validate_kbdint_response  s      %%9~"' KK99il,	 &&y1+/	$+K%KN%)$	%:N  [[99(INF""6*'+Io,F'O!O  "&ov!> &L * ' "' ' "PsH   C?AC+ -C).C+ AC?C=C?)C+ +C:6C?9C::C?rU  c                 :   |j                          | j                  s| j                  s| j                  r| j	                  | j
                  | j                  | j                  | j                        }| j                  r:t        | j                  | j                  | j                  | j                        }||fS t        | j                  | j                  | j                  | j                        }||fS | j                  j                         }|st        t         d      t#        |t$              r|\  }}n<| j	                  | j
                  | j                  | j                  | j                        }t'        |      rt        |      }||fS t)        t*        |      }||fS )z(Process an incoming session open requestzSession refused)r  r  r  r  create_server_channelr  r  r"  r#  r   r  r!  r   r  session_requestedr   rZ   re  tupler  r   r   )r  rU  r  r  r  s        r  r%  z)SSHServerConnection._process_session_open  sr    	
   D$9$9T=O=O--dnndll.2llD<M<MOD $$*4+@+@+/+=+=+/+=+=+/??<6 W}- 11F1F151C1C151C1C15B, W}# [[224F&':<MNN&%(%f11$..$,,26,,262C2CE 08 W} /8W}r	  c                 @   |j                         }|j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }| j                  d      r| j                  d      st        t        d      t        t        t        t        t        f      | j                  d            }|r"||f|vr|df|vrt        t        d|d|      | j                   j#                  ||||      }	|	st        t$        d	      |	d
u r't        t&        t(           | j+                  ||            }	t-        |	t.              r|	\  }
}	n| j1                         }
t3        |	      rt5        t(           |	      }nt        t&        t(           |	      }| j6                  j9                  d||f       | j6                  j9                  d||f       |
j;                  ||||       |
|fS # t        $ r t        d      dw xY w)z.Process an incoming direct TCP/IP open requestr  z*Invalid direct TCP/IP channel open requestNport-forwardingPort forwarding not permitted
permitopenz!Port forwarding not permitted to z port Connection refusedTz,Accepted direct TCP connection request to %sr)  )r  rI  r  r  r  r   check_key_permissioncheck_certificate_permissionr   rY   r   r   r   r  r  rJ  r  connection_requestedrZ   r   r  rv  re  rr  r^  r  r   r{   r~  r<  )r  rU  r,  rr  r-  rj  rq  ri  permitted_opensr  r  r  s               r  r'  z.SSHServerConnection._process_direct_tcpip_open?  s.    !++-%%'	 ++-%%'		:'..w7I'..w7I
 (():;001BC"#C#BD D s5c?3#22<@B y!8tO3"#C099$FG G 11)Y2;YH "#68LMMT>-.11)YGIF fe$!LD&**,D F)%08G=/8GG#Y/	1/)Y1GH##Iy)YOW}_ " 	: !/ 059:	:s   "H Hc                    |j                         }|j                         }|j                          	 |j                  d      j	                         }| j                  d      r| j                  d      s0| j                  j                  d||f       | j                  d       y| j                  | j                  ||             y# t
        $ r t        d      dw xY w)z2Process an incoming TCP/IP port forwarding requestr  zInvalid TCP/IP forward requestNrt  zDRequest for TCP listener on %s denied: port forwarding not permittedF)r  rI  r  r  r   r  r   rx  ry  r{   r~  r  r  _finish_port_forward)r  rU  listen_host_bytesr  r  s        r  %_process_tcpip_forward_global_requestz9SSHServerConnection._process_tcpip_forward_global_request}  s     #--/'')	L+227;AACK (():;001BCKK 8);79 ((/22;LM " 	L @AtK	Ls   C Cr  r  c                   K   | j                   j                  ||      }	 t        j                  |      rt	        t
        t           |       d{   }|du r| j                  ||||       d{   }n(t        |      r| j                  |||||       d{   }|s0| j                  j                  d||f       | j                  d       y|dk(  r|j                         }t        |      }nd}| j                  j                  d||f       || j                   ||f<   | j                  |       y7 7 7 # t        $ r/ | j                  j                  d       | j                  d       Y yw xY ww)z2Finish processing a TCP/IP port forwarding requestNTzFailed to create TCP listenerFz4Request for TCP listener on %s denied by applicationr   zCreated TCP listener on %s)r  server_requestedr  r  r   r
   _ListenerArgr  r  rt  r{   r  r  r~  r  r   r  )r  r  r  r  r  s        r  r}  z(SSHServerConnection._finish_port_forward  s     ;;//[I	""8,!%i&=x!HH4!%!8!8k;"H H(#!%!8!8h"8 8 KK +-8+,FH ((/
 !"++-KK(FF5%{3	5 ;Ck;67$$V,E IH8  	KK>?((/	s_   E4/D9 D3D9 /D50(D9 D7D9 BE43D9 5D9 7D9 95E1.E40E11E4c                    |j                         }|j                         }|j                          	 |j                  d      j	                         }	 | j                  j                  ||f      }| j                  j                  d||f       |j                          | j                  d       y# t
        $ r t        d      dw xY w# t        $ r t        d      dw xY w)z2Process a request to cancel TCP/IP port forwardingr  z%Invalid TCP/IP cancel forward requestNzTCP/IP listener not foundzClosed TCP listener on %sT)r  rI  r  r  r   r  r   r  r  rJ  r{   r~  r  r  )r  rU  r~  r  r  r  s         r  ,_process_cancel_tcpip_forward_global_requestz@SSHServerConnection._process_cancel_tcpip_forward_global_request  s     #--/'')	=+227;AACK
	G,,00+{1KLH 	4%{3	5 	$$T* " 	= !2 38<=	=  	G ;<$F	Gs   B/ C /CCc                    |j                         }|j                         }|j                         }|j                          	 |j                  d      }| j                  d      r| j                  d      st        t        d      | j                  j                  |      }|st        t        d      |du r&t        t        t           | j!                  |            }t#        |t$              r|\  }}n| j'                         }t)        |      rt+        t           |      }nt        t        t           |      }| j,                  j/                  d|       |j1                  |       ||fS # t        $ r t        d      dw xY w)	z:Process an incoming direct UNIX domain socket open requestr  z/Invalid direct UNIX domain channel open requestNrt  ru  rw  Tz%Accepted direct UNIX connection on %s)r  rI  r  r  r  r   rx  ry  r   rY   r  unix_connection_requestedrZ   r   r   r  ry  re  rr  r`  r  r   r{   r~  r<  )r  rU  r6  rY  rw  r  r  r  s           r  r2  zGSSHServerConnection._process_direct_streamlocal_at_openssh_dot_com_open  sv   
 !++- 	:'..w7I
 (():;001BC"#C#BD D 66yA"#68LMMT>./66yACF fe$!LD&++-D F*51&9G>%0&9G@)L##I.W}E " 	: !/ 059:	:s   E( (E>c                 z   |j                         }|j                          	 |j                  d      }| j                  d      r| j                  d      s.| j                  j                  d|       | j                  d       y| j                  | j                  |             y# t        $ r t	        d      dw xY w)z9Process an incoming UNIX domain socket forwarding requestr  z*Invalid UNIX domain socket forward requestNrt  zERequest for UNIX listener on %s denied: port forwarding not permittedF)r  r  r  r  r   rx  ry  r{   r~  r  r  _finish_path_forward)r  rU  listen_path_bytesr  s       r  >_process_streamlocal_forward_at_openssh_dot_com_global_requestzRSSHServerConnection._process_streamlocal_forward_at_openssh_dot_com_global_request  s     #--/	=+227;K
 (():;001BCKK 89DF ((/22;?@ " 	= !2 38<=	=s   B$ $B:r  c                 Z  K   | j                   j                  |      }	 t        j                  |      rt	        t
        t           |       d{   }|du r| j                  ||       d{   }|s.| j                  j                  d|       | j                  d       y| j                  j                  d|       t	        t        |      | j                  |<   | j                  d       y7 7 # t        $ r/ | j                  j                  d       | j                  d       Y yw xY ww)z9Finish processing a UNIX domain socket forwarding requestNTzFailed to create UNIX listenerFz5Request for UNIX listener on %s denied by applicationzCreated UNIX listener on %s)r  unix_server_requestedr  r  r   r
   r  r  rt  r{   r  r  r~  rr   r  )r  r  r  s      r  r  z(SSHServerConnection._finish_path_forward$  s     ;;44[A
	""8,!%i&=x!HH4!%!8!89D"F F KK +,79 ((/6D-1+x-Hk*$$T*) IF 	KK?@((/	sM   D+/C0 C,C0 ,C.-C0 1A;D+,C0 .C0 05D(%D+'D((D+c                 ~   |j                         }|j                          	 |j                  d      }	 | j
                  j                  |      }| j                  j                  d|       |j                          | j                  d       y# t        $ r t	        d      dw xY w# t        $ r t	        d      dw xY w)z9Process a request to cancel UNIX domain socket forwardingr  z*Invalid UNIX domain cancel forward requestNzUNIX domain listener not foundr9  T)r  r  r  r  r   r  r  rJ  r{   r~  r  r  )r  rU  r  r  r  s        r  E_process_cancel_streamlocal_forward_at_openssh_dot_com_global_requestzYSSHServerConnection._process_cancel_streamlocal_forward_at_openssh_dot_com_global_requestA  s     #--/	=+227;K
	L,,00=H 	5{C$$T* " 	= !2 38<=	=  	L @AtK	Ls   B B& B#&B<c                    |j                         }|j                         }|j                          |t        k(  rd}|t        k(  r| j                  j                  |      }n'|t        k(  r| j                  j                  |      }nd}|st        t        d      |du r t        t        | j                  ||            }t        |t              r|\  }}n| j                         }t!        |      rt#        |      }nt        t        |      }| j$                  j'                  d|t        k(  rdnd|t        k(  rdn
t)        |             |j+                  |       ||fS )	z(Process an incoming TUN/TAP open requestNFrw  Tz+Accepted layer %d tunnel request to unit %sr$  r  r  )rI  r  r   r   r  tun_requestedr   tap_requestedr   rZ   r   r   r  re  rr  rc  r  r   r{   r~  r  set_mode)r  rU  r  r  r  r  r  s          r  r4  z8SSHServerConnection._process_tun_at_openssh_dot_com_openY  s:   
   "$//1##D,,[[..t4F**[[..t4FF"#68LMMT>*D,?,?d,KLFfe$!LD&--/D F,V4G+V4GF"&??Q"&*:":D		K 	dW}r	  c           
         t        d      t        | j                        z   }g }|rX	 |j                         }| j                  |   }|j	                  t        |j                  |t        |      z                      |rX| j                  dj                  |             y# t        t        f$ r | j                  d       Y yw xY w)z=Prove the server has private keys for all requested host keysrF  FNr	  )
r   r$  r  r   r  r  rJ  r   r  r  )r  rU  r  
signaturesr  r  s         r  <_process_hostkeys_prove_00_at_openssh_dot_com_global_requestzPSSHServerConnection._process_hostkeys_prove_00_at_openssh_dot_com_global_request  s     78(()* 
!,,.00:!!&&6(;K2K)L"MN	  	$$SXXj%9:	 n- ,,U3s   AB  CCr  
auth_proto	auth_datascreenc                 l  K   | j                   r"| j                  d      r| j                  d      s| j                  j	                  d       y| j
                  s0t        | | j                  | j                  ||       d{   | _        | j
                  r| j
                  j                  ||      S y7 2w)z(Attach a channel to a remote X11 displayzX11-forwardingz;X11 forwarding request denied: X11 forwarding not permittedN)
r  rx  ry  r{   r~  r  r   r  r  rT  )r  r  r  r  r  s        r  rU  z'SSHServerConnection.attach_x11_listener  s     
 $$--.>?556FGKK 8 9 !!'Adjj$"5"5z9(N "ND %%,,T6::"Ns   A=B4?B2 3B4c                 d    | j                   r$| j                   j                  |      rd| _         yyy)z+Detach a session from a remote X11 listenerNrW  r  s     r  r  z'SSHServerConnection.detach_x11_listener  rY  r	  c                   K   | j                   r"| j                  d      r| j                  d      s| j                  j	                  d       y| j
                  ry	 t        j                  d      }t        t        |j                  d            }t        | | j                  | j                  |       d{   }t        |||      | _        y7 # t        $ r Y yw xY ww)	z6Create a listener for forwarding ssh-agent connectionszagent-forwardingz?Agent forwarding request denied: Agent forwarding not permittedFTz	asyncssh-)r  agentN)r  rx  ry  r{   r~  r&  tempfileTemporaryDirectoryr  r   r6  rx   r  create_agent_connectionr   rt  )r  tempdirpathunix_listeners       r  create_agent_listenerz)SSHServerConnection.create_agent_listener  s      &&--.@A556HIKK 8 9 	11EGtGLL'23D">djj$">">#F FM $4GT4A$CD F  		s=   ACAC 5C6C CC 	CCCCc                 P    | j                   r| j                   j                         S y)z8Return the path of the ssh-agent listener, if one existsN)r&  get_pathr  s    r  get_agent_pathz"SSHServerConnection.get_agent_path  s%     ''0022r	  c                     | j                   rt        d      | j                  j                  d       | j	                  t
        t        |      t        |             y)a9  Send an authentication banner to the client

           This method can be called to send an authentication banner to
           the client, displaying information while authentication is
           in progress. It is an error to call this method after the
           authentication is complete.

           :param msg:
               The message to display
           :param lang:
               The language the message is in
           :type msg: `str`
           :type lang: `str`

           :raises: :exc:`OSError` if authentication is already completed

        z Authentication already completedzSending authentication bannerN)r|  rt  r{   r  rM  rS   r   )r  rs  r  s      r  send_auth_bannerz$SSHServerConnection.send_auth_banner  sG    & <==:;,fSk6$<Hr	  authorized_keysc                 T    t        |t        t        f      rt        |      }|| _        y)aO  Set the keys trusted for client public key authentication

           This method can be called to set the trusted user and
           CA keys for client public key authentication. It should
           generally be called from the :meth:`begin_auth
           <SSHServer.begin_auth>` method of :class:`SSHServer` to
           set the appropriate keys for the user attempting to
           authenticate.

           :param authorized_keys:
               The keys to trust for client public key authentication
           :type authorized_keys: *see* :ref:`SpecifyingAuthorizedKeys`

        N)re  r  r  r'   r  )r  r  s     r  set_authorized_keysz'SSHServerConnection.set_authorized_keys  s$      oT{32?CO'6$r	  optionr7  c                 :    | j                   j                  ||      S )a  Return option from authorized_keys

           If a client key or certificate was presented during authentication,
           this method returns the value of the requested option in the
           corresponding authorized_keys entry if it was set. Otherwise, it
           returns the default value provided.

           The following standard options are supported:

               | command (string)
               | environment (dictionary of name/value pairs)
               | from (list of host patterns)
               | no-touch-required (boolean)
               | permitopen (list of host/port tuples)
               | principals (list of usernames)

           Non-standard options are also supported and will return the
           value `True` if the option is present without a value or
           return a list of strings containing the values associated
           with each occurrence of that option name. If the option is
           not present, the specified default value is returned.

           :param option:
               The name of the option to look up.
           :param default:
               The default value to return if the option is not present.
           :type option: `str`

           :returns: The value of the option in authorized_keys, if set

        r$  r  r  r  r7  s      r  rJ  z"SSHServerConnection.get_key_option	  s    B   $$VW55r	  
permissionc                 B    | j                   j                  d|z   d       S )a  Check permissions in authorized_keys

           If a client key or certificate was presented during
           authentication, this method returns whether the specified
           permission is allowed by the corresponding authorized_keys
           entry. By default, all permissions are granted, but they
           can be revoked by specifying an option starting with
           'no-' without a value.

           The following standard options are supported:

               | X11-forwarding
               | agent-forwarding
               | port-forwarding
               | pty
               | user-rc

           AsyncSSH internally enforces X11-forwarding, agent-forwarding,
           port-forwarding and pty permissions but ignores user-rc since
           it does not implement that feature.

           Non-standard permissions can also be checked, as long as the
           option follows the convention of starting with 'no-'.

           :param permission:
               The name of the permission to check (without the 'no-').
           :type permission: `str`

           :returns: A `bool` indicating if the permission is granted.

        zno-Fr  r  r  s     r  rx  z(SSHServerConnection.check_key_permission,  s&    B $$(();UCCCr	  c                 V    | j                   | j                   j                  ||      S |S )a  Return option from user certificate

           If a user certificate was presented during authentication,
           this method returns the value of the requested option in
           the certificate if it was set. Otherwise, it returns the
           default value provided.

           The following options are supported:

               | force-command (string)
               | no-touch-required (boolean)
               | source-address (list of CIDR-style IP network addresses)

           :param option:
               The name of the option to look up.
           :param default:
               The default value to return if the option is not present.
           :type option: `str`

           :returns: The value of the option in the user certificate, if set

        )r%  r  r  s      r  rL  z*SSHServerConnection.get_certificate_optionO  s.    2 )%%))&'::Nr	  c                 v    | j                   -t        t        | j                   j                  d|z   d            S y)a  Check permissions in user certificate

           If a user certificate was presented during authentication,
           this method returns whether the specified permission was
           granted in the certificate. Otherwise, it acts as if all
           permissions are granted and returns `True`.

           The following permissions are supported:

               | X11-forwarding
               | agent-forwarding
               | port-forwarding
               | pty
               | user-rc

           AsyncSSH internally enforces agent-forwarding, port-forwarding
           and pty permissions but ignores the other values since it does
           not implement those features.

           :param permission:
               The name of the permission to check (without the 'permit-').
           :type permission: `str`

           :returns: A `bool` indicating if the permission is granted.

        zpermit-FT)r%  r   r  r  r  s     r  ry  z0SSHServerConnection.check_certificate_permissionm  sA    8 )d0044Y5K5:< = = r	  rX  rY  rZ  r[  c                     t        | | j                  | j                  | j                  | j                  | j
                  | j                  |dk(  r| j                  n||dk(  r| j                  n||xs | j                  |xs | j                        S )ar  Create an SSH server channel for a new SSH session

           This method can be called by :meth:`session_requested()
           <SSHServer.session_requested>` to create an
           :class:`SSHServerChannel` with the desired encoding, Unicode
           error handling strategy, window, and max packet size for a
           newly created SSH server session.

           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the
               session, defaulting to UTF-8 (ISO 10646) format. If `None`
               is passed in, the application can send and receive raw
               bytes.
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: :class:`SSHServerChannel`

        r  )r*   r  r	  r  r  r  r  r  r  r"  r#  r]  s        r  rp  z)SSHServerConnection.create_server_channel  sy    >  djj$// $ 1 14?? $ 2 2D4I4I2:b.h06"& & 6$,, + @t/@/@B 	Br	  rW  rh  r  r  r  ri  rj  c                   K   | j                   j                  d||f       | j                   j                  d||f       | j                  ||||	      }
|
j                  |||||       d{   }|
|fS 7 w)a	  Create an SSH TCP forwarded connection

           This method is a coroutine which can be called to notify the
           client about a new inbound TCP connection arriving on the
           specified remote host and port. If the connection is successfully
           opened, a new SSH channel will be opened with data being handled
           by a :class:`SSHTCPSession` object created by `session_factory`.

           Optional arguments include the host and port of the original
           client opening the connection when performing TCP port forwarding.

           By default, this class expects data to be sent and received as
           raw bytes. However, an optional encoding argument can be
           passed in to select the encoding to use, allowing the
           application to send and receive string data. When encoding is
           set, an optional errors argument can be passed in to select
           what Unicode error handling strategy to use.

           Other optional arguments include the SSH receive window size and
           max packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHTCPSession` object
               that will be created to handle activity on this session
           :param remote_host:
               The hostname or address the connection was received on
           :param remote_port:
               The port number the connection was received on
           :param orig_host: (optional)
               The hostname or address of the client requesting the connection
           :param orig_port: (optional)
               The port number of the client requesting the connection
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_host: `str`
           :type remote_port: `int`
           :type orig_host: `str`
           :type orig_port: `int`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHTCPChannel` and :class:`SSHTCPSession`

        z&Opening forwarded TCP connection to %sr)  N)r{   r~  r^  acceptr  s               r  r  z%SSHServerConnection.create_connection  s     z 	A%{3	5/)Y1GH&&xMO[$/IG G W}Gr  r[  r  c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)a  Open an SSH TCP forwarded connection

           This method is a coroutine wrapper around :meth:`create_connection`
           designed to provide a "high-level" stream interface for creating
           an SSH TCP forwarded connection. Instead of taking a
           `session_factory` argument for constructing an object which will
           handle activity on the session via callbacks, it returns
           :class:`SSHReader` and :class:`SSHWriter` objects which can be
           used to perform I/O on the connection.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_connection` are supported and have the same
           meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

        Nr  rp  s        r  r  z#SSHServerConnection.open_connection  sV     ( 5d442"&2*02 2g
 $'7D)AAA2r  rn  c                   K   | j                   j                  d|       | j                  ||||      }|j                  ||       d{   }||fS 7 w)a  Create an SSH UNIX domain socket forwarded connection

           This method is a coroutine which can be called to notify the
           client about a new inbound UNIX domain socket connection arriving
           on the specified remote path. If the connection is successfully
           opened, a new SSH channel will be opened with data being handled
           by a :class:`SSHUNIXSession` object created by `session_factory`.

           By default, this class expects data to be sent and received as
           raw bytes. However, an optional encoding argument can be
           passed in to select the encoding to use, allowing the
           application to send and receive string data. When encoding is
           set, an optional errors argument can be passed in to select
           what Unicode error handling strategy to use.

           Other optional arguments include the SSH receive window size and
           max packet size which default to 2 MB and 32 KB, respectively.

           :param session_factory:
               A `callable` which returns an :class:`SSHUNIXSession` object
               that will be created to handle activity on this session
           :param remote_path:
               The path the connection was received on
           :param encoding: (optional)
               The Unicode encoding to use for data exchanged on the connection
           :param errors: (optional)
               The error handling strategy to apply on encode/decode errors
           :param window: (optional)
               The receive window size for this session
           :param max_pktsize: (optional)
               The maximum packet size for this session
           :type session_factory: `callable`
           :type remote_path: `str`
           :type encoding: `str` or `None`
           :type errors: `str`
           :type window: `int`
           :type max_pktsize: `int`

           :returns: an :class:`SSHTCPChannel` and :class:`SSHUNIXSession`

        z'Opening forwarded UNIX connection to %sN)r{   r~  r`  r  r  s	            r  rp  z*SSHServerConnection.create_unix_connection  sW     ` 	BKP''&&+NO[AAW} Br  c                    K    | j                   t        g|i | d{   \  }}t        ||      t        ||      fS 7 w)a,  Open an SSH UNIX domain socket forwarded connection

           This method is a coroutine wrapper around
           :meth:`create_unix_connection` designed to provide a "high-level"
           stream interface for creating an SSH UNIX domain socket forwarded
           connection. Instead of taking a `session_factory` argument for
           constructing an object which will handle activity on the session
           via callbacks, it returns :class:`SSHReader` and :class:`SSHWriter`
           objects which can be used to perform I/O on the connection.

           With the exception of `session_factory`, all of the arguments
           to :meth:`create_unix_connection` are supported and have the same
           meaning here.

           :returns: an :class:`SSHReader` and :class:`SSHWriter`

        Nr  rp  s        r  r  z(SSHServerConnection.open_unix_connectionQ  sY     * .$--$7'+7/57 7 	g $'7D)AAA7r  r  c                   K   | j                   j                  d       | j                  ||      }|j                  |||       d{   }||fS 7 w)z&Create an SSH X11 forwarded connectionz Opening forwarded X11 connectionN)r{   r~  re  r  )r  r  ri  rj  rZ  r[  r  r  s           r  create_x11_connectionz)SSHServerConnection.create_x11_connectionm  sR      	;<&&v{;		/9iHHW} Is   AAA	Ac                   K   | j                   st        t        d      | j                  j	                  d       | j                  ||      }|j                  |       d{   }||fS 7 w)z:Create a forwarded ssh-agent connection back to the clientzAgent forwarding not permittedz"Opening forwarded agent connectionN)r&  r   rY   r{   r~  rg  r  )r  r  rZ  r[  r  r  s         r  r  z+SSHServerConnection.create_agent_connection}  sm      ##"#C#CE E 	=>((=		/22W} 3s   AA+ A)!	A+c                    K   | j                  t               d{   \  }}t        t           ||      t	        t           ||      fS 7 -w)z8Open a forwarded ssh-agent connection back to the clientN)r  r   r   r  r   )r  r  r  s      r  open_agent_connectionz)SSHServerConnection.open_agent_connection  sN     
 ../CDD 	g
 .	%0@$0OOO	 Es   AA	.Ar  r
  r,  )r  r  r   r   r  )er  r  r  r  r  r   r   r   r2  r  r  r  r  r.  rT  r  r  r!  r   r  r  r  r   r  r  r5  r7  r:  r=  rA  r   r   rN  r   rS  rU  rX  rZ  rW  r]  r_  rc  re  r   rh  r    rl  r   r   r*   r   r%  r+   r   r'  r  r  r}  r  r,   r   r2  r  r  r  r-   r   r4  r  r	   rU  r(   r  r  r  r<   r  _AuthKeysArgr  r  rJ  rx  rL  ry  rp  r  r  r   r  r   r   r  r   rp  r  r.   r  r/   r  r  rU  r  s   @r  r  r  
  sO   B +*011 -104'+	1@W66 1@61@)1@ !.1@  }	1@fHY/ D A><3;E?GK*	%Xj%9 	%	B " "
"S "# "58"=A"";4 ;)"s )"e )"47)"JM)",1)">C)"HL)"V..'<. .`!!'>! !F==+0=5=f5E= # 49>Fv>NB;4 ;#  ',9>CG,M M
" "s "t "
"c 
" 
",/
"48
"t 3 c /27F$ s  2@  D)I )"$445)V< <-&e(<<=<|NI N$ N.*-c *-03*-8<*-X+#+(,+41#1nU+^E-BBC1fA#A(,A.+c +d +:+#+(,+0+#+&(889+Z;#;(,;(.>v.F .3@E*-2:3-,*
6(: *t *T 6  6B IC Is Id I47< 7D 7*!6S !66 !6V !6F!Ds !Dt !DH 26S (.:@< s  t  D ?A>?12%Bhsm %B&)%B8;%B+.%B7G%BR BDF >B"/3F#7#?FF+.F;>F F .6c]F 	F -0	F
 F mF+]6-BBCFPB6 BV B)Y&'B: <@"/3	6#8#@66+3C=6 6 -06 	6
 nV,nV.DDE6pB B& B)Y&'B< 34 *3	#7#>,/  	
 m]5%99:$ )3#8#?  o~e'<<=	&	P)E"Ie$445	Pr	  r  c            <           e Zd ZU dZeed<   eej                     ed<   e	ed<   e
ed<   eed<   eed<   eed<   eee      ed	<   eed
<   eed<   eed<   ee
   ed<   ee
   ed<   ee
   ed<   ee
   ed<   ee
   ed<   eed<   eed<   eed<   eed<   eee      ed<   ee   ed<   edeee   f   ed<   eed<   eed<   ee   ed<   eed<   eed<   eed<   d)d ed!   d"ef fd#Zed)d ed!   d"ed$efd%       Zdede	dededee   ded&ee   d	ee   d
ee   dee   dee   dededededededededededee   de deeeef      deeeef      deeeef      deeef   d'eeef   ded$df<d(Z! xZ"S )*r   zSSH connection optionsr^  r}  r  r  rk  rm  rZ  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  NrD  ra  rc  connect_timeoutr  keepalive_internalrh  rp  r   r  c                 J    |r|j                   nd }t        |   d||d| y )N)rp  last_configr  )r^  r-  r.  )r  rp  r  r  r5  s       r  r.  zSSHConnectionOptions.__init__  s'    (/gnnTLkLVLr	  r  c                    K   t        j                         }t        t        |j	                  dt        j                  | |fd|i|       d{         S 7 w)z8Construct a new options object from within an async taskNr%  )r2  get_event_loopr   r   r  	functoolsr   )clsrp  r  r%  s       r  r/  zSSHConnectionOptions.construct  s]     
 %%'HD$8$8)##CFtFvF%H H I 	I Hs   AAA
	Ar]  rj  c           
         || _         || _        t        |      | _        t	        t
        |j                  d|            | _        t	        t        |dk7  r|n|j                  dt                    | _
        |dk7  r|n|j                  d      | _        || _        |dk(  r&t	        t        t
           |j                  d            }t        |t
              rt        |      }|| _        t	        t        |	dk7  r|	n|j                  dt"        j$                              | _        |j                  d      }t	        t(        |
dk7  r|
n|r|dfnd	      | _        t	        t,        |dk7  r|n|j                  d
d            | _        t1        |||||||d	u      \  | _        | _        | _        | _        | _        t	        t,        |dk7  r|n|j                  dd            | _        t	        t,        |dk7  r|n|j                  dd            | _        t	        t,        |dk7  r|n!|j                  d|j                  dd                  | _         t	        t,        |dk7  r|n|j                  dd            | _!        |@tE        |      }|D ]  } | jF                  rtI        d       t	        tJ        tL           |      }|r.|D ])  }!tO        |!      jQ                         rtI        d|!        || _)        || _*        || _+        t	        tX        tZ        t           tZ        t           f   |j                  dd            \  }"}#|dk(  r|"}|dk(  rt\        }nt        |t
              rt_        |      }|dk  rtI        d      |dk(  r|#}|dk(  rt`        }nt        |t
              rtc        |      }|r|dk  rtI        d      t        |t
              rtc        |      }|r|dk  rtI        d      t        |t
              rtc        |      }|r|dk  rtI        d      t        |t
              rtc        |      }|r|dk  rtI        d      |dk  rtI        d      || _2        || _3        |xs d	| _4        || _5        || _6        || _7        y	)z/Prepare common connection configuration optionsHostnamer  Port	ProxyJumpProxyCommandAddressFamilyBindAddressr   NTCPKeepAliveTHostbasedAuthenticationPubkeyAuthenticationKbdInteractiveAuthenticationChallengeResponseAuthenticationPasswordAuthenticationz7OpenSSH certificates not allowed in X.509 trusted certsz0X.509 trusted certificate path not a directory: 
RekeyLimit)r  r  z&Rekey bytes cannot be negative or zeroz(Rekey seconds cannot be negative or zeroz"Connect timeout cannot be negativez Login timeout cannot be negativerS  z.Keepalive count max cannot be negative or zero)8r^  r  r  r  r   r  r  rk  r  r=   rm  rZ  r]  r   re  r   r{  r  	AF_UNSPECry  r   rz  r  r  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r   is_x509r  r   r   r   is_dirr=  r?  rD  r   r   _DEFAULT_REKEY_BYTESr   _DEFAULT_REKEY_SECONDSr   ra  rc  r  r  rj  rh  )$r  r^  r  r  rk  rm  rZ  r]  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  rD  ra  rc  r  r  rj  rh  	bind_addrcertsr  r  config_rekey_bytesconfig_rekey_secondss$                                       r  preparezSSHConnectionOptions.prepare  sg   *  0(1fjjT:;	dbjdJJv|,.	 !'"f&**[2I$B #

>0JKMmS)&}5M*3&B,JJ(8(89; JJ}-	xzR7G#,)Q$8 "$"9LND13
 68_h+^-T9;	3t+T]t2 /R*?

4d;= 	
 /R*?

148: 	
 kR&7{

9JJ@$GIJ 	 (;}

3T:< 	 )%&89E||$ &= > > 
 "&h/A&BE!J"/Dz((*$ &559F&< = = 0
 #5'>$* x}hsm34L(35 	10 ",K".KS)*;7K !EFFB0MB2Ms+/>M ]a/GHHos+1/BO2ABBmS)/>M]Q.?@@(#.!45G!H"4q"8DEE!#MNN&*.6$*"4#6 r	  r,  )#r  r  r  r  r9   r  r   r2  Future_ProtocolFactoryr  r  r  r  r   r   r  r   r   r   r  r.  classmethodr   r/  _VersionArgr   r~   _ProxyCommandr  _AuthArgr   r   r  rU  r  s   @r  r   r     s    W^^$$&&N
I
INHSM**Kuoe_$uouo%UO# *<!=>>%h//sHSM122e_$M 4 Mv M Ihz&: I"(I-5I IV7i V7"2V7=HV7V7!)#V78>V7 %Z0V7  (6	V7 AI	V7
 %X.V7
 @H~V7 #V7 6>V7 #V7 7?V7 !)V7 <DV7 "*V7 9AV7  (V7 >IV7 *2();V7  0V7 &eCHo6V7  (eSj(9:V7 "*%s
*;!<V7   %UCZ0!V7" %*%*$5#V7$ &)%V7$ .2%V7r	  c                       e Zd ZU dZeed<   eed<   eed<   eed<   e	e
   ed<   ee
ee
   f   ed<   eed<   e
ed	<   e	e
   ed
<   e	e
   ed<   ee   ed<   eeeef      ed<   e	e
   ed<   e
ed<   e	ee      ed<   ee   ed<   eed<   ee	e
      ed<   e	eeef      ed<   eed<   eed<   eed<   ee
   ed<   eed<   e	e
   ed<   e	ee      ed<   e	e
   ed<   e	e
   ed<   e	e
   ed<   e	e
   ed<   e	e
   ed <   eed!<   eed"<   eed#<   e	e
   ed$<   eed%<   eed&<   eee
f   ed'<   e	e
   ed(<   e	e
   ed)<   eed*<   e	e
   ed+<   e
ed,<   eed-<   eed.<   d/d/d/d0d/d1d2d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d3d1d1d1ed1d1d1d1d1d/d1d/d1d/d1d/d1d1d1d/d1d1d/d1d1d1d1d0d1d1d1d1d/d1d/d1d1d1d/d/d/d1d/d/d0d4d5eefJd6e	ej@                     d7e	e!   dee"   d8ede	e   de#d9e
d:ee   d;e$d<ee%   d=ee   d>ee&   d?ee   d@e'dAe'dBe'dCe'dDe'dEe(dFe(dGe(dHe(dIe)dJee   dKe*dLeeee
f      dMeee+e
f      dNee	ee+e
f         dOee+e
f   dPeee+e
f      dQee   dedee	e
      de'ded	ee
   d
e	e
   dee,   dRe	e-   dSee   de	e
   dee
   de-dee   dTe	e   dee   dee	e
      de	eee.f      dee   dee   dee   deee
ee
   f      dedee	e
      dee	e/      dUee   dee	e
      de	e
   dee	e
      d e	e
   d!ee   d"ee   d#ee   d$e	e
   d%ed&ed'eeee
f      d(e	e
   d)e	e
   d*ed+e	e
   d,e
d-ed.edVd/f fdWZ0 xZ1S )Xr  ae  SSH client connection options

       The following options are available to control the establishment
       of SSH client connections:

       :param client_factory: (optional)
           A `callable` which returns an :class:`SSHClient` object that will
           be created for each new connection.
       :param proxy_command: (optional)
           A string or list of strings specifying a command and arguments
           to run to make a connection to the SSH server. Data will be
           forwarded to this process over stdin/stdout instead of opening a
           TCP connection. If specified as a string, standard shell quoting
           will be applied when splitting the command and its arguments.
       :param known_hosts: (optional)
           The list of keys which will be used to validate the server host
           key presented during the SSH handshake. If this is not specified,
           the keys will be looked up in the file :file:`.ssh/known_hosts`.
           If this is explicitly set to `None`, server host key validation
           will be disabled.
       :param host_key_alias: (optional)
           An alias to use instead of the real host name when looking up a host
           key in known_hosts and when validating host certificates.
       :param server_host_key_algs: (optional)
           A list of server host key algorithms to use instead of the
           default of those present in known_hosts when performing the SSH
           handshake, taken from :ref:`server host key algorithms
           <PublicKeyAlgs>`. This is useful when using the
           validate_host_public_key callback to validate server host keys,
           since AsyncSSH can not determine which server host key algorithms
           are preferred. This argument can also be set to 'default' to
           specify that the client should always send its default list of
           supported algorithms to avoid leaking information about what
           algorithms are present for the server in known_hosts.

               .. note:: The 'default' keyword should be used with
                         caution, as it can result in a host key mismatch
                         if the client trusts only a subset of the host
                         keys the server might return.
       :param server_host_keys_handler: (optional)
          A `callable` or coroutine handler function which if set will be
          called when a global request from the server is received which
          provides an updated list of server host keys. The handler takes
          four arguments (added, removed, retained, and revoked), each of
          which is a list of SSHKey public keys, reflecting differences
          between what the server reported and what is currently matching
          in known_hosts.

               .. note:: This handler will only be called when known
                         host checking is enabled and the check succeeded.
       :param x509_trusted_certs: (optional)
           A list of certificates which should be trusted for X.509 server
           certificate authentication. If no trusted certificates are
           specified, an attempt will be made to load them from the file
           :file:`.ssh/ca-bundle.crt`. If this argument is explicitly set
           to `None`, X.509 server certificate authentication will not
           be performed.

               .. note:: X.509 certificates to trust can also be provided
                         through a :ref:`known_hosts <KnownHosts>` file
                         if they are converted into OpenSSH format.
                         This allows their trust to be limited to only
                         specific host names.
       :param x509_trusted_cert_paths: (optional)
           A list of path names to "hash directories" containing certificates
           which should be trusted for X.509 server certificate authentication.
           Each certificate should be in a separate file with a name of the
           form *hash.number*, where *hash* is the OpenSSL hash value of the
           certificate subject name and *number* is an integer counting up
           from zero if multiple certificates have the same hash. If no
           paths are specified, an attempt with be made to use the directory
           :file:`.ssh/crt` as a certificate hash directory.
       :param x509_purposes: (optional)
           A list of purposes allowed in the ExtendedKeyUsage of a
           certificate used for X.509 server certificate authentication,
           defulting to 'secureShellServer'. If this argument is explicitly
           set to `None`, the server certificate's ExtendedKeyUsage will
           not be checked.
       :param username: (optional)
           Username to authenticate as on the server. If not specified,
           the currently logged in user on the local machine will be used.
       :param password: (optional)
           The password to use for client password authentication or
           keyboard-interactive authentication which prompts for a password,
           or a `callable` or coroutine which returns the password to use.
           If this is not specified or set to `None`, client password
           authentication will not be performed.
       :param client_host_keysign: (optional)
           Whether or not to use `ssh-keysign` to sign host-based
           authentication requests. If set to `True`, an attempt will be
           made to find `ssh-keysign` in its typical locations. If set to
           a string, that will be used as the `ssh-keysign` path. When set,
           client_host_keys should be a list of public keys. Otherwise,
           client_host_keys should be a list of private keys with optional
           paired certificates.
       :param client_host_keys: (optional)
           A list of keys to use to authenticate this client via host-based
           authentication. If `client_host_keysign` is set and no host keys
           or certificates are specified, an attempt will be made to find
           them in their typical locations. If `client_host_keysign` is
           not set, host private keys must be specified explicitly or
           host-based authentication will not be performed.
       :param client_host_certs: (optional)
           A list of optional certificates which can be paired with the
           provided client host keys.
       :param client_host: (optional)
           The local hostname to use when performing host-based
           authentication. If not specified, the hostname associated with
           the local IP address of the SSH connection will be used.
       :param client_username: (optional)
           The local username to use when performing host-based
           authentication. If not specified, the username of the currently
           logged in user will be used.
       :param client_keys: (optional)
           A list of keys which will be used to authenticate this client
           via public key authentication. These keys will be used after
           trying keys from a PKCS11 provider or an ssh-agent, if either
           of those are configured. If no client keys are specified,
           an attempt will be made to load them from the files
           :file:`.ssh/id_ed25519_sk`, :file:`.ssh/id_ecdsa_sk`,
           :file:`.ssh/id_ed448`, :file:`.ssh/id_ed25519`,
           :file:`.ssh/id_ecdsa`, :file:`.ssh/id_rsa`, and
           :file:`.ssh/id_dsa` in the user's home directory, with
           optional certificates loaded from the files
           :file:`.ssh/id_ed25519_sk-cert.pub`,
           :file:`.ssh/id_ecdsa_sk-cert.pub`, :file:`.ssh/id_ed448-cert.pub`,
           :file:`.ssh/id_ed25519-cert.pub`, :file:`.ssh/id_ecdsa-cert.pub`,
           :file:`.ssh/id_rsa-cert.pub`, and :file:`.ssh/id_dsa-cert.pub`.
           If this argument is explicitly set to `None`, client public key
           authentication will not be performed.
       :param client_certs: (optional)
           A list of optional certificates which can be paired with the
           provided client keys.
       :param passphrase: (optional)
           The passphrase to use to decrypt client keys if they are
           encrypted, or a `callable` or coroutine which takes a filename
           as a parameter and returns the passphrase to use to decrypt
           that file. If not specified, only unencrypted client keys can
           be loaded. If the keys passed into client_keys are already
           loaded, this argument is ignored.

               .. note:: A callable or coroutine passed in as a passphrase
                         will be called on all filenames configured as
                         client keys or client host keys each time an
                         SSHClientConnectionOptions object is instantiated,
                         even if the keys aren't encrypted or aren't ever
                         used for authentication.

       :param ignore_encrypted: (optional)
           Whether or not to ignore encrypted keys when no passphrase is
           specified. This defaults to `True` when keys are specified via
           the IdentityFile config option, causing encrypted keys in the
           config to be ignored when no passphrase is specified. Note
           that encrypted keys loaded into an SSH agent can still be used
           when this option is set.
       :param host_based_auth: (optional)
           Whether or not to allow host-based authentication. By default,
           host-based authentication is enabled if client host keys are
           made available.
       :param public_key_auth: (optional)
           Whether or not to allow public key authentication. By default,
           public key authentication is enabled if client keys are made
           available.
       :param kbdint_auth: (optional)
           Whether or not to allow keyboard-interactive authentication. By
           default, keyboard-interactive authentication is enabled if a
           password is specified or if callbacks to respond to challenges
           are made available.
       :param password_auth: (optional)
           Whether or not to allow password authentication. By default,
           password authentication is enabled if a password is specified
           or if callbacks to provide a password are made available.
       :param gss_host: (optional)
           The principal name to use for the host in GSS key exchange and
           authentication. If not specified, this value will be the same
           as the `host` argument. If this argument is explicitly set to
           `None`, GSS key exchange and authentication will not be performed.
       :param gss_store: (optional)
           The GSS credential store from which to acquire credentials.
       :param gss_kex: (optional)
           Whether or not to allow GSS key exchange. By default, GSS
           key exchange is enabled.
       :param gss_auth: (optional)
           Whether or not to allow GSS authentication. By default, GSS
           authentication is enabled.
       :param gss_delegate_creds: (optional)
           Whether or not to forward GSS credentials to the server being
           accessed. By default, GSS credential delegation is disabled.
       :param preferred_auth:
           A list of authentication methods the client should attempt to
           use in order of preference. By default, the preferred list is
           gssapi-keyex, gssapi-with-mic, hostbased, publickey,
           keyboard-interactive, and then password. This list may be
           limited by which auth methods are implemented by the client
           and which methods the server accepts.
       :param disable_trivial_auth: (optional)
           Whether or not to allow "trivial" forms of auth where the
           client is not actually challenged for credentials. Setting
           this will cause the connection to fail if a server does not
           perform some non-trivial form of auth during the initial
           SSH handshake. If not specified, all forms of auth supported
           by the server are allowed, including none.
       :param agent_path: (optional)
           The path of a UNIX domain socket to use to contact an ssh-agent
           process which will perform the operations needed for client
           public key authentication, or the :class:`SSHServerConnection`
           to use to forward ssh-agent requests over. If this is not
           specified and the environment variable `SSH_AUTH_SOCK` is
           set, its value will be used as the path. If this argument is
           explicitly set to `None`, an ssh-agent will not be used.
       :param agent_identities: (optional)
           A list of identities used to restrict which SSH agent keys may
           be used. These may be specified as byte strings in binary SSH
           format or as public keys or certificates (*see*
           :ref:`SpecifyingPublicKeys` and :ref:`SpecifyingCertificates`).
           If set to `None`, all keys loaded into the SSH agent will be
           made available for use. This is the default.
       :param agent_forwarding: (optional)
           Whether or not to allow forwarding of ssh-agent requests from
           processes running on the server. By default, ssh-agent forwarding
           requests from the server are not allowed.
       :param pkcs11_provider: (optional)
           The path of a shared library which should be used as a PKCS#11
           provider for accessing keys on PIV security tokens. By default,
           no local security tokens will be accessed.
       :param pkcs11_pin: (optional)
           The PIN to use when accessing security tokens via PKCS#11.

               .. note:: If your application opens multiple SSH connections
                         using PKCS#11 keys, you should consider calling
                         :func:`load_pkcs11_keys` explicitly instead of
                         using these arguments. This allows you to pay
                         the cost of loading the key information from the
                         security tokens only once. You can then pass the
                         returned keys via the `client_keys` argument to
                         any calls that need them.

                         Calling :func:`load_pkcs11_keys` explicitly also
                         gives you the ability to load keys from multiple
                         tokens with different PINs and to select which
                         tokens to load keys from and which keys on those
                         tokens to load.

       :param client_version: (optional)
           An ASCII string to advertise to the SSH server as the version of
           this client, defaulting to `'AsyncSSH'` and its version number.
       :param kex_algs: (optional)
           A list of allowed key exchange algorithms in the SSH handshake,
           taken from :ref:`key exchange algorithms <KexAlgs>`.
       :param encryption_algs: (optional)
           A list of encryption algorithms to use during the SSH handshake,
           taken from :ref:`encryption algorithms <EncryptionAlgs>`.
       :param mac_algs: (optional)
           A list of MAC algorithms to use during the SSH handshake, taken
           from :ref:`MAC algorithms <MACAlgs>`.
       :param compression_algs: (optional)
           A list of compression algorithms to use during the SSH handshake,
           taken from :ref:`compression algorithms <CompressionAlgs>`, or
           `None` to disable compression.
       :param signature_algs: (optional)
           A list of public key signature algorithms to use during the SSH
           handshake, taken from :ref:`signature algorithms <SignatureAlgs>`.
       :param rekey_bytes: (optional)
           The number of bytes which can be sent before the SSH session
           key is renegotiated. This defaults to 1 GB.
       :param rekey_seconds: (optional)
           The maximum time in seconds before the SSH session key is
           renegotiated. This defaults to 1 hour.
       :param connect_timeout: (optional)
           The maximum time in seconds allowed to complete an outbound
           SSH connection. This includes the time to establish the TCP
           connection and the time to perform the initial SSH protocol
           handshake, key exchange, and authentication. This is disabled
           by default, relying on the system's default TCP connect timeout
           and AsyncSSH's login timeout.
       :param login_timeout: (optional)
           The maximum time in seconds allowed for authentication to
           complete, defaulting to 2 minutes. Setting this to 0 will
           disable the login timeout.

               .. note:: This timeout only applies after the SSH TCP
                         connection is established. To set a timeout
                         which includes establishing the TCP connection,
                         use the `connect_timeout` argument above.
       :param keepalive_interval: (optional)
           The time in seconds to wait before sending a keepalive message
           if no data has been received from the server. This defaults to
           0, which disables sending these messages.
       :param keepalive_count_max: (optional)
           The maximum number of keepalive messages which will be sent
           without getting a response before disconnecting from the
           server. This defaults to 3, but only applies when
           keepalive_interval is non-zero.
       :param command: (optional)
           The default remote command to execute on client sessions.
           An interactive shell is started if no command or subsystem is
           specified.
       :param subsystem: (optional)
           The default remote subsystem to start on client sessions.
       :param env: (optional)
           The  default environment variables to set for client sessions.
           Keys and values passed in here will be converted to Unicode
           strings encoded as UTF-8 (ISO 10646) for transmission.

               .. note:: Many SSH servers restrict which environment
                         variables a client is allowed to set. The
                         server's configuration may need to be edited
                         before environment variables can be
                         successfully set in the remote environment.
       :param send_env: (optional)
           A list of environment variable names to pull from
           `os.environ` and set by default for client sessions. Wildcards
           patterns using `'*'` and `'?'` are allowed, and all variables
           with matching names will be sent with whatever value is set in
           the local environment. If a variable is present in both env
           and send_env, the value from env will be used.
       :param request_pty: (optional)
           Whether or not to request a pseudo-terminal (PTY) by default for
           client sessions. This defaults to `True`, which means to request
           a PTY whenever the `term_type` is set. Other possible values
           include `False` to never request a PTY, `'force'` to always
           request a PTY even without `term_type` being set, or `'auto'`
           to request a TTY when `term_type` is set but only when starting
           an interactive shell.
       :param term_type: (optional)
           The default terminal type to set for client sessions.
       :param term_size: (optional)
           The terminal width and height in characters and optionally
           the width and height in pixels to set for client sessions.
       :param term_modes: (optional)
           POSIX terminal modes to set for client sessions, where keys are
           taken from :ref:`POSIX terminal modes <PTYModes>` with values
           defined in section 8 of :rfc:`RFC 4254 <4254#section-8>`.
       :param x11_forwarding: (optional)
           Whether or not to request X11 forwarding for client sessions,
           defaulting to `False`. If set to `True`, X11 forwarding will be
           requested and a failure will raise :exc:`ChannelOpenError`. It
           can also be set to `'ignore_failure'` to attempt X11 forwarding
           but ignore failures.
       :param x11_display: (optional)
           The display that X11 connections should be forwarded to,
           defaulting to the value in the environment variable `DISPLAY`.
       :param x11_auth_path: (optional)
           The path to the Xauthority file to read X11 authentication
           data from, defaulting to the value in the environment variable
           `XAUTHORITY` or the file :file:`.Xauthority` in the user's
           home directory if that's not set.
       :param x11_single_connection: (optional)
           Whether or not to limit X11 forwarding to a single connection,
           defaulting to `False`.
       :param encoding: (optional)
           The default Unicode encoding to use for data exchanged on client
           sessions.
       :param errors: (optional)
           The default error handling strategy to apply on Unicode
           encode/decode errors.
       :param window: (optional)
           The default receive window size to set for client sessions.
       :param max_pktsize: (optional)
           The default maximum packet size to set for client sessions.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options.

               .. note:: Specifying configuration files when creating an
                         :class:`SSHClientConnectionOptions` object will
                         cause the config file to be read and parsed at
                         the time of creation of the object, including
                         evaluation of any conditional blocks. If you want
                         the config to be parsed for every new connection,
                         this argument should be added to the connect or
                         listen calls instead. However, if you want to
                         save the parsing overhead and your configuration
                         doesn't depend on conditions that would change
                         between calls, this argument may be an option.
       :param options: (optional)
           A previous set of options to use as the base to incrementally
           build up a configuration. When an option is not explicitly
           specified, its value will be pulled from this options object
           (if present) before falling back to the default value.
       :type client_factory: `callable` returning :class:`SSHClient`
       :type proxy_command: `str` or `list` of `str`
       :type known_hosts: *see* :ref:`SpecifyingKnownHosts`
       :type host_key_alias: `str`
       :type server_host_key_algs: `str` or `list` of `str`
       :type server_host_keys_handler: `callable` or coroutine
       :type x509_trusted_certs: *see* :ref:`SpecifyingCertificates`
       :type x509_trusted_cert_paths: `list` of `str`
       :type x509_purposes: *see* :ref:`SpecifyingX509Purposes`
       :type username: `str`
       :type password: `str`
       :type client_host_keysign: `bool` or `str`
       :type client_host_keys:
           *see* :ref:`SpecifyingPrivateKeys` or :ref:`SpecifyingPublicKeys`
       :type client_host_certs: *see* :ref:`SpecifyingCertificates`
       :type client_host: `str`
       :type client_username: `str`
       :type client_keys: *see* :ref:`SpecifyingPrivateKeys`
       :type client_certs: *see* :ref:`SpecifyingCertificates`
       :type passphrase: `str` or `bytes`
       :type ignore_encrypted: `bool`
       :type host_based_auth: `bool`
       :type public_key_auth: `bool`
       :type kbdint_auth: `bool`
       :type password_auth: `bool`
       :type gss_host: `str`
       :type gss_store:
           `str`, `bytes`, or a `dict` with `str` or `bytes` keys and values
       :type gss_kex: `bool`
       :type gss_auth: `bool`
       :type gss_delegate_creds: `bool`
       :type preferred_auth: `str` or `list` of `str`
       :type disable_trivial_auth: `bool`
       :type agent_path: `str`
       :type agent_identities:
           *see* :ref:`SpecifyingPublicKeys` and :ref:`SpecifyingCertificates`
       :type agent_forwarding: `bool`
       :type pkcs11_provider: `str` or `None`
       :type pkcs11_pin: `str`
       :type client_version: `str`
       :type kex_algs: `str` or `list` of `str`
       :type encryption_algs: `str` or `list` of `str`
       :type mac_algs: `str` or `list` of `str`
       :type compression_algs: `str` or `list` of `str`
       :type signature_algs: `str` or `list` of `str`
       :type rekey_bytes: *see* :ref:`SpecifyingByteCounts`
       :type rekey_seconds: *see* :ref:`SpecifyingTimeIntervals`
       :type connect_timeout: *see* :ref:`SpecifyingTimeIntervals`
       :type login_timeout: *see* :ref:`SpecifyingTimeIntervals`
       :type keepalive_interval: *see* :ref:`SpecifyingTimeIntervals`
       :type keepalive_count_max: `int`
       :type command: `str`
       :type subsystem: `str`
       :type env: `dict` with `str` keys and values
       :type send_env: `list` of `str`
       :type request_pty: `bool`, `'force'`, or `'auto'`
       :type term_type: `str`
       :type term_size: `tuple` of 2 or 4 `int` values
       :type term_modes: `dict` with `int` keys and values
       :type x11_forwarding: `bool` or `'ignore_failure'`
       :type x11_display: `str`
       :type x11_auth_path: `str`
       :type x11_single_connection: `bool`
       :type encoding: `str` or `None`
       :type errors: `str`
       :type window: `int`
       :type max_pktsize: `int`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

    r^  r  r,  r  r  r  r  rd  r  r  r  r  r  r  r  client_certsignore_encryptedr  r  r  r  r  r  r  r  r  r  r  r  r&  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  NFr  r  secureShellServerr  rW  r%  r  r+  rk  rm  rZ  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  rD  ra  rc  r  r  rj  rh  client_host_keysclient_host_certsr]  r  r  cK                 $   	 t        j                         }K|dk(  rR|r|j                  sDt        ddd      j                         }Lt        j                  |Lt        j                        rLgng }t        j                  |||K|$||      }|dk(  rJt        ddd      j                         }Mt        j                  |Mt        j                        rt        M      }|dk(  r7t        ddd      j                         }N|Nj                         rt        N      g}|dk(  r4t        t        t         t"        t        f      |j%                  d	d            }|dk(  r1t        t         t"        t        f   |j%                  d
t&                    }|dk(  r$t        t(        |j%                  dt*                    }t,        P| ]  ||xs t0        ||||	|-|
|||||||||||||||||||||       | dk7  r| nRt        t2        t           |j%                  dg             t        t2        t           |j%                  dg             z   xs d| _        t        t        t           |!dk7  r|!n|j%                  d            | _        |"| _        t;        |"t        t<        t           |j%                  dd            g        |#| _        tA        t        t        |$dk7  r|$n|j%                  dK                  | _!        |%| _"        |&dk(  r t        tF        |j%                  dd            }&|&r<tI        |&      }&|'rtK        t        tL        |'            | _'        n4tQ               | _'        n$d}&tS        t        tT        |'      |-|(|      | _+        |&| _,        |)| _-        tA        t        t        |*dk7  r|*nK            | _.        |/| _/        ta        |0tb        t        f      r
d|0i| _2        n|0| _2        t        tF        |1dk7  r|1n|j%                  dd            | _3        t        tF        |2dk7  r|2n|j%                  dd            | _4        t        tF        |3dk7  r|3n|j%                  dd            | _5        |4dk(  r t        t        |j%                  dd            }4ta        |4t              r|4jm                  d      }4|4| _7        |5| _8        |6dk(  r't        t<        t           |j%                  dd            }6|6dk(  r t        jr                  j%                  dd      }6|6r"t        t        |6      j                               nd}6|9dk(  r&t        t        t           |j%                  d            }9|.dk(  r|+dk(  }.|+dk(  r t        tt        |j%                  dd            }+|,dk(  r't        tv        tx           |j%                  d d            },t        tF        |j%                  d!            }O|7dk(  rOrt        tL        |+      }7nd}7|7rt{        |7O      | _>        n|7dk(  rt               | _>        nd| _>        |+r%tS        t        tT        |+      |-|,O|.|      | _@        n|+t        |-|,      | _@        nd| _@        | j                  |6| _B        |9| _C        |:| _D        nd| _B        d| _C        d| _D        |8dk(  r t        tF        |j%                  d"d            }8|8r|6nd| _E        t        t        t           |;dk7  r|;n|j%                  d#            | _F        |<| _G        t        t        |=dk7  r|=n|j%                  d$            | _I        t        t        |>dk7  r|>n|j%                  d%            | _K        t        t        |?dk7  r|?n|j%                  d&d            | _M        @| _N        A| _O        B| _P        t        t         tF        t        f   Cdk7  rCn|j%                  d'      xr d(      | _Q        D| _R        E| _S        F| _T        G| _U        H| _V        I| _W        J| _X        y# t        $ r t        d      dw xY w))z/Prepare client connection configuration optionszWUnknown local username: set one of LOGNAME, USER, LNAME, or USERNAME in the environmentNr  r  r  r^  zca-bundle.crtcrtConnectTimeoutServerAliveIntervalServerAliveCountMaxUserKnownHostsFileGlobalKnownHostsFileHostKeyAliasr  UserEnableSSHKeySignFr%  ccacheGSSAPIKeyExchangeTGSSAPIAuthenticationGSSAPIDelegateCredentialsPreferredAuthenticationsra  IdentityAgentSSH_AUTH_SOCKr  PKCS11ProviderIdentityFileCertificateFileIdentitiesOnlyForwardAgentRemoteCommandSetEnvSendEnv
RequestTTYForwardX11Trustedignore_failure)YgetpassgetuserrJ  r  loadedr   r  r`  r  r  r:   loadr  r  r   r   r   r  r  _DEFAULT_KEEPALIVE_INTERVALr  _DEFAULT_KEEPALIVE_COUNT_MAXr-  r  r0   r   r  r  r  r  r   r  r   rd  r  r  rm   r   r   r  r   r   r   r  r  r  r  r  re  r  r  r  r  r  rf  r  r  rS  _ClientKeysArgr   r   r   r  r   r  r   r  r  r  r  r&  rZ  r  r[  r  r\  _RequestPTYr]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  )Qr  r%  r  r^  r+  r  r,  rk  rm  rZ  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  rD  ra  rc  r  r  rj  rh  r  r  r  r  rd  r  r  r  r  r  r  r  r  r]  r  r  r  r  r  r  r  r  r  r  r  r  r  r&  rZ  r[  r\  r]  r^  r_  r`  ra  rb  rc  rd  rX  rY  rZ  r[  local_usernamedefault_configdefault_x509_certsdefault_x509_cert_pathidentities_onlyr5  sQ                                                                                   r  r  z"SSHClientConnectionOptions.prepare[  s   D	:$__.N R<K4F4F!#vx8CCEN)+>3577*<n%AC  !%%k66&4hdL #!%c6?!C!N!N!Pyy+RWW5%();%<""b(%)#vu%=%H%H%J"%,,.+./E+F*G'b "8E%*,=#>#)::.>#EGO
 #U5#:&

3H3N)P Q  "$S&**%:%AC D   	 ;)^dFJv"M8_ "2N'+%'9/%*,?	A +6*;;$s)VZZ(<bAB$s)VZZ(>CDE LIK 	
 #.B2F

>*, 	 %9! 	2#

+> CDb	J )A% cx2~8&,jj&H"J K !"$T6::&8%@A   "./B"C$T*6F%GH ( ,I+J("& d>3CD(*;$H % $7 &'S"b( 3B.<)>  ? !i%.&	2DN&DNDW]'JJ*D13 Tx2~8JJ-t46 #'t"4":

6>#@ RS&**%?DE  nc*+11#6N -$8!hsmVZZ-LMJ<J;ESj)44672
b Xc]FJJ/?$@A 
 r!*b0 "~vzz."/MNK2Xh'4Er)JK  tVZZ0@%ABr!#'
K#@ #' $34D4C%ED!#$;$=D!$(D!d>;?*O=M#')  $4ZND#D'(DO#2D (DO"DO#'D "DOr!#D&**^U*KL0@*dHSMgm7JJ') #SBYcFJJx4HIX8r>xJJy!#  K2<M[L$/1 #"$"5s#3,2N

./D4DF '*%:" &C  	: / 059:	:s   _9 9`)2r  r  r  r  r:   r  r  r  ro   r   r  r   r   _ServerHostKeysHandlerr   r   r   r   r  r   r   r~   r  r  r  r   r   r  _DEFAULT_LOGIN_TIMEOUTr  r  r2  r  r9   r8   r  r  r  r   r  r  r   r   r  rk   r  r   r   r  rU  r  s   @r  r  r  e  s]   DL ""SM!Xc] 23344Msm!#&":..!%(>"?@@#(:.//8$$x}%%Z3455MNSM!x// %c]"c]}	I}$)$$#C= smKK =A3704U;?.0b&(29;(*1302%'R%'b+-2,.*,24>@2E9;=?IK3IBD57-/:<13CG*,=?=A8:-113.035373546IM*,57FH-268HJ35;=,035+/r/157+/)-+/=?-1/3.3*1-#7e'w889e'%i0e' !-e' ?Ce' !) 8	e'
 !,e'
 9<e' sme' 39e'  (6e' !e' %X.e'  (~e' #e' ;Ce' #e' <De' !)e' AIe' "*e' >Fe'  (e'  %0!e'" *2();#e'$  0%e'& &eCHo6'e'(  (eSj(9:)e'* "*(53D*E!F+e',  %UCZ0-e'. %-U5#:->$?/e'0 &.c]1e'2 +3e'4 !)# 75e'6 '/7e'8 +A9e': #3-;e': 9A;e'< &.k%:=e'> #+>":?e'@ $,H#5Ae'B &c]Ce'D "*#Ee'F ,Ge'H 'x0Ie'J %Z0Ke'L #+4.Me'N #8C=1Oe'P $E*n*D$EFQe'R "$Se'R 9ASe'T %-TNUe'V !)sHSM/A)B CWe'X '+Ye'Z %Xc]3[e'\ #+8O+D"E]e'^ #+4._e'` "*(3-!8ae'b %SMce'd "(3-0ee'f $C=ge'f 7?tnge'h #8,ie'j &k2ke'l $C=me'n 'oe'p )qe'r !)tSy)9 :se't &c]ue'v  (}we'x (,ye'z #3-{e'z <?{e'| }e'~ !e'~ =Ae' e'r	  r  c                   ,    e Zd ZU dZeed<   eed<   eed<   ded<   ded<   eed<   e	ed	<   eed
<   e
ee      ed<   ee   ed<   eeeef      ed<   eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed<   eed<   ee   ed<   eed<   ee   ed<   ee   ed<   ee   ed<   eed<   ee   ed<   eed<   eed<   eed <   eed!<   d"d"d"d#d$d%d$d$d$d"d&d$d&d&d&d&d&d&d&d&d&d&d&d&d&d&d&d&d&d'd&d&d"d&d&d&d&d&d#d"d"d#d&d&d"d&d&d&d(d(eed&d#d"d&d"d"d)d*d"ed#eefAd+eej4                     d,ee   de
e   d-ed.ed/ed0ed1ed2edee   ded3ed4e
e   d5ed6e
e   d7e
e   d8e
e    d9e
e   d:e!d;e!d<e!d=e!d>e!d?e"d@e"dAe"dBe"dCe#dDe$e%   dEe&dFe
e'eef      dGe
e'e(ef      dHee'e(ef      dIe
e'e(ef      dJe
e'e(ef      dKe
e   de)dLe#dedMee   d	e	d
ede*de
ee      dee'ee+f      de
e   de
e   de
e   dedededede
e   dedee   de
e   dee   dee   dee   dedee   deded ed!edNd"f fdOZ, xZ-S )Pr  agI  SSH server connection options

       The following options are available to control the acceptance
       of SSH server connections:

       :param server_factory:
           A `callable` which returns an :class:`SSHServer` object that will
           be created for each new connection.
       :param proxy_command: (optional)
           A string or list of strings specifying a command and arguments
           to run when using :func:`connect_reverse` to make a reverse
           direction connection to an SSH client. Data will be forwarded
           to this process over stdin/stdout instead of opening a TCP
           connection. If specified as a string, standard shell quoting
           will be applied when splitting the command and its arguments.
       :param server_host_keys: (optional)
           A list of private keys and optional certificates which can be
           used by the server as a host key. Either this argument or
           `gss_host` must be specified. If this is not specified,
           only GSS-based key exchange will be supported.
       :param server_host_certs: (optional)
           A list of optional certificates which can be paired with the
           provided server host keys.
       :param send_server_host_keys: (optional)
           Whether or not to send a list of the allowed server host keys
           for clients to use to update their known hosts like for the
           server.

               .. note:: Enabling this option will allow multiple server
                         host keys of the same type to be configured. Only
                         the first key of each type will be actively used
                         during key exchange, but the others will be
                         reported as reserved keys that clients should
                         begin to trust, to allow for future key rotation.
                         If this option is disabled, specifying multiple
                         server host keys of the same type is treated as
                         a configuration error.
       :param passphrase: (optional)
           The passphrase to use to decrypt server host keys if they are
           encrypted, or a `callable` or coroutine which takes a filename
           as a parameter and returns the passphrase to use to decrypt
           that file. If not specified, only unencrypted server host keys
           can be loaded. If the keys passed into server_host_keys are
           already loaded, this argument is ignored.

               .. note:: A callable or coroutine passed in as a passphrase
                         will be called on all filenames configured as
                         server host keys each time an
                         SSHServerConnectionOptions object is instantiated,
                         even if the keys aren't encrypted or aren't ever
                         used for server validation.

       :param known_client_hosts: (optional)
           A list of client hosts which should be trusted to perform
           host-based client authentication. If this is not specified,
           host-based client authentication will be not be performed.
       :param trust_client_host: (optional)
           Whether or not to use the hostname provided by the client
           when performing host-based authentication. By default, the
           client-provided hostname is not trusted and is instead
           determined by doing a reverse lookup of the IP address the
           client connected from.
       :param authorized_client_keys: (optional)
           A list of authorized user and CA public keys which should be
           trusted for certificate-based client public key authentication.
       :param x509_trusted_certs: (optional)
           A list of certificates which should be trusted for X.509 client
           certificate authentication. If this argument is explicitly set
           to `None`, X.509 client certificate authentication will not
           be performed.

               .. note:: X.509 certificates to trust can also be provided
                         through an :ref:`authorized_keys <AuthorizedKeys>`
                         file if they are converted into OpenSSH format.
                         This allows their trust to be limited to only
                         specific client IPs or user names and allows
                         SSH functions to be restricted when these
                         certificates are used.
       :param x509_trusted_cert_paths: (optional)
           A list of path names to "hash directories" containing certificates
           which should be trusted for X.509 client certificate authentication.
           Each certificate should be in a separate file with a name of the
           form *hash.number*, where *hash* is the OpenSSL hash value of the
           certificate subject name and *number* is an integer counting up
           from zero if multiple certificates have the same hash.
       :param x509_purposes: (optional)
           A list of purposes allowed in the ExtendedKeyUsage of a
           certificate used for X.509 client certificate authentication,
           defulting to 'secureShellClient'. If this argument is explicitly
           set to `None`, the client certificate's ExtendedKeyUsage will
           not be checked.
       :param host_based_auth: (optional)
           Whether or not to allow host-based authentication. By default,
           host-based authentication is enabled if known client host keys
           are specified or if callbacks to validate client host keys
           are made available.
       :param public_key_auth: (optional)
           Whether or not to allow public key authentication. By default,
           public key authentication is enabled if authorized client keys
           are specified or if callbacks to validate client keys are made
           available.
       :param kbdint_auth: (optional)
           Whether or not to allow keyboard-interactive authentication. By
           default, keyboard-interactive authentication is enabled if the
           callbacks to generate challenges are made available.
       :param password_auth: (optional)
           Whether or not to allow password authentication. By default,
           password authentication is enabled if callbacks to validate a
           password are made available.
       :param gss_host: (optional)
           The principal name to use for the host in GSS key exchange and
           authentication. If not specified, the value returned by
           :func:`socket.gethostname` will be used if it is a fully qualified
           name. Otherwise, the value used by :func:`socket.getfqdn` will be
           used. If this argument is explicitly set to `None`, GSS
           key exchange and authentication will not be performed.
       :param gss_store: (optional)
           The GSS credential store from which to acquire credentials.
       :param gss_kex: (optional)
           Whether or not to allow GSS key exchange. By default, GSS
           key exchange is enabled.
       :param gss_auth: (optional)
           Whether or not to allow GSS authentication. By default, GSS
           authentication is enabled.
       :param allow_pty: (optional)
           Whether or not to allow allocation of a pseudo-tty in sessions,
           defaulting to `True`
       :param line_editor: (optional)
           Whether or not to enable input line editing on sessions which
           have a pseudo-tty allocated, defaulting to `True`
       :param line_echo: (bool)
           Whether or not to echo completed input lines when they are
           entered, rather than waiting for the application to read and
           echo them, defaulting to `True`. Setting this to `False`
           and performing the echo in the application can better synchronize
           input and output, especially when there are input prompts.
       :param line_history: (int)
           The number of lines of input line history to store in the
           line editor when it is enabled, defaulting to 1000
       :param max_line_length: (int)
           The maximum number of characters allowed in an input line when
           the line editor is enabled, defaulting to 1024
       :param rdns_lookup: (optional)
           Whether or not to perform reverse DNS lookups on the client's
           IP address to enable hostname-based matches in authorized key
           file "from" options and "Match Host" config options, defaulting
           to `False`.
       :param x11_forwarding: (optional)
           Whether or not to allow forwarding of X11 connections back
           to the client when the client supports it, defaulting to `False`
       :param x11_auth_path: (optional)
           The path to the Xauthority file to write X11 authentication
           data to, defaulting to the value in the environment variable
           `XAUTHORITY` or the file :file:`.Xauthority` in the user's
           home directory if that's not set
       :param agent_forwarding: (optional)
           Whether or not to allow forwarding of ssh-agent requests back
           to the client when the client supports it, defaulting to `True`
       :param process_factory: (optional)
           A `callable` or coroutine handler function which takes an AsyncSSH
           :class:`SSHServerProcess` argument that will be called each time a
           new shell, exec, or subsystem other than SFTP is requested by the
           client. If set, this takes precedence over the `session_factory`
           argument.
       :param session_factory: (optional)
           A `callable` or coroutine handler function which takes AsyncSSH
           stream objects for stdin, stdout, and stderr that will be called
           each time a new shell, exec, or subsystem other than SFTP is
           requested by the client. If not specified, sessions are rejected
           by default unless the :meth:`session_requested()
           <SSHServer.session_requested>` method is overridden on the
           :class:`SSHServer` object returned by `server_factory` to make
           this decision.
       :param encoding: (optional)
           The Unicode encoding to use for data exchanged on sessions on
           this server, defaulting to UTF-8 (ISO 10646) format. If `None`
           is passed in, the application can send and receive raw bytes.
       :param errors: (optional)
           The error handling strategy to apply on Unicode encode/decode
           errors of data exchanged on sessions on this server, defaulting
           to 'strict'.
       :param sftp_factory: (optional)
           A `callable` which returns an :class:`SFTPServer` object that
           will be created each time an SFTP session is requested by the
           client, or `True` to use the base :class:`SFTPServer` class
           to handle SFTP requests. If not specified, SFTP sessions are
           rejected by default.
       :param sftp_version: (optional)
           The maximum version of the SFTP protocol to support, currently
           either 3 or 4, defaulting to 3.
       :param allow_scp: (optional)
           Whether or not to allow incoming scp requests to be accepted.
           This option can only be used in conjunction with `sftp_factory`.
           If not specified, scp requests will be passed as regular
           commands to the `process_factory` or `session_factory`.
           to the client when the client supports it, defaulting to `True`
       :param window: (optional)
           The receive window size for sessions on this server
       :param max_pktsize: (optional)
           The maximum packet size for sessions on this server
       :param server_version: (optional)
           An ASCII string to advertise to SSH clients as the version of
           this server, defaulting to `'AsyncSSH'` and its version number.
       :param kex_algs: (optional)
           A list of allowed key exchange algorithms in the SSH handshake,
           taken from :ref:`key exchange algorithms <KexAlgs>`
       :param encryption_algs: (optional)
           A list of encryption algorithms to use during the SSH handshake,
           taken from :ref:`encryption algorithms <EncryptionAlgs>`
       :param mac_algs: (optional)
           A list of MAC algorithms to use during the SSH handshake, taken
           from :ref:`MAC algorithms <MACAlgs>`
       :param compression_algs: (optional)
           A list of compression algorithms to use during the SSH handshake,
           taken from :ref:`compression algorithms <CompressionAlgs>`, or
           `None` to disable compression
       :param signature_algs: (optional)
           A list of public key signature algorithms to use during the SSH
           handshake, taken from :ref:`signature algorithms <SignatureAlgs>`
       :param rekey_bytes: (optional)
           The number of bytes which can be sent before the SSH session
           key is renegotiated, defaulting to 1 GB
       :param rekey_seconds: (optional)
           The maximum time in seconds before the SSH session key is
           renegotiated, defaulting to 1 hour
       :param connect_timeout: (optional)
           The maximum time in seconds allowed to complete an outbound
           SSH connection. This includes the time to establish the TCP
           connection and the time to perform the initial SSH protocol
           handshake, key exchange, and authentication. This is disabled
           by default, relying on the system's default TCP connect timeout
           and AsyncSSH's login timeout.
       :param login_timeout: (optional)
           The maximum time in seconds allowed for authentication to
           complete, defaulting to 2 minutes. Setting this to 0
           will disable the login timeout.

               .. note:: This timeout only applies after the SSH TCP
                         connection is established. To set a timeout
                         which includes establishing the TCP connection,
                         use the `connect_timeout` argument above.
       :param keepalive_interval: (optional)
           The time in seconds to wait before sending a keepalive message
           if no data has been received from the client. This defaults to
           0, which disables sending these messages.
       :param keepalive_count_max: (optional)
           The maximum number of keepalive messages which will be sent
           without getting a response before disconnecting a client.
           This defaults to 3, but only applies when keepalive_interval is
           non-zero.
       :param tcp_keepalive: (optional)
           Whether or not to enable keepalive probes at the TCP level to
           detect broken connections, defaulting to `True`
       :param config: (optional)
           Paths to OpenSSH server configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options.

               .. note:: Specifying configuration files when creating an
                         :class:`SSHServerConnectionOptions` object will
                         cause the config file to be read and parsed at
                         the time of creation of the object, including
                         evaluation of any conditional blocks. If you want
                         the config to be parsed for every new connection,
                         this argument should be added to the connect or
                         listen calls instead. However, if you want to
                         save the parsing overhead and your configuration
                         doesn't depend on conditions that would change
                         between calls, this argument may be an option.
       :param options: (optional)
           A previous set of options to use as the base to incrementally
           build up a configuration. When an option is not explicitly
           specified, its value will be pulled from this options object
           (if present) before falling back to the default value.
       :type server_factory: `callable` returning :class:`SSHServer`
       :type proxy_command: `str` or `list` of `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type server_host_keys: *see* :ref:`SpecifyingPrivateKeys`
       :type server_host_certs: *see* :ref:`SpecifyingCertificates`
       :type send_server_host_keys: `bool`
       :type passphrase: `str` or `bytes`
       :type known_client_hosts: *see* :ref:`SpecifyingKnownHosts`
       :type trust_client_host: `bool`
       :type authorized_client_keys: *see* :ref:`SpecifyingAuthorizedKeys`
       :type x509_trusted_certs: *see* :ref:`SpecifyingCertificates`
       :type x509_trusted_cert_paths: `list` of `str`
       :type x509_purposes: *see* :ref:`SpecifyingX509Purposes`
       :type host_based_auth: `bool`
       :type public_key_auth: `bool`
       :type kbdint_auth: `bool`
       :type password_auth: `bool`
       :type gss_host: `str`
       :type gss_store:
           `str`, `bytes`, or a `dict` with `str` or `bytes` keys and values
       :type gss_kex: `bool`
       :type gss_auth: `bool`
       :type allow_pty: `bool`
       :type line_editor: `bool`
       :type line_echo: `bool`
       :type line_history: `int`
       :type max_line_length: `int`
       :type rdns_lookup: `bool`
       :type x11_forwarding: `bool`
       :type x11_auth_path: `str`
       :type agent_forwarding: `bool`
       :type process_factory: `callable` or coroutine
       :type session_factory: `callable` or coroutine
       :type encoding: `str` or `None`
       :type errors: `str`
       :type sftp_factory: `callable`
       :type sftp_version: `int`
       :type allow_scp: `bool`
       :type window: `int`
       :type max_pktsize: `int`
       :type server_version: `str`
       :type kex_algs: `str` or `list` of `str`
       :type encryption_algs: `str` or `list` of `str`
       :type mac_algs: `str` or `list` of `str`
       :type compression_algs: `str` or `list` of `str`
       :type signature_algs: `str` or `list` of `str`
       :type rekey_bytes: *see* :ref:`SpecifyingByteCounts`
       :type rekey_seconds: *see* :ref:`SpecifyingTimeIntervals`
       :type connect_timeout: *see* :ref:`SpecifyingTimeIntervals`
       :type login_timeout: *see* :ref:`SpecifyingTimeIntervals`
       :type keepalive_interval: *see* :ref:`SpecifyingTimeIntervals`
       :type keepalive_count_max: `int`
       :type config: `list` of `str`
       :type options: :class:`SSHServerConnectionOptions`

    r^  server_factoryr.  zOrderedDict[bytes, SSHKeyPair]r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  ra  rc  r  r  r  rX  rY  r  r  r   rZ  r[  NFr  r   r  secureShellClientTr  rW  r%  r  r+  r,  r-  rd  r  r.  rk  rm  rZ  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  rD  ra  rc  r  r  rj  rh  server_host_certsr]  r  cB                     t        j                  ||||||||	      }|"dk(  r1t        t        t        t
        f   |j                  dt                    }"|#dk(  r1t        t        t        t
        f   |j                  dt                    }#|$dk(  r$t        t        |j                  dt                    }$t        E| 1  ||
xs t        |||||(|||||||||||||||||| |!|"|#|$       |%dk(  r&t        t        t
           |j                  d            }%|&dk(  r't        t        t
           |j                  dd            }&t        |%|(|&|      }Bt!               | _        t!               | _        |BD ]z  }C|Cj&                  D ]i  }D|D| j"                  v r |'st)        dDj+                  d	       d
      D| j"                  vrC| j"                  D<   |'sQC| j$                  |Cj,                  <   k | |)| _        |*| _        |+dk(  r(|r&t        t2        t
           |j                  d            }+t5        |+t
        t6        f      rt9        |+      | _        n|+| _        |,dk(  r,t=        j>                         },d|,vrt=        j@                         },|,| _!        t5        |-tD        t
        f      r
d|-i| _#        n|-| _#        t        tH        |.dk7  r|.n|j                  dd            | _%        t        tH        |/dk7  r|/n|j                  dd            | _&        Bs|,st)        d      t        tH        |0dk7  r|0n|j                  dd            | _'        |1| _(        |2| _)        |3| _*        |4| _+        t        tH        |5dk7  r|5n|j                  dd            | _,        |6| _-        |7| _.        t        tH        |8dk7  r|8n|j                  dd            | _/        |9| _0        |:| _1        |;| _2        |<| _3        |=du rth        n|=| _5        |>| _6        |?| _7        @| _8        A| _9        y)z/Prepare server connection configuration optionsr  LoginGraceTimeClientAliveIntervalClientAliveCountMaxHostKeyHostCertificater  zMultiple keys of type r  zL found: Enable send_server_host_keys to allow reserved keys to be configuredAuthorizedKeysFiler  r  r  Tr  zNo server host keys provided	PermitTTYUseDNSFAllowAgentForwardingN):r;   r  r   r   r  r  r  r  r  r  r  r-  r  r   r   r   r   r  r  host_key_algorithmsr  r  public_datar  r  r   re  r  r'   r  r  gethostnamegetfqdnr  r  r  r  r  r  r  r
  r  r  r  r  ra  rc  r  r  r  rX  rY  r   r  r  r   rZ  r[  )Fr  r%  r  r^  r+  r,  r-  rd  r  r.  r  r.  rk  rm  rZ  r{  ry  rz  r  r  rG  r  rJ  rL  rN  rP  rR  rT  r=  r?  rD  ra  rc  r  r  rj  rh  r  r  r  r]  r  r  r  r  r  r  r  r  r
  r  r  r  r  ra  rc  r  r  r  rX  rY  r  r  r   rZ  r[  server_keysr  r  r5  sF                                                                        r  r  z"SSHServerConnectionOptions.prepare   s1   r !%%k66&1;&1;@ BU5#:&

3C3I)K L  #U5#:&

3H3N)P Q  "$S&**%:%AC D   	 ;)^dFJv"M8_ "2N'+%'9/#]O%'9;N	P r!#HSM6::i3HI" $Xc]%+ZZ0A2%F!H $$4j$5DB !,$/M!"G22$///8M$%=(+

7(;'< =L&L M M
 d33318D))#.(ELD--g.A.AB 3 # #5!2!R'FT#Y

+? @A # ,sDk:$%;< ' +AD'r>))+H("!>>+ !i%.&	2DN&DNDW]'JJ*D13 Tx2~8JJ-t46 8;<<dbIJJ{D)+ '"(.[B5FkJJx') -* $T 0B 6

148!:  /. *6$*>JL("&r	  ).r  r  r  r  r;   r  _ServerFactoryr  r  ro   r   r   r&   r  r   r~   r  r   r   r   _DEFAULT_LINE_HISTORY_DEFAULT_MAX_LINE_LENGTHr   r  r  r2  r  r9   r8   r  r  r  r   r  r  r   r   r   r   r   r  r   r  r   r  rU  r  s   @r  r  r    s   JX
 ""66::%%$X.?%@AAsmZ3455MNOOC= 566566smK,--OK =A3704U#%! "r#%;?.0b&(29;(*1302%'R%'b+-2,.*,24>@2E9;=??C=?BD573513.33748*/7946IM*,+-,.$("&$9'?.0',/335EIEI*1<@$4"'#7mv'w889v'%i0v' !-v' ?Cv' !	v' 58	v'
 v'
 25v' !v' !) 8v' !,v' 9<v' smv' 39v'  (6v' !v' %X.v'  (~v' #v' ;Cv' #v' <Dv'  !)!v'  AI!v'" "*#v'" >F#v'$  (%v'& %0'v'( *2();)v'*  0+v', &eCHo6-v'.  (eSj(9:/v'0 "*%s
*;!<1v'2  (eSj(9:3v'4 %-U5#:->$?5v'6 &.c]7v'8 #19v': $/;v'< (,=v'> %Z0?v'@ %2Av'B $(Cv'D )5Ev'F #8C=1Gv'H $E*n*D$EFIv'J "$Kv'L #4.Mv'N $D>Ov'P "Qv'R  Sv'T "Uv'V "%Wv'X &d^Yv'Z !%[v'\  (}]v'^ #+4._v'` "**A!Bav'b "**A!Bcv'd #3-ev'd <?ev'f ''89gv'h "iv'j  kv'j 25kv'l !mv'l =Amv' v'r	  r  r  r  c                   K   dt         ffd}t        j                         t        j                  |fd|i| d{   t        j
                  t        |d| |d      j                         d{   S 7 <7 w)a  Start an SSH client connection on an already-connected socket

       This function is a coroutine which starts an SSH client on an
       existing already-connected socket. It can be used instead of
       :func:`connect` when a socket is connected outside of asyncio.

       :param sock:
           An existing already-connected socket to run an SSH client on,
           instead of opening up a new connection.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. If no paths are specified and
           no config paths were set when constructing the `options`
           argument (if any), an attempt will be made to load the
           configuration from the file :file:`.ssh/config`. If this
           argument is explicitly set to `None`, no new configuration
           files will be loaded, but any configuration loaded when
           constructing the `options` argument will still apply. See
           :ref:`SupportedClientConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when establishing the SSH client connection. These
           options can be specified either through this parameter or as direct
           keyword arguments to this function.
       :type sock: :class:`socket.socket`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

       :returns: :class:`SSHClientConnection`

    r  c                       t         d      S 'Return an SSH client connection factoryr  r  r_  r%  new_optionss   r  r'  z run_client.<locals>.conn_factory!       #46BBr	  r^  Nr   zStarting SSH client onr  r_  r2  r  r  r/  wait_forr  r  rr  r^  rp  r  r'  r%  r7  s        @@r  
run_clientr=  !  s     LC- C
 !!#D2<<**"(* *K !!fdAt\)	+++- - -*-#   =BA>7B9B :B Bc                   K   dt         ffd}t        j                         t        j                  |fd|i| d{   t        j
                  t        |d| |d      j                         d{   S 7 <7 w)a2  Start an SSH server connection on an already-connected socket

       This function is a coroutine which starts an SSH server on an
       existing already-connected TCP socket. It can be used instead of
       :func:`listen` when connections are accepted outside of asyncio.

       :param sock:
           An existing already-connected socket to run SSH over, instead of
           opening up a new connection.
       :param config: (optional)
           Paths to OpenSSH server configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. By default, no OpenSSH
           configuration files will be loaded. See
           :ref:`SupportedServerConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when starting the reverse-direction SSH server.
           These options can be specified either through this parameter
           or as direct keyword arguments to this function.
       :type sock: :class:`socket.socket`
       :type config: `list` of `str`
       :type options: :class:`SSHServerConnectionOptions`

       :returns: :class:`SSHServerConnection`

    r  c                       t         d      S 'Return an SSH server connection factoryr  r4  r  r6  s   r  r'  z run_server.<locals>.conn_factory"  r8  r	  r^  Nr   zStarting SSH server onr9  r  r2  r  r  r/  r;  r  r  r<  s        @@r  
run_serverrE  !  s     BC- C
 !!#D2<<**"(* *K !!fdAt\)	+++- - -*-r>  )rZ  ry  rq  rz  rr  r^  rp  rm  rZ  ry  rz  c                  K   dt         ffd}
t        j                         t        j                  |f|| ||||d|	 d{   t        j
                  t        ||||
d      j                         d{   S 7 <7 w)a  Make an SSH client connection

       This function is a coroutine which can be run to create an outbound SSH
       client connection to the specified host and port.

       When successful, the following steps occur:

           1. The connection is established and an instance of
              :class:`SSHClientConnection` is created to represent it.
           2. The `client_factory` is called without arguments and should
              return an instance of :class:`SSHClient` or a subclass.
           3. The client object is tied to the connection and its
              :meth:`connection_made() <SSHClient.connection_made>` method
              is called.
           4. The SSH handshake and authentication process is initiated,
              calling methods on the client object if needed.
           5. When authentication completes successfully, the client's
              :meth:`auth_completed() <SSHClient.auth_completed>` method is
              called.
           6. The coroutine returns the :class:`SSHClientConnection`. At
              this point, the connection is ready for sessions to be opened
              or port forwarding to be set up.

       If an error occurs, it will be raised as an exception and the partially
       open connection and client objects will be cleaned up.

       :param host: (optional)
           The hostname or address to connect to.
       :param port: (optional)
           The port number to connect to. If not specified, the default
           SSH port is used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param family: (optional)
           The address family to use when creating the socket. By default,
           the address family is automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host address
       :param local_addr: (optional)
           The host and port to bind the socket to before connecting
       :param sock: (optional)
           An existing already-connected socket to run SSH over, instead of
           opening up a new connection. When this is specified, none of
           host, port family, flags, or local_addr should be specified.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. If no paths are specified and
           no config paths were set when constructing the `options`
           argument (if any), an attempt will be made to load the
           configuration from the file :file:`.ssh/config`. If this
           argument is explicitly set to `None`, no new configuration
           files will be loaded, but any configuration loaded when
           constructing the `options` argument will still apply. See
           :ref:`SupportedClientConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when establishing the SSH client connection. These
           options can be specified either through this parameter or as direct
           keyword arguments to this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type local_addr: tuple of `str` and `int`
       :type sock: :class:`socket.socket` or `None`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

       :returns: :class:`SSHClientConnection`

    r  c                       t         d      S r2  r5  r6  s   r  r'  zconnect.<locals>.conn_factoryw"  r8  r	  r^  rk  rm  rZ  ry  rz  NzOpening SSH connection tor9  r:  rk  rm  rZ  ry  rq  rz  rr  r^  rp  r  r'  r%  r7  s              @@r  rh  rh  "  s     LC- C
 !!#D2<<8TV*8068 8K !!fdE4,	.++- - -	8-$   ABB7B>B?BBc                  K   dt         ffd}
t        j                         t        j                  |f|| ||||d|	 d{   t        j
                  t        ||||
d      j                         d{   S 7 <7 w)aa  Create a reverse direction SSH connection

       This function is a coroutine which behaves similar to :func:`connect`,
       making an outbound TCP connection to a remote server. However, instead
       of starting up an SSH client which runs on that outbound connection,
       this function starts up an SSH server, expecting the remote system to
       start up a reverse-direction SSH client.

       Arguments to this function are the same as :func:`connect`, except
       that the `options` are of type :class:`SSHServerConnectionOptions`
       instead of :class:`SSHClientConnectionOptions`.

       :param host: (optional)
           The hostname or address to connect to.
       :param port: (optional)
           The port number to connect to. If not specified, the default
           SSH port is used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param family: (optional)
           The address family to use when creating the socket. By default,
           the address family is automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host address
       :param local_addr: (optional)
           The host and port to bind the socket to before connecting
       :param sock: (optional)
           An existing already-connected socket to run SSH over, instead of
           opening up a new connection. When this is specified, none of
           host, port family, flags, or local_addr should be specified.
       :param config: (optional)
           Paths to OpenSSH server configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. By default, no OpenSSH
           configuration files will be loaded. See
           :ref:`SupportedServerConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when starting the reverse-direction SSH server.
           These options can be specified either through this parameter
           or as direct keyword arguments to this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type local_addr: tuple of `str` and `int`
       :type sock: :class:`socket.socket` or `None`
       :type config: `list` of `str`
       :type options: :class:`SSHServerConnectionOptions`

       :returns: :class:`SSHServerConnection`

    r  c                       t         d      S rA  rC  r6  s   r  r'  z%connect_reverse.<locals>.conn_factory"  r8  r	  rH  Nz!Opening reverse SSH connection tor9  rD  rI  s              @@r  r  r  "  s     hC- C
 !!#D2<<8TV*8068 8K !!fdE44	6++- - -	8-rJ  d   F)rZ  ry  rq  r  rr  r  r  r  r  r^  rp  r  r  c                ,  	
K   dt         f	
fd}t        j                         t        j                  |f|| |||d| d{   d_        t        j                  t        |||||||d
      j                         d{   S 7 F7 w)a[  Start an SSH server

       This function is a coroutine which can be run to create an SSH server
       listening on the specified host and port. The return value is an
       :class:`SSHAcceptor` which can be used to shut down the listener.

       :param host: (optional)
           The hostname or address to listen on. If not specified, listeners
           are created for all addresses.
       :param port: (optional)
           The port number to listen on. If not specified, the default
           SSH port is used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param family: (optional)
           The address family to use when creating the server. By default,
           the address families are automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host
       :param backlog: (optional)
           The maximum number of queued connections allowed on listeners
       :param sock: (optional)
           A pre-existing socket to use instead of creating and binding
           a new socket. When this is specified, host and port should not
           be specified.
       :param reuse_address: (optional)
           Whether or not to reuse a local socket in the TIME_WAIT state
           without waiting for its natural timeout to expire. If not
           specified, this will be automatically set to `True` on UNIX.
       :param reuse_port: (optional)
           Whether or not to allow this socket to be bound to the same
           port other existing sockets are bound to, so long as they all
           set this flag when being created. If not specified, the
           default is to not allow this. This option is not supported
           on Windows or Python versions prior to 3.4.4.
       :param acceptor: (optional)
           A `callable` or coroutine which will be called when the
           SSH handshake completes on an accepted connection, taking
           the :class:`SSHServerConnection` as an argument.
       :param error_handler: (optional)
           A `callable` which will be called whenever the SSH handshake
           fails on an accepted connection. It is called with the failed
           :class:`SSHServerConnection` and an exception object describing
           the failure. If not specified, failed handshakes result in the
           connection object being silently cleaned up.
       :param config: (optional)
           Paths to OpenSSH server configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. By default, no OpenSSH
           configuration files will be loaded. See
           :ref:`SupportedServerConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when accepting SSH server connections. These
           options can be specified either through this parameter or
           as direct keyword arguments to this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type backlog: `int`
       :type sock: :class:`socket.socket` or `None`
       :type reuse_address: `bool`
       :type reuse_port: `bool`
       :type acceptor: `callable` or coroutine
       :type error_handler: `callable`
       :type config: `list` of `str`
       :type options: :class:`SSHServerConnectionOptions`

       :returns: :class:`SSHAcceptor`

    r  c                       t               S )rB  rC  r  r  r%  r7  s   r  r'  zlisten.<locals>.conn_factoryU#       #4hNNr	  r^  rk  rm  rZ  ry  NzCreating SSH listener onr9  )	r  r2  r  r  r/  r{  r;  r  r  rk  rm  rZ  ry  rq  r  rr  r  r  r  r  r^  rp  r  r'  r%  r7  s            ``    @@r  r  r  "  s     PO- O O
 !!#D2<<!TV!! !K
 !%K!!VT5'4L*D	F++- - -!-%   AB	B
ABBBBc                ,  	
K   dt         f	
fd}t        j                         t        j                  |f|| |||d| d{   d_        t        j                  t        |||||||d
      j                         d{   S 7 F7 w)a  Create a reverse-direction SSH listener

       This function is a coroutine which behaves similar to :func:`listen`,
       creating a listener which accepts inbound connections on the specified
       host and port. However, instead of starting up an SSH server on each
       inbound connection, it starts up a reverse-direction SSH client,
       expecting the remote system making the connection to start up a
       reverse-direction SSH server.

       Arguments to this function are the same as :func:`listen`, except
       that the `options` are of type :class:`SSHClientConnectionOptions`
       instead of :class:`SSHServerConnectionOptions`.

       The return value is an :class:`SSHAcceptor` which can be used to
       shut down the reverse listener.

       :param host: (optional)
           The hostname or address to listen on. If not specified, listeners
           are created for all addresses.
       :param port: (optional)
           The port number to listen on. If not specified, the default
           SSH port is used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param family: (optional)
           The address family to use when creating the server. By default,
           the address families are automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host
       :param backlog: (optional)
           The maximum number of queued connections allowed on listeners
       :param sock: (optional)
           A pre-existing socket to use instead of creating and binding
           a new socket. When this is specified, host and port should not
       :param reuse_address: (optional)
           Whether or not to reuse a local socket in the TIME_WAIT state
           without waiting for its natural timeout to expire. If not
           specified, this will be automatically set to `True` on UNIX.
       :param reuse_port: (optional)
           Whether or not to allow this socket to be bound to the same
           port other existing sockets are bound to, so long as they all
           set this flag when being created. If not specified, the
           default is to not allow this. This option is not supported
           on Windows or Python versions prior to 3.4.4.
       :param acceptor: (optional)
           A `callable` or coroutine which will be called when the
           SSH handshake completes on an accepted connection, taking
           the :class:`SSHClientConnection` as an argument.
       :param error_handler: (optional)
           A `callable` which will be called whenever the SSH handshake
           fails on an accepted connection. It is called with the failed
           :class:`SSHClientConnection` and an exception object describing
           the failure. If not specified, failed handshakes result in the
           connection object being silently cleaned up.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. If no paths are specified and
           no config paths were set when constructing the `options`
           argument (if any), an attempt will be made to load the
           configuration from the file :file:`.ssh/config`. If this
           argument is explicitly set to `None`, no new configuration
           files will be loaded, but any configuration loaded when
           constructing the `options` argument will still apply. See
           :ref:`SupportedClientConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when starting reverse-direction SSH clients.
           These options can be specified either through this parameter
           or as direct keyword arguments to this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type backlog: `int`
       :type sock: :class:`socket.socket` or `None`
       :type reuse_address: `bool`
       :type reuse_port: `bool`
       :type acceptor: `callable` or coroutine
       :type error_handler: `callable`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

       :returns: :class:`SSHAcceptor`

    r  c                       t               S )r3  r5  rP  s   r  r'  z$listen_reverse.<locals>.conn_factory#  rQ  r	  rR  Nz*Creating reverse direction SSH listener onr9  )	r_  r2  r  r  r/  r{  r;  r  r  rS  s            ``    @@r  r  r  i#  s     nO- O O
 !!#D2<<!TV!! !K
 !%K!!VT5'4z<<	> ++	- - -!-rT  r  c                 |   K   t        ||fd| i| d{   }|t        t        |j                               fS 7 $w)a  Create an SSH client connection

       This is a coroutine which wraps around :func:`connect`, providing
       backward compatibility with older AsyncSSH releases. The only
       differences are that the `client_factory` argument is the first
       positional argument in this call rather than being a keyword argument
       or specified via an :class:`SSHClientConnectionOptions` object and
       the return value is a tuple of an :class:`SSHClientConnection` and
       :class:`SSHClient` rather than just the connection, mirroring
       :meth:`asyncio.AbstractEventLoop.create_connection`.

       :returns: An :class:`SSHClientConnection` and :class:`SSHClient`

    r  N)rh  r   r0   r  )r  rk  rm  r  rj  s        r  r  r  #  sJ     & t #N #!# #D i!1222#s   <:%<r  c                 <   K   t        ||fd| i| d{   S 7 w)a  Create an SSH server

       This is a coroutine which wraps around :func:`listen`, providing
       backward compatibility with older AsyncSSH releases. The only
       difference is that the `server_factory` argument is the first
       positional argument in this call rather than being a keyword argument
       or specified via an :class:`SSHServerConnectionOptions` object,
       mirroring :meth:`asyncio.AbstractEventLoop.create_server`.

    r  Nr  )r  rk  rm  r  s       r  r!  r!  $  s2      d "> " " " " "r  )rZ  r{  ry  rq  rz  rr  r,  r  r  r^  rp  r{  r,  r  r  c                  K   dt         ffd}t        j                         t        j	                  ||| |||||d|
dddd|	|       d{   t        j
                  t        ||||d      j                         d{   }|j                         }|j                          |j                          d{    |S 7 v7 @7 
w)a,  Retrieve an SSH server's host key

       This is a coroutine which can be run to connect to an SSH server and
       return the server host key presented during the SSH handshake.

       A list of server host key algorithms can be provided to specify
       which host key types the server is allowed to choose from. If the
       key exchange is successful, the server host key sent during the
       handshake is returned.

           .. note:: Not all key exchange methods involve the server
                     presenting a host key. If something like GSS key
                     exchange is used without a server host key, this
                     method may return `None` even when the handshake
                     completes.

       :param host: (optional)
           The hostname or address to connect to
       :param port: (optional)
           The port number to connect to. If not specified, the default
           SSH port is used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param proxy_command: (optional)
           A string or list of strings specifying a command and arguments
           to run to make a connection to the SSH server. Data will be
           forwarded to this process over stdin/stdout instead of opening a
           TCP connection. If specified as a string, standard shell quoting
           will be applied when splitting the command and its arguments.
       :param family: (optional)
           The address family to use when creating the socket. By default,
           the address family is automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host address
       :param local_addr: (optional)
           The host and port to bind the socket to before connecting
       :param sock: (optional)
           An existing already-connected socket to run SSH over, instead of
           opening up a new connection. When this is specified, none of
           host, port family, flags, or local_addr should be specified.
       :param client_version: (optional)
           An ASCII string to advertise to the SSH server as the version of
           this client, defaulting to `'AsyncSSH'` and its version number.
       :param kex_algs: (optional)
           A list of allowed key exchange algorithms in the SSH handshake,
           taken from :ref:`key exchange algorithms <KexAlgs>`
       :param server_host_key_algs: (optional)
           A list of server host key algorithms to allow during the SSH
           handshake, taken from :ref:`server host key algorithms
           <PublicKeyAlgs>`.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. If no paths are specified and
           no config paths were set when constructing the `options`
           argument (if any), an attempt will be made to load the
           configuration from the file :file:`.ssh/config`. If this
           argument is explicitly set to `None`, no new configuration
           files will be loaded, but any configuration loaded when
           constructing the `options` argument will still apply. See
           :ref:`SupportedClientConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when establishing the SSH client connection used
           to retrieve the server host key. These options can be specified
           either through this parameter or as direct keyword arguments to
           this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type proxy_command: `str` or `list` of `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type local_addr: tuple of `str` and `int`
       :type sock: :class:`socket.socket` or `None`
       :type client_version: `str`
       :type kex_algs: `str` or `list` of `str`
       :type server_host_key_algs: `str` or `list` of `str`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

       :returns: An :class:`SSHKey` public key or `None`

    r  c                       t         d      S )r3  r  r4  r5  r6  s   r  r'  z)get_server_host_key.<locals>.conn_factory$  s     #45AAr	  Nr  )r^  rk  rm  rZ  r{  ry  rz  r  r  r=  r?  rD  r  r  r,  zFetching server host key fromr9  )r_  r2  r  r  r/  r;  r  r  r  rQ  r  )rk  rm  rZ  r{  ry  rq  rz  rr  r,  r  r  r^  rp  r'  rj  server_host_keyr%  r7  s                   @@r  r  r  !$  s     fB- B
 !!#D2<<TV#Fz/CdX% = ' 'K !!fdE40	2++- -D
 ..0OJJL



''- s6   A
CC7CC7C>C	?CC	Crd  c                  K   dt         ffd}t        j                         t        j	                  ||| ||||||d|dddd|
|	       d{   t        j
                  t        ||||d      j                         d{   }|j                         }|j                          |j                          d{    |S 7 v7 @7 
w)ar  Retrieve an SSH server's allowed auth methods

       This is a coroutine which can be run to connect to an SSH server and
       return the auth methods available to authenticate to it.

           .. note:: The key exchange with the server must complete
                     successfully before the list of available auth
                     methods can be returned, so be sure to specify any
                     arguments needed to complete the key exchange.
                     Also, auth methods may vary by user, so you may
                     want to specify the specific user you would like
                     to get auth methods for.

       :param host: (optional)
           The hostname or address to connect to
       :param port: (optional)
           The port number to connect to. If not specified, the default
           SSH port is used.
       :param username: (optional)
           Username to authenticate as on the server. If not specified,
           the currently logged in user on the local machine will be used.
       :param tunnel: (optional)
           An existing SSH client connection that this new connection should
           be tunneled over. If set, a direct TCP/IP tunnel will be opened
           over this connection to the requested host and port rather than
           connecting directly via TCP. A string of the form
           [user@]host[:port] may also be specified, in which case a
           connection will be made to that host and then used as a tunnel.
           A comma-separated list may also be specified to establish a
           tunnel through multiple hosts.

               .. note:: When specifying tunnel as a string, any config
                         options in the call will apply only when opening
                         a connection to the final destination host and
                         port. However, settings to use when opening
                         tunnels may be specified via a configuration file.
                         To get more control of config options used to
                         open the tunnel, :func:`connect` can be called
                         explicitly, and the resulting client connection
                         can be passed as the tunnel argument.

       :param proxy_command: (optional)
           A string or list of strings specifying a command and arguments
           to run to make a connection to the SSH server. Data will be
           forwarded to this process over stdin/stdout instead of opening a
           TCP connection. If specified as a string, standard shell quoting
           will be applied when splitting the command and its arguments.
       :param family: (optional)
           The address family to use when creating the socket. By default,
           the address family is automatically selected based on the host.
       :param flags: (optional)
           The flags to pass to getaddrinfo() when looking up the host address
       :param local_addr: (optional)
           The host and port to bind the socket to before connecting
       :param sock: (optional)
           An existing already-connected socket to run SSH over, instead of
           opening up a new connection. When this is specified, none of
           host, port family, flags, or local_addr should be specified.
       :param client_version: (optional)
           An ASCII string to advertise to the SSH server as the version of
           this client, defaulting to `'AsyncSSH'` and its version number.
       :param kex_algs: (optional)
           A list of allowed key exchange algorithms in the SSH handshake,
           taken from :ref:`key exchange algorithms <KexAlgs>`
       :param server_host_key_algs: (optional)
           A list of server host key algorithms to allow during the SSH
           handshake, taken from :ref:`server host key algorithms
           <PublicKeyAlgs>`.
       :param config: (optional)
           Paths to OpenSSH client configuration files to load. This
           configuration will be used as a fallback to override the
           defaults for settings which are not explicitly specified using
           AsyncSSH's configuration options. If no paths are specified and
           no config paths were set when constructing the `options`
           argument (if any), an attempt will be made to load the
           configuration from the file :file:`.ssh/config`. If this
           argument is explicitly set to `None`, no new configuration
           files will be loaded, but any configuration loaded when
           constructing the `options` argument will still apply. See
           :ref:`SupportedClientConfigOptions` for details on what
           configuration options are currently supported.
       :param options: (optional)
           Options to use when establishing the SSH client connection used
           to retrieve the server host key. These options can be specified
           either through this parameter or as direct keyword arguments to
           this function.
       :type host: `str`
       :type port: `int`
       :type tunnel: :class:`SSHClientConnection` or `str`
       :type proxy_command: `str` or `list` of `str`
       :type family: `socket.AF_UNSPEC`, `socket.AF_INET`, or `socket.AF_INET6`
       :type flags: flags to pass to :meth:`getaddrinfo() <socket.getaddrinfo>`
       :type local_addr: tuple of `str` and `int`
       :type sock: :class:`socket.socket` or `None`
       :type client_version: `str`
       :type kex_algs: `str` or `list` of `str`
       :type server_host_key_algs: `str` or `list` of `str`
       :type config: `list` of `str`
       :type options: :class:`SSHClientConnectionOptions`

       :returns: a `list` of `str`

    r  c                       t         d      S )r3  r#  r4  r5  r6  s   r  r'  z-get_server_auth_methods.<locals>.conn_factory#%  s     #4>JJr	  Nr  )r^  rk  rm  rd  rZ  r{  ry  rz  r  r  r=  r?  rD  r  r  r,  z!Fetching server auth methods fromr9  )r_  r2  r  r  r/  r;  r  r  r  rQ  r  )rk  rm  rd  rZ  r{  ry  rq  rz  rr  r,  r  r  r^  rp  r'  rj  server_auth_methodsr%  r7  s                    @@r  r  r  $  s     dK- K
 !!#D2<<Tx]641dX% = ' 'K !!fdE44	6++- -D
 668JJL



)'- s6   ACC7CC7C?C
 CC
Cr,  )r  Nr  )r  r  r  (x  r  r2  r  r  r  r  r`  r  r  r  r  r]  collectionsr   r   pathlibr   typesr   typingr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   typing_extensionsr   r   r  r   r   r  r   r   r   r   r    r!   r"   r#   r$   r%   	auth_keysr&   r'   channelr(   r)   r*   r+   r,   r-   r.   r/   clientr0   r  r1   r2   r3   r4   r5   r6   r7   r^  r8   r9   r:   r;   	constantsr<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r  r\   r]   r^   r_   r`   forwardra   gssrb   rc   rd   re   r  rf   rg   rh   ri   rj   keysignrk   rl   rm   rn   r  ro   rp   r  rq   rr   rs   rt   ru   rv   rw   rx   ry   loggingrz   r{   rQ  r|   r}   miscr~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rU  r   r   r   r   r   r   r   r   r   r  r   pkcs11r   r|  r   r   r   r   r   r   r   
public_keyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   streamr   r   r   r   r   r   r   r   r   r   
subprocessr   r   r   r   tuntapr   r   r   r   r  r   x11r   r   r   r   r   cryptor   r  r-  r  r   r   r  r   r  r  r  rT  r  r8  r1  r  r  r  r  r  r  r  r  r  _GlobalRequestr  _GlobalRequestResultr  _KeyOrCertOptionsr  r  r  r  r  _TunnelConnector_TunnelListenerr  r  r  r  r;  r5  r8  r  r  r  r  r  r  r  r  r.  r/  r  r[  ro  r  r  r  r  r  r  r  r  r  r   r_  r  r   r  r  r=  rE  rh  r  
AI_PASSIVEr  r  r  r!  r  r  r  r	  r  <module>rz     s  *      	 	   
   #    H H F F F ' ' , 3 B B 8 G G > C C D D 3  G G M 9 L L 1 * + O O L L F / : L L A @ < > * L 0 7 3 = ! 8 8 8 8 ) 3 3 9 , A = O + & 3 J J F F H H G G > > I I ; + = @ @ C C N N @ @ $ $ 7 7 A 7 F F L L L L = C E H J 1 9 < G ) @ -  A A D D B B C C : : : # # ; ; ; D D B B = = * * E E A A D D 3 3     & & ; ; G G'' "i-("i-(78 /:%;<!(DL$v,,0L$v,,H+5d+;,< #= >  h  3 30ox 0 (O#4j6F#FGH?#+I#6#89=#> ? @ U+;=M+M%NNO9+t+,E#x},-.D>dCc4EEFGz#445z>12gc3h'#678HSM"x/D@AS)^, CK( T;&'sHSM123D#I#S#J0G$GH $R)@%@A s$<<= c#::;z"S#J
4(889  $ '                      HE''HE2:3-HEr5y)HE.3HEV HZ4H '4&'DG%J G%0E G% 22G%;>G%!&--0G% "*"e)!4G% <?G% DIG%T7(: 7(x/D 7(117(:=7(7(&.v}}&=7( "&7( 487( !)U 3	7(
 7(
  -7(tx
3  ,!3 !c ! $U!#E{!  $! )1!L 04"A3 "Ah "AX "A $U"A;?;"A%e_"A8@"AJ5 5x 5(,U58@5"<9 "<H "<!)"<9A"<!)"<9A"<  $"< 	huoxuox/ 	0	"<Ji% i%XW&"$g&6&6 W&"tLj%5- j%5ZKOP- OPd,F77 F7R['!5 ['|d'!5 d'N JLEI2-6== 2-(;2G 2-&'AB2-%2-*=2- 2-j JLEI--6== --(;2G --&'AB-- &--+>-- --` s-79*,1352624BFs-8C= s-"#34s-"3-s-58s- 'x0s- !/	s-
 #;/s- $$>?s- #s- (;s- s-l )+a--/ ")+(,(*8<a-!#a-)*a- a- ,/a- X&	a-
 v}}%a- %a- 45a- a- 1a- a-H x-57)+9J9J #T',,00413AEx-(3- x-!/2x-!#x-36x- x- ,4FMM+Bx- !%	x- ;?	x-
 *x- !.x- "+.x- ##=>x- "x- '2x- x-v H-=?13&,&7&79=/4488<9;IMH-(3- H-!)/!:H-!)#H- !$H- CFH-  (6	H-
 )-H-
 CGH- $2H- )6H- "*+!6H- #++E"FH- $*H- /:H- H-X >@3N 3-5c]3&,3 	!9,-32 9;" ")1#""("-8" "& *,M-/13R(,/1"(*8<M!#M)*M  .M >Fc]M 	M %-X$6	M
 v}}%M !,M M 8@M %M 45M Mb HJM-/13R(,/1"(*8<M!#M7?}M)*M  .M >Fc]M 	M %-X$6	M
 v}}%M !,M M 8@M %M 45M BJ#Mr	  