U
    ¹êW[È.  ã                   @   sò   d Z ddlmZ ddlmZ ddlmZmZmZm	Z
 ddlmZ ddlmZ ddl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 ddlZddlZddlZddlZer¼ddl Z dZ!e"Z#dd„ Z$dd„ Z%dd„ Z&G dd„ dej'ƒZ'dS )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}.
é    )Úprint_function)Úlog)ÚnativeStringÚ	raw_inputÚ_PY3Ú_b64decodebytes)ÚFilePath)Ú
ConchError)ÚcommonÚkeysÚuserauth)ÚdeferÚprotocolÚreactor)ÚKnownHostsFileÚ	ConsoleUI)ÚagentNz~/.ssh/known_hostsc                 C   sV   | j jd }tj |¡}t t| j jd p4tj	 
t¡ƒ¡}tdd„ ƒ}| ||||¡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-hostsc                   S   s   t ddddS )Nú/dev/ttyzr+br   )Ú	buffering)Ú_open© r   r   ú>/usr/lib/python3/dist-packages/twisted/conch/client/default.pyÚ<lambda>X   ó    zverifyHostKey.<locals>.<lambda>)ÚfactoryÚoptionsr   ÚKeyZ
fromStringr   ÚfromPathr   ÚosÚpathÚ
expanduserÚ_KNOWN_HOSTSr   ÚverifyHostKey)Ú	transportr   ÚpubKeyZfingerprintZ
actualHostZ	actualKeyZkhZuir   r   r   r$   *   s    (
þr$   c              	   C   s"  t  |¡d }d}|d sHtj tj d¡¡sHtdƒ t tj d¡¡ |d pRt}zt	tj |¡dƒ}W n t
k
r€   Y dS X |’ | ¡ D ]‚}| ¡ }t|ƒdk rªq|dd… \}	}
}| |	 d	¡krÌq|
|krÖqzt|ƒ}W n   Y qY nX ||kr W 5 Q R £ d
S d}qW 5 Q R X |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}
    r   r   z~/.ssh/zCreating ~/.ssh directory...z~/.sshÚrbé   Nó   ,é   é   )r
   ZgetNSr    r!   Úexistsr"   ÚprintÚmkdirr#   ÚopenÚIOErrorÚ	readlinesÚsplitÚlenÚdecodebytes)r   r&   r   ÚkeyTypeZretValZkh_fileZknown_hostsÚliner2   ZhostsZhostKeyTypeZ
encodedKeyZ
decodedKeyr   r   r   ÚisInKnownHosts]   s8    

r7   c                 C   sX   t  t|d ptj t¡ƒ¡}g }| ¡ D ]$}| | ¡r*|j	|kr*| 
|j	¡ q*|pVdS )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}.
    r   N)r   r   r   r    r!   r"   r#   ZiterentriesZmatchesHostr5   Úappend)r   r   Z
knownHostsZkeyTypesÚentryr   r   r   ÚgetHostKeyAlgorithms…   s    
þ

r:   c                   @   s„   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	d
„ Zdd„ Zddd„Z	dd„ Z
dd„ Zdd„ Zdd„ Zedd„ ƒZeejdd„ ƒƒZdS )ÚSSHUserAuthClientc                 G   s:   t jj| |f|žŽ  d | _|| _g | _|js6ddg|_d S )Nz~/.ssh/id_rsaz~/.ssh/id_dsa)r   r;   Ú__init__ÚkeyAgentr   Ú	usedFilesÚ	identitys)ÚselfÚuserr   Úargsr   r   r   r<       s    zSSHUserAuthClient.__init__c                 C   sf   dt jkrV| jd sVt d¡ t ttj	¡}| 
t jd ¡}| | j¡ | | j¡ ntj | ¡ d S )NZSSH_AUTH_SOCKZnoagentzusing agent)r    Úenvironr   r   Úmsgr   ZClientCreatorr   r   ZSSHAgentClientZconnectUNIXZaddCallbackÚ	_setAgentZ
addErrbackÚ_ebSetAgentr   r;   ÚserviceStarted)r@   ZccÚdr   r   r   rG   ©   s    
z SSHUserAuthClient.serviceStartedc                 C   s   | j r| j j ¡  d | _ d S ©N)r=   r%   ZloseConnection©r@   r   r   r   ÚserviceStopped´   s    z SSHUserAuthClient.serviceStoppedc                 C   s    || _ | j  ¡ }| | j¡ |S rI   )r=   ZgetPublicKeysZaddBothrF   )r@   ÚarH   r   r   r   rE   º   s    
zSSHUserAuthClient._setAgentc                 C   s   t j | ¡ d S rI   )r   r;   rG   )r@   Úfr   r   r   rF   Á   s    zSSHUserAuthClient._ebSetAgentc              
   C   s\   |   ¡ J zt |¡}|W W  5 Q R £ S  ttfk
rL   tƒ  tdƒ‚Y nX W 5 Q R X dS )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}
        ZPEBKACN)Ú_replaceStdoutStdinÚgetpassÚKeyboardInterruptr0   r-   r	   ©r@   ÚpromptÚpr   r   r   Ú_getPasswordÅ   s    	

zSSHUserAuthClient._getPasswordNc                 C   sl   |rt |ƒ}ndt | jƒ| jj ¡ jf }z |  |¡ t ¡ ¡}t	 
|¡W S  tk
rf   t	 ¡  Y S X d S )Nz%s@%s's password: )r   rA   r%   ZgetPeerr   rT   ÚencodeÚsysÚgetdefaultencodingr   Úsucceedr	   ÚfailrQ   r   r   r   ÚgetPassword×   s    
ÿzSSHUserAuthClient.getPasswordc                    sÒ   ˆ j rˆ j  ¡ }|dk	r|S ‡ fdd„ˆ jjD ƒ}t tˆ jjƒ¡ t t|ƒ¡ |sZdS |d }t |¡ ˆ j |¡ t	j
 |¡}|d7 }t	j
 |¡s ˆ  ¡ S ztj |¡W S  tjk
rÌ   ˆ  ¡  Y S X dS )z‡
        Get a public key from the key agent if possible, otherwise look in
        the next configured identity file for one.
        Nc                    s   g | ]}|ˆ j kr|‘qS r   )r>   )Ú.0ÚxrJ   r   r   Ú
<listcomp>ñ   s     
 z2SSHUserAuthClient.getPublicKey.<locals>.<listcomp>r   z.pub)r=   ÚgetPublicKeyr   r?   r   rD   Ústrr>   r8   r    r!   r"   r,   r   r   ÚfromFileÚBadKeyError)r@   ÚkeyÚfilesÚfiler   rJ   r   r^   è   s(    

zSSHUserAuthClient.getPublicKeyc                 C   s,   | j s| j | ¡ |¡S tj | ||¡S d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}
        N)r>   r=   ÚsignDataZblobr   r;   )r@   Z	publicKeyre   r   r   r   re     s    zSSHUserAuthClient.signDatac                 C   sô   t j | jd ¡}t j |¡s"dS zt tj 	|¡¡W S  tj
k
rÎ   tdƒD ]v}d| jd  }z4|  |¡ t ¡ ¡}t tjj	||d¡W    Y S  tjtfk
r°   Y nX t tdƒ¡   Y S ‚ Y n" tk
rî   tƒ  t ¡  Y nX dS )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(   zEnter passphrase for key '%s': )Z
passphrasezbad password)r    r!   r"   r>   r,   r   rX   r   r   r`   ZEncryptedKeyErrorÚrangerT   rU   rV   Úgetfilesystemencodingra   r	   rY   rP   r-   r   Ústop)r@   rd   ÚirR   rS   r   r   r   ÚgetPrivateKey  s(    
ÿ zSSHUserAuthClient.getPrivateKeyc              	   C   s‚   g }|   ¡ f |r t| d¡ƒ |r2t| d¡ƒ |D ]6\}}| d¡}|r\| t|ƒ¡ q6| t |¡¡ q6W 5 Q R X t |¡S )Nzutf-8)rN   r-   Údecoder8   r   rO   r   rX   )r@   ÚnameZinstructionZpromptsZ	responsesrR   Zechor   r   r   ÚgetGenericAnswers,  s    

z#SSHUserAuthClient.getGenericAnswersc                 C   s4   t ddƒ}t ddƒ}tr,t |¡}t |¡}||fS )ah  
        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.
                A L{tuple} of binary files on Python 2.
        r   r'   Úwb)r/   r   ÚioÚTextIOWrapper)ÚclsÚstdinÚstdoutr   r   r   Ú_openTty<  s    



zSSHUserAuthClient._openTtyc              	   c   sR   t jt j }}|  ¡ \t _t _z
dV  W 5 t j ¡  t j ¡  || t _t _X dS )zv
        Contextmanager that replaces stdout and stdin with /dev/tty
        and resets them when it is done.
        N)rV   rt   rs   ru   Úclose)rr   ZoldoutZoldinr   r   r   rN   O  s    


z%SSHUserAuthClient._replaceStdoutStdin)N)Ú__name__Ú
__module__Ú__qualname__r<   rG   rK   rE   rF   rT   rZ   r^   re   rk   rn   Úclassmethodru   Ú
contextlibÚcontextmanagerrN   r   r   r   r   r;   ž   s    	

r;   )(Ú__doc__Z
__future__r   Ztwisted.pythonr   Ztwisted.python.compatr   r   r   r   r4   Ztwisted.python.filepathr   Ztwisted.conch.errorr	   Ztwisted.conch.sshr
   r   r   Ztwisted.internetr   r   r   Ztwisted.conch.client.knownhostsr   r   Ztwisted.conch.clientr   r    rV   rO   r{   rp   r#   r/   r   r$   r7   r:   r;   r   r   r   r   Ú<module>   s$   	 3(