3 L]@sdZddlmZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z m Z ddlmZddlmZmZmZddlZddlmZddlmZdd lmZdd lmZdd lmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZIdd lJmKZKmLZLdd lMmNZNddlOmPZPddlQmRZRddlSmTZTmUZUddlVmWZWddlXmYZYmZZZddl[m\Z\ddl]m^Z^m_Z_m`Z`ddlambZbmcZcmdZdddlemfZfddlgmhZhmiZiddljmkZkddllmmZmmnZnmoZompZpmqZqmrZrddlsmtZtddlumvZvddlwmxZxddlymzZzddl{m|Z|m}Z}m~Z~mZddlmZmZmZgZd d!ZddlZejeGd"d#d#ejeZGd$d%d%eZGd&d'd'eZdS)(z Core protocol implementation )print_functionN)md5sha1sha256sha512)default_backend) algorithmsCiphermodes)util) AuthHandler)GSSAuth)Channel)- xffffffffcMSG_CHANNEL_OPEN cMSG_IGNOREcMSG_GLOBAL_REQUESTDEBUG MSG_KEXINIT MSG_IGNOREMSG_DISCONNECT MSG_DEBUGERRORWARNINGcMSG_UNIMPLEMENTEDINFO cMSG_KEXINIT cMSG_NEWKEYS MSG_NEWKEYScMSG_REQUEST_SUCCESScMSG_REQUEST_FAILURECONNECTION_FAILED_CODE'OPEN_FAILED_ADMINISTRATIVELY_PROHIBITEDOPEN_SUCCEEDEDcMSG_CHANNEL_OPEN_FAILUREcMSG_CHANNEL_OPEN_SUCCESSMSG_GLOBAL_REQUESTMSG_REQUEST_SUCCESSMSG_REQUEST_FAILUREMSG_CHANNEL_OPEN_SUCCESSMSG_CHANNEL_OPEN_FAILUREMSG_CHANNEL_OPENMSG_CHANNEL_SUCCESSMSG_CHANNEL_FAILUREMSG_CHANNEL_DATAMSG_CHANNEL_EXTENDED_DATAMSG_CHANNEL_WINDOW_ADJUSTMSG_CHANNEL_REQUESTMSG_CHANNEL_EOFMSG_CHANNEL_CLOSEMIN_WINDOW_SIZEMIN_PACKET_SIZEMAX_WINDOW_SIZEDEFAULT_WINDOW_SIZEDEFAULT_MAX_PACKET_SIZEHIGHEST_USERAUTH_MESSAGE_IDMSG_UNIMPLEMENTED MSG_NAMES)ZlibCompressorZlibDecompressor)DSSKey) Ed25519Key) KexCurve25519)KexGex KexGexSHA256) KexGroup1) KexGroup14KexGroup14SHA256)KexGroup16SHA512) KexNistp256 KexNistp384 KexNistp521) KexGSSGex KexGSSGroup1 KexGSSGroup14)Message) PacketizerNeedRekeyException) ModulusPack) string_typeslongbyte_ordbinputPY2)RSAKey)ECDSAKey)ServerInterface) SFTPClient) SSHExceptionBadAuthenticationTypeChannelExceptionProxyCommandFailure)retry_on_signalClosingContextManager clamp_valuecCsxtD] }|jqWdS)N)_active_threads stop_thread)Zthrrd8/tmp/pip-install-wfra5znf/paramiko/paramiko/transport.py_join_lingering_threadsws rfc@seZdZdZeZeZdZdje j Z dZ dZ dZdZejrHdeZdZdZejejd(d(d)ejejd(d*d)ejejd(d+d)ejejd,d(d)ejejd(d(d)ejejd(d*d)ejejd(d+d)ejejd,d*d)d-Zed.d/ed0d/ed+d/ed+d/ed1d/ed1d/ed(d/ed0d/d2Z e!e!e"e"e#e#e#e#e#e#e$e$d3 Z%e&e'e(e)e*e+e,e-e.e/e0e1d4 Z2ejrjee2d#<e3e4fe3e4fdd6Z5d5Z6d7Z7e8e9d8d9d5fd:d;Z:dd?Z=ee`, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings). Instances of this class may be used as context managers. z2.0z paramiko_{} aes128-ctr aes192-ctr aes256-ctr aes128-cbc aes192-cbc aes256-cbc blowfish-cbc3des-cbc hmac-sha2-256 hmac-sha2-512hmac-sha2-256-etm@openssh.comhmac-sha2-512-etm@openssh.com hmac-sha1hmac-md5 hmac-sha1-96 hmac-md5-96 ssh-ed25519ecdsa-sha2-nistp256ecdsa-sha2-nistp384ecdsa-sha2-nistp521ssh-rsassh-dssecdh-sha2-nistp256ecdh-sha2-nistp384ecdh-sha2-nistp521diffie-hellman-group16-sha512$diffie-hellman-group-exchange-sha256diffie-hellman-group14-sha256"diffie-hellman-group-exchange-sha1diffie-hellman-group14-sha1diffie-hellman-group1-sha1curve25519-sha256@libssh.org%gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==)gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==(gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==none)classmodez block-sizezkey-size )z aes128-ctrz aes192-ctrz aes256-ctrz blowfish-cbcz aes128-cbcz aes192-cbcz aes256-cbcz3des-cbc)rsize @)z hmac-sha1z hmac-sha1-96z hmac-sha2-256zhmac-sha2-256-etm@openssh.comz hmac-sha2-512zhmac-sha2-512-etm@openssh.comzhmac-md5z hmac-md5-96) zssh-rsazssh-rsa-cert-v01@openssh.comzssh-dsszssh-dss-cert-v01@openssh.comzecdsa-sha2-nistp256z(ecdsa-sha2-nistp256-cert-v01@openssh.comzecdsa-sha2-nistp384z(ecdsa-sha2-nistp384-cert-v01@openssh.comzecdsa-sha2-nistp521z(ecdsa-sha2-nistp521-cert-v01@openssh.comz ssh-ed25519z ssh-ed25519-cert-v01@openssh.com) zdiffie-hellman-group1-sha1zdiffie-hellman-group14-sha1z"diffie-hellman-group-exchange-sha1z$diffie-hellman-group-exchange-sha256zdiffie-hellman-group14-sha256zdiffie-hellman-group16-sha512z(gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==z)gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==z%gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==zecdh-sha2-nistp256zecdh-sha2-nistp384zecdh-sha2-nistp521N)zzlib@openssh.comzlibrg?FTcsd|_d|_ttrZjdd}|d|_t|dkrF|ddfn|dt|dfttkr\|_d}t j t j t j } x| D]t\} } } } }| t j kr| }t j |t j yt fdd Wn.t jk r}zt|}WYdd}~XqXPqWtd j|tjj||jd |_|jj|jt|_d |jd |j|_d|_d|_|_ d|_!|_"d|_#|_$d|_%|_&d|_'d|_(d|_)||_*d|_+d|_,d|_-|j*rt.d||_,|j/|j0|_0d|_1d|_2d|_3d|_4d|_5d|_6t|_7tj8|_9t:|_;i|_||_?||_@d|_Ad|_Bd|_Cd|_DtjE|_Ftj8|_Gd|_Hd|_ItJjK|jI|_L|jjM|jLd|_Nd|_Od|_Pd|_Qd|_Rd|_S|pi|_Td|_Ud|_Vi|_Wg|_XtjY|j9|_Zi|_[dS)a{ Create a new SSH session over an existing socket, or socket-like object. This only creates the `.Transport` object; it doesn't begin the SSH session yet. Use `connect` or `start_client` to begin a client session, or `start_server` to begin a server session. If the object is not actually a socket, it must have the following methods: - ``send(str)``: Writes from 1 to ``len(str)`` bytes, and returns an int representing the number of bytes written. Returns 0 or raises ``EOFError`` if the stream has been closed. - ``recv(int)``: Reads from 1 to ``int`` bytes and returns them as a string. Returns 0 or raises ``EOFError`` if the stream has been closed. - ``close()``: Closes the socket. - ``settimeout(n)``: Sets a (float) timeout on I/O operations. For ease of use, you may also pass in an address (as a tuple) or a host string as the ``sock`` argument. (A host string is a hostname with an optional port (separated by ``":"``) which will be converted into a tuple of ``(hostname, port)``.) A socket will be connected to this address and used for communication. Exceptions from the ``socket`` call may be thrown in this case. .. note:: Modifying the the window and packet sizes might have adverse effects on your channels created from this transport. The default values are the same as in the OpenSSH code base and have been battle tested. :param socket sock: a socket or socket-like object to create the session over. :param int default_window_size: sets the default window size on the transport. (defaults to 2097152) :param int default_max_packet_size: sets the default max packet size on the transport. (defaults to 32768) :param bool gss_kex: Whether to enable GSSAPI key exchange when GSSAPI is in play. Default: ``False``. :param bool gss_deleg_creds: Whether to enable GSSAPI credential delegation when GSSAPI is in play. Default: ``True``. :param dict disabled_algorithms: If given, must be a dictionary mapping algorithm type to an iterable of algorithm identifiers, which will be disabled for the lifetime of the transport. Keys should match the last word in the class' builtin algorithm tuple attributes, such as ``"ciphers"`` to disable names within ``_preferred_ciphers``; or ``"kex"`` to disable something defined inside ``_preferred_kex``. Values should exactly match members of the matching attribute. For example, if you need to disable ``diffie-hellman-group16-sha512`` key exchange (perhaps because your code talks to a server which implements it differently from Paramiko), specify ``disabled_algorithms={"kex": ["diffie-hellman-group16-sha512"]}``. .. versionchanged:: 1.15 Added the ``default_window_size`` and ``default_max_packet_size`` arguments. .. versionchanged:: 1.15 Added the ``gss_kex`` and ``gss_deleg_creds`` kwargs. .. versionchanged:: 2.6 Added the ``disabled_algorithms`` kwarg. FN:rzNo suitable address familycsjfS)N)connectrd)hostnameportsockrdresz$Transport.__init__..zUnable to connect to {}: {}TzSSH--z gssapi-keyexg>@zparamiko.transport)\activer isinstancerQsplitleninttypetuplesocket getaddrinfo AF_UNSPEC SOCK_STREAMr_errorstrr[format threadingThread__init__ setDaemonr settimeout_active_check_timeoutrN packetizer _PROTO_ID _CLIENT_ID local_versionremote_version local_cipher remote_cipherlocal_kex_initremote_kex_init local_mac remote_maclocal_compressionremote_compression session_id host_key_typehost_keyZ use_gss_kex gss_kex_usedZ kexgss_ctxtgss_hostr _preferred_gsskex_preferred_kex kex_engineHKinitial_kex_donein_kex authenticated_expected_packetLocklock ChannelMap _channelschannel_events channels_seen_channel_counterdefault_max_packet_sizedefault_window_size_forward_agent_handler _x11_handler _tcp_handlersaved_exceptionEvent clear_to_sendclear_to_send_lockclear_to_send_timeoutlog_namer get_loggerloggerset_log auth_handlerglobal_responsecompletion_eventbanner_timeouthandshake_timeoutZ auth_timeoutdisabled_algorithms server_mode server_objectserver_key_dictserver_accepts Conditionserver_accept_cvsubsystem_table)selfrrrgss_kexgss_deleg_credsrZhlreasonZ addrinfosfamilysocktypeproto canonnameZsockaddraferd)rrrrer1sO                 zTransport.__init__cs(tdj}tfdd|DS)Nz _preferred_{}c3s$|]}|jjgkr|VqdS)N)rget).0x)rtype_rdre sz.Transport._filter_algorithm..)getattrrr)rrdefaultrd)rrre_filter_algorithms zTransport._filter_algorithmcCs |jdS)Nciphers)r)rrdrdrepreferred_ciphersszTransport.preferred_cipherscCs |jdS)NZmacs)r)rrdrdrepreferred_macsszTransport.preferred_macscCs |jdS)Nkeys)r)rrdrdrepreferred_keysszTransport.preferred_keyscCs |jdS)Nkex)r)rrdrdre preferred_kexszTransport.preferred_kexcCs |jdS)N compression)r)rrdrdrepreferred_compression szTransport.preferred_compressioncCsttt|t@}dj|}|js.|d7}nb|jdkrZ|dj|j|j|jdd7}|jrx|djt |j 7}n|j r|d7}n|d 7}|d 7}|S) zP Returns a string representation of this object, for debugging. z) hexrRidrrrr _cipher_infois_authenticatedrrr)rZid_outrdrdre__repr__s     zTransport.__repr__cCs|jj|jdS)a Terminate this Transport without closing the session. On posix systems, if a Transport is open during process forking, both parent and child will share the underlying socket, but only one process can use the connection (without corrupting the session). Use this method to clean up a Transport object without disrupting the other process. .. versionadded:: 1.5.3 N)rclose)rrdrdreatfork)s zTransport.atforkcCst|S)a  Return a `.SecurityOptions` object which can be used to tweak the encryption algorithms this transport will permit (for encryption, digest/hash operations, public keys, and key exchanges) and the order of preference for them. )SecurityOptions)rrdrdreget_security_options6szTransport.get_security_optionscCs6|sdS|dkr|j}|r,|dk r,tj|}||_dS)a Normalize/canonicalize ``self.gss_host`` depending on various factors. :param str gss_host: The explicitly requested GSS-oriented hostname to connect to (i.e. what the host's name is in the Kerberos database.) Defaults to ``self.hostname`` (which will be the 'real' target hostname and/or host portion of given socket object.) :param bool trust_dns: Indicates whether or not DNS is trusted; if true, DNS will be used to canonicalize the GSS hostname (which again will either be ``gss_host`` or the transport's default hostname.) (Defaults to True due to backwards compatibility.) :param bool gssapi_requested: Whether GSSAPI key exchange or authentication was even requested. If not, this is a no-op and nothing happens (and ``self.gss_host`` is not set.) (Defaults to True due to backwards compatibility.) :returns: ``None``. N)rrgetfqdnr)rr trust_dnsgssapi_requestedrdrdre set_gss_host?s  zTransport.set_gss_hostcCsd|_|dk r ||_|jdStj|_}|j|dk rJtj|nd}xN|jd|js||j}|dk rt|td|j s|dk rPtj|krPPqPWdS)a| Negotiate a new SSH2 session as a client. This is the first step after creating a new `.Transport`. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given ``Event`` will be triggered. On failure, `is_active` will return ``False``. (Since 1.4) If ``event`` is ``None``, this method will not return until negotiation is done. On success, the method returns normally. Otherwise an SSHException is raised. After a successful negotiation, you will usually want to authenticate, calling `auth_password ` or `auth_publickey `. .. note:: `connect` is a simpler method for connecting as a client. .. note:: After calling this method (or `start_server` or `connect`), you should no longer directly read from or write to the original socket object. :param .threading.Event event: an event to trigger when negotiation is complete (optional) :param float timeout: a timeout, in seconds, for SSH2 session negotiation (optional) :raises: `.SSHException` -- if negotiation fails (and no ``event`` was passed in) TNg?zNegotiation failed.) rrstartrrtimewait get_exceptionr[is_set)reventtimeoutZmax_timerrdrdre start_clientas$# zTransport.start_clientcCs|dkrt}d|_||_d|_|dk r:||_|jdStj|_}|jx:|jd|js~|j }|dk rv|t d|j rRPqRWdS)ap Negotiate a new SSH2 session as a server. This is the first step after creating a new `.Transport` and setting up your server host key(s). A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given ``Event`` will be triggered. On failure, `is_active` will return ``False``. (Since 1.4) If ``event`` is ``None``, this method will not return until negotiation is done. On success, the method returns normally. Otherwise an SSHException is raised. After a successful negotiation, the client will need to authenticate. Override the methods `get_allowed_auths <.ServerInterface.get_allowed_auths>`, `check_auth_none <.ServerInterface.check_auth_none>`, `check_auth_password <.ServerInterface.check_auth_password>`, and `check_auth_publickey <.ServerInterface.check_auth_publickey>` in the given ``server`` object to control the authentication process. After a successful authentication, the client should request to open a channel. Override `check_channel_request <.ServerInterface.check_channel_request>` in the given ``server`` object to allow channels to be opened. .. note:: After calling this method (or `start_client` or `connect`), you should no longer directly read from or write to the original socket object. :param .threading.Event event: an event to trigger when negotiation is complete. :param .ServerInterface server: an object used to perform authentication and create `channels <.Channel>` :raises: `.SSHException` -- if negotiation fails (and no ``event`` was passed in) NTg?zNegotiation failed.) rYrrrrrrrr r!r[r")rr#serverrrdrdre start_servers(* zTransport.start_servercCs||j|j<dS)a Add a host key to the list of keys used for server mode. When behaving as a server, the host key is used to sign certain packets during the SSH2 negotiation, so that the client can trust that we are who we say we are. Because this is used for signing, the key must contain private key info, not just the public half. Only one key of each type (RSA or DSS) is kept. :param .PKey key: the host key to add, usually an `.RSAKey` or `.DSSKey`. N)rget_name)rkeyrdrdreadd_server_keys zTransport.add_server_keyc Cs&y |j|jStk r YnXdS)a Return the active host key, in server mode. After negotiating with the client, this method will return the negotiated host key. If only one type of host key was set with `add_server_key`, that's the only key that will ever be returned. But in cases where you have set more than one type of host key (for example, an RSA key and a DSS key), the key type will be negotiated by the client, and this method will return the key of the type agreed on. If the host key has not been negotiated yet, ``None`` is returned. In client mode, the behavior is undefined. :return: host key (`.PKey`) of the type negotiated by the client, or ``None``. N)rrKeyError)rrdrdreget_server_keys  zTransport.get_server_keyc Csbtt_ddg}|dk r$|jd|x2|D]*}ytjj|dStk rRYq*Xq*Wdt_dS)a (optional) Load a file of prime moduli for use in doing group-exchange key negotiation in server mode. It's a rather obscure option and can be safely ignored. In server mode, the remote client may request "group-exchange" key negotiation, which asks the server to send a random prime number that fits certain criteria. These primes are pretty difficult to compute, so they can't be generated on demand. But many systems contain a file of suitable primes (usually named something like ``/etc/ssh/moduli``). If you call `load_server_moduli` and it returns ``True``, then this file of primes has been loaded and we will support "group-exchange" in server mode. Otherwise server mode will just claim that it doesn't support that method of key negotiation. :param str filename: optional path to the moduli file, if you happen to know that it's not in a standard location. :return: True if a moduli file was successfully loaded; False otherwise. .. note:: This has no effect when used in client mode. z/etc/ssh/moduliz/usr/local/etc/moduliNrTF)rPrg _modulus_packinsert read_fileIOError)filename file_listfnrdrdreload_server_modulis    zTransport.load_server_modulicCs@|js dS|jxt|jjD] }|jq"W|jjdS)zP Close this session, and any open channels that are tied to it. N)rrclistrvalues_unlinkrr)rchanrdrdrer)s  zTransport.closecCs|j s|j rtd|jS)a Return the host key of the server (in client mode). .. note:: Previously this call returned a tuple of ``(key type, key string)``. You can get the same effect by calling `.PKey.get_name` for the key type, and ``str(key)`` for the key string. :raises: `.SSHException` -- if no session is currently active. :return: public key (`.PKey`) of the remote server zNo existing session)rrr[r)rrdrdreget_remote_server_key4s zTransport.get_remote_server_keycCs|jS)z Return true if this session is active (open). :return: True if the session is still active (open); False if the session is closed )r)rrdrdre is_activeEszTransport.is_activecCs|jd|||dS)a Request a new channel to the server, of type ``"session"``. This is just an alias for calling `open_channel` with an argument of ``"session"``. .. note:: Modifying the the window and packet sizes might have adverse effects on the session created. The default values are the same as in the OpenSSH code base and have been battle tested. :param int window_size: optional window size for this session. :param int max_packet_size: optional max packet size for this session. :return: a new `.Channel` :raises: `.SSHException` -- if the request is rejected or the session ends prematurely .. versionchanged:: 1.13.4/1.14.3/1.15.3 Added the ``timeout`` argument. .. versionchanged:: 1.15 Added the ``window_size`` and ``max_packet_size`` arguments. session) window_sizemax_packet_sizer$) open_channel)rr<r=r$rdrdre open_sessionOs zTransport.open_sessioncCs|jd|dS)a Request a new channel to the client, of type ``"x11"``. This is just an alias for ``open_channel('x11', src_addr=src_addr)``. :param tuple src_addr: the source address (``(str, int)``) of the x11 server (port is the x11 port, ie. 6010) :return: a new `.Channel` :raises: `.SSHException` -- if the request is rejected or the session ends prematurely x11)src_addr)r>)rrArdrdreopen_x11_channelrszTransport.open_x11_channelcCs |jdS)aB Request a new channel to the client, of type ``"auth-agent@openssh.com"``. This is just an alias for ``open_channel('auth-agent@openssh.com')``. :return: a new `.Channel` :raises: `.SSHException` -- if the request is rejected or the session ends prematurely zauth-agent@openssh.com)r>)rrdrdreopen_forward_agent_channels z$Transport.open_forward_agent_channelcCs|jd||S)aC Request a new channel back to the client, of type ``forwarded-tcpip``. This is used after a client has requested port forwarding, for sending incoming connections back to the client. :param src_addr: originator's address :param dest_addr: local (server) connected address zforwarded-tcpip)r>)rrA dest_addrrdrdreopen_forwarded_tcpip_channels z&Transport.open_forwarded_tcpip_channelc Cs|jstd|dkrdn|}|jjz|j|}|j|}|j}t}|jt |j ||j ||j ||j ||dks|dkr|j |d|j |d|j |d|j |dn$|dkr|j |d|j |dt |} |j j|| tj|j|<} d |j|<| j|| j||Wd|jjX|j|tj} x^| jd |js|j} | dkrtd } | | jrPn| |tjkrZtd qZW|j j|} | dk r| S|j} | dkrtd } | dS) as Request a new channel to the server. `Channels <.Channel>` are socket-like objects used for the actual transfer of data across the session. You may only request a channel after negotiating encryption (using `connect` or `start_client`) and authenticating. .. note:: Modifying the the window and packet sizes might have adverse effects on the channel created. The default values are the same as in the OpenSSH code base and have been battle tested. :param str kind: the kind of channel requested (usually ``"session"``, ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``) :param tuple dest_addr: the destination address (address + port tuple) of this port forwarding, if ``kind`` is ``"forwarded-tcpip"`` or ``"direct-tcpip"`` (ignored for other channel types) :param src_addr: the source address of this port forwarding, if ``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"`` :param int window_size: optional window size for this session. :param int max_packet_size: optional max packet size for this session. :param float timeout: optional timeout opening a channel, default 3600s (1h) :return: a new `.Channel` on success :raises: `.SSHException` -- if the request is rejected, the session ends prematurely or there is a timeout openning a channel .. versionchanged:: 1.15 Added the ``window_size`` and ``max_packet_size`` arguments. zSSH session not activeNizforwarded-tcpipz direct-tcpiprrr@Tg?zUnable to open channel.zTimeout opening channel.)rr[racquire_sanitize_window_size_sanitize_packet_size _next_channelrMadd_byter add_stringadd_intrrputrrrr_set_transport _set_windowrelease_send_user_messagerr r!r"r) rkindrDrAr<r=r$chanidmr8r#start_tsrrdrdrer>sb,                  zTransport.open_channelcsljstdt|}jd||fdd}|dkr:td|dkrJ|j}|dkrbfdd }|}|_|S) a Ask the server to forward TCP connections from a listening port on the server, across this SSH session. If a handler is given, that handler is called from a different thread whenever a forwarded connection arrives. The handler parameters are:: handler( channel, (origin_addr, origin_port), (server_addr, server_port), ) where ``server_addr`` and ``server_port`` are the address and port that the server was listening on. If no handler is set, the default behavior is to send new incoming forwarded connections into the accept queue, to be picked up via `accept`. :param str address: the address to bind when forwarding :param int port: the port to forward, or 0 to ask the server to allocate any port :param callable handler: optional handler for incoming forwarded connections, of the form ``func(Channel, (str, int), (str, int))``. :return: the port number (`int`) allocated by the server :raises: `.SSHException` -- if the server refused the TCP forward request zSSH session not activez tcpip-forwardT)r NzTCP forwarding request deniedrcsj|dS)N)_queue_incoming_channel)channelrAZdest_addr_port)rrdredefault_handler(sz7Transport.request_port_forward..default_handler)rr[rglobal_requestget_intr)raddressrhandlerresponserXrd)rrerequest_port_forwards! zTransport.request_port_forwardcCs(|js dSd|_|jd||fdddS)a. Ask the server to cancel a previous port-forwarding request. No more connections to the given address & port will be forwarded across this ssh connection. :param str address: the address to stop forwarding :param int port: the port to stop forwarding Nzcancel-tcpip-forwardT)r )rrrY)rr[rrdrdrecancel_port_forward1s zTransport.cancel_port_forwardcCs tj|S)aE Create an SFTP client channel from an open transport. On success, an SFTP session will be opened with the remote host, and a new `.SFTPClient` object will be returned. :return: a new `.SFTPClient` referring to an sftp session (channel) across this transport )rZZfrom_transport)rrdrdreopen_sftp_client?s zTransport.open_sftp_clientcCsLt}|jt|dkr.ttjddd}|jtj||j|dS)a Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls. :param int byte_count: the number of random bytes to send in the payload of the ignored packet -- defaults to a random number from 10 to 41. Nrr )rMrJrrSosurandom add_bytesrQ)rZ byte_countrTrdrdre send_ignoreKs  zTransport.send_ignorecCsVtj|_|jx>|jjd|jsB|j}|dk r:|td|jjrPqWdS)aK Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating new keys causes a pause in traffic both ways as the two sides swap keys and do computations. This method returns when the session has switched to new keys. :raises: `.SSHException` -- if the key renegotiation failed (which causes the session to end) g?NzNegotiation failed.) rrr_send_kex_initr rr!r[r")rrrdrdrerenegotiate_keys]s   zTransport.renegotiate_keyscCs$tj|fdd}|jj||dS)a Turn on/off keepalive packets (default is off). If this is set, after ``interval`` seconds without sending any data over the connection, a "keepalive" packet will be sent (and ignored by the remote host). This can be useful to keep connections alive over a NAT, for example. :param int interval: seconds to wait before sending a keepalive packet (or 0 to disable keepalives). cSs|jdddS)Nzkeepalive@lag.netF)r )rY)rrdrdre_requestsz)Transport.set_keepalive.._requestN)weakrefproxyr set_keepalive)rintervalrhrdrdrerkws zTransport.set_keepalivecCs|rtj|_t}|jt|j||j||dk rD|j||j t dj ||j ||shdSx&|jj d|jsdS|jjrjPqjW|jS)a Make a global request to the remote host. These are normally extensions to the SSH2 protocol. :param str kind: name of the request. :param tuple data: an optional tuple containing additional data to attach to the request. :param bool wait: ``True`` if this method should not return until a response is received; ``False`` otherwise. :return: a `.Message` containing possible additional data if the request was successful (or an empty `.Message` if ``wait`` was ``False``); ``None`` if the request was denied. NzSending global request "{}"g?)rrrrMrJrrK add_booleanadd_logrrrQr rr"r)rrRdatar rTrdrdrerYs&        zTransport.global_requestc Csh|jjzLt|jdkr(|jjd}n,|jj|t|jdkrP|jjd}nd}Wd|jjX|S)aW Return the next channel opened by the client over this transport, in server mode. If no channel is opened before the given timeout, ``None`` is returned. :param int timeout: seconds to wait for a channel, or ``None`` to wait forever :return: a new `.Channel` opened by the client rN)rrFrrpoprr rP)rr$r8rdrdreaccepts   zTransport.acceptrc Csl|dk r|jg|_|j|| |p"|d|j|dk r| r|j} | j|jksf| j|jkr|jtd|jtdj|jt |j|jtdj| jt | jt d|jtdj|j|dk s|dk s|s|rh|r|jtd|j ||j |nZ|r,|jtd|j |n<|dk rP|jtd |j||n|jtd |j||dS) a Negotiate an SSH2 session, and optionally verify the server's host key and authenticate using a password or private key. This is a shortcut for `start_client`, `get_remote_server_key`, and `Transport.auth_password` or `Transport.auth_publickey`. Use those methods if you want more control. You can use this method immediately after creating a Transport to negotiate encryption with a server. If it fails, an exception will be thrown. On success, the method will return cleanly, and an encrypted session exists. You may immediately call `open_channel` or `open_session` to get a `.Channel` object, which is used for data transfer. .. note:: If you fail to supply a password or private key, this method may succeed, but a subsequent `open_channel` or `open_session` call may fail because you haven't authenticated yet. :param .PKey hostkey: the host key expected from the server, or ``None`` if you don't want to do host key verification. :param str username: the username to authenticate as. :param str password: a password to use for authentication, if you want to use password authentication; otherwise ``None``. :param .PKey pkey: a private key to use for authentication, if you want to use private key authentication; otherwise ``None``. :param str gss_host: The target's name in the kerberos database. Default: hostname :param bool gss_auth: ``True`` if you want to use GSS-API authentication. :param bool gss_kex: Perform GSS-API Key Exchange and user authentication. :param bool gss_deleg_creds: Whether to delegate GSS-API client credentials. :param gss_trust_dns: Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default ``True``). :raises: `.SSHException` -- if the SSH2 negotiation fails, the host key supplied by the server is incorrect, or authentication fails. .. versionchanged:: 2.3 Added the ``gss_trust_dns`` argument. N)rrrzBad host key from serverzExpected: {}: {}zGot : {}: {}zHost key verified ({})z,Attempting GSS-API auth... (gssapi-with-mic)z)Attempting GSS-API auth... (gssapi-keyex)zAttempting public-key auth...zAttempting password auth...)r(_preferred_keysrr%r9asbytesrorrreprr[auth_gssapi_with_micrauth_gssapi_keyexauth_publickey auth_password) rZhostkeyusernamepasswordZpkeyrZgss_authrrZ gss_trust_dnsr)rdrdrersL<         zTransport.connectc Cs,|jjz|j}d|_|S|jjXdS)ay Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like `start_client`. The exception (if any) is cleared after this call. :return: an exception, or ``None`` if there is no stored exception. .. versionadded:: 1.1 N)rrFrrP)rrrdrdrer!<s zTransport.get_exceptionc Os0z|jj|||f|j|<Wd|jjXdS)a' Set the handler class for a subsystem in server mode. If a request for this subsystem is made on an open ssh channel later, this handler will be constructed and called -- see `.SubsystemHandler` for more detailed documentation. Any extra parameters (including keyword arguments) are saved and passed to the `.SubsystemHandler` constructor later. :param str name: name of the subsystem. :param handler: subclass of `.SubsystemHandler` that handles this subsystem. N)rrFrrP)rnamer\Zlargkwargrdrdreset_subsystem_handlerPs zTransport.set_subsystem_handlercCs|jo|jdk o|jjS)a Return true if this session is active and authenticated. :return: True if the session is still open and has been authenticated successfully; False if authentication failed and/or the session is closed. N)rrr)rrdrdrerds  zTransport.is_authenticatedcCs |j s|jdkrdS|jjS)a Return the username this connection is authenticated for. If the session is not authenticated (or authentication failed), this method returns ``None``. :return: username that was authenticated (a `str`), or ``None``. N)rr get_username)rrdrdrersszTransport.get_usernamecCs|j s|jdkrdS|jjS)z Return the banner supplied by the server upon connect. If no banner is supplied, this method returns ``None``. :returns: server supplied banner (`str`), or ``None``. .. versionadded:: 1.13 N)rrZbanner)rrdrdre get_banners zTransport.get_bannercCsD|j s|j rtdtj}t||_|jj|||jj|S)a Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the `.BadAuthenticationType` exception raised. :param str username: the username to authenticate as :return: list of auth types permissible for the next stage of authentication (normally empty) :raises: `.BadAuthenticationType` -- if "none" authentication isn't allowed by the server for this user :raises: `.SSHException` -- if the authentication failed due to a network error .. versionadded:: 1.5 zNo existing session) rrr[rrr r auth_nonewait_for_response)rrzmy_eventrdrdrers  zTransport.auth_nonecs|j s|j rtd|dkr*tj}n|}t||_|jj|||dk rTgSy |jj|St k r}zJ| sd|j kryfdd}|j ||Stk r|YnXWYdd}~XnXdS)a Authenticate to the server using a password. The username and password are sent over an encrypted link. If an ``event`` is passed in, this method will return immediately, and the event will be triggered once authentication succeeds or fails. On success, `is_authenticated` will return ``True``. On failure, you may use `get_exception` to get more detailed error information. Since 1.1, if no event is passed, this method will block until the authentication succeeds or fails. On failure, an exception is raised. Otherwise, the method simply returns. Since 1.5, if no event is passed and ``fallback`` is ``True`` (the default), if the server doesn't support plain password authentication but does support so-called "keyboard-interactive" mode, an attempt will be made to authenticate using this interactive mode. If it fails, the normal exception will be thrown as if the attempt had never been made. This is useful for some recent Gentoo and Debian distributions, which turn off plain password authentication in a misguided belief that interactive authentication is "more secure". (It's not.) If the server requires multi-step authentication (which is very rare), this method will return a list of auth types permissible for the next step. Otherwise, in the normal case, an empty list is returned. :param str username: the username to authenticate as :param basestring password: the password to authenticate with :param .threading.Event event: an event to trigger when the authentication attempt is complete (whether it was successful or not) :param bool fallback: ``True`` if an attempt at an automated "interactive" password auth should be made if the server doesn't support normal password auth :return: list of auth types permissible for the next stage of authentication (normally empty) :raises: `.BadAuthenticationType` -- if password authentication isn't allowed by the server for this user (and no event was passed in) :raises: `.AuthenticationException` -- if the authentication failed (and no event was passed in) :raises: `.SSHException` -- if there was a network error zNo existing sessionNzkeyboard-interactivecs*t|dkrtdt|dkr$gSgS)NrzFallback authentication failed.r)rr[)title instructionsfields)r{rdrer\s   z(Transport.auth_password..handler) rrr[rrr rryrr\Z allowed_typesauth_interactive)rrzr{r#fallbackrrr\rd)r{rerys&/    zTransport.auth_passwordcCs`|j s|j rtd|dkr*tj}n|}t||_|jj||||dk rTgS|jj|S)a Authenticate to the server using a private key. The key is used to sign data from the server, so it must include the private part. If an ``event`` is passed in, this method will return immediately, and the event will be triggered once authentication succeeds or fails. On success, `is_authenticated` will return ``True``. On failure, you may use `get_exception` to get more detailed error information. Since 1.1, if no event is passed, this method will block until the authentication succeeds or fails. On failure, an exception is raised. Otherwise, the method simply returns. If the server requires multi-step authentication (which is very rare), this method will return a list of auth types permissible for the next step. Otherwise, in the normal case, an empty list is returned. :param str username: the username to authenticate as :param .PKey key: the private key to authenticate with :param .threading.Event event: an event to trigger when the authentication attempt is complete (whether it was successful or not) :return: list of auth types permissible for the next stage of authentication (normally empty) :raises: `.BadAuthenticationType` -- if public-key authentication isn't allowed by the server for this user (and no event was passed in) :raises: `.AuthenticationException` -- if the authentication failed (and no event was passed in) :raises: `.SSHException` -- if there was a network error zNo existing sessionN) rrr[rrr rrxr)rrzr)r#rrdrdrerxs#  zTransport.auth_publickeycCsH|j s|j rtdtj}t||_|jj|||||jj|S)a Authenticate to the server interactively. A handler is used to answer arbitrary questions from the server. On many servers, this is just a dumb wrapper around PAM. This method will block until the authentication succeeds or fails, peroidically calling the handler asynchronously to get answers to authentication questions. The handler may be called more than once if the server continues to ask questions. The handler is expected to be a callable that will handle calls of the form: ``handler(title, instructions, prompt_list)``. The ``title`` is meant to be a dialog-window title, and the ``instructions`` are user instructions (both are strings). ``prompt_list`` will be a list of prompts, each prompt being a tuple of ``(str, bool)``. The string is the prompt and the boolean indicates whether the user text should be echoed. A sample call would thus be: ``handler('title', 'instructions', [('Password:', False)])``. The handler should return a list or tuple of answers to the server's questions. If the server requires multi-step authentication (which is very rare), this method will return a list of auth types permissible for the next step. Otherwise, in the normal case, an empty list is returned. :param str username: the username to authenticate as :param callable handler: a handler for responding to server questions :param str submethods: a string list of desired submethods (optional) :return: list of auth types permissible for the next stage of authentication (normally empty). :raises: `.BadAuthenticationType` -- if public-key authentication isn't allowed by the server for this user :raises: `.AuthenticationException` -- if the authentication failed :raises: `.SSHException` -- if there was a network error .. versionadded:: 1.5 zNo existing session) rrr[rrr rrr)rrzr\ submethodsrrdrdrer.s+  zTransport.auth_interactivecCs|s dd}|j|||S)a Autenticate to the server interactively but dumber. Just print the prompt and / or instructions to stdout and send back the response. This is good for situations where partial auth is achieved by key and then the user has to enter a 2fac token. cSsVg}|rt|j|r$t|jx,|D]$\}}t|jdd|jtq*W|S)N )end)printstripappendrU)rrZ prompt_listZanswerspromptZ show_inputrdrdrer\ms  z0Transport.auth_interactive_dumb..handler)r)rrzr\rrdrdreauth_interactive_dumbcs zTransport.auth_interactive_dumbcCsH|j s|j rtdtj}t||_|jj|||||jj|S)a Authenticate to the Server using GSS-API / SSPI. :param str username: The username to authenticate as :param str gss_host: The target host :param bool gss_deleg_creds: Delegate credentials or not :return: list of auth types permissible for the next stage of authentication (normally empty) :raises: `.BadAuthenticationType` -- if gssapi-with-mic isn't allowed by the server (and no event was passed in) :raises: `.AuthenticationException` -- if the authentication failed (and no event was passed in) :raises: `.SSHException` -- if there was a network error zNo existing session) rrr[rrr rrvr)rrzrrrrdrdrervzs  zTransport.auth_gssapi_with_miccCsD|j s|j rtdtj}t||_|jj|||jj|S)aZ Authenticate to the server with GSS-API/SSPI if GSS-API kex is in use. :param str username: The username to authenticate as. :returns: a list of auth types permissible for the next stage of authentication (normally empty) :raises: `.BadAuthenticationType` -- if GSS-API Key Exchange was not performed (and no event was passed in) :raises: `.AuthenticationException` -- if the authentication failed (and no event was passed in) :raises: `.SSHException` -- if there was a network error zNo existing session) rrr[rrr rrwr)rrzrrdrdrerws  zTransport.auth_gssapi_keyexcCs$||_tj||_|jj|jdS)ag Set the channel for this transport's logging. The default is ``"paramiko.transport"`` but it can be set to anything you want. (See the `.logging` module for more info.) SSH Channels will log to a sub-channel of the one specified. :param str name: new channel name for logging .. versionadded:: 1.1 N)rr rrrr)rr|rdrdreset_log_channels  zTransport.set_log_channelcCs|jS)z Return the channel name used for this transport's logging. :return: channel name as a `str` .. versionadded:: 1.2 )r)rrdrdreget_log_channelszTransport.get_log_channelcCs|jj|dS)aa Turn on/off logging a hex dump of protocol traffic at DEBUG level in the logs. Normally you would want this off (which is the default), but if you are debugging something, it may be useful. :param bool hexdump: ``True`` to log protocol traffix (in hex) to the log; ``False`` otherwise. N)r set_hexdump)rZhexdumprdrdrers zTransport.set_hexdumpcCs |jjS)z Return ``True`` if the transport is currently logging hex dumps of protocol traffic. :return: ``True`` if hex dumps are being logged, else ``False``. .. versionadded:: 1.4 )r get_hexdump)rrdrdrers zTransport.get_hexdumpcCs|r d|_nd|_dS)a Turn on/off compression. This will only have an affect before starting the transport (ie before calling `connect`, etc). By default, compression is off since it negatively affects interactive sessions. :param bool compress: ``True`` to ask the remote client/server to compress traffic; ``False`` to refuse compression .. versionadded:: 1.5.2 zlib@openssh.comrrN)rrr)r)_preferred_compression)rcompressrdrdreuse_compressions zTransport.use_compressioncCs t|jdd}|dkrdS|S)a Return the address of the remote side of this Transport, if possible. This is effectively a wrapper around ``getpeername`` on the underlying socket. If the socket-like object has no ``getpeername`` method, then ``("unknown", 0)`` is returned. :return: the address of the remote host, if known, as a ``(str, int)`` tuple. getpeernameNunknownr)rr)rr)rZgprdrdrers zTransport.getpeernamecCsvd|_|jjtr:x\|jr6|tjk r6|jdqWn8x6|jrp|tjk rp|jj rp|jj rp|jdq.default_handler)r)rr\rXrd)rre_set_forward_agent_handlers z$Transport._set_forward_agent_handlercs&|dkrfdd}|_n|_dS)Ncsj|dS)N)rV)rWZ src_addr_port)rrdrerXsz3Transport._set_x11_handler..default_handler)r)rr\rXrd)rre_set_x11_handlers zTransport._set_x11_handlerc Cs6|jjz|jj||jjWd|jjXdS)N)rrFrrrnotifyrP)rrWrdrdrerVs   z!Transport._queue_incoming_channelcCs|dkr|j}tt|tS)N)rrar4r6)rr<rdrdrerGszTransport._sanitize_window_sizecCs|dkr|j}tt|tS)N)rrar5r6)rr=rdrdrerHszTransport._sanitize_packet_sizecCs|j s|tks|jrdSt}|tkr6|jtnJ|tkr|j}|j }|jt |j ||j t |j d|j d|S)ao Checks message type against current auth state. If server mode, and auth has not succeeded, and the message is of a post-auth type (channel open or global request) an appropriate error response Message is crafted and returned to caller for sending. Otherwise (client mode, authed, or pre-auth message) returns None. Nren)rr9rrMr&rJr r+get_textrZr$rLr"rK)rptypemessageZreplyrRrSrdrdre_ensure_autheds       zTransport._ensure_authedcCs"t|_tj|ttt|t@}|jr>|jt dj |n|jt dj |yy|j j t |jd|jt dj |j|j|j j|j|j|jtx6|jr|j jr|j r|jy|j j\}}Wntk rwYnX|tkrqn.|tkr |j|Pn|tkr6|j|qt|j dkr||j krdt!dj |j |t"|_ |dkr|dkr|j#j$||q||j%kr|j&||}|r|j'|n|j%|||n||j(kr@|j)}|j*j+|}|dk r |j(|||n4||j,kr*|jt d j |n|jt-d j |Pn|j.dk r||j.j%kr|j.j%|}||j.|t|j dkrqnPt/|}d j ||} |jt0| |t1krt2} | j3t4| j5|j6|j'| |j j7qWWnVt!k r8} z0|jt-d t8| |jt-t9j:| |_;WYdd} ~ Xntk r} zht?| j@t"kr| j@rdj | j@d| j@d} nt8| ptA| } n| j@} |jt-d| | |_;WYdd} ~ XnNtBk r>} z0|jt-dt8| |jt-t9j:| |_;WYdd} ~ XnXtjC|x tD|j*jED]}|jFqZW|jrd|_|j jG|jHdk r|jHjI|j.dk r|j.jJx|jKjED]} | jIqWz|jLjM|jNjOWd|jLjPX|jQjGWn|jjRdk rYnXdS)Nz!starting thread (server mode): {}z!starting thread (client mode): {}z zLocal version/idstring: {}rz$Expecting packet from {!r}, got {:d}r)z&Ignoring message for dead channel {:d}z(Channel request for unknown channel {:d}zOops, unhandled type {} ({!r})z Exception: zEOF in transport threadz {} ({:d})rzSocket exception: zUnknown exception: F)SsysrbrrrRrrrrorrrZ write_allrTr _check_bannerZstart_handshakerrfrrr need_rekeyrZ read_messagerOrr_parse_disconnectr _parse_debugrrr[rrZ parse_next_handler_tablerr_channel_handler_tablerZrrrrrr;rr:rMrJrrLZseqnoZcomplete_handshakerr Z tb_stringsrEOFErrorrrrrru Exceptionremover5r6r7rrsetabortrrrFrrrPrmodules)rtidrrT error_msgrSr8r\r|warningrrZemsgr#rdrdreruns                                   z Transport.runcCs<dj|}||kr||7}n|dj||7}|jt|dS)Nz {} agreed: zlocal={}, remote={})rror)rwhichlocalremoterrdrdre_log_agreements   zTransport._log_agreementc CsP|jjz|jjWd|jjX|jdkr8|j|j||jj dS)N) rrFrclearrPrrf_parse_kex_initrZ start_kex)rrTrdrdre_negotiate_keyss    zTransport._negotiate_keysc CsjxtdD]}|dkr|j}nd}y|jj|}WnFtk rHYn2tk rx}ztdt|WYdd}~XnX|dddkrP|jt d|q W|dddkrtd|d ||_ |jt d j ||j d }|dkr|d|}|j d d}t|d krtd|d}|d}|dkrN|dkrNd}t|j |dj ||}|jt|dS)Ndrz!Error reading SSH protocol bannerzSSH-zBanner: z!Indecipherable protocol version ""zRemote version/idstring: {}rrzInvalid SSH bannerrz1.99z2.0z(Incompatible version ({} instead of 2.0)z!Connected (version {}, client {}))rangerrreadliner^rr[rrorrrfindrrr) rir$bufrZsegsversionclientrrdrdrers>     zTransport._check_bannerc sn|jjz|jjWd|jjXd|_d|_|jrdfdd|jD}|j dkrt |dkrfdd|j j D}||j _ t tt |jjj|j}n|j}t}|jt|jtjd |j|j|j||j|j|j|j|j|j|j|j|j|j|j|j|jt|jt|jd|j d|j!|_"|j#|dS) z announce to the other side that we'd like to negotiate keys, and what kind of key negotiation we support. NFTz!diffie-hellman-group-exchange-shacsg|]}|jr|qSrd) startswith)rr)mp_required_prefixrdre sz,Transport._send_kex_init..rcsg|]}|js|qSrd)r)rr)rrdrersr)$rrFrrrPrrrr r-rrr r5filterrr  __contains__r rMrJrrdrbrcZadd_listrrrrKbytesrmrLrtrr)rZkex_mpZpkexavailable_server_keysrTrd)rrerfsH                     zTransport._send_kex_initcCs|jd|j}|j}|j}|j}|j}|j}|j}|j} |j} |j} |j} |j|jtdt|dt|dt|dt|dt|dt|dt|d t| d t| d t| d t| |jrtt |j j |} ntt |j |j } t | d kr:t d|j| d ||_|jtdj| d |jrtt t|jjj |j}tt |j |}ntt |j |j}t |d krt d|d |_|jr|jdkrt d|jd|d |d |jr.tt |jj |}tt |jj |}n$tt |j |j}tt |j |j}t |d ksnt |d krvt d|d |_|d |_|jd|j|jd|jrtt |jj |}tt |jj |}n$tt |j |j}tt |j |j}t |d ks t |d krt d|d |_|d |_|jd|j|jd|jrjtt |jj |}tt |jj | }n$tt |j |j}tt | j |j}t |d kst |d krd}|d7}t |j|||j|d |_|d |_|jd|j|jdt |j!|_"dS)Nrz kex algos:z server key:z client encrypt:z server encrypt:z client mac:z server mac:z client compress:z server compress:z client lang:z server lang:z kex follows?rz3Incompatible ssh peer (no acceptable kex algorithm)zKex agreed: {}z.Incompatible ssh peer (no acceptable host key)z;Incompatible ssh peer (can't match requested host key type)ZHostKeyz/Incompatible ssh server (no acceptable ciphers)r )rrz,Incompatible ssh server (no acceptable macs)ZMACz3Incompatible ssh server (no acceptable compression)z {!r} {!r} {!r}Z Compression)# get_bytesZget_list get_booleanrZrorrrr5rr rrr[ _kex_inforrrr r rr,rrrrrrrrrrrZ get_so_farr)rrTZ kex_algo_listZserver_key_algo_listZclient_encrypt_algo_listZserver_encrypt_algo_listZclient_mac_algo_listZserver_mac_algo_listZclient_compress_algo_listZserver_compress_algo_listZclient_lang_listZserver_lang_listZ kex_followsZ agreed_kexrZ agreed_keysZagreed_local_ciphersZagreed_remote_ciphersZagreed_remote_macsZagreed_local_macsZagreed_remote_compressionZagreed_local_compressionrrdrdrers                 zTransport._parse_kex_initc Cs*|j|jd}|jr<|jd|}|jd|j|jd}n$|jd|}|jd|j|jd}|j|j|||j}d|jk}|j|jd}|j|jd }|jr|jd |j}n|jd |j}|j j ||||||d |j |j d } | dk r&|j dks |j r&|jtd|j j| dS)zMswitch on newly negotiated encryption parameters for inbound trafficz block-sizeACzkey-sizeBDzetm@openssh.comrrEF)etmrNzzlib@openssh.comz$Switching on inbound compression ...)rrrrr_DECRYPTr _mac_info digest_sizerZset_inbound_cipher_compression_inforrrorset_inbound_compressor) r block_sizeZIV_inZkey_inenginermac_size mac_enginemac_key compress_inrdrdre_activate_inbound s.     zTransport._activate_inboundc Csnt}|jt|j||j|jd}|jrV|jd|}|jd|j|jd}n$|jd|}|jd|j|jd}|j|j|||j }d|j k}|j |j d}|j |j d }|jr|jd |j } n|jd |j } |jj d } |jj||||| | |d |j|jd} | dk rN|jdks4|jrN|jtd|jj| |jjs`d|_|jtdS)zNswitch on newly negotiated encryption parameters for outbound trafficz block-sizerrzkey-sizerrzetm@openssh.comrrrrz-ctr)rrNzzlib@openssh.comz%Switching on outbound compression ...F)rMrJrrrrrrrrrrrendswithrZset_outbound_cipherrrrrorset_outbound_compressorrrrr) rrTrZIV_outZkey_outrrrrrZsdctr compress_outrdrdre_activate_outbound s<         zTransport._activate_outboundcCsrd|_|jdkr:|j|jd}|jtd|jj||jdkrn|j|jd}|jtd|jj|dS)NTzzlib@openssh.comrz%Switching on outbound compression ...rz$Switching on inbound compression ...) rrrrorrrrr)rr rrdrdre _auth_trigger s    zTransport._auth_triggerc Cs|jtd|jd|_|_d|_d|_|jrF|jdkrFt ||_|j sRd|_ |j dk rf|j j |j jsvd|_|jjz|jj Wd|jjXdS)NzSwitch to new keys ...TF)rorrrrrrrrr rrrrrrrrFrrP)rrTrdrdre_parse_newkeys s$        zTransport._parse_newkeyscCs(|j}|j}|jtdj||dS)NzDisconnect (code {:d}): {})rZrrorr)rrTcodedescrdrdrer9 szTransport._parse_disconnectc Cs|j}|jtdj||j}|js@|jtdj|d}nl|dkrr|j}|j}|jj||}|r|f}n:|dkr|j}|j}|jj ||d}n|jj ||}f}t |t kr|}d}|rt }|r|jt|j|n |jt|j|dS)NzReceived global request "{}"z*Rejecting "{}" global request from server.Fz tcpip-forwardzcancel-tcpip-forwardT)rrorrrrrZrZcheck_port_forward_requestZcancel_port_forward_requestZcheck_global_requestrrrMrJrrnr r) rrTrRZ want_replyokr[rextrarrdrdre_parse_global_request> s>     zTransport._parse_global_requestcCs*|jtd||_|jdk r&|jjdS)NzGlobal request successful.)rorrrr)rrTrdrdre_parse_request_successb s  z Transport._parse_request_successcCs*|jtdd|_|jdk r&|jjdS)NzGlobal request denied.)rorrrr)rrTrdrdre_parse_request_failureh s  z Transport._parse_request_failurec Cs|j}|j}|j}|j}|jj|}|dkrD|jtddS|jjzD|j||||jtdj |||j kr|j |j |j |=Wd|jj XdS)Nz%Success for unrequested channel! [??]zSecsh channel {:d} opened.) rZrrrorrrF_set_remote_channelrrrrrP)rrTrSZ server_chanidZserver_window_sizeZserver_max_packet_sizer8rdrdre_parse_channel_open_successn s$       z%Transport._parse_channel_open_successc Cs|j}|j}|j}|jtj|d}|jtdj||||jjzFt |||_ ||j kr|j j |||j kr|j |j|j |=Wd|jjXdS)Nz(unknown code)z&Secsh channel {:d} open FAILED: {}: {})rZrr!rrorrrrFr]rrrrrrP)rrTrSrZ reason_strZ reason_textrdrdre_parse_channel_open_failure s&         z%Transport._parse_channel_open_failurecCsf|j}|j}|j}|j}d}|dkrj|jdk rj|jtd|jjz |j}Wd|jjXn|dkr|j dk r|j}|j} |jtdj || |jjz |j}Wd|jjXn(|dko|j dk r6|j} |j} |j}|j} |jtdj || |jjz |j}Wd|jjXn|j sZ|jtdj |d }t } n|jjz |j}Wd|jjX|d kr|j} |j}|j}|j} |jj||| f| |f} n|jj||} | tkr|jtd j |d }|rrXr?rrCrDrArBrErFrKrLrJrGrHrIrr<r=rr-rr7r8rrpropertyrrr r rrrrrr%r'r*r, staticmethodr4rr9r:r?rBrCrEr>r^r_r`rergrkrYrrrr!r~rrrrryrxrrrvrwrrrrrrrcrorrIrrrQrrrrrrrrVrGrHrrrrrrfrrr r r rrrrrrrrrrr&r'r(r)r*r+rrr,rZ_request_successr-Z_request_failedr.Z_feedr/Z_feed_extendedr0Z_window_adjustr1Z_handle_requestr2Z _handle_eofr3Z _handle_closerrdrdrdrergs     =       " : B (  "  X 6  %  l   U 1 5         &!  +8H$, $~ rgc@seZdZdZdZddZddZddZed d Z e j d d Z ed d Z e j dd Z eddZ e j ddZ eddZ e j ddZ eddZej ddZdS)ra: Simple object containing the security preferences of an ssh transport. These are tuples of acceptable ciphers, digests, key types, and key exchange algorithms, listed in order of preference. Changing the contents and/or order of these fields affects the underlying `.Transport` (but only if you change them before starting the session). If you try to add an algorithm that paramiko doesn't recognize, ``ValueError`` will be raised. If you try to assign something besides a tuple to one of the fields, ``TypeError`` will be raised. _transportcCs ||_dS)N)r%)r transportrdrdrerO szSecurityOptions.__init__cCs dj|jS)zP Returns a string representation of this object, for debugging. z#)rr%)rrdrdrerR szSecurityOptions.__repr__cstt|tkrt|}t|tk r(tdtt|j|jfdd|D}t|dkrbtdt |j||dS)Nzexpected tuple or listcsg|]}|kr|qSrdrd)rn)possiblerdrer^ sz(SecurityOptions._set..rzunknown cipher) rr5r TypeErrorrr%r r ValueErrorr)rr|origr forbiddenrd)r(re_setX s   zSecurityOptions._setcCs|jjS)zSymmetric encryption ciphers)r%r!)rrdrdrerc szSecurityOptions.cipherscCs|jdd|dS)Nr!r)r-)rrrdrdrerh scCs|jjS)z Digest (one-way hash) algorithms)r%r")rrdrdredigestsl szSecurityOptions.digestscCs|jdd|dS)Nr"r)r-)rrrdrdrer.q scCs|jjS)zPublic-key algorithms)r%rs)rrdrdre key_typesu szSecurityOptions.key_typescCs|jdd|dS)Nrsr)r-)rrrdrdrer/z scCs|jjS)zKey exchange algorithms)r%r)rrdrdrer ~ szSecurityOptions.kexcCs|jdd|dS)Nrr)r-)rrrdrdrer  scCs|jjS)zCompression algorithms)r%r)rrdrdrer  szSecurityOptions.compressioncCs|jdd|dS)Nrr)r-)rrrdrdrer  sN)rrrr __slots__rrr-r#rsetterr.r/r r rdrdrdrer@ s      rc@s<eZdZddZddZddZddZd d Zd d Zd S)rcCstj|_tj|_dS)N)riWeakValueDictionary_maprr_lock)rrdrdrer s zChannelMap.__init__c Cs*|jjz||j|<Wd|jjXdS)N)r4rFr3rP)rrSr8rdrdrerM s zChannelMap.putc Cs*|jjz|jj|dS|jjXdS)N)r4rFr3rrP)rrSrdrdrer s zChannelMap.getcCsB|jjz&y |j|=Wntk r,YnXWd|jjXdS)N)r4rFr3r+rP)rrSrdrdrer s   zChannelMap.deletec Cs*|jjzt|jjS|jjXdS)N)r4rFr5r3r6rP)rrdrdrer6 s zChannelMap.valuesc Cs&|jjz t|jS|jjXdS)N)r4rFrr3rP)rrdrdre__len__ s  zChannelMap.__len__N) rrrrrMrrr6r5rdrdrdrer s  r)r __future__rrbrrrrrihashlibrrrrZcryptography.hazmat.backendsrZ&cryptography.hazmat.primitives.ciphersrr r rr Zparamiko.auth_handlerr Zparamiko.ssh_gssr Zparamiko.channelrZparamiko.commonrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;Zparamiko.compressr<r=Zparamiko.dsskeyr>Zparamiko.ed25519keyr?Zparamiko.kex_curve25519r@Zparamiko.kex_gexrArBZparamiko.kex_group1rCZparamiko.kex_group14rDrEZparamiko.kex_group16rFZparamiko.kex_ecdh_nistrGrHrIZparamiko.kex_gssrJrKrLZparamiko.messagerMZparamiko.packetrNrOZparamiko.primesrPZparamiko.py3compatrQrRrSrTrUrVZparamiko.rsakeyrWZparamiko.ecdsakeyrXZparamiko.serverrYZparamiko.sftp_clientrZZparamiko.ssh_exceptionr[r\r]r^Z paramiko.utilr_r`rarbrfatexitregisterrrgrrrrdrdrdres      /             TQ