Ϫf2dZddlZddlmZmZmZddlmZddl m Z ddl m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZedr#ddlmZddlm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)ndZ*dZ+dZ,dZ-dZ.ee+Z/ee,Z0ee-Z1ee.Z2de+zdzZ3de,zdzZ4de+zdzZ5de+zdzZ6GddZ7Gdd e7eZ8Gd!d"e8Z9Gd#d$e7eeZ:Gd%d&e:Z;Gd'd(ee7Z<Gd)d*eZ=Gd+d,eZ>Gd-d.Z?Gd/d0eZ@Gd1d2ZAGd3d4ZBeed5j d6Gd7d8eZDy)9z/ Tests for L{twisted.conch.client.knownhosts}. N)Error a2b_base64 b2a_base64)skipIf) verifyObject)HostKeyChanged InvalidEntryUserRejectedKey)IKnownHostEntry)Deferred) networkString)FilePath) requireModule)ComparisonTestsMixin)TestCase cryptography)default) ConsoleUI HashedEntryKnownHostsFile PlainEntry UnparsedEntry) BadKeyErrorKey)keydataz3cryptography required for twisted.conch.knownhosts.stAAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3ytNvue4Riqv/SVkPRNwMb7eWH29SviXaBxUhYyzKkDoNUq3rTNnH1Vnif6d6X4JCrUb5d3W+DmYClyJrZ5HgD/hUpdSkTRqdbQ2TrvSAxRacj+vHHT4F4dm1bJSewm3B2D8HVOoi/CbVh3dsIiCdp8VltdZx4qYVfYe2LwVINCbAa3d3tj9ma7RVfw3OH2Mfb+toLd1N5tBQFb7oqTt2nC6I/6Bd4JwPUld+IEitw/suElq/AIJVQXXujeyiZlea90HE65U2mF1ytr17HTAIT2ySokJWyuBANGACk6iIaw==sAAAAB3NzaC1yc2EAAAABIwAAAIEAwaeCZd3UCuPXhX39+/p9qO028jTF76DMVd9mPvYVDVXufWckKZauF7+0b7qm+ChT7kan6BzRVo4++gCVNfAlMzLysSt3ylmOR48tFpAfygg9UCX3DjHz0ElOOUKh3iifc9aUShD0OPaK3pR5JJ8jfiBfzSYWt/hDi/iZ4igsSs8=stAAAAB3NzaC1yc2EAAAABIwAAAQEAl/TQakPkePlnwCBRPitIVUTg6Z8VzN1en+DGkyo/evkmLw7o4NWR5qbysk9A9jXW332nxnEuAnbcCam9SHe1su1liVfyIK0+3bdn0YRB0sXIbNEtMs2LtCho/aV3cXPS+Cf1yut3wvIpaRnAzXxuKPCTXQ7/y0IXa8TwkRBH58OJa3RqfQ/NsSp5SAfdsrHyH2aitiVKm2jfbTKzSEqOQG/zq4J9GXTkq61gZugory/Tvl5/yPgSnOR6C9jVOMHf27ZPoRtyj9SY343Hd2QHiIE0KPZJEgCynKeWoKz8v6eTSK8n4rBnaqWdp8MnGZK1WGy05MguXbyCDuTC8AmJXQ==sAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIFwh3/zBANyPPIE60SMMfdKMYo3OvfvzGLZphzuKrzSt0q4uF+/iYqtYiHhryAwU/fDWlUQ9kck9f+IlpsNtY4=swww.twistedmatrix.com ssh-rsa  sdivmod.com ssh-rsa s-www.twistedmatrix.com,198.49.126.131 ssh-rsa sE|1|gJbSEPBG9ZSBoZpHNtZBD1bHKBA=|bQv+0Xa0dByrwkA1EB0E7Xop/Fo= ssh-rsa c(eZdZdZdZdZdZdZy)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. c8tt|jy)zA The given entry should provide IKnownHostEntry. N)rr entryselfs D/usr/lib/python3/dist-packages/twisted/conch/test/test_knownhosts.pytest_providesInterfacez&EntryTestsMixin.test_providesInterfacebs _djj1c|j}|j|jtjt |j|j dy)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 sampleKeykeyType)r"r s r#test_fromStringzEntryTestsMixin.test_fromStringhs>  #..*CD  3r%ctjt}tjt}|j d|j j ||j d|j j |y)zj L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given SSH key. TFN)rr*r+otherSampleKeyr(r matchesKey)r"twistedmatrixDotCom divmodDotComs r#test_matchesKeyzEntryTestsMixin.test_matchesKeyus` "nnY7~~n5  tzz445HIJ  5 5l CDr%c|j|jjd|j|jjdy)zl L{IKnownHostEntry.matchesHost} checks to see if an entry matches a given hostname. www.twistedmatrix.comswww.divmod.comN) assertTruer matchesHost assertFalser!s r#test_matchesHostz EntryTestsMixin.test_matchesHosts>  ../GHI //0ABCr%N)__name__ __module__ __qualname____doc__r$r-r3r9r%r#rrXs2 4EDr%rc*eZdZdZeZeZdZdZ dZ y)PlainEntryTestsz' Test cases for L{PlainEntry}. cLtj|j|_y)zU Set 'entry' to a sample plain-text entry with sampleKey as its key. N)rr* plaintextLiner r!s r#setUpzPlainEntryTests.setUps **4+=+=> r%ctj|j|_|j |jj d|j y)zU A "hostname,ip" formatted line will match both the host and the IP. s198.49.126.131N)rr* hostIPLiner r6r7r9r!s r#test_matchesHostIPz"PlainEntryTests.test_matchesHostIPsB **4??;   ../@AB r%c:|j|jj|jj dt j |j}|j|j|jj dy)z| L{PlainEntry.toString} generates the serialized OpenSSL format string for the entry, sans newline. rN)r(r toStringrBrstriprr*rE)r"multiHostEntrys r# test_toStringzPlainEntryTests.test_toStringsn ,,.0B0B0I0I%0PQ#..t? 002DOO4J4J54QRr%N) r:r;r<r=samplePlaintextLinerBsampleHostIPLinerErCrFrKr>r%r#r@r@s#(M!J?  Sr%r@c0eZdZdZedddzZedddzZy)PlainTextWithCommentTestsN Test cases for L{PlainEntry} when parsed from a line with a comment. N plain text comment. s text following host/IP line )r:r;r<r=rLrBrMrEr>r%r#rOrOs-(,/HHM!#2&)JJJr%rOc&eZdZdZeZdZdZdZy)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.) cLtj|j|_y)zo Set 'entry' to a sample hashed entry for twistedmatrix.com with sampleKey as its key. N)rr* hashedLiner r!s r#rCzHashedEntryTests.setUps !++DOO< r%c|j|jj|jj dy)z L{HashedEntry.toString} generates the serialized OpenSSL format string for the entry, sans the newline. rN)r(r rHrVrIr!s r#rKzHashedEntryTests.test_toStrings0 ,,.0F0Fu0MNr%cNd}d}tjt}t|j }d}t |||||}t |||||}|j ||t |ddd|||||j ||t ||ddd||||j ||t |||ddd|||j ||t |||tjt||j ||t |||||dddy)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. sgJbSEPBG9ZSBoZpHNtZBD1bHKBAsbQv+0Xa0dByrwkA1EB0E7Xop/Fos hello, worldNrQ)rr*r+r typer"assertNormalEqualityImplementationr/)r"hostSalthostHashr)r,commentr duplicates r# test_equalityzHashedEntryTests.test_equalitys@ 21NN9-   01!HhGL(GYP  //   2'9g N  //   (4R4.'9g N  //   (GDbDM9g N  //   (GS^^N-KW   //   (GY" N r%N) r:r;r<r=sampleHashedLinerVrCrKr_r>r%r#rTrTs"J=O2 r%rTc eZdZdZedddzZy)HashedEntryWithCommentTestsrPNrQrR)r:r;r<r=r`rVr>r%r#rbrbs"#2&)BBJr%rbc.eZdZdZdZdZdZdZdZy)UnparsedEntryTestsz$ Tests for L{UnparsedEntry} c$td|_y)zR Set up the 'entry' to be an unparsed entry for some random text.  This is a bogus entry. N)rr r!s r#rCzUnparsedEntryTests.setUp s##DE r%cP|jd|jjy)ze Creating an L{UnparsedEntry} should simply record the string it was passed. rfN)r(r _stringr!s r#r-z"UnparsedEntryTests.test_fromStrings :DJJr%r#rdrds%F PK K Qr%rdcFeZdZdZdZdZdZdZdZdZ dZ d Z d Z y ) 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. cF|jt|jdy)zm If there are fewer than three elements, C{fromString} should raise L{InvalidEntry}. sinvalidN) assertRaisesr r*r"clss r#invalidEntryTestz ParseErrorTests.invalidEntryTest8s , Cr%cF|jt|jdy)zX If the key is not base64, C{fromString} should raise L{BinasciiError}. sx x xN)ro BinasciiErrorr*rps r# notBase64TestzParseErrorTests.notBase64Test?s -Br%c |jt|jdj|dt dj gy)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'sHey, this isn't an SSH key!N)rorr*joinrstrip)r"rqprefixs r# badKeyTestzParseErrorTests.badKeyTestEsA   NN IIZ0N%O%U%U%WX  r%c.|jty)z If there are fewer than three whitespace-separated elements in an entry, L{PlainEntry.fromString} should raise L{InvalidEntry}. N)rrrr!s r#test_invalidPlainEntryz&ParseErrorTests.test_invalidPlainEntryRs j)r%c |jttj\}}}|j t tj dj|dz||gy)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}. rws||N)rrrr`splitror r*rxr"abcs r#test_invalidHashedEntryz'ParseErrorTests.test_invalidHashedEntryYsU k*"((*1a  +00$))QY1>1E F    " " II{((:h+?+E+E+GG%OQRTUV W  ;11499iA=N3O r%c`tj\}}}|jt|y)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)r`rr{rrs r#test_hashedBadKeyz!ParseErrorTests.test_hashedBadKeys& #((*1a  Q'r%c0|jtdy)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}. shostnameN)r{rr!s r#test_plainBadKeyz ParseErrorTests.test_plainBadKeys  K0r%N) r:r;r<r=rrrur{r}rrrrrr>r%r#rmrm.s6DC  *  ' 0(1r%rmceZdZdZdZeezdzfdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"d Z#d!Z$d"Z%d#Z&d$Z'd%Z(d&Z)y')(KnownHostsDatabaseTestsz& Tests for L{KnownHostsFile}. cZt|j}|j||S)zC Return a FilePath with the given initial content. )rmktemp setContent)r"contentfps r#pathWithContentz'KnownHostsDatabaseTests.pathWithContents%dkkm $ g r%sN # That was a blank line. This is just unparseable. |1|This also unparseable. cJtj|j|S)zq Return a sample hosts file, with keys for www.twistedmatrix.com and divmod.com present. )rfromPathr)r"rs r#loadSampleHostsFilez+KnownHostsDatabaseTests.loadSampleHostsFiles &&t';';G'DEEr%ct|j}t|j}t|}|jtt |d||j ||jy)z L{KnownHostsFile.savePath} is read-only; if an assignment is made to it, L{AttributeError} is raised and the value is unchanged. savePathN)rrrroAttributeErrorsetattrr(r)r"pathnew hostsFiles r#test_readOnlySavePathz-KnownHostsDatabaseTests.test_readOnlySavePathsZ  &t{{}%"4(  .'9j#N y112r%ct|jt}|jgt |j y)zz The default initializer for L{KnownHostsFile} disregards any existing contents in the save path. N)rrr`r(list iterentriesr"rs r#&test_defaultInitializerIgnoresExistingz>KnownHostsDatabaseTests.test_defaultInitializerIgnoresExistings8 #4#7#78H#IJ  T)"7"7"9:;r%cl|jt}t|}|jdt j t }|j|j|gt|j|j|jdz|jy)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.comrN) rr`r addHostKeyrr*r/saver(rrrH getContent)r"rrr s r#'test_defaultInitializerClobbersExistingz?KnownHostsDatabaseTests.test_defaultInitializerClobbersExistings ##$45"4( $$%79WX %$y'<'<'>"?@ )E14??3DEr%czt|jt}|jdt j t }|j|jdt j t}|j|j||gt|jy)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. rsanother.example.comN) rrr`rrr*r/rthirdSampleKeyr(rr)r"rpreSavepostSaves r#test_saveResetsClobberStatez3KnownHostsDatabaseTests.test_saveResetsClobberStates #4#7#78H#IJ && ~ >  '' "CNN>$B   '8,d93H3H3J.KLr%c |j}|jdtt|j y)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)rr(lenrrrs r#test_loadFromPathz)KnownHostsDatabaseTests.test_loadFromPaths5 ,,.  CY%:%:%< =>?r%c tt|j}|jdt j t |jdtt|jy)z If the save path for a L{KnownHostsFile} does not exist, L{KnownHostsFile.iterentries} still returns added but unsaved entries. rN) rrrrrr*r+r(rrrrs r#test_iterentriesUnsavedz/KnownHostsDatabaseTests.test_iterentriesUnsavedsV #8DKKM#:; / 1JK CY%:%:%< =>?r%c|jt}t|j}|j |dt |j |djd|jdt|y)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. rr5rN) rr`rrassertIsInstancerr6r7r(rr"rentriess r#test_verifyHashedEntryz.KnownHostsDatabaseTests.test_verifyHashedEntrysl ,,-=> y,,./ gaj+6  ../GHI CL)r%c|jt}t|j}|j |dt |j |djd|jdt|y)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.comrN) rotherSamplePlaintextLinerrrrr6r7r(rrs r#test_verifyPlainEntryz-KnownHostsDatabaseTests.test_verifyPlainEntrysk ,,-EF y,,./ gaj*5  ..}=> CL)r%c|jd}t|j}|j|dt|j |dj d|j dt|y)z Loading a L{KnownHostsFile} from a path that only contains ' ' will result in a L{KnownHostsFile} object containing a L{UnparsedEntry} object. rrr%rNrrrrrr(rHrrs r#test_verifyUnparsedEntryz0KnownHostsDatabaseTests.test_verifyUnparsedEntrysl ,,U3 y,,./ gaj-8 ,,.4 CL)r%c|jd}t|j}|j|dt|j |dj dy)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. rs# That was a blank line.N)rrrrrr(rHrs r#test_verifyUnparsedCommentz2KnownHostsDatabaseTests.test_verifyUnparsedCommentsZ ,,-JK y,,./ gaj-8 ,,.0KLr%c|jd}t|j}|j|dt|j |dj d|j dt|y)z Loading a L{KnownHostsFile} from a path that contains an unparseable line will be represented as an L{UnparsedEntry} instance. sThis is just unparseable. rsThis is just unparseable.rNrrs r#test_verifyUnparsableLinez1KnownHostsDatabaseTests.test_verifyUnparsableLine&sn ,,-KL y,,./ gaj-8 ,,.0LM CL)r%c|jd}t|j}|j|dt|j |dj d|j dt|y)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. rs|1|This is unparseable.rNrrs r#%test_verifyUnparsableEncryptionMarkerz=KnownHostsDatabaseTests.test_verifyUnparsableEncryptionMarker1sn ,,-IJ y,,./ gaj-8 ,,.0JK CL)r%cv|j}tjt|}t |j }|j g||jt|j|j|jt|jy)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) rrrrrrr(r8existsrr6)r"pnknownHostsFilers r#test_loadNonExistentz,KnownHostsDatabaseTests.test_loadNonExistent=s [[]'00">~1134 W% ",,./  ++-.r%c t|j}|jdjd}tj|}|j |j d|j|jy)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. foos known_hostsFN) rrchildrrrrestatr6r)r"thePathknownHostsPathrs r#test_loadNonExistentParentz2KnownHostsDatabaseTests.test_loadNonExistentParentJsl 4;;=) u-33NC'00@e$ --/0r%cF|jttz}tj|}|j dt jt}ttztjzt|jjzdzt|jjzdztzdz}|j!d|j#d|j%|j!||j'y)zq L{KnownHostsFile.save} will write out a new file with any entries that have been added. some.example.com|s ssh-rsa rN)rr`rrrrrr*rrrr _hostSaltry _hostHashthirdSampleEncodedKeyr(countrr)r"rrnewEntryexpectedContents r#test_savingAddsEntryz,KnownHostsDatabaseTests.test_savingAddsEntryWs  ##$47O$OP'006!,, !?  & ' ++,224 5   ++,224  5   $ $   O11%89 $//*;>);TU#,,T2  %$z'='='?"@Ar%c X|jt}tj|}|j d5}|j t dddtjt}|jd||jtj|}|jgd|jdtjt|jdtjt|jd|gy#1swYxYw)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. rNbrandnew.example.com)TTTr5r)rr`rropenwriterrr*rrrr( hasHostKeyr+r/)r"rr hostsFileObjkeys r#test_savingsPreservesExistingz5KnownHostsDatabaseTests.test_savingsPreservesExistings##$45#,,T2 YYs^ 9|   7 8 9nn^,5s;$,,T2   %%,cnnY.G%%mS^^N5ST%%&=sC    9 9s D  D)c|j}|j|jdtjt y)z L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given hostname is present and matches the expected key. r5N)rr6rrr*r+rs r#test_hasPresentKeyz*KnownHostsDatabaseTests.test_hasPresentKeys8 ,,.    !93>>);T U r%ct|j}|j|jdtjt |j |jdtjt |j|jdtjty)zy L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given hostname is not present. snon-existent.example.comr5N)rr8rrr*r+r6ecdsaSampleKeyrs r#test_notPresentKeyz*KnownHostsDatabaseTests.test_notPresentKeys ,,.    !W X    !93>>);T U    (#..*H  r%cxtjt}tdg|j |d}|j }|j jd5}|j|jdzddd|jd|jd|y#1swY,xYw)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. rr%rrNT) rr*r+rsshTyperrrrrHr(r)r"rr rrs r#test_hasLaterAddedKeyz-KnownHostsDatabaseTests.test_hasLaterAddedKeys nnY'34ckkmS#N,,.    $ $S ) 9\   u~~/%7 8 9 y334KSQR 9 9s "#B00B9c|j}t|j}|jt|j dt jt}|j|j|d|j|jd|j|j|jy)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. r5rrN)rrrrorrrr*r/r(offendingEntrylinenorr)r"rr exceptions r#test_savedEntryHasKeyMismatchz5KnownHostsDatabaseTests.test_savedEntryHasKeyMismatchs,,. y,,./%%   $ NN> *  1171:> ))1- );); *  ))1- );); *  1159 )**+ )..)r%c|j}tjt}|j d|j d||j d|}|j dt|j|j d|jd|j |jd|j ||j|j d|j d|y)zr L{KnownHostsFile.addHostKey} adds a new L{HashedEntry} to the host file, and returns it. Fsomewhere.example.comTr'N) rrr*rr(rrrrr7r,r))r"raKeyrs r#test_addHostKeyz'KnownHostsDatabaseTests.test_addHostKeys ,,. ~~n-  4 45Mt TU''(@$G S!3!345 x334LMN )):6 x112 y334LdSTr%c|j}tjt}|j |j d|j |j d|j y)z L{KnownHostsFile.addHostKey} generates a random salt for each new key, so subsequent salts will be different. rssomewhere-else.example.comN)rrr*rassertNotEqualrr)r"rrs r#test_randomSaltsz(KnownHostsDatabaseTests.test_randomSaltss\ ,,. ~~n-   !94 @ J J  !> E O O r%c@|j}|jdtjtt }|j |ddtjt}g}|j|j|j|dgy)zb Verifying a valid key should return a L{Deferred} which fires with True. 1.2.3.4r5TN) rrrr*r+FakeUI verifyHostKey addCallbackappendr()r"ruidls r#test_verifyValidKeyz+KnownHostsDatabaseTests.test_verifyValidKey%s~ ,,. Z )BC X  # # (*cnnY6O   ahh TF#r%c|j}tjt}t }|j dtjt |j|dd|}|j|tS)z| Verifying an invalid key should return a L{Deferred} which fires with a L{HostKeyChanged} failure. rr5) rrr*rr rr+r  assertFailurerr"rwrongKeyr rs r#test_verifyInvalidKeyz-KnownHostsDatabaseTests.test_verifyInvalidKey4sj ,,. >>.1 XZ )BC  # #B(@*h W!!!^44r%c0|j}tjt}t }g}|j |dd|}|j |j|jg||j|jd|||fS)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.com4.3.2.1sThe 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)? ) rrr*rr r addBothr r( promptText)r"r absentKeyr rrs r#verifyNonPresentKeyz+KnownHostsDatabaseTests.verifyNonPresentKey@s,,. NN>2 X   # # *J   !(( Q  MM G 1ir%c |j\}}}|jjd|jdg|t j |j }|jd|jdtjt|jd|jdtjty)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. TrrN) rpromptDeferredcallbackr(rrrrrr*r)r"r rrreloadeds r#test_verifyNonPresentKey_Yesz4KnownHostsDatabaseTests.test_verifyNonPresentKey_Yes^s !% 8 8 :A~ ""4( $#!**>+B+BC  (%%j#..2PQ      *CNN>,J  r%c|j\}}}|jjd|djty)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. FrN)rrrtrapr )r"r rrs r#test_verifyNonPresentKey_Noz3KnownHostsDatabaseTests.test_verifyNonPresentKey_Nors=!% 8 8 :A~ ""5) ! /"r%ctjtjdtjdtjdtjd}|j }t }g}|j |dd|}|j|j|jg||j|jdy ) 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. xy privateValuecurve)r&r'r(r)rrsThe 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_fromECComponentsrECDatanistp256rr r rr r(r)r"ecObjrr rrs r#test_verifyNonPresentECKeyz2KnownHostsDatabaseTests.test_verifyNonPresentECKey}s %%$$S)$$S) //?((1  ,,. X   # #B(BJPU V !(( Q  MM G r%c|j}tjt}t }|j |dd|}|j |tS)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. r5r)rrr*rr r rrrs r#test_verifyHostIPMismatchz1KnownHostsDatabaseTests.test_verifyHostIPMismatchsQ ,,. >>.1 X  # #B(@*h W!!!^44r%cJt}|j}tjt}|j |dd||j dtj|jjd||j dg|jy)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. r5s5.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 rrr*r+r r(rrrr userWarnings)r"r r expectedKeys r#test_verifyKeyForHostAndIPz2KnownHostsDatabaseTests.test_verifyKeyForHostAndIPs X,,. nnY/ $r%r#rrs & '+ +F 3< FM$@@ * * * M * * / 1=8 B B  $ S=&=&*(U&   $ 5 < ( # 8 5 0 9r%rc(eZdZdZdZdZdZdZy)FakeFilez[ A fake file-like object that acts enough like a file for L{ConsoleUI.prompt}. c.g|_g|_d|_y)NF)inlines outchunksclosedr!s r#__init__zFakeFile.__init__s  r%c8|jjdS)z8 Return a line from the 'inlines' list. r)r>popr!s r#readlinezFakeFile.readlines||""r%ch|jr td|jj|y)z@ Append the given item to the 'outchunks' list. zthe file was closedN)r@OSErrorr?r )r"chunks r#rzFakeFile.writes) ;;/0 0 e$r%cd|_y)zd Set the 'closed' flag to True, explicitly marking that it has been closed. TN)r@r!s r#closezFakeFile.closes  r%N)r:r;r<r=rArDrrIr>r%r#r<r<s  # %r%r<cFeZdZdZdZdZdZdZdZdZ dZ d Z d Z y ) ConsoleUITestsz& Test cases for L{ConsoleUI}. cVt|_t|j|_y)zA Create a L{ConsoleUI} pointed at a L{FakeFile}. N)r<fakeFileropenFiler r!s r#rCzConsoleUITests.setUps!  DMM*r%c|jS)z/ Return the current fake file. )rMr!s r#rNzConsoleUITests.openFiles}}r%cDt|_||j_y)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<rMr>)r"liness r#newFilezConsoleUITests.newFiles !  % r%c`dD]}|j|gg}|jjdj|j|j dg|j j|j dg||j|j jy)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. )yessYessyes z Hello, world!TN rRr promptr r r(rMr?r6r@)r"okYesrs r#test_promptYeszConsoleUITests.test_promptYess 0 2E LL% !A GGNN? + 7 7 A   o. 0G0G H   dVQ ' OODMM00 1  2r%c`dD]}|j|gg}|jjdj|j|j dg|j j|j dg||j|j jy)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. )nosNosno zGoodbye, world!FNrU)r"okNors r# test_promptNozConsoleUITests.test_promptNos , 2D LL$ A GGNN, - 9 9!(( C   /0$--2I2I J   eWa ( OODMM00 1  2r%c|jgdg}|jjdj|j|j dg||j |j jdgdgdzz|j|j j|jgdg}|jjdj|j|j dg||j |j jdgdgdzz|j|j jy ) 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. )swhatsuhsokayrTsPlease say something useful.TsPlease type 'yes' or 'no': r)sblahrsfehrZsPlease say something negative.FNrUr"rs r#test_promptRepeatedlyz$ConsoleUITests.test_promptRepeatedly$s 67  67CCAHHM $#  MM # # , -1O0PST0T T   ,,- 78  89EEahhO %!$  MM # # . /3Q2RUV2V V   ,,-r%cld}t|}|jd}|j|tS)z If the C{opener} passed to L{ConsoleUI} raises an exception, that exception will fail the L{Deferred} returned from L{ConsoleUI.prompt}. ctN)rFr>r%r#raiseItz5ConsoleUITests.test_promptOpenFailed..raiseItDs )Or%zThis is a test.)rrVrIOError)r"rcr rs r#test_promptOpenFailedz$ConsoleUITests.test_promptOpenFailed>s5  w  II' (!!!W--r%c|jjd|jdg|jj|j |jj y)zR L{ConsoleUI.warn} should output a message to the console object. z Test message.N)r warnr(rMr?r6r@r!s r# test_warnzConsoleUITests.test_warnKsG  _% /*DMM,C,CD  ,,-r%cd}t|}|jd|jt|j t dy)zY L{ConsoleUI.warn} should log a traceback if the output can't be opened. cddz y)Nrrr>r>r%r#rcz3ConsoleUITests.test_warnOpenFailed..raiseItXs Er%zThis message never makes it.rN)rrgr(rflushLoggedErrorsZeroDivisionError)r"rcr s r#test_warnOpenFailedz"ConsoleUITests.test_warnOpenFailedSsA  w  ./ T334EFGKr%N) r:r;r<r=rCrNrRrXr\r_rerhrmr>r%r#rKrKs5+ & 2 2.4 .. Lr%rKc"eZdZdZdZdZdZy)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.g|_d|_d|_yrb)r1rrr!s r#rAzFakeUI.__init__ls"r%cF||_t|_|jS)zV Issue the user an interactive prompt, which they can accept or deny. )rr rr"texts r#rVz FakeUI.promptqs!&j"""r%c:|jj|y)z> Issue a non-interactive warning to the user. N)r1r rqs r#rgz FakeUI.warnys   &r%N)r:r;r<r=rArVrgr>r%r#r r `s  #'r%r ceZdZdZy) FakeObjectzw A fake object that can have some attributes. Used to fake L{SSHClientTransport} and L{SSHClientFactory}. N)r:r;r<r=r>r%r#rurusr%ru/dev/ttyzPlatform lacks /dev/ttycReZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zy )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 |j|d|j|d|j|dd|jS)z The patched version of 'open'; this returns a L{FakeFile} that the instantiated L{ConsoleUI} can use. rvzr+b bufferingr)r(rM)r"fnamemodekwargss r# patchedOpenzDefaultAPITests.patchedOpensC  + u%  ,a0}}r%c$t|_|jtd|j|j |_i|_tt|j }dD]:}|j|tjt}||j|<<|jt|_t|j _d|j dx|_|j j"_y)z0 Patch 'open' in verifyHostKey. _open)exists.example.comrr)hostr5N)r<rMpatchrr~r hostsOption hashedEntriesrrrrr*r+rru fakeTransportfactoryr7)r"rrr s r#rCzDefaultAPITests.setUps!   7GT%5%56;;='1A1A(BC7 -D"--dCNN94MNE',D  t $ - '\%/\")++=   t))119r%cg}tj|jdtdj |j |j dg|y)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.rN)rr rr+r r r(r^s r#test_verifyOKKeyz DefaultAPITests.test_verifyOKKeysG     I7G +ahh  !a r%ctjjdfd}|j||tjd<y)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} HOMEcTtjd=ytjd<y)Nr)osenviron)oldHomesr# cleanupHomez0DefaultAPITests.replaceHome..cleanupHomes"JJv&%, 6"r%N)rrget addCleanup)r"tempHomerrs @r# replaceHomezDefaultAPITests.replaceHomes8**..( -  $% 6r%cg}|j}|j}t|jdjd}|j j t|j ||j|d|jd<tj|jdtdj|j|jdg|y)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.ssh known_hostsNr5rrr)rrrrparentmakedirsmoveTorr7rr rr+r r r()r"rtmpdiroldHostsOptionhostsNonOptions r#test_noKnownHostsOptionz'DefaultAPITests.test_noKnownHostsOptions ))!&)//7==mL((* ''7  &* ]#    I7G +ahh  !a r%cg}tj|jdtdj |j |j dg|jj|j dg|tjt|j}|j|jdtj ty)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. s8.7.6.5sFingerprint not required.z`Warning: Permanently added the RSA host key for IP address '8.7.6.5' to the list of known hosts.rN)rr rr+r r r(rMr?rrrrr6rrr*)r"rrs r#test_verifyHostButNotIPz'DefaultAPITests.test_verifyHostButNotIPs     I7S +ahh  8  MM # #   !a '00$:J:J1KL   % %j#..2K L r%cXd|jjjd<|jjj dt j|jdtd}|jdg|jj|j|tS)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. sfake.example.comrrZs9.8.7.6sNo fingerprint!sThe 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)? ) rrr7rMr>r rr r/r(r?rr r"rs r#test_verifyQuestionz#DefaultAPITests.test_verifyQuestions 6I""**62 $$U+  ! !    N>@C  " "  NN9 % * * , HT%5%56;; <  Ar%ctjdddt|jji}|j d|y)z} L{default.isInKnownHosts} should return C{0} when a host with a key is not in the known hosts file. z not.theres irrelevantr5rN)rrrrrr()r"rs r#test_notInKnownHostsz$DefaultAPITests.test_notInKnownHosts%sC  " " AQAQ8R8W8W(X  Ar%c:|jdjjd}tj|t j tjdt|jji}|jd|y)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. rrr5N) rrHrrrrr*r/rrrrr(rs r#test_inKnownHostsKeyChangedz+DefaultAPITests.test_inKnownHostsKeyChanged/s~ !!*-668>>@C  " "  NN> * / / 1 HT%5%56;; <  Ar%N)r:r;r<r=r~rCrrrrrrrrrr>r%r#rxrxs>  ( !&*!& 06,5  r%rx)Er=rbinasciirrtrrunittestrzope.interface.verifyrtwisted.conch.errorrr r twisted.conch.interfacesr twisted.internet.deferr twisted.python.compatr twisted.python.filepathrtwisted.python.reflectrtwisted.test.testutilsrtwisted.trial.unittestrtwisted.conch.clientrtwisted.conch.client.knownhostsrrrrrtwisted.conch.ssh.keysrrtwisted.conch.testrskipsampleEncodedKeyotherSampleEncodedKeyrecdsaSampleEncodedKeyr+r/rrrLrrMr`rr@rOrTrbrdrmrr<rKr rurrxr>r%r#rs  CC.MM4+/,07+ ,8* @D> N ' ( 1212127:JJUR14IIEQ57GG%O M  -D-D`SoxS@KKL (