U
    
W[öÀ  ã                   @   s8  d Z ddlmZm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 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 edƒrúedƒrúddlmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ndZ+dZ,dZ-dZ.dZ/e	e,ƒZ0e	e-ƒZ1e	e.ƒZ2e	e/ƒZ3de, d Z4de- d Z5de, d Z6de, d Z7G dd„ dƒZ8G d d!„ d!e8eƒZ9G d"d#„ d#e9ƒZ:G d$d%„ d%e8eeƒZ;G d&d'„ d'e;ƒZ<G d(d)„ d)ee8ƒZ=G d*d+„ d+eƒZ>G d,d-„ d-eƒZ?G d.d/„ d/e@ƒZAG d0d1„ d1eƒZBG d2d3„ d3e@ƒZCG d4d5„ d5e@ƒZDG d6d7„ d7eƒZEdS )8z/
Tests for L{twisted.conch.client.knownhosts}.
é    )Úabsolute_importÚdivisionN)ÚErrorÚ
b2a_base64Ú
a2b_base64)ÚverifyObject)ÚnetworkString)ÚrequireModule)ÚFilePath)ÚTestCase)ÚDeferred)ÚIKnownHostEntry)ÚHostKeyChangedÚUserRejectedKeyÚInvalidEntry)ÚComparisonTestsMixinZcryptographyZpyasn1)ÚKeyÚBadKeyError)Ú
PlainEntryÚHashedEntryÚKnownHostsFileÚUnparsedEntryÚ	ConsoleUI)Údefault)Úkeydataz>cryptography and PyASN1 required for twisted.conch.knownhosts.st  AAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3ytNvue4Riqv/SVkPRNwMb7eWH29SviXaBxUhYyzKkDoNUq3rTNnH1Vnif6d6X4JCrUb5d3W+DmYClyJrZ5HgD/hUpdSkTRqdbQ2TrvSAxRacj+vHHT4F4dm1bJSewm3B2D8HVOoi/CbVh3dsIiCdp8VltdZx4qYVfYe2LwVINCbAa3d3tj9ma7RVfw3OH2Mfb+toLd1N5tBQFb7oqTt2nC6I/6Bd4JwPUld+IEitw/suElq/AIJVQXXujeyiZlea90HE65U2mF1ytr17HTAIT2ySokJWyuBANGACk6iIaw==sÈ   AAAAB3NzaC1yc2EAAAABIwAAAIEAwaeCZd3UCuPXhX39+/p9qO028jTF76DMVd9mPvYVDVXufWckKZauF7+0b7qm+ChT7kan6BzRVo4++gCVNfAlMzLysSt3ylmOR48tFpAfygg9UCX3DjHz0ElOOUKh3iifc9aUShD0OPaK3pR5JJ8jfiBfzSYWt/hDi/iZ4igsSs8=st  AAAAB3NzaC1yc2EAAAABIwAAAQEAl/TQakPkePlnwCBRPitIVUTg6Z8VzN1en+DGkyo/evkmLw7o4NWR5qbysk9A9jXW332nxnEuAnbcCam9SHe1su1liVfyIK0+3bdn0YRB0sXIbNEtMs2LtCho/aV3cXPS+Cf1yut3wvIpaRnAzXxuKPCTXQ7/y0IXa8TwkRBH58OJa3RqfQ/NsSp5SAfdsrHyH2aitiVKm2jfbTKzSEqOQG/zq4J9GXTkq61gZugory/Tvl5/yPgSnOR6C9jVOMHf27ZPoRtyj9SY343Hd2QHiIE0KPZJEgCynKeWoKz8v6eTSK8n4rBnaqWdp8MnGZK1WGy05MguXbyCDuTC8AmJXQ==sŒ   AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIFwh3/zBANyPPIE60SMMfdKMYo3OvfvzGLZphzuKrzSt0q4uF+/iYqtYiHhryAwU/fDWlUQ9kck9f+IlpsNtY4=s   www.twistedmatrix.com ssh-rsa ó   
s   divmod.com ssh-rsa s-   www.twistedmatrix.com,198.49.126.131 ssh-rsa sE   |1|gJbSEPBG9ZSBoZpHNtZBD1bHKBA=|bQv+0Xa0dByrwkA1EB0E7Xop/Fo= ssh-rsa c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )ÚEntryTestsMixina<  
    Tests for implementations of L{IKnownHostEntry}.  Subclasses must set the
    'entry' attribute to a provider of that interface, the implementation of
    that interface under test.

    @ivar entry: a provider of L{IKnownHostEntry} with a hostname of
    www.twistedmatrix.com and an RSA key of sampleKey.
    c                 C   s   t t| jƒ dS )zA
        The given entry should provide IKnownHostEntry.
        N)r   r   Úentry©Úself© r    úD/usr/lib/python3/dist-packages/twisted/conch/test/test_knownhosts.pyÚtest_providesInterfaceZ   s    z&EntryTestsMixin.test_providesInterfacec                 C   s,   | j }|  |jt t¡¡ |  |jd¡ dS )a¦  
        Constructing a plain text entry from an unhashed known_hosts entry will
        result in an L{IKnownHostEntry} provider with 'keyString', 'hostname',
        and 'keyType' attributes.  While outside the interface in question,
        these attributes are held in common by L{PlainEntry} and L{HashedEntry}
        implementations; other implementations should override this method in
        subclasses.
        ó   ssh-rsaN)r   ÚassertEqualÚ	publicKeyr   Ú
fromStringÚ	sampleKeyÚkeyType)r   r   r    r    r!   Útest_fromStringa   s    	zEntryTestsMixin.test_fromStringc                 C   s@   t  t¡}t  t¡}|  d| j |¡¡ |  d| j |¡¡ dS )zj
        L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
        SSH key.
        TFN)r   r&   r'   ÚotherSampleKeyr$   r   Ú
matchesKey)r   ZtwistedmatrixDotComZdivmodDotComr    r    r!   Útest_matchesKeyo   s    


þ
þzEntryTestsMixin.test_matchesKeyc                 C   s(   |   | j d¡¡ |  | j d¡¡ dS )zl
        L{IKnownHostEntry.matchesHost} checks to see if an entry matches a
        given hostname.
        ó   www.twistedmatrix.coms   www.divmod.comN)Ú
assertTruer   ÚmatchesHostÚassertFalser   r    r    r!   Útest_matchesHost~   s    z EntryTestsMixin.test_matchesHostN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   r)   r,   r1   r    r    r    r!   r   P   s
   	r   c                   @   s0   e Zd ZdZeZeZdd„ Zdd„ Z	dd„ Z
dS )	ÚPlainEntryTestsz'
    Test cases for L{PlainEntry}.
    c                 C   s   t  | j¡| _dS )zU
        Set 'entry' to a sample plain-text entry with sampleKey as its key.
        N)r   r&   ÚplaintextLiner   r   r    r    r!   ÚsetUp   s    zPlainEntryTests.setUpc                 C   s,   t  | j¡| _|  | j d¡¡ |  ¡  dS )zU
        A "hostname,ip" formatted line will match both the host and the IP.
        s   198.49.126.131N)r   r&   Ú
hostIPLiner   r.   r/   r1   r   r    r    r!   Útest_matchesHostIP–   s    z"PlainEntryTests.test_matchesHostIPc                 C   sB   |   | j ¡ | j d¡¡ t | j¡}|   | ¡ | j d¡¡ dS )z|
        L{PlainEntry.toString} generates the serialized OpenSSL format string
        for the entry, sans newline.
        r   N)r$   r   ÚtoStringr7   Úrstripr   r&   r9   )r   ZmultiHostEntryr    r    r!   Útest_toStringŸ   s
    

ÿzPlainEntryTests.test_toStringN)r2   r3   r4   r5   ÚsamplePlaintextLiner7   ÚsampleHostIPLiner9   r8   r:   r=   r    r    r    r!   r6   ˆ   s   	r6   c                   @   s0   e Zd ZdZedd… d Zedd… d ZdS )ÚPlainTextWithCommentTestsúN
    Test cases for L{PlainEntry} when parsed from a line with a comment.
    Néÿÿÿÿó    plain text comment.
s    text following host/IP line
)r2   r3   r4   r5   r>   r7   r?   r9   r    r    r    r!   r@   «   s   r@   c                   @   s,   e Zd ZdZeZdd„ Zdd„ Zdd„ ZdS )	ÚHashedEntryTestsaF  
    Tests for L{HashedEntry}.

    This suite doesn't include any tests for host/IP pairs because hashed
    entries store IP addresses the same way as hostnames and does not support
    comma-separated lists.  (If you hash the IP and host together you can't
    tell if you've got the key already for one or the other.)
    c                 C   s   t  | j¡| _dS )zo
        Set 'entry' to a sample hashed entry for twistedmatrix.com with
        sampleKey as its key.
        N)r   r&   Ú
hashedLiner   r   r    r    r!   r8   À   s    zHashedEntryTests.setUpc                 C   s   |   | j ¡ | j d¡¡ dS )z
        L{HashedEntry.toString} generates the serialized OpenSSL format string
        for the entry, sans the newline.
        r   N)r$   r   r;   rE   r<   r   r    r    r!   r=   È   s    zHashedEntryTests.test_toStringc                 C   sö   d}d}t  t¡}t| ¡ ƒ}d}t|||||ƒ}t|||||ƒ}|  ||t|ddd… ||||ƒ¡ |  ||t||ddd… |||ƒ¡ |  ||t|||ddd… ||ƒ¡ |  ||t|||t  t¡|ƒ¡ |  ||t|||||ddd… ƒ¡ dS )zö
        Two L{HashedEntry} instances compare equal if and only if they represent
        the same host and key in exactly the same way: the host salt, host hash,
        public key type, public key, and comment fields must all be equal.
        s   gJbSEPBG9ZSBoZpHNtZBD1bHKBAs   bQv+0Xa0dByrwkA1EB0E7Xop/Fos   hello, worldNrB   )r   r&   r'   r   Útyper   Z"assertNormalEqualityImplementationr*   )r   ZhostSaltZhostHashr%   r(   Zcommentr   Z	duplicater    r    r!   Útest_equalityÐ   s”    
    ÿ    ÿ    þþ    þþ    þþ    þþ    þþzHashedEntryTests.test_equalityN)	r2   r3   r4   r5   ÚsampleHashedLinerE   r8   r=   rG   r    r    r    r!   rD   µ   s
   rD   c                   @   s    e Zd ZdZedd… d ZdS )ÚHashedEntryWithCommentTestsrA   NrB   rC   )r2   r3   r4   r5   rH   rE   r    r    r    r!   rI     s   rI   c                   @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )ÚUnparsedEntryTestsz$
    Tests for L{UnparsedEntry}
    c                 C   s   t dƒ| _dS )zR
        Set up the 'entry' to be an unparsed entry for some random text.
        ó       This is a bogus entry.  
N)r   r   r   r    r    r!   r8     s    zUnparsedEntryTests.setUpc                 C   s   |   d| jj¡ dS )ze
        Creating an L{UnparsedEntry} should simply record the string it was
        passed.
        rK   N)r$   r   Z_stringr   r    r    r!   r)     s    ÿz"UnparsedEntryTests.test_fromStringc                 C   s   |   | j d¡¡ dS )z:
        An unparsed entry can't match any hosts.
        r-   N)r0   r   r/   r   r    r    r!   r1   #  s    z#UnparsedEntryTests.test_matchesHostc                 C   s   |   | j t t¡¡¡ dS )z9
        An unparsed entry can't match any keys.
        N)r0   r   r+   r   r&   r'   r   r    r    r!   r,   *  s    z"UnparsedEntryTests.test_matchesKeyc                 C   s   |   d| j ¡ ¡ dS )zd
        L{UnparsedEntry.toString} returns its input string, sans trailing
        newline.
        s       This is a bogus entry.  N)r$   r   r;   r   r    r    r!   r=   1  s    z UnparsedEntryTests.test_toStringN)	r2   r3   r4   r5   r8   r)   r1   r,   r=   r    r    r    r!   rJ     s   	rJ   c                   @   sX   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ ZdS )ÚParseErrorTestsa¢  
    L{HashedEntry.fromString} and L{PlainEntry.fromString} can raise a variety
    of errors depending on misformattings of certain strings.  These tests make
    sure those errors are caught.  Since many of the ways that this can go
    wrong are in the lower-level APIs being invoked by the parsing logic,
    several of these are integration tests with the C{base64} and
    L{twisted.conch.ssh.keys} modules.
    c                 C   s   |   t|jd¡ dS )zm
        If there are fewer than three elements, C{fromString} should raise
        L{InvalidEntry}.
        s   invalidN)ÚassertRaisesr   r&   ©r   Úclsr    r    r!   ÚinvalidEntryTestD  s    z ParseErrorTests.invalidEntryTestc                 C   s   |   t|jd¡ dS )zX
        If the key is not base64, C{fromString} should raise L{BinasciiError}.
        s   x x xN)rM   ÚBinasciiErrorr&   rN   r    r    r!   ÚnotBase64TestL  s    zParseErrorTests.notBase64Testc              
   C   s(   |   t|jd |dtdƒ ¡ g¡¡ dS )z•
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{fromString} should raise L{BadKeyError}.
        ó    r#   s   Hey, this isn't an SSH key!N)rM   r   r&   Újoinr   Ústrip)r   rO   Úprefixr    r    r!   Ú
badKeyTestS  s
    ÿÿzParseErrorTests.badKeyTestc                 C   s   |   t¡ dS )z™
        If there are fewer than three whitespace-separated elements in an
        entry, L{PlainEntry.fromString} should raise L{InvalidEntry}.
        N)rP   r   r   r    r    r!   Útest_invalidPlainEntry]  s    z&ParseErrorTests.test_invalidPlainEntryc              	   C   s<   |   t¡ t ¡ \}}}|  ttjd |d ||g¡¡ dS )zà
        If there are fewer than three whitespace-separated elements in an
        entry, or the hostname salt/hash portion has more than two elements,
        L{HashedEntry.fromString} should raise L{InvalidEntry}.
        rS   s   ||N)rP   r   rH   ÚsplitrM   r   r&   rT   ©r   ÚaÚbÚcr    r    r!   Útest_invalidHashedEntrye  s
    
ÿz'ParseErrorTests.test_invalidHashedEntryc                 C   s   |   t¡ dS )z†
        If the key portion of a plain entry is not decodable as base64,
        C{fromString} should raise L{BinasciiError}.
        N)rR   r   r   r    r    r!   Útest_plainNotBase64q  s    z#ParseErrorTests.test_plainNotBase64c              	   C   sŽ   |   t¡ t ¡ \}}}|  ttjd dtdƒ 	¡  ||g¡¡ |  ttjd tj
tdƒ 	¡  d ||g¡¡ |  ttjd d||g¡¡ dS )z‡
        If the key, host salt, or host hash portion of a hashed entry is not
        encoded, it will raise L{BinasciiError}.
        rS   s   |1|x|ó   stuffs   |xs   |1|x|xN)rR   r   rH   rY   rM   rQ   r&   rT   r   rU   ÚMAGICrZ   r    r    r!   Útest_hashedNotBase64y  s,    
 þ  ÿÿþ þz$ParseErrorTests.test_hashedNotBase64c                 C   s   t  ¡ \}}}|  t|¡ dS )z¡
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{HashedEntry.fromString} should raise L{BadKeyError}.
        N)rH   rY   rW   r   rZ   r    r    r!   Útest_hashedBadKey  s    z!ParseErrorTests.test_hashedBadKeyc                 C   s   |   td¡ dS )z 
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{PlainEntry.fromString} should raise L{BadKeyError}.
        s   hostnameN)rW   r   r   r    r    r!   Útest_plainBadKey™  s    z ParseErrorTests.test_plainBadKeyN)r2   r3   r4   r5   rP   rR   rW   rX   r^   r_   rb   rc   rd   r    r    r    r!   rL   :  s   	
	rL   c                   @   s<  e Zd ZdZdd„ Zee d fdd„Zdd„ Zd	d
„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ Zd7d8„ Z d9d:„ Z!d;d<„ Z"d=d>„ Z#d?d@„ Z$dAdB„ Z%dCdD„ Z&dEdF„ Z'dGdH„ Z(dIdJ„ Z)dKS )LÚKnownHostsDatabaseTestsz&
    Tests for L{KnownHostsFile}.
    c                 C   s   t |  ¡ ƒ}| |¡ |S )zC
        Return a FilePath with the given initial content.
        )r
   ÚmktempZ
setContent)r   ÚcontentÚfpr    r    r!   ÚpathWithContent§  s    
z'KnownHostsDatabaseTests.pathWithContentsN   
# That was a blank line.
This is just unparseable.
|1|This also unparseable.
c                 C   s   t  |  |¡¡S )zq
        Return a sample hosts file, with keys for www.twistedmatrix.com and
        divmod.com present.
        )r   ÚfromPathri   )r   rg   r    r    r!   ÚloadSampleHostsFile°  s    	z+KnownHostsDatabaseTests.loadSampleHostsFilec                 C   sD   t |  ¡ ƒ}t |  ¡ ƒ}t|ƒ}|  tt|d|¡ |  ||j¡ dS )zš
        L{KnownHostsFile.savePath} is read-only; if an assignment is made to
        it, L{AttributeError} is raised and the value is unchanged.
        ÚsavePathN)r
   rf   r   rM   ÚAttributeErrorÚsetattrr$   rl   )r   ÚpathÚnewÚ	hostsFiler    r    r!   Útest_readOnlySavePath¼  s
    z-KnownHostsDatabaseTests.test_readOnlySavePathc                 C   s&   t |  t¡ƒ}|  g t| ¡ ƒ¡ dS )zz
        The default initializer for L{KnownHostsFile} disregards any existing
        contents in the save path.
        N)r   ri   rH   r$   ÚlistÚiterentries©r   rq   r    r    r!   Ú&test_defaultInitializerIgnoresExistingÈ  s    z>KnownHostsDatabaseTests.test_defaultInitializerIgnoresExistingc                 C   s^   |   t¡}t|ƒ}| dt t¡¡}| ¡  |  |gt	| 
¡ ƒ¡ |  | ¡ d | ¡ ¡ dS )z·
        After using the default initializer for L{KnownHostsFile}, the first use
        of L{KnownHostsFile.save} overwrites any existing contents in the save
        path.
        ó   www.example.comr   N)ri   rH   r   Ú
addHostKeyr   r&   r*   Úsaver$   rs   rt   r;   Ú
getContent)r   ro   rq   r   r    r    r!   Ú'test_defaultInitializerClobbersExistingÑ  s    
 ÿz?KnownHostsDatabaseTests.test_defaultInitializerClobbersExistingc                 C   s^   t |  t¡ƒ}| dt t¡¡}| ¡  | dt t¡¡}| ¡  |  	||gt
| ¡ ƒ¡ dS )z»
        After L{KnownHostsFile.save} is used once with an instance initialized
        by the default initializer, contents of the save path are respected and
        preserved.
        rw   s   another.example.comN)r   ri   rH   rx   r   r&   r*   ry   ÚthirdSampleKeyr$   rs   rt   )r   rq   ZpreSaveZpostSaver    r    r!   Útest_saveResetsClobberStateâ  s     ÿ ÿz3KnownHostsDatabaseTests.test_saveResetsClobberStatec                 C   s$   |   ¡ }|  dtt| ¡ ƒƒ¡ dS )z·
        Loading a L{KnownHostsFile} from a path with six entries in it will
        result in a L{KnownHostsFile} object with six L{IKnownHostEntry}
        providers in it.
        é   N)rk   r$   Úlenrs   rt   ru   r    r    r!   Útest_loadFromPathó  s    z)KnownHostsDatabaseTests.test_loadFromPathc                 C   s>   t t|  ¡ ƒƒ}| dt t¡¡ |  dtt	| 
¡ ƒƒ¡ dS )z™
        If the save path for a L{KnownHostsFile} does not exist,
        L{KnownHostsFile.iterentries} still returns added but unsaved entries.
        rw   é   N)r   r
   rf   rx   r   r&   r'   r$   r   rs   rt   ru   r    r    r!   Útest_iterentriesUnsavedý  s    z/KnownHostsDatabaseTests.test_iterentriesUnsavedc                 C   sN   |   t¡}t| ¡ ƒ}|  |d t¡ |  |d  d¡¡ |  dt	|ƒ¡ dS )zÈ
        Loading a L{KnownHostsFile} from a path containing a single valid
        L{HashedEntry} entry will result in a L{KnownHostsFile} object
        with one L{IKnownHostEntry} provider.
        r   r-   r   N)
rk   rH   rs   rt   ÚassertIsInstancer   r.   r/   r$   r   ©r   rq   Úentriesr    r    r!   Útest_verifyHashedEntry  s
    
z.KnownHostsDatabaseTests.test_verifyHashedEntryc                 C   sN   |   t¡}t| ¡ ƒ}|  |d t¡ |  |d  d¡¡ |  dt	|ƒ¡ dS )zÇ
        Loading a L{KnownHostsFile} from a path containing a single valid
        L{PlainEntry} entry will result in a L{KnownHostsFile} object
        with one L{IKnownHostEntry} provider.
        r   ó
   divmod.comr   N)
rk   ÚotherSamplePlaintextLiners   rt   rƒ   r   r.   r/   r$   r   r„   r    r    r!   Útest_verifyPlainEntry  s
    
z-KnownHostsDatabaseTests.test_verifyPlainEntryc                 C   sN   |   d¡}t| ¡ ƒ}|  |d t¡ |  |d  ¡ d¡ |  dt|ƒ¡ dS )z°
        Loading a L{KnownHostsFile} from a path that only contains '
' will
        result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
        object.
        r   r   ó    r   N©rk   rs   rt   rƒ   r   r$   r;   r   r„   r    r    r!   Útest_verifyUnparsedEntry!  s
    
z0KnownHostsDatabaseTests.test_verifyUnparsedEntryc                 C   s>   |   d¡}t| ¡ ƒ}|  |d t¡ |  |d  ¡ d¡ dS )z±
        Loading a L{KnownHostsFile} from a path that contains a comment will
        result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
        object.
        s   # That was a blank line.
r   s   # That was a blank line.N)rk   rs   rt   rƒ   r   r$   r;   r„   r    r    r!   Útest_verifyUnparsedComment.  s    
z2KnownHostsDatabaseTests.test_verifyUnparsedCommentc                 C   sN   |   d¡}t| ¡ ƒ}|  |d t¡ |  |d  ¡ d¡ |  dt|ƒ¡ dS )z˜
        Loading a L{KnownHostsFile} from a path that contains an unparseable
        line will be represented as an L{UnparsedEntry} instance.
        s   This is just unparseable.
r   s   This is just unparseable.r   Nr‹   r„   r    r    r!   Útest_verifyUnparsableLine:  s
    
z1KnownHostsDatabaseTests.test_verifyUnparsableLinec                 C   sN   |   d¡}t| ¡ ƒ}|  |d t¡ |  |d  ¡ d¡ |  dt|ƒ¡ dS )zÃ
        Loading a L{KnownHostsFile} from a path containing an unparseable line
        that starts with an encryption marker will be represented as an
        L{UnparsedEntry} instance.
        s   |1|This is unparseable.
r   s   |1|This is unparseable.r   Nr‹   r„   r    r    r!   Ú%test_verifyUnparsableEncryptionMarkerF  s
    
z=KnownHostsDatabaseTests.test_verifyUnparsableEncryptionMarkerc                 C   s^   |   ¡ }t t|ƒ¡}t| ¡ ƒ}|  g |¡ |  t|ƒ ¡ ¡ | 	¡  |  
t|ƒ ¡ ¡ dS )z£
        Loading a L{KnownHostsFile} from a path that does not exist should
        result in an empty L{KnownHostsFile} that will save back to that path.
        N)rf   r   rj   r
   rs   rt   r$   r0   Úexistsry   r.   )r   ZpnÚknownHostsFiler…   r    r    r!   Útest_loadNonExistentS  s    z,KnownHostsDatabaseTests.test_loadNonExistentc                 C   sJ   t |  ¡ ƒ}| d¡ d¡}t |¡}| ¡  | d¡ |  | ¡ ¡ dS )zð
        Loading a L{KnownHostsFile} from a path whose parent directory does not
        exist should result in an empty L{KnownHostsFile} that will save back
        to that path, creating its parent directory(ies) in the process.
        Zfoos   known_hostsFN)	r
   rf   Úchildr   rj   ry   Zrestatr.   r   )r   ZthePathZknownHostsPathr‘   r    r    r!   Útest_loadNonExistentParenta  s    

z2KnownHostsDatabaseTests.test_loadNonExistentParentc                 C   s’   |   tt ¡}t |¡}| dt t¡¡}tt t	j
 t|jƒ ¡  d t|jƒ ¡  d t d }|  d| d¡¡ | ¡  |  || ¡ ¡ dS )zq
        L{KnownHostsFile.save} will write out a new file with any entries
        that have been added.
        ó   some.example.comó   |s	    ssh-rsa r   é   N)ri   rH   rˆ   r   rj   rx   r   r&   r|   r   ra   r   Ú	_hostSaltrU   Z	_hostHashÚthirdSampleEncodedKeyr$   Úcountry   rz   )r   ro   r‘   ÚnewEntryZexpectedContentr    r    r!   Útest_savingAddsEntryo  s8    ÿ
ÿÿÿþþýýüüÿ	z,KnownHostsDatabaseTests.test_savingAddsEntryc                 C   sZ   t |  ¡ ƒ}t|ƒ}| dt t¡¡}| ¡  | ¡  t |¡}|  	|gt
| ¡ ƒ¡ dS )z²
        L{KnownHostsFile.save} only writes new entries to the save path, not
        entries which were added and already written by a previous call to
        C{save}.
        r•   N)r
   rf   r   rx   r   r&   r'   ry   rj   r$   rs   rt   )r   ro   Ú
knownHostsr   r    r    r!   Útest_savingAvoidsDuplication‡  s     ÿ
z4KnownHostsDatabaseTests.test_savingAvoidsDuplicationc              
   C   sœ   |   t¡}t |¡}| d¡}| t¡ W 5 Q R X t t	¡}| 
d|¡ | ¡  t |¡}|  dddg| dt t¡¡| dt t¡¡| d|¡g¡ dS )zÁ
        L{KnownHostsFile.save} will not overwrite existing entries in its save
        path, even if they were only added after the L{KnownHostsFile} instance
        was initialized.
        r[   ó   brandnew.example.comTr-   r‡   N)ri   rH   r   rj   ÚopenÚwriterˆ   r   r&   r|   rx   ry   r$   Ú
hasHostKeyr'   r*   )r   ro   r   ÚhostsFileObjÚkeyr    r    r!   Útest_savingsPreservesExisting˜  s&    



 ÿ ÿ
ûz5KnownHostsDatabaseTests.test_savingsPreservesExistingc                 C   s$   |   ¡ }|  | dt t¡¡¡ dS )z‘
        L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
        hostname is present and matches the expected key.
        r-   N)rk   r.   r¢   r   r&   r'   ru   r    r    r!   Útest_hasPresentKey¶  s
     ÿz*KnownHostsDatabaseTests.test_hasPresentKeyc                 C   sT   |   ¡ }|  | dt t¡¡¡ |  | dt t¡¡¡ |  | dt t¡¡¡ dS )zy
        L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
        hostname is not present.
        s   non-existent.example.comr-   N)rk   r0   r¢   r   r&   r'   r.   ÚecdsaSampleKeyru   r    r    r!   Útest_notPresentKeyÀ  s     ÿ ÿ ÿz*KnownHostsDatabaseTests.test_notPresentKeyc              	   C   sh   t  t¡}tdg| ¡ |dƒ}|  ¡ }|j d¡}| | 	¡ d ¡ W 5 Q R X |  
d| d|¡¡ dS )zâ
        L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
        hostname is present in the file, even if it is only added to the file
        after the L{KnownHostsFile} instance is initialized.
        rŸ   rŠ   r[   r   TN)r   r&   r'   r   ZsshTyperk   rl   r    r¡   r;   r$   r¢   )r   r¤   r   rq   r£   r    r    r!   Útest_hasLaterAddedKeyÎ  s    
 
ÿz-KnownHostsDatabaseTests.test_hasLaterAddedKeyc                 C   s`   |   ¡ }t| ¡ ƒ}|  t|jdt t¡¡}|  	|j
|d ¡ |  	|jd¡ |  	|j|j¡ dS )a  
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
        present in the underlying file, but different from the expected one.
        The resulting exception should have an C{offendingEntry} indicating the
        given entry.
        r-   r   r   N)rk   rs   rt   rM   r   r¢   r   r&   r*   r$   ÚoffendingEntryÚlinenoro   rl   )r   rq   r…   Ú	exceptionr    r    r!   Útest_savedEntryHasKeyMismatchÝ  s      þz5KnownHostsDatabaseTests.test_savedEntryHasKeyMismatchc                 C   sT   |   ¡ }| dt t¡¡ |  t|jdt t¡¡}|  |j	d¡ |  |j
|j¡ dS )ai  
        Even after a new entry has been added in memory but not yet saved, the
        L{HostKeyChanged} exception raised by L{KnownHostsFile.hasHostKey} has a
        C{lineno} attribute which indicates the 1-based line number of the
        offending entry in the underlying file when the given host key does not
        match the expected host key.
        rw   r-   r   N)rk   rx   r   r&   r*   rM   r   r¢   r$   r«   ro   rl   )r   rq   r¬   r    r    r!   Ú%test_savedEntryAfterAddHasKeyMismatchî  s     ÿ  þz=KnownHostsDatabaseTests.test_savedEntryAfterAddHasKeyMismatchc                 C   sd   t t|  ¡ ƒƒ}| dt t¡¡}|  t|j	dt t
¡¡}|  |j|¡ |  |j¡ |  |j¡ dS )az  
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
        present in memory (but not yet saved), but different from the expected
        one.  The resulting exception has a C{offendingEntry} indicating the
        given entry, but no filename or line number information (reflecting the
        fact that the entry exists only in memory).
        rw   N)r   r
   rf   rx   r   r&   r*   rM   r   r¢   r|   r$   rª   ZassertIsNoner«   ro   )r   rq   r   r¬   r    r    r!   Útest_unsavedEntryHasKeyMismatch   s     ÿ  þz7KnownHostsDatabaseTests.test_unsavedEntryHasKeyMismatchc                 C   sŠ   |   ¡ }t t¡}|  d| d|¡¡ | d|¡}|  dt|jƒ¡ |  d| 	d¡¡ |  |j
d¡ |  ||j¡ |  d| d|¡¡ dS )zr
        L{KnownHostsFile.addHostKey} adds a new L{HashedEntry} to the host
        file, and returns it.
        Fó   somewhere.example.comé   Tr#   N)rk   r   r&   r|   r$   r¢   rx   r   r˜   r/   r(   r%   )r   rq   ÚaKeyr›   r    r    r!   Útest_addHostKey  s    

ÿÿ
ÿz'KnownHostsDatabaseTests.test_addHostKeyc                 C   s6   |   ¡ }t t¡}|  | d|¡j| d|¡j¡ dS )z‡
        L{KnownHostsFile.addHostKey} generates a random salt for each new key,
        so subsequent salts will be different.
        r°   s   somewhere-else.example.comN)rk   r   r&   r|   ZassertNotEqualrx   r˜   )r   rq   r²   r    r    r!   Útest_randomSalts*  s    
þz(KnownHostsDatabaseTests.test_randomSaltsc                 C   sX   |   ¡ }| dt t¡¡ tƒ }| |ddt t¡¡}g }| |j¡ |  	|dg¡ dS )zb
        Verifying a valid key should return a L{Deferred} which fires with
        True.
        ó   1.2.3.4r-   TN)
rk   rx   r   r&   r'   ÚFakeUIÚverifyHostKeyÚaddCallbackÚappendr$   )r   rq   ÚuiÚdÚlr    r    r!   Útest_verifyValidKey6  s    
ÿz+KnownHostsDatabaseTests.test_verifyValidKeyc                 C   sF   |   ¡ }t t¡}tƒ }| dt t¡¡ | |dd|¡}|  |t	¡S )z|
        Verifying an invalid key should return a L{Deferred} which fires with a
        L{HostKeyChanged} failure.
        rµ   r-   )
rk   r   r&   r|   r¶   rx   r'   r·   ÚassertFailurer   ©r   rq   ZwrongKeyrº   r»   r    r    r!   Útest_verifyInvalidKeyE  s    
   ÿz-KnownHostsDatabaseTests.test_verifyInvalidKeyc                 C   s\   |   ¡ }t t¡}tƒ }g }| |dd|¡}| |j¡ |  g |¡ |  |j	d¡ |||fS )a  
        Set up a test to verify a key that isn't present.  Return a 3-tuple of
        the UI, a list set up to collect the result of the verifyHostKey call,
        and the sample L{KnownHostsFile} being used.

        This utility method avoids returning a L{Deferred}, and records results
        in the returned list instead, because the events which get generated
        here are pre-recorded in the 'ui' object.  If the L{Deferred} in
        question does not fire, the it will fail quickly with an empty list.
        ó   sample-host.example.comó   4.3.2.1sÖ   The authenticity of host 'sample-host.example.com (4.3.2.1)' can't be established.
RSA key fingerprint is SHA256:mS7mDBGhewdzJkaKRkx+wMjUdZb/GzvgcdoYjX5Js9I=.
Are you sure you want to continue connecting (yes/no)? )
rk   r   r&   r|   r¶   r·   ÚaddBothr¹   r$   Ú
promptText)r   rq   Z	absentKeyrº   r¼   r»   r    r    r!   ÚverifyNonPresentKeyS  s"    
   ÿþz+KnownHostsDatabaseTests.verifyNonPresentKeyc              	   C   sl   |   ¡ \}}}|j d¡ |  dg|¡ t |j¡}|  d| dt 	t
¡¡¡ |  d| dt 	t
¡¡¡ dS )zæ
        Verifying a key where neither the hostname nor the IP are present
        should result in the UI being prompted with a message explaining as
        much.  If the UI says yes, the Deferred should fire with True.
        TrÂ   rÁ   N)rÅ   ÚpromptDeferredÚcallbackr$   r   rj   rl   r¢   r   r&   r|   )r   rº   r¼   r‘   Zreloadedr    r    r!   Útest_verifyNonPresentKey_Yesp  s    þÿþz4KnownHostsDatabaseTests.test_verifyNonPresentKey_Yesc                 C   s,   |   ¡ \}}}|j d¡ |d  t¡ dS )zø
        Verifying a key where neither the hostname nor the IP are present
        should result in the UI being prompted with a message explaining as
        much.  If the UI says no, the Deferred should fail with
        UserRejectedKey.
        Fr   N)rÅ   rÆ   rÇ   Ztrapr   )r   rº   r¼   r‘   r    r    r!   Útest_verifyNonPresentKey_Noƒ  s    z3KnownHostsDatabaseTests.test_verifyNonPresentKey_Noc                 C   sv   t jtjd tjd tjd tjd d}|  ¡ }tƒ }g }| |dd|¡}| |j¡ |  	g |¡ |  	|j
d¡ d	S )
zâ
        Set up a test to verify an ECDSA key that isn't present.
        Return a 3-tuple of the UI, a list set up to collect the result
        of the verifyHostKey call, and the sample L{KnownHostsFile} being used.
        ÚxÚyÚprivateValueÚcurve)rÊ   rË   rÌ   rÍ   rÁ   rÂ   sØ   The authenticity of host 'sample-host.example.com (4.3.2.1)' can't be established.
ECDSA key fingerprint is SHA256:fJnSpgCcYoYYsaBbnWj1YBghGh/QTDgfe4w4U5M5tEo=.
Are you sure you want to continue connecting (yes/no)? N)r   Z_fromECComponentsr   ZECDatanistp256rk   r¶   r·   rÃ   r¹   r$   rÄ   )r   ZecObjrq   rº   r¼   r»   r    r    r!   Útest_verifyNonPresentECKey  s*    ü   ÿþz2KnownHostsDatabaseTests.test_verifyNonPresentECKeyc                 C   s4   |   ¡ }t t¡}tƒ }| |dd|¡}|  |t¡S )z¾
        Verifying a key where the host is present (and correct), but the IP is
        present and different, should result the deferred firing in a
        HostKeyChanged failure.
        r-   rÂ   )rk   r   r&   r|   r¶   r·   r¾   r   r¿   r    r    r!   Útest_verifyHostIPMismatch¬  s    
   ÿz1KnownHostsDatabaseTests.test_verifyHostIPMismatchc                 C   sX   t ƒ }|  ¡ }t t¡}| |dd|¡ |  dt |j	¡ 
d|¡¡ |  dg|j¡ dS )z½
        Verifying a key where the hostname is present but the IP is not should
        result in the key being added for the IP and the user being warned
        about the change.
        r-   s   5.4.3.2Tz`Warning: Permanently added the RSA host key for IP address '5.4.3.2' to the list of known hosts.N)r¶   rk   r   r&   r'   r·   r$   r   rj   rl   r¢   ÚuserWarnings)r   rº   rq   ZexpectedKeyr    r    r!   Útest_verifyKeyForHostAndIPº  s(    
   ÿ  ÿÿýz2KnownHostsDatabaseTests.test_verifyKeyForHostAndIPc                 C   sh   |   ¡ }| dt t¡¡ | dt t¡¡ | ¡  i }|jj|d< t	 
d|¡}ddg}|  ||¡ dS )zn
        For a given host, get the host key algorithms for that
        host in the known_hosts file.
        r-   úknown-hostsr#   s   ecdsa-sha2-nistp256N)rk   rx   r   r&   r*   r§   ry   rl   ro   r   ZgetHostKeyAlgorithmsr$   )r   rq   ÚoptionsZ
algorithmsZexpectedAlgorithmsr    r    r!   Útest_getHostKeyAlgorithmsÎ  s$     ÿ ÿ ÿz1KnownHostsDatabaseTests.test_getHostKeyAlgorithmsN)*r2   r3   r4   r5   ri   rH   rˆ   rk   rr   rv   r{   r}   r€   r‚   r†   r‰   rŒ   r   rŽ   r   r’   r”   rœ   rž   r¥   r¦   r¨   r©   r­   r®   r¯   r³   r´   r½   rÀ   rÅ   rÈ   rÉ   rÎ   rÏ   rÑ   rÔ   r    r    r    r!   re   ¢  sP   
ÿÿ
	


re   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )ÚFakeFilez[
    A fake file-like object that acts enough like a file for
    L{ConsoleUI.prompt}.
    c                 C   s   g | _ g | _d| _d S )NF)ÚinlinesÚ	outchunksÚclosedr   r    r    r!   Ú__init__è  s    zFakeFile.__init__c                 C   s   | j  d¡S )z8
        Return a line from the 'inlines' list.
        r   )rÖ   Úpopr   r    r    r!   Úreadlineî  s    zFakeFile.readlinec                 C   s   | j rtdƒ‚| j |¡ dS )z@
        Append the given item to the 'outchunks' list.
        zthe file was closedN)rØ   ÚIOErrorr×   r¹   )r   Úchunkr    r    r!   r¡   õ  s    zFakeFile.writec                 C   s
   d| _ dS )zd
        Set the 'closed' flag to True, explicitly marking that it has been
        closed.
        TN)rØ   r   r    r    r!   Úcloseþ  s    zFakeFile.closeN)r2   r3   r4   r5   rÙ   rÛ   r¡   rÞ   r    r    r    r!   rÕ   â  s
   	rÕ   c                   @   sX   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ ZdS )ÚConsoleUITestsz&
    Test cases for L{ConsoleUI}.
    c                 C   s   t ƒ | _t| jƒ| _dS )zA
        Create a L{ConsoleUI} pointed at a L{FakeFile}.
        N)rÕ   ÚfakeFiler   ÚopenFilerº   r   r    r    r!   r8     s    zConsoleUITests.setUpc                 C   s   | j S )z/
        Return the current fake file.
        )rà   r   r    r    r!   rá     s    zConsoleUITests.openFilec                 C   s   t ƒ | _|| j_dS )z”
        Create a new fake file (the next file that self.ui will open) with the
        given list of lines to be returned from readline().
        N)rÕ   rà   rÖ   )r   Úlinesr    r    r!   ÚnewFile  s    zConsoleUITests.newFilec                 C   s`   dD ]V}|   |g¡ g }| j d¡ |j¡ |  dg| jj¡ |  dg|¡ |  | jj	¡ qdS )z´
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is 'yes', then it returns a L{Deferred} that fires with
        True.
        )ó   yess   Yess   yes
zHello, world!TN©
rã   rº   Úpromptr¸   r¹   r$   rà   r×   r.   rØ   )r   ZokYesr¼   r    r    r!   Útest_promptYes$  s    zConsoleUITests.test_promptYesc                 C   s`   dD ]V}|   |g¡ g }| j d¡ |j¡ |  dg| jj¡ |  dg|¡ |  | jj	¡ qdS )z´
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is 'no', then it returns a L{Deferred} that fires with
        False.
        )ó   nos   Nos   no
zGoodbye, world!FNrå   )r   ZokNor¼   r    r    r!   Útest_promptNo3  s    zConsoleUITests.test_promptNoc                 C   sÈ   |   ddddg¡ g }| j d¡ |j¡ |  dg|¡ |  | jjdgdgd  ¡ |  | jj	¡ |   d	d
ddg¡ g }| j d¡ |j¡ |  dg|¡ |  | jjdgdgd  ¡ |  | jj	¡ dS )a,  
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is neither 'yes' nor 'no', then it says "Please enter
        'yes' or 'no'" until it gets a 'yes' or a 'no', at which point it
        returns a Deferred that answers either True or False.
        s   whats   uhs   okayrä   s   Please say something useful.Ts   Please type 'yes' or 'no': r—   s   blahr`   s   fehrè   s   Please say something negative.FNrå   ©r   r¼   r    r    r!   Útest_promptRepeatedlyB  s(    
ÿÿ
ÿÿz$ConsoleUITests.test_promptRepeatedlyc                 C   s&   dd„ }t |ƒ}| d¡}|  |t¡S )z¢
        If the C{opener} passed to L{ConsoleUI} raises an exception, that
        exception will fail the L{Deferred} returned from L{ConsoleUI.prompt}.
        c                   S   s
   t ƒ ‚d S ©N)rÜ   r    r    r    r!   ÚraiseIt`  s    z5ConsoleUITests.test_promptOpenFailed.<locals>.raiseItzThis is a test.)r   ræ   r¾   rÜ   )r   rí   rº   r»   r    r    r!   Útest_promptOpenFailed[  s    
z$ConsoleUITests.test_promptOpenFailedc                 C   s0   | j  d¡ |  dg| jj¡ |  | jj¡ dS )zR
        L{ConsoleUI.warn} should output a message to the console object.
        zTest message.N)rº   Úwarnr$   rà   r×   r.   rØ   r   r    r    r!   Ú	test_warng  s    zConsoleUITests.test_warnc                 C   s4   dd„ }t |ƒ}| d¡ |  t|  t¡ƒd¡ dS )zY
        L{ConsoleUI.warn} should log a traceback if the output can't be opened.
        c                   S   s   dd  d S )Nr   r   r    r    r    r    r!   rí   t  s    z3ConsoleUITests.test_warnOpenFailed.<locals>.raiseItzThis message never makes it.r   N)r   rï   r$   r   ZflushLoggedErrorsÚZeroDivisionError)r   rí   rº   r    r    r!   Útest_warnOpenFailedp  s    
z"ConsoleUITests.test_warnOpenFailedN)r2   r3   r4   r5   r8   rá   rã   rç   ré   rë   rî   rð   rò   r    r    r    r!   rß     s   		rß   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	r¶   a  
    A fake UI object, adhering to the interface expected by
    L{KnownHostsFile.verifyHostKey}

    @ivar userWarnings: inputs provided to 'warn'.

    @ivar promptDeferred: last result returned from 'prompt'.

    @ivar promptText: the last input provided to 'prompt'.
    c                 C   s   g | _ d | _d | _d S rì   )rÐ   rÆ   rÄ   r   r    r    r!   rÙ   ˆ  s    zFakeUI.__init__c                 C   s   || _ tƒ | _| jS )zV
        Issue the user an interactive prompt, which they can accept or deny.
        )rÄ   r   rÆ   ©r   Útextr    r    r!   ræ   Ž  s    zFakeUI.promptc                 C   s   | j  |¡ dS )z>
        Issue a non-interactive warning to the user.
        N)rÐ   r¹   ró   r    r    r!   rï   —  s    zFakeUI.warnN)r2   r3   r4   r5   rÙ   ræ   rï   r    r    r    r!   r¶   |  s   	r¶   c                   @   s   e Zd ZdZdS )Ú
FakeObjectzw
    A fake object that can have some attributes.  Used to fake
    L{SSHClientTransport} and L{SSHClientFactory}.
    N)r2   r3   r4   r5   r    r    r    r!   rõ   Ÿ  s   rõ   c                   @   sh   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ ZdS )ÚDefaultAPITestszœ
    The API in L{twisted.conch.client.default.verifyHostKey} is the integration
    point between the code in the rest of conch and L{KnownHostsFile}.
    c                 K   s.   |   |d¡ |   |d¡ |   |d d¡ | jS )z
        The patched version of 'open'; this returns a L{FakeFile} that the
        instantiated L{ConsoleUI} can use.
        z/dev/ttyzr+bÚ	bufferingr   )r$   rà   )r   ÚfnameÚmodeÚkwargsr    r    r!   ÚpatchedOpen¬  s    zDefaultAPITests.patchedOpenc                 C   s’   t ƒ | _|  td| j¡ |  ¡ | _i | _tt	| jƒƒ}dD ] }| 
|t t¡¡}|| j|< q:| ¡  tƒ | _tƒ | j_d| jdœ | _| jj_dS )z0
        Patch 'open' in verifyHostKey.
        Z_open)ó   exists.example.comrÂ   rü   )ÚhostrÒ   N)rÕ   rà   Zpatchr   rû   rf   ÚhostsOptionÚhashedEntriesr   r
   rx   r   r&   r'   ry   rõ   ÚfakeTransportÚfactoryrÓ   )r   r‘   rý   r   r    r    r!   r8   ·  s    

þzDefaultAPITests.setUpc                 C   s0   g }t  | jdtd¡ |j¡ |  dg|¡ dS )zÎ
        L{default.verifyHostKey} should return a L{Deferred} which fires with
        C{1} when passed a host, IP, and key which already match the
        known_hosts file it is supposed to check.
        rÂ   ó   I don't care.r   N)r   r·   r   r'   r¸   r¹   r$   rê   r    r    r!   Útest_verifyOKKeyÌ  s    ÿÿz DefaultAPITests.test_verifyOKKeyc                    s0   t j d¡‰ ‡ fdd„}|  |¡ |t jd< dS )aC  
        Replace the HOME environment variable until the end of the current
        test, with the given new home-directory, so that L{os.path.expanduser}
        will yield controllable, predictable results.

        @param tempHome: the pathname to replace the HOME variable with.

        @type tempHome: L{str}
        ÚHOMEc                      s    ˆ d krt jd= n
ˆ t jd< d S )Nr  )ÚosÚenvironr    ©ZoldHomer    r!   ÚcleanupHomeã  s    
z0DefaultAPITests.replaceHome.<locals>.cleanupHomeN)r  r  ÚgetZ
addCleanup)r   ZtempHomer  r    r  r!   ÚreplaceHomeØ  s    

zDefaultAPITests.replaceHomec                 C   s€   g }|   ¡ }| j}t|ƒ d¡ d¡}| ¡  ¡  t|ƒ |¡ |  |¡ d| jd< t	 
| jdtd¡ |j¡ |  dg|¡ dS )z«
        L{default.verifyHostKey} should find your known_hosts file in
        ~/.ssh/known_hosts if you don't specify one explicitly on the command
        line.
        z.sshZknown_hostsNrÒ   rÂ   r  r   )rf   rþ   r
   r“   ÚparentÚmakedirsZmoveTor
  rÓ   r   r·   r   r'   r¸   r¹   r$   )r   r¼   ZtmpdirZoldHostsOptionZhostsNonOptionr    r    r!   Útest_noKnownHostsOptionì  s    

ÿÿz'DefaultAPITests.test_noKnownHostsOptionc                 C   sj   g }t  | jdtd¡ |j¡ |  dg| jj¡ |  dg|¡ t	 
t| jƒ¡}|  | dt t¡¡¡ dS )a  
        L{default.verifyHostKey} should return a L{Deferred} which fires with
        C{1} when passed a host which matches with an IP is not present in its
        known_hosts file, and should also warn the user that it has added the
        IP address.
        s   8.7.6.5s   Fingerprint not required.z`Warning: Permanently added the RSA host key for IP address '8.7.6.5' to the list of known hosts.r   N)r   r·   r   r'   r¸   r¹   r$   rà   r×   r   rj   r
   rþ   r.   r¢   r   r&   )r   r¼   r‘   r    r    r!   Útest_verifyHostButNotIPÿ  s    ÿÿý
ÿz'DefaultAPITests.test_verifyHostButNotIPc                 C   sL   d| j jjd< | jj d¡ t | j dtd¡}|  	dg| jj
¡ |  |t¡S )z¥
        L{default.verifyHostKey} should return a L{Default} which fires with
        C{0} when passed an unknown host that the user refuses to acknowledge.
        s   fake.example.comrý   rè   s   9.8.7.6s   No fingerprint!sÏ   The authenticity of host 'fake.example.com (9.8.7.6)' can't be established.
RSA key fingerprint is SHA256:vD0YydsNIUYJa7yLZl3tIL8h0vZvQ8G+HPG7JLmQV0s=.
Are you sure you want to continue connecting (yes/no)? )r   r  rÓ   rà   rÖ   r¹   r   r·   r*   r$   r×   r¾   r   ©r   r»   r    r    r!   Útest_verifyQuestion  s      þúz#DefaultAPITests.test_verifyQuestionc                 C   s   t  | jdtd¡}|  |t¡S )z
        L{default.verifyHostKey} should return a L{Deferred} which fails with
        L{HostKeyChanged} if the host key is incorrect.
        rÂ   zAgain, not required.)r   r·   r   r*   r¾   r   r  r    r    r!   Útest_verifyBadKey'  s      þz!DefaultAPITests.test_verifyBadKeyc                 C   sJ   | j d  ¡  ¡ d }t |t t¡ ¡ dt	| j
ƒji¡}|  d|¡ dS )zy
        L{default.isInKnownHosts} should return C{1} when a host with a key
        is in the known hosts file.
        rÂ   r   rÒ   r   N)rÿ   r;   rY   r   ÚisInKnownHostsr   r&   r'   Úblobr
   rþ   ro   r$   ©r   rý   Úrr    r    r!   Útest_inKnownHosts2  s     þz!DefaultAPITests.test_inKnownHostsc                 C   s*   t  dddt| jƒji¡}|  d|¡ dS )z}
        L{default.isInKnownHosts} should return C{0} when a host with a key
        is not in the known hosts file.
        z	not.theres
   irrelevantrÒ   r   N)r   r  r
   rþ   ro   r$   )r   r  r    r    r!   Útest_notInKnownHosts>  s     þz$DefaultAPITests.test_notInKnownHostsc                 C   sJ   | j d  ¡  ¡ d }t |t t¡ ¡ dt	| j
ƒji¡}|  d|¡ dS )z’
        L{default.isInKnownHosts} should return C{2} when a host with a key
        other than the given one is in the known hosts file.
        rÂ   r   rÒ   é   N)rÿ   r;   rY   r   r  r   r&   r*   r  r
   rþ   ro   r$   r  r    r    r!   Útest_inKnownHostsKeyChangedI  s     þz+DefaultAPITests.test_inKnownHostsKeyChangedN)r2   r3   r4   r5   rû   r8   r  r
  r  r  r  r  r  r  r  r    r    r    r!   rö   ¦  s   rö   )Fr5   Z
__future__r   r   r  Zbinasciir   rQ   r   r   Zzope.interface.verifyr   Ztwisted.python.compatr   Ztwisted.python.reflectr	   Ztwisted.python.filepathr
   Ztwisted.trial.unittestr   Ztwisted.internet.deferr   Ztwisted.conch.interfacesr   Ztwisted.conch.errorr   r   r   Ztwisted.test.testutilsr   Ztwisted.conch.ssh.keysr   r   Ztwisted.conch.client.knownhostsr   r   r   r   r   Ztwisted.conch.clientr   Ztwisted.conch.testr   ÚskipZsampleEncodedKeyZotherSampleEncodedKeyr™   ZecdsaSampleEncodedKeyr'   r*   r|   r§   r>   rˆ   r?   rH   r   r6   r@   rD   rI   rJ   rL   re   ÚobjectrÕ   rß   r¶   rõ   rö   r    r    r    r!   Ú<module>   sv   ÿ	ÿÿ	ÿ
ÿ
ÿ
ÿÿÿÿ8#
Q	+h    D%u#