Ϫf u^dZgdZddlZddlmZddlmZddlmZm Z ddl m Z ddl m Z dd lmZmZdd lmZdd lmZmZdd lmZdd lmZddlmZddlmZddlmZm Z m!Z!ddl"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0ddl1m2Z2ddl3m4Z4Gdde5Z6GddeZ7GddZ8Gdd eZ9Gd!d"eZ:Gd#d$eZ;Gd%d&eZ<e e)Gd'd(Z=Gd)d*Z>e e7Gd+d,Z?e e7Gd-d.Z@y)/z7 Endpoint implementations of various SSH interactions. )AuthenticationFailedSSHCommandAddressSSHCommandClientEndpointN) expanduser)unpack) Interface implementer)SSHAgentClient) _KNOWN_HOSTS) ConsoleUIKnownHostsFile) SSHChannel)NSgetNS) SSHConnection)Key)SSHClientTransport)SSHUserAuthClient)CancelledErrorDeferredsucceed)TCP4ClientEndpointconnectProtocol)ConnectionDoneProcessTerminated)IStreamClientEndpoint)Factory)Logger) nativeString networkString)Failure)FilePathceZdZdZy)rz` An SSH session could not be established because authentication was not successful. N)__name__ __module__ __qualname____doc__9/usr/lib/python3/dist-packages/twisted/conch/endpoints.pyrr%sr)rceZdZdZdZdZy)_ISSHConnectionCreatorzS An L{_ISSHConnectionCreator} knows how to create SSH connections somehow. cy)z Return a new, connected, secured, but not yet authenticated instance of L{twisted.conch.ssh.transport.SSHServerTransport} or L{twisted.conch.ssh.transport.SSHClientTransport}. Nr(r(r)r*secureConnectionz'_ISSHConnectionCreator.secureConnection2r)cy)a Perform cleanup necessary for a connection object previously returned from this creator's C{secureConnection} method. @param connection: An L{twisted.conch.ssh.transport.SSHServerTransport} or L{twisted.conch.ssh.transport.SSHClientTransport} returned by a previous call to C{secureConnection}. It is no longer needed by the caller of that method and may be closed or otherwise cleaned up as necessary. @param immediate: If C{True} don't wait for any network communication, just close the connection immediately and as aggressively as necessary. Nr() connection immediates r*cleanupConnectionz(_ISSHConnectionCreator.cleanupConnection9r/r)N)r$r%r&r'r.r3r(r)r*r,r,-s  r)r,ceZdZdZdZy)ra$ An L{SSHCommandAddress} instance represents the address of an SSH server, a username which was used to authenticate with that server, and a command which was run there. @ivar server: See L{__init__} @ivar username: See L{__init__} @ivar command: See L{__init__} c.||_||_||_y)a @param server: The address of the SSH server on which the command is running. @type server: L{IAddress} provider @param username: An authentication username which was used to authenticate against the server at the given address. @type username: L{bytes} @param command: A command which was run in a session channel on the server at the given address. @type command: L{bytes} N)serverusernamecommand)selfr6r7r8s r*__init__zSSHCommandAddress.__init__Us    r)N)r$r%r&r'r:r(r)r*rrJs r)rcXeZdZdZdZeZdZdZdZ dZ dZ dZ d Z d Zd Zy ) _CommandChannela A L{_CommandChannel} executes a command in a session channel and connects its input and output to an L{IProtocol} provider. @ivar _creator: See L{__init__} @ivar _command: See L{__init__} @ivar _protocolFactory: See L{__init__} @ivar _commandConnected: See L{__init__} @ivar _protocol: An L{IProtocol} provider created using C{_protocolFactory} which is hooked up to the running command's input and output streams. ssessioncttj|||_||_||_||_d|_y)a @param creator: The L{_ISSHConnectionCreator} provider which was used to get the connection which this channel exists on. @type creator: L{_ISSHConnectionCreator} provider @param command: The command to be executed. @type command: L{bytes} @param protocolFactory: A client factory to use to build a L{IProtocol} provider to use to associate with the running command. @param commandConnected: A L{Deferred} to use to signal that execution of the command has failed or that it has succeeded and the command is now running. @type commandConnected: L{Deferred} N)rr:_creator_command_protocolFactory_commandConnected_reason)r9creatorr8protocolFactorycommandConnecteds r*r:z_CommandChannel.__init__xs7" D!  /!1 r)c:|jj|y)z When the request to open a new channel to run this command in fails, fire the C{commandConnected} deferred with a failure indicating that. NrAerrbackr9reasons r* openFailedz_CommandChannel.openFaileds &&v.r)c|jj|dt|jd}|j |j |j y)z When the request to open a new channel to run this command in succeeds, issue an C{"exec"} request to run the command. sexecT) wantReplyN)conn sendRequestrr? addCallbacks _execSuccess _execFailure)r9ignoredr8s r* channelOpenz_CommandChannel.channelOpensM ))'' '2dmm,(  T..0A0ABr)c:|jj|y)a When the request to execute the command in this channel fails, fire the C{commandConnected} deferred with a failure indicating this. @param reason: The cause of the command execution failure. @type reason: L{Failure} NrGrIs r*rRz_CommandChannel._execFailures &&v.r)c|jjt|jjjj |jjj j|jjj j|_ |jj||jj|jy)a When the request to execute the command in this channel succeeds, use C{protocolFactory} to build a protocol to handle the command's input and output and connect the protocol to a transport representing those streams. Also fire C{commandConnected} with the created protocol after it is connected to its transport. @param ignored: The (ignored) result of the execute request N) r@ buildProtocolrrN transportgetPeerrCr7r8 _protocolmakeConnectionrAcallback)r9rSs r*rQz_CommandChannel._execSuccesss..<<  ##--557 ##++44 ##++33   %%d+ ''7r)c:|jj|y)z When the command's stdout data arrives over the channel, deliver it to the protocol instance. @param data: The bytes from the command's stdout. @type data: L{bytes} N)rZ dataReceivedr9datas r*r^z_CommandChannel.dataReceiveds ##D)r)cPtd|\}|dk7rt|dd|_yy)a When the server sends the command's exit status, record it for later delivery to the protocol. @param data: The network-order four byte representation of the exit status of the command. @type data: L{bytes} z>LrN)rrrB)r9r`statuss r*request_exit_statusz#_CommandChannel.request_exit_statuss.4&  Q;,VT4@DL r)cPt|\}}tt|dd|dd}}t|\}}t|\}}dt|}t t |d}|j jd|||jd|td|d|_ y) a When the server sends the command's exit status, record it for later delivery to the protocol. @param data: The network-order four byte representation of the exit signal of the command. @type data: L{bytes} rNSIGzProcess exited with signal {shortSignalName!r}; core dumped: {coreDumped}; error message: {errorMessage}; language: {languageTag!r}zutf-8)shortSignalName coreDumped errorMessage languageTag) rboolordrgetattrsignal_loginfodecoderrB)r9r`rhrirjrk signalNamesignalIDs r*request_exit_signalz#_CommandChannel.request_exit_signals!&d D1I/abD "4[ d!$K T<89: 6:r2  ),!%,,W5#  )x> r)c|jj|jd|j t d}n |j}|j j t|y)zf When the channel closes, deliver disconnection notification to the protocol. FNzssh channel closed)r>r3rNrBrrZconnectionLostr!rIs r*closedz_CommandChannel.closedsP '' 59 << #$89F\\F %%gfo6r)N)r$r%r&r'namerrpr:rKrTrRrQr^rcrurxr(r)r*r<r<hsD  D 8D0/C/8,* A?6 7r)r<ceZdZdZdZdZy)_ConnectionReadyz L{_ConnectionReady} is an L{SSHConnection} (an SSH service) which only propagates the I{serviceStarted} event to a L{Deferred} to be handled elsewhere. c<tj|||_y)zo @param ready: A L{Deferred} which should be fired when I{serviceStarted} happens. N)rr:_ready)r9readys r*r:z_ConnectionReady.__init__s t$ r)c>|jj||`y)z When the SSH I{connection} I{service} this object represents is ready to be used, fire the C{connectionReady} L{Deferred} to publish that event to some other interested party. N)r}r\r9s r*serviceStartedz_ConnectionReady.serviceStarteds T" Kr)N)r$r%r&r'r:rr(r)r*r{r{s r)r{cFeZdZdZdZdZdZdZdZdZ dZ dZ dZ d Z y) _UserAuthaG L{_UserAuth} implements the client part of SSH user authentication in the convenient way a user might expect if they are familiar with the interactive I{ssh} command line client. L{_UserAuth} supports key-based authentication, password-based authentication, and delegating authentication to an agent. Nc|j|jjS|jr!|jjd|_nd|_|jj S)a~ Retrieve the next public key object to offer to the server, possibly delegating to an authentication agent if there is one. @return: The public part of a key pair that could be used to authenticate with the server, or L{None} if there are no more public keys to try. @rtype: L{twisted.conch.ssh.keys.Key} or L{None} Nr)agent getPublicKeykeyspopkeypublicrs r*rz_UserAuth.getPublicKey(sT :: !::**, , 99yy}}Q'DHDHxx  r)c|j*|jj|j|Stj|||S)z Extend the base signing behavior by using an SSH agent to sign the data, if one is available. @type publicKey: L{Key} @type signData: L{str} )rsignDatablobr)r9 publicKeyrs r*rz_UserAuth.signData;sA :: !::&&y~~'7B B$--dIxH Hr)c,t|jS)a Get the private part of a key pair to use for authentication. The key corresponds to the public part most recently returned from C{getPublicKey}. @return: A L{Deferred} which fires with the private key. @rtype: L{Deferred} )rrrs r* getPrivateKeyz_UserAuth.getPrivateKeyHstxx  r)cF|jyt|jS)z Get the password to use for authentication. @return: A L{Deferred} which fires with the password, or L{None} if the password was not specified. N)passwordrrs r* getPasswordz_UserAuth.getPasswordSs  == t}}%%r)cPd|j_tj||S)z Handle user authentication success in the normal way, but also make a note of the state change on the L{_CommandTransport}. s CHANNELLING)rX_staterssh_USERAUTH_SUCCESS)r9packets r*rz_UserAuth.ssh_USERAUTH_SUCCESS^s# !/ 55dFCCr)ct}t|_|j|}fd}|j ||S)as Set up a connection to the authentication agent and trigger its initialization. @param endpoint: An endpoint which can be used to connect to the authentication agent. @type endpoint: L{IStreamClientEndpoint} provider @return: A L{Deferred} which fires when the agent connection is ready for use. c2|_|jSN)r getPublicKeys)rr9s r* connectedz+_UserAuth.connectToAgent..connectedvsDJ&&( (r))rr protocolconnect addCallback)r9endpointfactorydrs` r*connectToAgentz_UserAuth.connectToAgentfs<))   W % ) i r)cf|jy|jjjy)z' Disconnect the agent. N)rrXloseConnectionrs r*loseAgentConnectionz_UserAuth.loseAgentConnection}s' ::   ++-r))r$r%r&r'rrrrrrrrrrr(r)r*rrs=H D E!& I ! &D..r)rc:eZdZdZdZdZdZdZdZdZ dZ dZ y) _CommandTransporta L{_CommandTransport} is an SSH client I{transport} which includes a host key verification step before it will proceed to secure the connection. L{_CommandTransport} also knows how to set up a connection to an authentication agent if it is told where it can connect to one. @ivar _userauth: The L{_UserAuth} instance which is in charge of the overall authentication process or L{None} if the SSH connection has not reach yet the C{user-auth} service. @type _userauth: L{_UserAuth} sSTARTINGNcztfd_fd}jj||_y)z @param creator: The L{_NewConnectionHelper} that created this connection. @type creator: L{_NewConnectionHelper}. c8jjSr)rXabortConnection)rr9s r*z,_CommandTransport.__init__..s$..2P2P2Rr)cd_|Sr)connectionReady)resultr9s r* readyFiredz._CommandTransport.__init__..readyFireds#'D Mr)N)rraddBothrC)r9rCrs` r*r:z_CommandTransport.__init__s5 ((RS   $$Z0 r)cn|jj}t|jj j }d|_|jjj|jj||tj|}|j|j|S)a  Ask the L{KnownHostsFile} provider available on the factory which created this protocol this protocol to verify the given host key. @return: A L{Deferred} which fires with the result of L{KnownHostsFile.verifyHostKey}. SECURING)rChostnamer rXrYhostr knownHosts verifyHostKeyuir fromString addErrback_saveHostKeyFailure)r9hostKey fingerprintriprs r*rz_CommandTransport.verifyHostKeys<<(( 4>>11388 9! LL # # 1 1 LLOOXr3>>'+B  T--.r)c||_|S)a+ When host key verification fails, record the reason for the failure in order to fire a L{Deferred} with it later. @param reason: The cause of the host key verification failure. @type reason: L{Failure} @return: C{reason} @rtype: L{Failure} )_hostKeyFailurerIs r*rz%_CommandTransport._saveHostKeyFailures & r)c(d_tj}tjj |_jjj _jjr.tjjj _jj0j jjj}n td}fd}|j|y)zR When the connection is secure, start the authentication process. AUTHENTICATINGNc<jjyr)requestService _userauth)rSr9s r* maybeGotAgentz9_CommandTransport.connectionSecure..maybeGotAgents    /r))rr{rrrCr7rrrlist agentEndpointrrr)r9r8rrs` r*connectionSecurez"_CommandTransport.connectionSecures( "4#7#78"4<<#8#8'B"&,,"7"7 <<  "&t||'8'8"9DNN  << % % 1--dll.H.HIA A 0 - r)cT|jr|jj|jdk(s |jy|jdk(r|j |j}n#|jdk(rt t d}|jj|y)z When the underlying connection to the SSH server is lost, if there were any connection setup errors, propagate them. Also, clean up the connection to the ssh agent if one was created. sRUNNINGNrrz$Connection lost while authenticating)rrrrrr!rrHrIs r*rwz _CommandTransport.connectionLosts >> NN . . 0 ;;* $(<(<(D  ;;+ %$*>*>*J))F [[- -$%KLF $$V,r)) r$r%r&r'rrrr:rrrrwr(r)r*rrs1 FOI($ !.-r)rcPeZdZdZdZe ddZedZdZdZ y) ra L{SSHCommandClientEndpoint} exposes the command-executing functionality of SSH servers. L{SSHCommandClientEndpoint} can set up a new SSH connection, authenticate it in any one of a number of different ways (keys, passwords, agents), launch a command over that connection and then associate its input and output with a protocol. It can also re-use an existing, already-authenticated SSH connection (perhaps one which already has some SSH channels being used for other purposes). In this case it creates a new SSH channel to use to execute the command. Notably this means it supports multiplexing several different command invocations over a single SSH connection. c ||_||_y)at @param creator: An L{_ISSHConnectionCreator} provider which will be used to set up the SSH connection which will be used to run a command. @type creator: L{_ISSHConnectionCreator} provider @param command: The command line to execute on the SSH server. This byte string is interpreted by a shell on the SSH server, so it may have a value like C{"ls /"}. Take care when trying to run a command like C{"/Volumes/My Stuff/a-program"} - spaces (and other special bytes) may require escaping. @type command: L{bytes} N)r>r?)r9rCr8s r*r:z!SSHCommandClientEndpoint.__init__ s   r)Nc <t||||||||| | } || |S)a Create and return a new endpoint which will try to create a new connection to an SSH server and run a command over it. It will also close the connection if there are problems leading up to the command being executed, after the command finishes, or if the connection L{Deferred} is cancelled. @param reactor: The reactor to use to establish the connection. @type reactor: L{IReactorTCP} provider @param command: See L{__init__}'s C{command} argument. @param username: The username with which to authenticate to the SSH server. @type username: L{bytes} @param hostname: The hostname of the SSH server. @type hostname: L{bytes} @param port: The port number of the SSH server. By default, the standard SSH port number is used. @type port: L{int} @param keys: Private keys with which to authenticate to the SSH server, if key authentication is to be attempted (otherwise L{None}). @type keys: L{list} of L{Key} @param password: The password with which to authenticate to the SSH server, if password authentication is to be attempted (otherwise L{None}). @type password: L{bytes} or L{None} @param agentEndpoint: An L{IStreamClientEndpoint} provider which may be used to connect to an SSH agent, if one is to be used to help with authentication. @type agentEndpoint: L{IStreamClientEndpoint} provider @param knownHosts: The currently known host keys, used to check the host key presented by the server we actually connect to. @type knownHosts: L{KnownHostsFile} @param ui: An object for interacting with users to make decisions about whether to accept the server host keys. If L{None}, a L{ConsoleUI} connected to /dev/tty will be used; if /dev/tty is unavailable, an object which answers C{b"no"} to all prompts will be used. @type ui: L{None} or L{ConsoleUI} @return: A new instance of C{cls} (probably L{SSHCommandClientEndpoint}). )_NewConnectionHelper) clsreactorr8r7rportrrrrrhelpers r* newConnectionz&SSHCommandClientEndpoint.newConnections<@&            67##r)c*t|}|||S)ar Create and return a new endpoint which will try to open a new channel on an existing SSH connection and run a command over it. It will B{not} close the connection if there is a problem executing the command or after the command finishes. @param connection: An existing connection to an SSH server. @type connection: L{SSHConnection} @param command: See L{SSHCommandClientEndpoint.newConnection}'s C{command} parameter. @type command: L{bytes} @return: A new instance of C{cls} (probably L{SSHCommandClientEndpoint}). )_ExistingConnectionHelper)rr1r8rs r*existingConnectionz+SSHCommandClientEndpoint.existingConnectionls$+:667##r)cr|jj}|j|j||S)a Set up an SSH connection, use a channel from that connection to launch a command, and hook the stdin and stdout of that command up as a transport for a protocol created by the given factory. @param protocolFactory: A L{Factory} to use to create the protocol which will be connected to the stdin and stdout of the command on the SSH server. @return: A L{Deferred} which will fire with an error if the connection cannot be set up for any reason or with the protocol instance created by C{protocolFactory} once it has been connected to the command. )r>r.r_executeCommand)r9rDrs r*rz SSHCommandClientEndpoint.connects/ MM * * , d**O<r)ct}fd}|j|tjj||}j ||S)a Given a secured SSH connection, try to execute a command in a new channel created on it and associate the result with a protocol from the given factory. @param connection: See L{SSHCommandClientEndpoint.existingConnection}'s C{connection} parameter. @param protocolFactory: See L{SSHCommandClientEndpoint.connect}'s C{protocolFactory} parameter. @return: See L{SSHCommandClientEndpoint.connect}'s return value. cj|jt}jj||Sr)checkrr>r3) passthroughr2r1r9s r*disconnectOnFailurezESSHCommandClientEndpoint._executeCommand..disconnectOnFailures/$)).9I MM + +J B r))rrr<r>r? openChannel)r9r1rDrErchannels`` r*rz(SSHCommandClientEndpoint._executeCommandsU$:  ##$78! MM4==/;K  w'r))NNNNNN) r$r%r&r'r: classmethodrrrrr(r)r*rrsU  $  K$K$Z$$(& r)rc*eZdZdZdZdZddZdZy) _ReadFilez A weakly file-like object which can be used with L{KnownHostsFile} to respond in the negative to all prompts for decisions. c||_y)zk @param contents: L{bytes} which will be returned from every C{readline} call. N _contents)r9contentss r*r:z_ReadFile.__init__s "r)cy)z6 No-op. @param data: ignored Nr(r_s r*writez_ReadFile.writer/r)c|jS)z Always give back the byte string that this L{_ReadFile} was initialized with. @param count: ignored @return: A fixed byte-string. @rtype: L{bytes} r)r9counts r*readlinez_ReadFile.readlines~~r)cy)z No-op. Nr(rs r*closez_ReadFile.closer/r)N)rg)r$r%r&r'r:rrrr(r)r*rrs "   r)rcPeZdZdZeZdZedfdZdZe dZ dZ dZ y ) rz L{_NewConnectionHelper} implements L{_ISSHConnectionCreator} by establishing a brand new SSH connection, securing it, and authenticating. s/dev/ttyc ||_||_|||_||_||_||_||_||_| |j} | |_ | t|j} | |_ | |_ y)z @param tty: The path of the tty device to use in case C{ui} is L{None}. @type tty: L{FilePath} @see: L{SSHCommandClientEndpoint.newConnection} N)rrrr8r7rrr _knownHostsrr _openerrtty) r9rrrr8r7rrrrrrs r*r:z_NewConnectionHelper.__init__s(    DI      *  ))+J$ :4<<(Br)cn |jjdS#t$rtdcYSwxYw)z Open the tty if possible, otherwise give back a file-like object from which C{b"no"} can be read. For use as the opener argument to L{ConsoleUI}. zrb+sno)ropen BaseExceptionrrs r*rz_NewConnectionHelper._opener s6 $88==' ' $U# # $s 44cdtjtt|jS)z @return: A L{KnownHostsFile} instance pointed at the user's personal I{known hosts} file. @rtype: L{KnownHostsFile} )r fromPathr"rr )rs r*rz _NewConnectionHelper._knownHostss%&&x 3;K;K0L'MNNr)ct|}|jt|jt |j |j }t||}|jfd|S)aR Create and return a new SSH connection which has been secured and on which authentication has already happened. @return: A L{Deferred} which fires with the ready-to-use connection or with a failure if something prevents the connection from being setup, secured, or authenticated. cSrr()rSr~s r*rz7_NewConnectionHelper.secureConnection..3ser)) rrrrrrrrr)r9r sshClientrr~s @r*r.z%_NewConnectionHelper.secureConnection"s\%T*((& LL,t}}5tyy  Ix 0 +,r)c|r%|jjjy|jjy)ab Clean up the connection by closing it. The command running on the endpoint has ended so the connection is no longer needed. @param connection: The L{SSHConnection} to close. @type connection: L{SSHConnection} @param immediate: Whether to close connection immediately. @type immediate: L{bool}. N)rXrrr9r1r2s r*r3z&_NewConnectionHelper.cleanupConnection6s3   * * : : <  / / 1r)N) r$r%r&r'r rr"r:rrrr.r3r(r)r*rrsH  L D [ !$L $OO(2r)rc"eZdZdZdZdZdZy)rz L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator} by handing out an existing SSH connection which is supplied to its initializer. c||_y)z~ @param connection: See L{SSHCommandClientEndpoint.existingConnection}'s C{connection} parameter. N)r1)r9r1s r*r:z"_ExistingConnectionHelper.__init__Qs %r)c,t|jS)z~ @return: A L{Deferred} that fires synchronously with the already-established connection object. )rr1rs r*r.z*_ExistingConnectionHelper.secureConnectionXs t''r)cy)a| Do not do any cleanup on the connection. Leave that responsibility to whatever code created it in the first place. @param connection: The L{SSHConnection} which will not be modified in any way. @type connection: L{SSHConnection} @param immediate: An argument which will be ignored. @type immediate: L{bool}. Nr(rs r*r3z+_ExistingConnectionHelper.cleanupConnection`r/r)N)r$r%r&r'r:r.r3r(r)r*rrIs %(  r)r)Ar'__all__roos.pathrstructrzope.interfacerr twisted.conch.client.agentr twisted.conch.client.defaultr twisted.conch.client.knownhostsr r twisted.conch.ssh.channelrtwisted.conch.ssh.commonrrtwisted.conch.ssh.connectionrtwisted.conch.ssh.keysrtwisted.conch.ssh.transportrtwisted.conch.ssh.userauthrtwisted.internet.deferrrrtwisted.internet.endpointsrrtwisted.internet.errorrrtwisted.internet.interfacesrtwisted.internet.protocolrtwisted.loggerrtwisted.python.compatrr twisted.python.failurer!twisted.python.filepathr" Exceptionrr,rr<r{rrrrrrr(r)r*rs$  T 155E0.6&:8DDJD=-!=*,9 Y :