o b.@sdZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZmZmZddlmZmZmZdd lmZdd lmZd ZeZeZd d Z ddZ!ddZ"Gdddej#Z#dS)aN Various classes and functions for implementing user-interaction in the command-line conch client. You probably shouldn't use anything in this module directly, since it assumes you are sitting at an interactive terminal. For example, to programmatically interact with a known_hosts database, use L{twisted.conch.client.knownhosts}. N) decodebytes)agent) ConsoleUIKnownHostsFile) ConchError)commonkeysuserauth)deferprotocolreactor) nativeString)FilePathz~/.ssh/known_hostscCsV|jjd}tj|}tt|jjdptj t }t dd}| ||||S)a% Verify a host's key. This function is a gross vestige of some bad factoring in the client internals. The actual implementation, and a better signature of this logic is in L{KnownHostsFile.verifyHostKey}. This function is not deprecated yet because the callers have not yet been rehabilitated, but they should eventually be changed to call that method instead. However, this function does perform two functions not implemented by L{KnownHostsFile.verifyHostKey}. It determines the path to the user's known_hosts file based on the options (which should really be the options object's job), and it provides an opener to L{ConsoleUI} which opens '/dev/tty' so that the user will be prompted on the tty of the process even if the input and output of the process has been redirected. This latter part is, somewhat obviously, not portable, but I don't know of a portable equivalent that could be used. @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is always the dotted-quad IP address of the host being connected to. @type host: L{str} @param transport: the client transport which is attempting to connect to the given host. @type transport: L{SSHClientTransport} @param fingerprint: the fingerprint of the given public key, in xx:xx:xx:... format. This is ignored in favor of getting the fingerprint from the key itself. @type fingerprint: L{str} @param pubKey: The public key of the server being connected to. @type pubKey: L{str} @return: a L{Deferred} which fires with C{1} if the key was successfully verified, or fails if the key could not be successfully verified. Failure types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or L{KeyboardInterrupt}. host known-hostscSstddddS)N/dev/ttyzr+br) buffering)_openrr>/usr/lib/python3/dist-packages/twisted/conch/client/default.pyVszverifyHostKey..)factoryoptionsrKey fromStringrfromPathrospath expanduser _KNOWN_HOSTSr verifyHostKey) transportrpubKey fingerprint actualHost actualKeykhuirrrr 's (  r c Cs8t|d}d}|ds$tjtjds$tdttjd|dp)t}z t tj|d}Wn t y?YdSw|P| D]B}| }t |dkrTqG|dd\} } } || d vreqG| |krjqGzt| } Wn tyyYqGw| |krWdd Sd }qGWd|S1swY|S) z Checks to see if host is in the known_hosts file for the user. @return: 0 if it isn't, 1 if it is and is the same, 2 if it's changed. @rtype: L{int} rrz~/.ssh/zCreating ~/.ssh directory...z~/.sshrbN,)rgetNSrrexistsrprintmkdirropenOSError readlinessplitlenr BaseException) rr"rkeyTyperetValkh_file known_hostsliner4hosts hostKeyType encodedKey decodedKeyrrrisInKnownHostsZsF       r@cCsXtt|dp tjt}g}|D]}||r'|j |vr'| |j q|p+dS)a Look in known_hosts for a key corresponding to C{host}. This can be used to change the order of supported key types in the KEXINIT packet. @type host: L{str} @param host: the host to check in known_hosts @type options: L{twisted.conch.client.options.ConchOptions} @param options: options passed to client @return: L{list} of L{str} representing key types or L{None}. rN) rrrrrrr iterentries matchesHostr7append)rr knownHostskeyTypesentryrrrgetHostKeyAlgorithmss     rGc@seZdZddZddZddZddZd d Zd d ZdddZ ddZ ddZ ddZ ddZ eddZeejddZd S)SSHUserAuthClientcGs@tjj||g|Rd|_||_g|_|jsddg|_dSdS)Nz ~/.ssh/id_rsaz ~/.ssh/id_dsa)r rH__init__keyAgentr usedFiles identitys)selfuserrargsrrrrIszSSHUserAuthClient.__init__cCstdtjvr2|jds2|jjdtjddtttj }| tjd}| |j | |jdStj|dS)N SSH_AUTH_SOCKnoagentzusing SSH agent {authSock!r})authSock)renvironr_logdebugr ClientCreatorr rSSHAgentClient connectUNIX addCallback _setAgent addErrback _ebSetAgentr rHserviceStarted)rMccdrrrr]s  z SSHUserAuthClient.serviceStartedcCs |jr|jjd|_dSdSN)rJr!loseConnectionrMrrrserviceStoppeds  z SSHUserAuthClient.serviceStoppedcCs ||_|j}||j|Sr`)rJ getPublicKeysaddBothr\)rMar_rrrrZs  zSSHUserAuthClient._setAgentcCstj|dSr`)r rHr])rMfrrrr\szSSHUserAuthClient._ebSetAgentc Cs^|!zt|}|WWdSttfy$ttdw1s(wYdS)z Prompt for a password using L{getpass.getpass}. @param prompt: Written on tty to ask for the input. @type prompt: L{str} @return: The input. @rtype: L{str} NPEBKAC)_replaceStdoutStdingetpassKeyboardInterruptr2r/rrMpromptprrr _getPasswords  zSSHUserAuthClient._getPasswordNcCsf|rt|}ndt|j|jjj}z||t }t |WSt y2t YSw)Nz{}@{}'s password: )r formatrNr!getPeerrroencodesysgetdefaultencodingr succeedrfailrlrrr getPasswords     zSSHUserAuthClient.getPasswordcsjrj}|dur|SfddjjD}jjdjj|d|s(dS|d}j|tj |}|d7}tj |sFSzt j |WSt jy[YSw)z Get a public key from the key agent if possible, otherwise look in the next configured identity file for one. Ncsg|] }|jvr|qSr)rK).0xrbrr sz2SSHUserAuthClient.getPublicKey..z+public key identities: {identities} {files}) identitiesfilesrz.pub)rJ getPublicKeyrrLrTrUrKrCrrrr.rrfromFile BadKeyError)rMkeyr|filerrbrr}s.     zSSHUserAuthClient.getPublicKeycCs(|js |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{bytes} )rKrJsignDatablobr rH)rM publicKeyrrrrrszSSHUserAuthClient.signDatac Cstj|jd}tj|sdSz ttj |WStj yct dD]:}d|jd}z| | t}ttjj ||dWYStjtfyVYnwttdYStysttYdSw)z Try to load the private key from the last used file identified by C{getPublicKey}, potentially asking for the passphrase if the key is encrypted. Nr)zEnter passphrase for key '%s': ) passphrasez bad password)rrrrKr.r rurrr~EncryptedKeyErrorrangerorrrsgetfilesystemencodingrrrvrkr/r stop)rMrirmrnrrr getPrivateKeys(    zSSHUserAuthClient.getPrivateKeycCsg}|8|rt|d|rt|d|D]\}}|d}|r.|t|q|t|qWdn1sAwYt|S)Nzutf-8)rir/decoderC_inputrjr ru)rMname instructionprompts responsesrmechorrrgetGenericAnswers s    z#SSHUserAuthClient.getGenericAnswerscCs(ttdd}ttdd}||fS)a0 Open /dev/tty as two streams one in read, one in write mode, and return them. @return: File objects for reading and writing to /dev/tty, corresponding to standard input and standard output. @rtype: A L{tuple} of L{io.TextIOWrapper} on Python 3. rr(wb)io TextIOWrapperr1)clsstdinstdoutrrr_openTty/s zSSHUserAuthClient._openTtyc csttjtj}}|\t_t_zdVWtjtj||t_t_dStjtj||t_t_w)zv Contextmanager that replaces stdout and stdin with /dev/tty and resets them when it is done. N)rsrrrclose)roldoutoldinrrrri=s   z%SSHUserAuthClient._replaceStdoutStdinr`)__name__ __module__ __qualname__rIr]rcrZr\rorwr}rrr classmethodr contextlibcontextmanagerrirrrrrHs"     rH)$__doc__rrjrrrsbase64rtwisted.conch.clientrtwisted.conch.client.knownhostsrrtwisted.conch.errorrtwisted.conch.sshrrr twisted.internetr r r twisted.python.compatr twisted.python.filepathrrr1rinputrr r@rGrHrrrrs*      3'