o
    ¯bÆM  ã                   @   sP  d Z ddlZddlZddlmZmZmZ ddl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 dd	lmZmZmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddl m!Z! eƒ Z"dd„ Z#dd„ Z$G dd„ dƒZ%eeƒG dd„ de%ƒƒZ&eeƒG dd„ dƒƒZ'dd„ Z(eeƒG dd„ de%e!ƒƒZ)G dd„ dƒZ*G dd „ d ƒZ+dS )!zE
An implementation of the OpenSSH known_hosts database.

@since: 8.2
é    N)ÚErrorÚ
a2b_base64Ú
b2a_base64)Úclosing)Úsha1)Úimplementer)ÚHostKeyChangedÚInvalidEntryÚUserRejectedKey)ÚIKnownHostEntry)ÚBadKeyErrorÚFingerprintFormatsÚKey)Údefer)ÚLogger)ÚnativeString)ÚsecureRandom)ÚFancyEqMixinc                 C   s   t | ƒ ¡ S )z½
    Encode a binary string as base64 with no trailing newline.

    @param s: The string to encode.
    @type s: L{bytes}

    @return: The base64-encoded string.
    @rtype: L{bytes}
    )r   Ústrip)Ús© r   úA/usr/lib/python3/dist-packages/twisted/conch/client/knownhosts.pyÚ
_b64encode    s   
r   c           	      C   sz   |   dd¡}t|ƒdkrtƒ ‚|\}}}|  dd¡}t|ƒdkr*|\}}| d¡}n|d }d}t t|ƒ¡}||||fS )aµ  
    Extract common elements of base64 keys from an entry in a hosts file.

    @param string: A known hosts file entry (a single line).
    @type string: L{bytes}

    @return: a 4-tuple of hostname data (L{bytes}), ssh key type (L{bytes}), key
        (L{Key}), and comment (L{bytes} or L{None}).  The hostname data is
        simply the beginning of the line up to the first occurrence of
        whitespace.
    @rtype: L{tuple}
    Né   é   é   ó   
r   )ÚsplitÚlenr	   Úrstripr   Ú
fromStringr   )	ÚstringÚelementsÚ	hostnamesÚkeyTypeÚkeyAndCommentÚsplitkeyÚ	keyStringÚcommentÚkeyr   r   r   Ú_extractCommon-   s   
r*   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú
_BaseEntryaª  
    Abstract base of both hashed and non-hashed entry objects, since they
    represent keys and key types the same way.

    @ivar keyType: The type of the key; either ssh-dss or ssh-rsa.
    @type keyType: L{bytes}

    @ivar publicKey: The server public key indicated by this line.
    @type publicKey: L{twisted.conch.ssh.keys.Key}

    @ivar comment: Trailing garbage after the key line.
    @type comment: L{bytes}
    c                 C   s   || _ || _|| _d S ©N)r$   Ú	publicKeyr(   )Úselfr$   r-   r(   r   r   r   Ú__init__X   s   
z_BaseEntry.__init__c                 C   s
   | j |kS )a  
        Check to see if this entry matches a given key object.

        @param keyObject: A public key object to check.
        @type keyObject: L{Key}

        @return: C{True} if this entry's key matches C{keyObject}, C{False}
            otherwise.
        @rtype: L{bool}
        )r-   )r.   Ú	keyObjectr   r   r   Ú
matchesKey]   s   
z_BaseEntry.matchesKeyN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r/   r1   r   r   r   r   r+   I   s    r+   c                       s<   e Zd ZdZ‡ fdd„Zedd„ ƒZdd„ Zdd	„ Z‡  Z	S )
Ú
PlainEntryzÖ
    A L{PlainEntry} is a representation of a plain-text entry in a known_hosts
    file.

    @ivar _hostnames: the list of all host-names associated with this entry.
    @type _hostnames: L{list} of L{bytes}
    c                    s   || _ tƒ  |||¡ d S r,   )Ú
_hostnamesÚsuperr/   )r.   r#   r$   r-   r(   ©Ú	__class__r   r   r/   u   s   zPlainEntry.__init__c                 C   s(   t |ƒ\}}}}| | d¡|||ƒ}|S )a¶  
        Parse a plain-text entry in a known_hosts file, and return a
        corresponding L{PlainEntry}.

        @param string: a space-separated string formatted like "hostname
        key-type base64-key-data comment".

        @type string: L{bytes}

        @raise DecodeError: if the key is not valid encoded as valid base64.

        @raise InvalidEntry: if the entry does not have the right number of
        elements and is therefore invalid.

        @raise BadKeyError: if the key, once decoded from base64, is not
        actually an SSH key.

        @return: an IKnownHostEntry representing the hostname and key in the
        input line.

        @rtype: L{PlainEntry}
        ó   ,)r*   r   )Úclsr!   r#   r$   r)   r(   r.   r   r   r   r    y   s   zPlainEntry.fromStringc                 C   s   t |tƒr
| d¡}|| jv S )aT  
        Check to see if this entry matches a given hostname.

        @param hostname: A hostname or IP address literal to check against this
            entry.
        @type hostname: L{bytes}

        @return: C{True} if this entry is for the given hostname or IP address,
            C{False} otherwise.
        @rtype: L{bool}
        úutf-8)Ú
isinstanceÚstrÚencoder7   ©r.   Úhostnamer   r   r   ÚmatchesHost•   s   


zPlainEntry.matchesHostc                 C   s>   d  | j¡| jt| j ¡ ƒg}| jdur| | j¡ d  |¡S )a  
        Implement L{IKnownHostEntry.toString} by recording the comma-separated
        hostnames, key type, and base-64 encoded key.

        @return: The string representation of this entry, with unhashed hostname
            information.
        @rtype: L{bytes}
        r;   Nó    )Újoinr7   r$   r   r-   Úblobr(   Úappend©r.   Úfieldsr   r   r   ÚtoString¥   s   

ý

zPlainEntry.toString)
r2   r3   r4   r5   r/   Úclassmethodr    rC   rJ   Ú__classcell__r   r   r9   r   r6   k   s    
r6   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )ÚUnparsedEntryzŒ
    L{UnparsedEntry} is an entry in a L{KnownHostsFile} which can't actually be
    parsed; therefore it matches no keys and no hosts.
    c                 C   ó
   || _ dS )zv
        Create an unparsed entry from a line in a known_hosts file which cannot
        otherwise be parsed.
        N)Ú_string)r.   r!   r   r   r   r/   ¿   s   
zUnparsedEntry.__init__c                 C   ó   dS ©z'
        Always returns False.
        Fr   rA   r   r   r   rC   Æ   ó   zUnparsedEntry.matchesHostc                 C   rP   rQ   r   )r.   r)   r   r   r   r1   Ì   rR   zUnparsedEntry.matchesKeyc                 C   s   | j  d¡S )a  
        Returns the input line, without its newline if one was given.

        @return: The string representation of this entry, almost exactly as was
            used to initialize this entry but without a trailing newline.
        @rtype: L{bytes}
        r   )rO   r   ©r.   r   r   r   rJ   Ò   s   zUnparsedEntry.toStringN)r2   r3   r4   r5   r/   rC   r1   rJ   r   r   r   r   rM   ¸   s    rM   c                 C   s4   t j| td�}t|tƒr| d¡}| |¡ | ¡ S )zù
    Return the SHA-1 HMAC hash of the given key and string.

    @param key: The HMAC key.
    @type key: L{bytes}

    @param string: The string to be hashed.
    @type string: L{bytes}

    @return: The keyed hash value.
    @rtype: L{bytes}
    )Ú	digestmodr=   )ÚhmacÚHMACr   r>   r?   r@   ÚupdateÚdigest)r)   r!   Úhashr   r   r   Ú_hmacedStringÝ   s
   


rZ   c                       sD   e Zd ZdZdZdZ‡ fdd„Zedd„ ƒZdd	„ Z	d
d„ Z
‡  ZS )ÚHashedEntrya�  
    A L{HashedEntry} is a representation of an entry in a known_hosts file
    where the hostname has been hashed and salted.

    @ivar _hostSalt: the salt to combine with a hostname for hashing.

    @ivar _hostHash: the hashed representation of the hostname.

    @cvar MAGIC: the 'hash magic' string used to identify a hashed line in a
    known_hosts file as opposed to a plaintext one.
    s   |1|)Ú	_hostSaltÚ	_hostHashr$   r-   r(   c                    s    || _ || _tƒ  |||¡ d S r,   )r\   r]   r8   r/   )r.   ÚhostSaltÚhostHashr$   r-   r(   r9   r   r   r/     s   zHashedEntry.__init__c           
      C   s^   t |ƒ\}}}}|t| jƒd…  d¡}t|ƒdkrtƒ ‚|\}}| t|ƒt|ƒ|||ƒ}	|	S )a#  
        Load a hashed entry from a string representing a line in a known_hosts
        file.

        @param string: A complete single line from a I{known_hosts} file,
            formatted as defined by OpenSSH.
        @type string: L{bytes}

        @raise DecodeError: if the key, the hostname, or the is not valid
            encoded as valid base64

        @raise InvalidEntry: if the entry does not have the right number of
            elements and is therefore invalid, or the host/hash portion contains
            more items than just the host and hash.

        @raise BadKeyError: if the key, once decoded from base64, is not
            actually an SSH key.

        @return: The newly created L{HashedEntry} instance, initialized with the
            information from C{string}.
        Nó   |r   )r*   r   ÚMAGICr   r	   r   )
r<   r!   Ústuffr$   r)   r(   ÚsaltAndHashr^   r_   r.   r   r   r   r      s   zHashedEntry.fromStringc                 C   s   t  t| j|ƒ| j¡S )a…  
        Implement L{IKnownHostEntry.matchesHost} to compare the hash of the
        input to the stored hash.

        @param hostname: A hostname or IP address literal to check against this
            entry.
        @type hostname: L{bytes}

        @return: C{True} if this entry is for the given hostname or IP address,
            C{False} otherwise.
        @rtype: L{bool}
        )rU   Úcompare_digestrZ   r\   r]   rA   r   r   r   rC   '  s   ÿzHashedEntry.matchesHostc                 C   sR   | j d t| jƒt| jƒg¡ | jt| j ¡ ƒg}| jdur$| 	| j¡ d |¡S )zï
        Implement L{IKnownHostEntry.toString} by base64-encoding the salt, host
        hash, and key.

        @return: The string representation of this entry, with the hostname part
            hashed.
        @rtype: L{bytes}
        r`   NrD   )
ra   rE   r   r\   r]   r$   r-   rF   r(   rG   rH   r   r   r   rJ   8  s   
ÿü

zHashedEntry.toString)r2   r3   r4   r5   ra   ÚcompareAttributesr/   rK   r    rC   rJ   rL   r   r   r9   r   r[   ñ   s    
r[   c                   @   sX   e Zd ZdZdd„ Zedd„ ƒZdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ Zedd„ ƒZdS )ÚKnownHostsFileaz  
    A structured representation of an OpenSSH-format ~/.ssh/known_hosts file.

    @ivar _added: A list of L{IKnownHostEntry} providers which have been added
        to this instance in memory but not yet saved.

    @ivar _clobber: A flag indicating whether the current contents of the save
        path will be disregarded and potentially overwritten or not.  If
        C{True}, this will be done.  If C{False}, entries in the save path will
        be read and new entries will be saved by appending rather than
        overwriting.
    @type _clobber: L{bool}

    @ivar _savePath: See C{savePath} parameter of L{__init__}.
    c                 C   s   g | _ || _d| _dS )a$  
        Create a new, empty KnownHostsFile.

        Unless you want to erase the current contents of C{savePath}, you want
        to use L{KnownHostsFile.fromPath} instead.

        @param savePath: The L{FilePath} to which to save new entries.
        @type savePath: L{FilePath}
        TN)Ú_addedÚ	_savePathÚ_clobber)r.   ÚsavePathr   r   r   r/   ]  s   

zKnownHostsFile.__init__c                 C   s   | j S )z<
        @see: C{savePath} parameter of L{__init__}
        )rh   rS   r   r   r   rj   k  s   zKnownHostsFile.savePathc                 c   sÄ   � | j D ]}|V  q| jrdS z| j ¡ }W n
 ty    Y dS w |�5 |D ])}z| tj¡r5t |¡}nt	 |¡}W n t
ttfyK   t|ƒ}Y nw |V  q&W d  ƒ dS 1 s[w   Y  dS )aK  
        Iterate over the host entries in this file.

        @return: An iterable the elements of which provide L{IKnownHostEntry}.
            There is an element for each entry in the file as well as an element
            for each added but not yet saved entry.
        @rtype: iterable of L{IKnownHostEntry} providers
        N)rg   ri   rh   ÚopenÚOSErrorÚ
startswithr[   ra   r    r6   ÚDecodeErrorr	   r   rM   )r.   ÚentryÚfpÚliner   r   r   Úiterentriesr  s.   €
	ÿ
€ÿø"ÿzKnownHostsFile.iterentriesc                 C   sx   t |  ¡ t| jƒ ƒD ].\}}| |¡r9|j| ¡ kr9| |¡r# dS |dk r,d}d}n|d }| j}t	|||ƒ‚qdS )a  
        Check for an entry with matching hostname and key.

        @param hostname: A hostname or IP address literal to check for.
        @type hostname: L{bytes}

        @param key: The public key to check for.
        @type key: L{Key}

        @return: C{True} if the given hostname and key are present in this file,
            C{False} if they are not.
        @rtype: L{bool}

        @raise HostKeyChanged: if the host key found for the given hostname
            does not match the given key.
        Tr   Nr   F)
Ú	enumeraterr   r   rg   rC   r$   ÚsshTyper1   rh   r   )r.   rB   r)   Úlineidxro   rq   Úpathr   r   r   Ú
hasHostKey‘  s   
€zKnownHostsFile.hasHostKeyc                    s.   t  ˆjˆ ˆ¡}‡ ‡‡‡‡fdd„}| |¡S )a¹  
        Verify the given host key for the given IP and host, asking for
        confirmation from, and notifying, the given UI about changes to this
        file.

        @param ui: The user interface to request an IP address from.

        @param hostname: The hostname that the user requested to connect to.

        @param ip: The string representation of the IP address that is actually
        being connected to.

        @param key: The public key of the server.

        @return: a L{Deferred} that fires with True when the key has been
            verified, or fires with an errback when the key either cannot be
            verified or has changed.
        @rtype: L{Deferred}
        c                    s¨   | r!ˆ  ˆˆ¡sˆ dˆ ¡ tˆƒf ¡ ˆ ˆˆ¡ ˆ ¡  | S ‡ ‡‡‡fdd„}ˆ ¡ }|dkr4d}dtˆ ƒtˆƒ|ˆjtjd�f }ˆ 	| 
t ¡ ¡¡}| |¡S )NzZWarning: Permanently added the %s host key for IP address '%s' to the list of known hosts.c                    s.   | rˆ  ˆ ˆ¡ ˆ  ˆˆ¡ ˆ ¡  | S tƒ ‚r,   )Ú
addHostKeyÚsaver
   )Úresponse)rB   Úipr)   r.   r   r   ÚpromptResponseÕ  s   zGKnownHostsFile.verifyHostKey.<locals>.gotHasKey.<locals>.promptResponseÚECÚECDSAz‘The authenticity of host '%s (%s)' can't be established.
%s key fingerprint is SHA256:%s.
Are you sure you want to continue connecting (yes/no)? )Úformat)rw   ÚwarnÚtyper   rx   ry   Úfingerprintr   ÚSHA256_BASE64Úpromptr@   ÚsysÚgetdefaultencodingÚaddCallback)Úresultr|   Úkeytyper„   Úproceed©rB   r{   r)   r.   Úuir   r   Ú	gotHasKeyÈ  s0   þÿ	üüÿ
z/KnownHostsFile.verifyHostKey.<locals>.gotHasKey)r   ÚmaybeDeferredrw   r‡   )r.   rŒ   rB   r{   r)   Úhhkr�   r   r‹   r   ÚverifyHostKey²  s   
*zKnownHostsFile.verifyHostKeyc                 C   s6   t dƒ}| ¡ }t|t||ƒ||dƒ}| j |¡ |S )aï  
        Add a new L{HashedEntry} to the key database.

        Note that you still need to call L{KnownHostsFile.save} if you wish
        these changes to be persisted.

        @param hostname: A hostname or IP address literal to associate with the
            new entry.
        @type hostname: L{bytes}

        @param key: The public key to associate with the new entry.
        @type key: L{Key}

        @return: The L{HashedEntry} that was added.
        @rtype: L{HashedEntry}
        é   N)r   rt   r[   rZ   rg   rG   )r.   rB   r)   Úsaltr$   ro   r   r   r   rx   ô  s
   zKnownHostsFile.addHostKeyc                 C   sŒ   | j  ¡ }| ¡ s| ¡  | jrd}nd}| j  |¡�}| jr2| d dd„ | jD ƒ¡d ¡ g | _W d  ƒ n1 s<w   Y  d| _dS )zM
        Save this L{KnownHostsFile} to the path it was loaded from.
        ÚwbÚabr   c                 S   s   g | ]}|  ¡ ‘qS r   )rJ   )Ú.0ro   r   r   r   Ú
<listcomp>  s    z'KnownHostsFile.save.<locals>.<listcomp>NF)	rh   ÚparentÚisdirÚmakedirsri   rk   rg   ÚwriterE   )r.   ÚpÚmodeÚhostsFileObjr   r   r   ry     s   
ÿ€û
zKnownHostsFile.savec                 C   s   | |ƒ}d|_ |S )aï  
        Create a new L{KnownHostsFile}, potentially reading existing known
        hosts information from the given file.

        @param path: A path object to use for both reading contents from and
            later saving to.  If no file exists at this path, it is not an
            error; a L{KnownHostsFile} with no entries is returned.
        @type path: L{FilePath}

        @return: A L{KnownHostsFile} initialized with entries from C{path}.
        @rtype: L{KnownHostsFile}
        F)ri   )r<   rv   Ú
knownHostsr   r   r   ÚfromPath   s   zKnownHostsFile.fromPathN)r2   r3   r4   r5   r/   Úpropertyrj   rr   rw   r�   rx   ry   rK   rŸ   r   r   r   r   rf   L  s    
!Brf   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	Ú	ConsoleUIz†
    A UI object that can ask true/false questions and post notifications on the
    console, to be used during key verification.
    c                 C   rN   )aA  
        @param opener: A no-argument callable which should open a console
            binary-mode file-like object to be used for reading and writing.
            This initializes the C{opener} attribute.
        @type opener: callable taking no arguments and returning a read/write
            file-like object
        N)Úopener)r.   r¢   r   r   r   r/   9  s   
zConsoleUI.__init__c                    s"   t  d¡}‡ ‡fdd„}| |¡S )a¿  
        Write the given text as a prompt to the console output, then read a
        result from the console input.

        @param text: Something to present to a user to solicit a yes or no
            response.
        @type text: L{bytes}

        @return: a L{Deferred} which fires with L{True} when the user answers
            'yes' and L{False} when the user answers 'no'.  It may errback if
            there were any I/O errors.
        Nc                    s~   t ˆ  ¡ ƒ�/}| ˆ¡ 	 | ¡  ¡  ¡ }|dkr"	 W d   ƒ dS |dkr/	 W d   ƒ dS | d¡ q1 s8w   Y  d S )NTs   yess   noFs   Please type 'yes' or 'no': )r   r¢   rš   Úreadliner   Úlower)ÚignoredÚfÚanswer©r.   Útextr   r   ÚbodyR  s   
ûù
	ùþzConsoleUI.prompt.<locals>.body)r   Úsucceedr‡   )r.   r©   Údrª   r   r¨   r   r„   C  s   

zConsoleUI.promptc                 C   s`   z t |  ¡ ƒ�}| |¡ W d  ƒ W dS 1 sw   Y  W dS  ty/   t d¡ Y dS w )zÖ
        Notify the user (non-interactively) of the provided text, by writing it
        to the console.

        @param text: Some information the user is to be made aware of.
        @type text: L{bytes}
        NzFailed to write to console)r   r¢   rš   Ú	ExceptionÚlogÚfailure)r.   r©   r¦   r   r   r   r€   `  s   &ÿÿzConsoleUI.warnN)r2   r3   r4   r5   r/   r„   r€   r   r   r   r   r¡   3  s
    
r¡   ),r5   rU   r…   Úbinasciir   rn   r   r   Ú
contextlibr   Úhashlibr   Úzope.interfacer   Útwisted.conch.errorr   r	   r
   Útwisted.conch.interfacesr   Útwisted.conch.ssh.keysr   r   r   Útwisted.internetr   Útwisted.loggerr   Útwisted.python.compatr   Útwisted.python.randbytesr   Útwisted.python.utilr   r®   r   r*   r+   r6   rM   rZ   r[   rf   r¡   r   r   r   r   Ú<module>   s:   "L$Z h