Ϫf.dZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZmZmZddlmZmZmZdd lmZdd lmZd ZeZeZd Z d Z!dZ"GddejFZ#y)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_hostscf|jjd}tjj |}t j t|jjdxs#tjjt}td}|j||||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-hostsctdddS)N/dev/ttyzr+br) buffering)_open>/usr/lib/python3/dist-packages/twisted/conch/client/default.pyzverifyHostKey..Vs5Ua@r)factoryoptionsr Key fromStringrfromPathrospath expanduser _KNOWN_HOSTSr verifyHostKey) transportrpubKey fingerprint actualHost actualKeykhuis rr$r$'sP""**62J##F+I      % %m 4 X8J8J<8X  B @ AB  B D) <}|j|s|j|vs$|j|j@|xsdS)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) rrrr r!r"r# iterentries matchesHostr<append)rr knownHostskeyTypesentrys rgetHostKeyAlgorithmsrMs (('K277+=+=l+KLJH'')/   T "}}H, ./  trceZdZdZdZdZdZdZdZddZ d Z d Z d Z d Z ed Zeej"dZy)SSHUserAuthClientctjj||g|d|_||_g|_|j s ddg|_yy)Nz ~/.ssh/id_rsaz ~/.ssh/id_dsa)r rO__init__keyAgentr usedFiles identitys)selfuserrargss rrQzSSHUserAuthClient.__init__sM""++D$>>    !0/ BG !rcdtjvr|jds|jj dtjdt j ttj}|jtjd}|j|j|j|jytj j#|y)N SSH_AUTH_SOCKnoagentzusing SSH agent {authSock!r})authSock)r environr_logdebugr ClientCreatorr rSSHAgentClient connectUNIX addCallback _setAgent addErrback _ebSetAgentr rOserviceStarted)rUccds rrfz SSHUserAuthClient.serviceStarteds bjj (i1H IIOO.O9T  ''1E1EFBrzz/:;A MM$.. ) LL)) *  & & 5 5d ;rct|jr,|jjjd|_yyN)rRr%loseConnection)rUs rserviceStoppedz SSHUserAuthClient.serviceStoppeds+ == MM # # 2 2 4 DM rc~||_|jj}|j|j|Srj)rR getPublicKeysaddBothre)rUarhs rrczSSHUserAuthClient._setAgents2 MM ' ' ) $""#rcBtjj|yrj)r rOrf)rUfs rrezSSHUserAuthClient._ebSetAgents""11$7rc|j5 tj|}|cdddS#ttf$rt t dwxYw#1swYyxYw)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)_replaceStdoutStdingetpassKeyboardInterruptr7r4rrUpromptps r _getPasswordzSSHUserAuthClient._getPasswordsf % % ' + +OOF+ + +&w/ + ** +  + +sA3%AAA$Nc|r t|}nQdjt|j|jjj j } |j |jtj}tj|S#t$rtjcYSwxYw)Nz{}@{}'s password: )rformatrVr%getPeerrr{encodesysgetdefaultencodingr succeedrfailrxs r getPasswordzSSHUserAuthClient.getPasswords !&)F)00TYY'((00277F !!&)001G1G1IJA==# # ::<  s!AB((CCc|jr|jj}||S|jjDcgc]}||jvs|}}|j j d|jj||sy|d}|jj|tjj|}|dz }tjj|s|jS tjj|Scc}w#tj$r|jcYSwxYw)z Get a public key from the key agent if possible, otherwise look in the next configured identity file for one. Nz+public key identities: {identities} {files}) identitiesfilesrz.pub)rR getPublicKeyrrTrSr]r^rIr r!r"r3r rfromFile BadKeyError)rUkeyxrfiles rrzSSHUserAuthClient.getPublicKeys ==--,,.C  LL22Nqat~~6MNN  :||--  Qx d#ww!!$' ww~~d#$$& & '88$$T* *O  '$$& & 'sD%D%D**#EEc|js*|jj|j|Stj j|||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} )rSrRsignDatablobr rO)rU publicKeyrs rrzSSHUserAuthClient.signDatasD~~==)))..*:HE E--66tYQ Qrctjj|jd}tjj |sy t j tjj|S#tj$rtdD]}d|jdz} |j|jtj}t j tjj||ccYS#tj t"f$rYnwxYwt j$t#dccYSt&$r!t)t+j,YywxYw)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)r r!r"rSr3r rr rrEncryptedKeyErrorranger{rrgetfilesystemencodingrrrrwr4r stop)rUriryrzs r getPrivateKeyzSSHUserAuthClient.getPrivateKeys* ww!!$.."45ww~~d# ==!2!24!89 9%% 1X >:T^^B=OO))&1889R9R9TUA ==):):4A):)NOO((*5zz*^"<== >    G LLN s=1B3F 4A%DF D:7F 9D::#F (F  F cg}|j5|rt|jd|rt|jd|D]W\}}|jd}|r|jt |4|jt j |Y dddt j|S#1swYxYw)Nzutf-8)rur4decoderI_inputrvr r)rUname instructionprompts responsesryechos rgetGenericAnswersz#SSHUserAuthClient.getGenericAnswers s  % % ' >dkk'*+k((12 ' > w/$$VF^4$$W__V%<=  > >}}Y'' > >s BCCctjtdd}tjtdd}||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 TextIOWrapperr6)clsstdinstdouts r_openTtyzSSHUserAuthClient._openTty/s<  j$!78!!$z4"89f}rc#Ktjtj}}|j\t_t_ dtjj tjj ||ct_t_y#tjj tjj ||ct_t_wxYww)zv Contextmanager that replaces stdout and stdin with /dev/tty and resets them when it is done. N)rrrrclose)roldoutoldins rruz%SSHUserAuthClient._replaceStdoutStdin=s CII #  3: 2  JJ    IIOO $*E !CJ  JJ    IIOO $*E !CJ s AC9 B! AC9!AC66C9rj)__name__ __module__ __qualname__rQrfrlrcrer{rrrrr classmethodr contextlibcontextmanagerrurrrrOrOsqC <!  8+" $'8 R2 (   2 2rrO)$__doc__rrvrr rbase64rtwisted.conch.clientrtwisted.conch.client.knownhostsrrtwisted.conch.errorrtwisted.conch.sshrr r twisted.internetr r r twisted.python.compatrtwisted.python.filepathrr#r6rinputrr$rErMrOrrrrsq  &E*4455.,$   0=f$N.s222s2r