test_knownhosts.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.conch.client.knownhosts}.
  5. """
  6. from __future__ import absolute_import, division
  7. import os
  8. from binascii import Error as BinasciiError, b2a_base64, a2b_base64
  9. from twisted.python.reflect import requireModule
  10. if requireModule('cryptography') and requireModule('pyasn1'):
  11. from twisted.conch.ssh.keys import Key, BadKeyError
  12. from twisted.conch.client.knownhosts import \
  13. PlainEntry, HashedEntry, KnownHostsFile, UnparsedEntry, ConsoleUI
  14. from twisted.conch.client import default
  15. from twisted.conch.test import keydata
  16. else:
  17. skip = "cryptography and PyASN1 required for twisted.conch.knownhosts."
  18. from zope.interface.verify import verifyObject
  19. from twisted.python.filepath import FilePath
  20. from twisted.python.compat import networkString
  21. from twisted.trial.unittest import TestCase
  22. from twisted.internet.defer import Deferred
  23. from twisted.conch.interfaces import IKnownHostEntry
  24. from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
  25. from twisted.test.testutils import ComparisonTestsMixin
  26. sampleEncodedKey = (
  27. b'AAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3y'
  28. b'tNvue4Riqv/SVkPRNwMb7eWH29SviXaBxUhYyzKkDoNUq3rTNnH1Vnif6d6X4JCrUb5d3W+Dm'
  29. b'YClyJrZ5HgD/hUpdSkTRqdbQ2TrvSAxRacj+vHHT4F4dm1bJSewm3B2D8HVOoi/CbVh3dsIiC'
  30. b'dp8VltdZx4qYVfYe2LwVINCbAa3d3tj9ma7RVfw3OH2Mfb+toLd1N5tBQFb7oqTt2nC6I/6Bd'
  31. b'4JwPUld+IEitw/suElq/AIJVQXXujeyiZlea90HE65U2mF1ytr17HTAIT2ySokJWyuBANGACk'
  32. b'6iIaw==')
  33. otherSampleEncodedKey = (
  34. b'AAAAB3NzaC1yc2EAAAABIwAAAIEAwaeCZd3UCuPXhX39+/p9qO028jTF76DMVd9mPvYVDVXuf'
  35. b'WckKZauF7+0b7qm+ChT7kan6BzRVo4++gCVNfAlMzLysSt3ylmOR48tFpAfygg9UCX3DjHz0E'
  36. b'lOOUKh3iifc9aUShD0OPaK3pR5JJ8jfiBfzSYWt/hDi/iZ4igsSs8=')
  37. thirdSampleEncodedKey = (
  38. b'AAAAB3NzaC1yc2EAAAABIwAAAQEAl/TQakPkePlnwCBRPitIVUTg6Z8VzN1en+DGkyo/evkmLw'
  39. b'7o4NWR5qbysk9A9jXW332nxnEuAnbcCam9SHe1su1liVfyIK0+3bdn0YRB0sXIbNEtMs2LtCho'
  40. b'/aV3cXPS+Cf1yut3wvIpaRnAzXxuKPCTXQ7/y0IXa8TwkRBH58OJa3RqfQ/NsSp5SAfdsrHyH2'
  41. b'aitiVKm2jfbTKzSEqOQG/zq4J9GXTkq61gZugory/Tvl5/yPgSnOR6C9jVOMHf27ZPoRtyj9SY'
  42. b'343Hd2QHiIE0KPZJEgCynKeWoKz8v6eTSK8n4rBnaqWdp8MnGZK1WGy05MguXbyCDuTC8AmJXQ'
  43. b'==')
  44. ecdsaSampleEncodedKey = (
  45. b'AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBIFwh3/zBANyPPIE60'
  46. b'SMMfdKMYo3OvfvzGLZphzuKrzSt0q4uF+/iYqtYiHhryAwU/fDWlUQ9kck9f+IlpsNtY4=')
  47. sampleKey = a2b_base64(sampleEncodedKey)
  48. otherSampleKey = a2b_base64(otherSampleEncodedKey)
  49. thirdSampleKey = a2b_base64(thirdSampleEncodedKey)
  50. ecdsaSampleKey = a2b_base64(ecdsaSampleEncodedKey)
  51. samplePlaintextLine = (
  52. b"www.twistedmatrix.com ssh-rsa " + sampleEncodedKey + b"\n")
  53. otherSamplePlaintextLine = (
  54. b"divmod.com ssh-rsa " + otherSampleEncodedKey + b"\n")
  55. sampleHostIPLine = (
  56. b"www.twistedmatrix.com,198.49.126.131 ssh-rsa " + sampleEncodedKey + b"\n")
  57. sampleHashedLine = (
  58. b"|1|gJbSEPBG9ZSBoZpHNtZBD1bHKBA=|bQv+0Xa0dByrwkA1EB0E7Xop/Fo= ssh-rsa " +
  59. sampleEncodedKey + b"\n")
  60. class EntryTestsMixin:
  61. """
  62. Tests for implementations of L{IKnownHostEntry}. Subclasses must set the
  63. 'entry' attribute to a provider of that interface, the implementation of
  64. that interface under test.
  65. @ivar entry: a provider of L{IKnownHostEntry} with a hostname of
  66. www.twistedmatrix.com and an RSA key of sampleKey.
  67. """
  68. def test_providesInterface(self):
  69. """
  70. The given entry should provide IKnownHostEntry.
  71. """
  72. verifyObject(IKnownHostEntry, self.entry)
  73. def test_fromString(self):
  74. """
  75. Constructing a plain text entry from an unhashed known_hosts entry will
  76. result in an L{IKnownHostEntry} provider with 'keyString', 'hostname',
  77. and 'keyType' attributes. While outside the interface in question,
  78. these attributes are held in common by L{PlainEntry} and L{HashedEntry}
  79. implementations; other implementations should override this method in
  80. subclasses.
  81. """
  82. entry = self.entry
  83. self.assertEqual(entry.publicKey, Key.fromString(sampleKey))
  84. self.assertEqual(entry.keyType, b"ssh-rsa")
  85. def test_matchesKey(self):
  86. """
  87. L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
  88. SSH key.
  89. """
  90. twistedmatrixDotCom = Key.fromString(sampleKey)
  91. divmodDotCom = Key.fromString(otherSampleKey)
  92. self.assertEqual(
  93. True,
  94. self.entry.matchesKey(twistedmatrixDotCom))
  95. self.assertEqual(
  96. False,
  97. self.entry.matchesKey(divmodDotCom))
  98. def test_matchesHost(self):
  99. """
  100. L{IKnownHostEntry.matchesHost} checks to see if an entry matches a
  101. given hostname.
  102. """
  103. self.assertTrue(self.entry.matchesHost(b"www.twistedmatrix.com"))
  104. self.assertFalse(self.entry.matchesHost(b"www.divmod.com"))
  105. class PlainEntryTests(EntryTestsMixin, TestCase):
  106. """
  107. Test cases for L{PlainEntry}.
  108. """
  109. plaintextLine = samplePlaintextLine
  110. hostIPLine = sampleHostIPLine
  111. def setUp(self):
  112. """
  113. Set 'entry' to a sample plain-text entry with sampleKey as its key.
  114. """
  115. self.entry = PlainEntry.fromString(self.plaintextLine)
  116. def test_matchesHostIP(self):
  117. """
  118. A "hostname,ip" formatted line will match both the host and the IP.
  119. """
  120. self.entry = PlainEntry.fromString(self.hostIPLine)
  121. self.assertTrue(self.entry.matchesHost(b"198.49.126.131"))
  122. self.test_matchesHost()
  123. def test_toString(self):
  124. """
  125. L{PlainEntry.toString} generates the serialized OpenSSL format string
  126. for the entry, sans newline.
  127. """
  128. self.assertEqual(self.entry.toString(), self.plaintextLine.rstrip(b"\n"))
  129. multiHostEntry = PlainEntry.fromString(self.hostIPLine)
  130. self.assertEqual(multiHostEntry.toString(),
  131. self.hostIPLine.rstrip(b"\n"))
  132. class PlainTextWithCommentTests(PlainEntryTests):
  133. """
  134. Test cases for L{PlainEntry} when parsed from a line with a comment.
  135. """
  136. plaintextLine = samplePlaintextLine[:-1] + b" plain text comment.\n"
  137. hostIPLine = sampleHostIPLine[:-1] + b" text following host/IP line\n"
  138. class HashedEntryTests(EntryTestsMixin, ComparisonTestsMixin, TestCase):
  139. """
  140. Tests for L{HashedEntry}.
  141. This suite doesn't include any tests for host/IP pairs because hashed
  142. entries store IP addresses the same way as hostnames and does not support
  143. comma-separated lists. (If you hash the IP and host together you can't
  144. tell if you've got the key already for one or the other.)
  145. """
  146. hashedLine = sampleHashedLine
  147. def setUp(self):
  148. """
  149. Set 'entry' to a sample hashed entry for twistedmatrix.com with
  150. sampleKey as its key.
  151. """
  152. self.entry = HashedEntry.fromString(self.hashedLine)
  153. def test_toString(self):
  154. """
  155. L{HashedEntry.toString} generates the serialized OpenSSL format string
  156. for the entry, sans the newline.
  157. """
  158. self.assertEqual(self.entry.toString(), self.hashedLine.rstrip(b"\n"))
  159. def test_equality(self):
  160. """
  161. Two L{HashedEntry} instances compare equal if and only if they represent
  162. the same host and key in exactly the same way: the host salt, host hash,
  163. public key type, public key, and comment fields must all be equal.
  164. """
  165. hostSalt = b"gJbSEPBG9ZSBoZpHNtZBD1bHKBA"
  166. hostHash = b"bQv+0Xa0dByrwkA1EB0E7Xop/Fo"
  167. publicKey = Key.fromString(sampleKey)
  168. keyType = networkString(publicKey.type())
  169. comment = b"hello, world"
  170. entry = HashedEntry(
  171. hostSalt, hostHash, keyType, publicKey, comment)
  172. duplicate = HashedEntry(
  173. hostSalt, hostHash, keyType, publicKey, comment)
  174. # Vary the host salt
  175. self.assertNormalEqualityImplementation(
  176. entry, duplicate,
  177. HashedEntry(
  178. hostSalt[::-1], hostHash, keyType, publicKey,
  179. comment))
  180. # Vary the host hash
  181. self.assertNormalEqualityImplementation(
  182. entry, duplicate,
  183. HashedEntry(
  184. hostSalt, hostHash[::-1], keyType, publicKey,
  185. comment))
  186. # Vary the key type
  187. self.assertNormalEqualityImplementation(
  188. entry, duplicate,
  189. HashedEntry(
  190. hostSalt, hostHash, keyType[::-1], publicKey,
  191. comment))
  192. # Vary the key
  193. self.assertNormalEqualityImplementation(
  194. entry, duplicate,
  195. HashedEntry(
  196. hostSalt, hostHash, keyType,
  197. Key.fromString(otherSampleKey), comment))
  198. # Vary the comment
  199. self.assertNormalEqualityImplementation(
  200. entry, duplicate,
  201. HashedEntry(
  202. hostSalt, hostHash, keyType, publicKey,
  203. comment[::-1]))
  204. class HashedEntryWithCommentTests(HashedEntryTests):
  205. """
  206. Test cases for L{PlainEntry} when parsed from a line with a comment.
  207. """
  208. hashedLine = sampleHashedLine[:-1] + b" plain text comment.\n"
  209. class UnparsedEntryTests(TestCase, EntryTestsMixin):
  210. """
  211. Tests for L{UnparsedEntry}
  212. """
  213. def setUp(self):
  214. """
  215. Set up the 'entry' to be an unparsed entry for some random text.
  216. """
  217. self.entry = UnparsedEntry(b" This is a bogus entry. \n")
  218. def test_fromString(self):
  219. """
  220. Creating an L{UnparsedEntry} should simply record the string it was
  221. passed.
  222. """
  223. self.assertEqual(b" This is a bogus entry. \n",
  224. self.entry._string)
  225. def test_matchesHost(self):
  226. """
  227. An unparsed entry can't match any hosts.
  228. """
  229. self.assertFalse(self.entry.matchesHost(b"www.twistedmatrix.com"))
  230. def test_matchesKey(self):
  231. """
  232. An unparsed entry can't match any keys.
  233. """
  234. self.assertFalse(self.entry.matchesKey(Key.fromString(sampleKey)))
  235. def test_toString(self):
  236. """
  237. L{UnparsedEntry.toString} returns its input string, sans trailing
  238. newline.
  239. """
  240. self.assertEqual(b" This is a bogus entry. ", self.entry.toString())
  241. class ParseErrorTests(TestCase):
  242. """
  243. L{HashedEntry.fromString} and L{PlainEntry.fromString} can raise a variety
  244. of errors depending on misformattings of certain strings. These tests make
  245. sure those errors are caught. Since many of the ways that this can go
  246. wrong are in the lower-level APIs being invoked by the parsing logic,
  247. several of these are integration tests with the C{base64} and
  248. L{twisted.conch.ssh.keys} modules.
  249. """
  250. def invalidEntryTest(self, cls):
  251. """
  252. If there are fewer than three elements, C{fromString} should raise
  253. L{InvalidEntry}.
  254. """
  255. self.assertRaises(InvalidEntry, cls.fromString, b"invalid")
  256. def notBase64Test(self, cls):
  257. """
  258. If the key is not base64, C{fromString} should raise L{BinasciiError}.
  259. """
  260. self.assertRaises(BinasciiError, cls.fromString, b"x x x")
  261. def badKeyTest(self, cls, prefix):
  262. """
  263. If the key portion of the entry is valid base64, but is not actually an
  264. SSH key, C{fromString} should raise L{BadKeyError}.
  265. """
  266. self.assertRaises(BadKeyError, cls.fromString, b' '.join(
  267. [prefix, b"ssh-rsa", b2a_base64(
  268. b"Hey, this isn't an SSH key!").strip()]))
  269. def test_invalidPlainEntry(self):
  270. """
  271. If there are fewer than three whitespace-separated elements in an
  272. entry, L{PlainEntry.fromString} should raise L{InvalidEntry}.
  273. """
  274. self.invalidEntryTest(PlainEntry)
  275. def test_invalidHashedEntry(self):
  276. """
  277. If there are fewer than three whitespace-separated elements in an
  278. entry, or the hostname salt/hash portion has more than two elements,
  279. L{HashedEntry.fromString} should raise L{InvalidEntry}.
  280. """
  281. self.invalidEntryTest(HashedEntry)
  282. a, b, c = sampleHashedLine.split()
  283. self.assertRaises(InvalidEntry, HashedEntry.fromString, b' '.join(
  284. [a + b"||", b, c]))
  285. def test_plainNotBase64(self):
  286. """
  287. If the key portion of a plain entry is not decodable as base64,
  288. C{fromString} should raise L{BinasciiError}.
  289. """
  290. self.notBase64Test(PlainEntry)
  291. def test_hashedNotBase64(self):
  292. """
  293. If the key, host salt, or host hash portion of a hashed entry is not
  294. encoded, it will raise L{BinasciiError}.
  295. """
  296. self.notBase64Test(HashedEntry)
  297. a, b, c = sampleHashedLine.split()
  298. # Salt not valid base64.
  299. self.assertRaises(
  300. BinasciiError, HashedEntry.fromString,
  301. b' '.join([b"|1|x|" + b2a_base64(b"stuff").strip(), b, c]))
  302. # Host hash not valid base64.
  303. self.assertRaises(
  304. BinasciiError, HashedEntry.fromString,
  305. b' '.join(
  306. [HashedEntry.MAGIC + b2a_base64(b"stuff").strip() + b"|x",
  307. b, c]))
  308. # Neither salt nor hash valid base64.
  309. self.assertRaises(
  310. BinasciiError, HashedEntry.fromString,
  311. b' '.join([b"|1|x|x", b, c]))
  312. def test_hashedBadKey(self):
  313. """
  314. If the key portion of the entry is valid base64, but is not actually an
  315. SSH key, C{HashedEntry.fromString} should raise L{BadKeyError}.
  316. """
  317. a, b, c = sampleHashedLine.split()
  318. self.badKeyTest(HashedEntry, a)
  319. def test_plainBadKey(self):
  320. """
  321. If the key portion of the entry is valid base64, but is not actually an
  322. SSH key, C{PlainEntry.fromString} should raise L{BadKeyError}.
  323. """
  324. self.badKeyTest(PlainEntry, b"hostname")
  325. class KnownHostsDatabaseTests(TestCase):
  326. """
  327. Tests for L{KnownHostsFile}.
  328. """
  329. def pathWithContent(self, content):
  330. """
  331. Return a FilePath with the given initial content.
  332. """
  333. fp = FilePath(self.mktemp())
  334. fp.setContent(content)
  335. return fp
  336. def loadSampleHostsFile(self, content=(
  337. sampleHashedLine + otherSamplePlaintextLine +
  338. b"\n# That was a blank line.\n"
  339. b"This is just unparseable.\n"
  340. b"|1|This also unparseable.\n")):
  341. """
  342. Return a sample hosts file, with keys for www.twistedmatrix.com and
  343. divmod.com present.
  344. """
  345. return KnownHostsFile.fromPath(self.pathWithContent(content))
  346. def test_readOnlySavePath(self):
  347. """
  348. L{KnownHostsFile.savePath} is read-only; if an assignment is made to
  349. it, L{AttributeError} is raised and the value is unchanged.
  350. """
  351. path = FilePath(self.mktemp())
  352. new = FilePath(self.mktemp())
  353. hostsFile = KnownHostsFile(path)
  354. self.assertRaises(AttributeError, setattr, hostsFile, "savePath", new)
  355. self.assertEqual(path, hostsFile.savePath)
  356. def test_defaultInitializerIgnoresExisting(self):
  357. """
  358. The default initializer for L{KnownHostsFile} disregards any existing
  359. contents in the save path.
  360. """
  361. hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
  362. self.assertEqual([], list(hostsFile.iterentries()))
  363. def test_defaultInitializerClobbersExisting(self):
  364. """
  365. After using the default initializer for L{KnownHostsFile}, the first use
  366. of L{KnownHostsFile.save} overwrites any existing contents in the save
  367. path.
  368. """
  369. path = self.pathWithContent(sampleHashedLine)
  370. hostsFile = KnownHostsFile(path)
  371. entry = hostsFile.addHostKey(
  372. b"www.example.com", Key.fromString(otherSampleKey))
  373. hostsFile.save()
  374. # Check KnownHostsFile to see what it thinks the state is
  375. self.assertEqual([entry], list(hostsFile.iterentries()))
  376. # And also directly check the underlying file itself
  377. self.assertEqual(entry.toString() + b"\n", path.getContent())
  378. def test_saveResetsClobberState(self):
  379. """
  380. After L{KnownHostsFile.save} is used once with an instance initialized
  381. by the default initializer, contents of the save path are respected and
  382. preserved.
  383. """
  384. hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
  385. preSave = hostsFile.addHostKey(
  386. b"www.example.com", Key.fromString(otherSampleKey))
  387. hostsFile.save()
  388. postSave = hostsFile.addHostKey(
  389. b"another.example.com", Key.fromString(thirdSampleKey))
  390. hostsFile.save()
  391. self.assertEqual([preSave, postSave], list(hostsFile.iterentries()))
  392. def test_loadFromPath(self):
  393. """
  394. Loading a L{KnownHostsFile} from a path with six entries in it will
  395. result in a L{KnownHostsFile} object with six L{IKnownHostEntry}
  396. providers in it.
  397. """
  398. hostsFile = self.loadSampleHostsFile()
  399. self.assertEqual(6, len(list(hostsFile.iterentries())))
  400. def test_iterentriesUnsaved(self):
  401. """
  402. If the save path for a L{KnownHostsFile} does not exist,
  403. L{KnownHostsFile.iterentries} still returns added but unsaved entries.
  404. """
  405. hostsFile = KnownHostsFile(FilePath(self.mktemp()))
  406. hostsFile.addHostKey(b"www.example.com", Key.fromString(sampleKey))
  407. self.assertEqual(1, len(list(hostsFile.iterentries())))
  408. def test_verifyHashedEntry(self):
  409. """
  410. Loading a L{KnownHostsFile} from a path containing a single valid
  411. L{HashedEntry} entry will result in a L{KnownHostsFile} object
  412. with one L{IKnownHostEntry} provider.
  413. """
  414. hostsFile = self.loadSampleHostsFile((sampleHashedLine))
  415. entries = list(hostsFile.iterentries())
  416. self.assertIsInstance(entries[0], HashedEntry)
  417. self.assertTrue(entries[0].matchesHost(b"www.twistedmatrix.com"))
  418. self.assertEqual(1, len(entries))
  419. def test_verifyPlainEntry(self):
  420. """
  421. Loading a L{KnownHostsFile} from a path containing a single valid
  422. L{PlainEntry} entry will result in a L{KnownHostsFile} object
  423. with one L{IKnownHostEntry} provider.
  424. """
  425. hostsFile = self.loadSampleHostsFile((otherSamplePlaintextLine))
  426. entries = list(hostsFile.iterentries())
  427. self.assertIsInstance(entries[0], PlainEntry)
  428. self.assertTrue(entries[0].matchesHost(b"divmod.com"))
  429. self.assertEqual(1, len(entries))
  430. def test_verifyUnparsedEntry(self):
  431. """
  432. Loading a L{KnownHostsFile} from a path that only contains '\n' will
  433. result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
  434. object.
  435. """
  436. hostsFile = self.loadSampleHostsFile((b"\n"))
  437. entries = list(hostsFile.iterentries())
  438. self.assertIsInstance(entries[0], UnparsedEntry)
  439. self.assertEqual(entries[0].toString(), b"")
  440. self.assertEqual(1, len(entries))
  441. def test_verifyUnparsedComment(self):
  442. """
  443. Loading a L{KnownHostsFile} from a path that contains a comment will
  444. result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
  445. object.
  446. """
  447. hostsFile = self.loadSampleHostsFile((b"# That was a blank line.\n"))
  448. entries = list(hostsFile.iterentries())
  449. self.assertIsInstance(entries[0], UnparsedEntry)
  450. self.assertEqual(entries[0].toString(), b"# That was a blank line.")
  451. def test_verifyUnparsableLine(self):
  452. """
  453. Loading a L{KnownHostsFile} from a path that contains an unparseable
  454. line will be represented as an L{UnparsedEntry} instance.
  455. """
  456. hostsFile = self.loadSampleHostsFile((b"This is just unparseable.\n"))
  457. entries = list(hostsFile.iterentries())
  458. self.assertIsInstance(entries[0], UnparsedEntry)
  459. self.assertEqual(entries[0].toString(), b"This is just unparseable.")
  460. self.assertEqual(1, len(entries))
  461. def test_verifyUnparsableEncryptionMarker(self):
  462. """
  463. Loading a L{KnownHostsFile} from a path containing an unparseable line
  464. that starts with an encryption marker will be represented as an
  465. L{UnparsedEntry} instance.
  466. """
  467. hostsFile = self.loadSampleHostsFile((b"|1|This is unparseable.\n"))
  468. entries = list(hostsFile.iterentries())
  469. self.assertIsInstance(entries[0], UnparsedEntry)
  470. self.assertEqual(entries[0].toString(), b"|1|This is unparseable.")
  471. self.assertEqual(1, len(entries))
  472. def test_loadNonExistent(self):
  473. """
  474. Loading a L{KnownHostsFile} from a path that does not exist should
  475. result in an empty L{KnownHostsFile} that will save back to that path.
  476. """
  477. pn = self.mktemp()
  478. knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
  479. entries = list(knownHostsFile.iterentries())
  480. self.assertEqual([], entries)
  481. self.assertFalse(FilePath(pn).exists())
  482. knownHostsFile.save()
  483. self.assertTrue(FilePath(pn).exists())
  484. def test_loadNonExistentParent(self):
  485. """
  486. Loading a L{KnownHostsFile} from a path whose parent directory does not
  487. exist should result in an empty L{KnownHostsFile} that will save back
  488. to that path, creating its parent directory(ies) in the process.
  489. """
  490. thePath = FilePath(self.mktemp())
  491. knownHostsPath = thePath.child("foo").child(b"known_hosts")
  492. knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
  493. knownHostsFile.save()
  494. knownHostsPath.restat(False)
  495. self.assertTrue(knownHostsPath.exists())
  496. def test_savingAddsEntry(self):
  497. """
  498. L{KnownHostsFile.save} will write out a new file with any entries
  499. that have been added.
  500. """
  501. path = self.pathWithContent(sampleHashedLine +
  502. otherSamplePlaintextLine)
  503. knownHostsFile = KnownHostsFile.fromPath(path)
  504. newEntry = knownHostsFile.addHostKey(b"some.example.com",
  505. Key.fromString(thirdSampleKey))
  506. expectedContent = (
  507. sampleHashedLine +
  508. otherSamplePlaintextLine + HashedEntry.MAGIC +
  509. b2a_base64(newEntry._hostSalt).strip() + b"|" +
  510. b2a_base64(newEntry._hostHash).strip() + b" ssh-rsa " +
  511. thirdSampleEncodedKey + b"\n")
  512. # Sanity check, let's make sure the base64 API being used for the test
  513. # isn't inserting spurious newlines.
  514. self.assertEqual(3, expectedContent.count(b"\n"))
  515. knownHostsFile.save()
  516. self.assertEqual(expectedContent, path.getContent())
  517. def test_savingAvoidsDuplication(self):
  518. """
  519. L{KnownHostsFile.save} only writes new entries to the save path, not
  520. entries which were added and already written by a previous call to
  521. C{save}.
  522. """
  523. path = FilePath(self.mktemp())
  524. knownHosts = KnownHostsFile(path)
  525. entry = knownHosts.addHostKey(
  526. b"some.example.com", Key.fromString(sampleKey))
  527. knownHosts.save()
  528. knownHosts.save()
  529. knownHosts = KnownHostsFile.fromPath(path)
  530. self.assertEqual([entry], list(knownHosts.iterentries()))
  531. def test_savingsPreservesExisting(self):
  532. """
  533. L{KnownHostsFile.save} will not overwrite existing entries in its save
  534. path, even if they were only added after the L{KnownHostsFile} instance
  535. was initialized.
  536. """
  537. # Start off with one host/key pair in the file
  538. path = self.pathWithContent(sampleHashedLine)
  539. knownHosts = KnownHostsFile.fromPath(path)
  540. # After initializing the KnownHostsFile instance, add a second host/key
  541. # pair to the file directly - without the instance's help or knowledge.
  542. with path.open("a") as hostsFileObj:
  543. hostsFileObj.write(otherSamplePlaintextLine)
  544. # Add a third host/key pair using the KnownHostsFile instance
  545. key = Key.fromString(thirdSampleKey)
  546. knownHosts.addHostKey(b"brandnew.example.com", key)
  547. knownHosts.save()
  548. # Check that all three host/key pairs are present.
  549. knownHosts = KnownHostsFile.fromPath(path)
  550. self.assertEqual([True, True, True], [
  551. knownHosts.hasHostKey(
  552. b"www.twistedmatrix.com", Key.fromString(sampleKey)),
  553. knownHosts.hasHostKey(
  554. b"divmod.com", Key.fromString(otherSampleKey)),
  555. knownHosts.hasHostKey(b"brandnew.example.com", key)])
  556. def test_hasPresentKey(self):
  557. """
  558. L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
  559. hostname is present and matches the expected key.
  560. """
  561. hostsFile = self.loadSampleHostsFile()
  562. self.assertTrue(hostsFile.hasHostKey(
  563. b"www.twistedmatrix.com", Key.fromString(sampleKey)))
  564. def test_notPresentKey(self):
  565. """
  566. L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
  567. hostname is not present.
  568. """
  569. hostsFile = self.loadSampleHostsFile()
  570. self.assertFalse(hostsFile.hasHostKey(
  571. b"non-existent.example.com", Key.fromString(sampleKey)))
  572. self.assertTrue(hostsFile.hasHostKey(
  573. b"www.twistedmatrix.com", Key.fromString(sampleKey)))
  574. self.assertFalse(hostsFile.hasHostKey(
  575. b"www.twistedmatrix.com", Key.fromString(ecdsaSampleKey)))
  576. def test_hasLaterAddedKey(self):
  577. """
  578. L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
  579. hostname is present in the file, even if it is only added to the file
  580. after the L{KnownHostsFile} instance is initialized.
  581. """
  582. key = Key.fromString(sampleKey)
  583. entry = PlainEntry([b"brandnew.example.com"], key.sshType(), key, b"")
  584. hostsFile = self.loadSampleHostsFile()
  585. with hostsFile.savePath.open("a") as hostsFileObj:
  586. hostsFileObj.write(entry.toString() + b"\n")
  587. self.assertEqual(
  588. True, hostsFile.hasHostKey(b"brandnew.example.com", key))
  589. def test_savedEntryHasKeyMismatch(self):
  590. """
  591. L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
  592. present in the underlying file, but different from the expected one.
  593. The resulting exception should have an C{offendingEntry} indicating the
  594. given entry.
  595. """
  596. hostsFile = self.loadSampleHostsFile()
  597. entries = list(hostsFile.iterentries())
  598. exception = self.assertRaises(
  599. HostKeyChanged, hostsFile.hasHostKey,
  600. b"www.twistedmatrix.com", Key.fromString(otherSampleKey))
  601. self.assertEqual(exception.offendingEntry, entries[0])
  602. self.assertEqual(exception.lineno, 1)
  603. self.assertEqual(exception.path, hostsFile.savePath)
  604. def test_savedEntryAfterAddHasKeyMismatch(self):
  605. """
  606. Even after a new entry has been added in memory but not yet saved, the
  607. L{HostKeyChanged} exception raised by L{KnownHostsFile.hasHostKey} has a
  608. C{lineno} attribute which indicates the 1-based line number of the
  609. offending entry in the underlying file when the given host key does not
  610. match the expected host key.
  611. """
  612. hostsFile = self.loadSampleHostsFile()
  613. hostsFile.addHostKey(
  614. b"www.example.com", Key.fromString(otherSampleKey))
  615. exception = self.assertRaises(
  616. HostKeyChanged, hostsFile.hasHostKey,
  617. b"www.twistedmatrix.com", Key.fromString(otherSampleKey))
  618. self.assertEqual(exception.lineno, 1)
  619. self.assertEqual(exception.path, hostsFile.savePath)
  620. def test_unsavedEntryHasKeyMismatch(self):
  621. """
  622. L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
  623. present in memory (but not yet saved), but different from the expected
  624. one. The resulting exception has a C{offendingEntry} indicating the
  625. given entry, but no filename or line number information (reflecting the
  626. fact that the entry exists only in memory).
  627. """
  628. hostsFile = KnownHostsFile(FilePath(self.mktemp()))
  629. entry = hostsFile.addHostKey(
  630. b"www.example.com", Key.fromString(otherSampleKey))
  631. exception = self.assertRaises(
  632. HostKeyChanged, hostsFile.hasHostKey,
  633. b"www.example.com", Key.fromString(thirdSampleKey))
  634. self.assertEqual(exception.offendingEntry, entry)
  635. self.assertIsNone(exception.lineno)
  636. self.assertIsNone(exception.path)
  637. def test_addHostKey(self):
  638. """
  639. L{KnownHostsFile.addHostKey} adds a new L{HashedEntry} to the host
  640. file, and returns it.
  641. """
  642. hostsFile = self.loadSampleHostsFile()
  643. aKey = Key.fromString(thirdSampleKey)
  644. self.assertEqual(False,
  645. hostsFile.hasHostKey(b"somewhere.example.com", aKey))
  646. newEntry = hostsFile.addHostKey(b"somewhere.example.com", aKey)
  647. # The code in OpenSSH requires host salts to be 20 characters long.
  648. # This is the required length of a SHA-1 HMAC hash, so it's just a
  649. # sanity check.
  650. self.assertEqual(20, len(newEntry._hostSalt))
  651. self.assertEqual(True,
  652. newEntry.matchesHost(b"somewhere.example.com"))
  653. self.assertEqual(newEntry.keyType, b"ssh-rsa")
  654. self.assertEqual(aKey, newEntry.publicKey)
  655. self.assertEqual(True,
  656. hostsFile.hasHostKey(b"somewhere.example.com", aKey))
  657. def test_randomSalts(self):
  658. """
  659. L{KnownHostsFile.addHostKey} generates a random salt for each new key,
  660. so subsequent salts will be different.
  661. """
  662. hostsFile = self.loadSampleHostsFile()
  663. aKey = Key.fromString(thirdSampleKey)
  664. self.assertNotEqual(
  665. hostsFile.addHostKey(b"somewhere.example.com", aKey)._hostSalt,
  666. hostsFile.addHostKey(b"somewhere-else.example.com", aKey)._hostSalt)
  667. def test_verifyValidKey(self):
  668. """
  669. Verifying a valid key should return a L{Deferred} which fires with
  670. True.
  671. """
  672. hostsFile = self.loadSampleHostsFile()
  673. hostsFile.addHostKey(b"1.2.3.4", Key.fromString(sampleKey))
  674. ui = FakeUI()
  675. d = hostsFile.verifyHostKey(ui, b"www.twistedmatrix.com", b"1.2.3.4",
  676. Key.fromString(sampleKey))
  677. l = []
  678. d.addCallback(l.append)
  679. self.assertEqual(l, [True])
  680. def test_verifyInvalidKey(self):
  681. """
  682. Verifying an invalid key should return a L{Deferred} which fires with a
  683. L{HostKeyChanged} failure.
  684. """
  685. hostsFile = self.loadSampleHostsFile()
  686. wrongKey = Key.fromString(thirdSampleKey)
  687. ui = FakeUI()
  688. hostsFile.addHostKey(b"1.2.3.4", Key.fromString(sampleKey))
  689. d = hostsFile.verifyHostKey(
  690. ui, b"www.twistedmatrix.com", b"1.2.3.4", wrongKey)
  691. return self.assertFailure(d, HostKeyChanged)
  692. def verifyNonPresentKey(self):
  693. """
  694. Set up a test to verify a key that isn't present. Return a 3-tuple of
  695. the UI, a list set up to collect the result of the verifyHostKey call,
  696. and the sample L{KnownHostsFile} being used.
  697. This utility method avoids returning a L{Deferred}, and records results
  698. in the returned list instead, because the events which get generated
  699. here are pre-recorded in the 'ui' object. If the L{Deferred} in
  700. question does not fire, the it will fail quickly with an empty list.
  701. """
  702. hostsFile = self.loadSampleHostsFile()
  703. absentKey = Key.fromString(thirdSampleKey)
  704. ui = FakeUI()
  705. l = []
  706. d = hostsFile.verifyHostKey(
  707. ui, b"sample-host.example.com", b"4.3.2.1", absentKey)
  708. d.addBoth(l.append)
  709. self.assertEqual([], l)
  710. self.assertEqual(
  711. ui.promptText,
  712. b"The authenticity of host 'sample-host.example.com (4.3.2.1)' "
  713. b"can't be established.\n"
  714. b"RSA key fingerprint is "
  715. b"SHA256:mS7mDBGhewdzJkaKRkx+wMjUdZb/GzvgcdoYjX5Js9I=.\n"
  716. b"Are you sure you want to continue connecting (yes/no)? ")
  717. return ui, l, hostsFile
  718. def test_verifyNonPresentKey_Yes(self):
  719. """
  720. Verifying a key where neither the hostname nor the IP are present
  721. should result in the UI being prompted with a message explaining as
  722. much. If the UI says yes, the Deferred should fire with True.
  723. """
  724. ui, l, knownHostsFile = self.verifyNonPresentKey()
  725. ui.promptDeferred.callback(True)
  726. self.assertEqual([True], l)
  727. reloaded = KnownHostsFile.fromPath(knownHostsFile.savePath)
  728. self.assertEqual(
  729. True,
  730. reloaded.hasHostKey(b"4.3.2.1", Key.fromString(thirdSampleKey)))
  731. self.assertEqual(
  732. True,
  733. reloaded.hasHostKey(b"sample-host.example.com",
  734. Key.fromString(thirdSampleKey)))
  735. def test_verifyNonPresentKey_No(self):
  736. """
  737. Verifying a key where neither the hostname nor the IP are present
  738. should result in the UI being prompted with a message explaining as
  739. much. If the UI says no, the Deferred should fail with
  740. UserRejectedKey.
  741. """
  742. ui, l, knownHostsFile = self.verifyNonPresentKey()
  743. ui.promptDeferred.callback(False)
  744. l[0].trap(UserRejectedKey)
  745. def test_verifyNonPresentECKey(self):
  746. """
  747. Set up a test to verify an ECDSA key that isn't present.
  748. Return a 3-tuple of the UI, a list set up to collect the result
  749. of the verifyHostKey call, and the sample L{KnownHostsFile} being used.
  750. """
  751. ecObj = Key._fromECComponents(
  752. x=keydata.ECDatanistp256['x'],
  753. y=keydata.ECDatanistp256['y'],
  754. privateValue=keydata.ECDatanistp256['privateValue'],
  755. curve=keydata.ECDatanistp256['curve']
  756. )
  757. hostsFile = self.loadSampleHostsFile()
  758. ui = FakeUI()
  759. l = []
  760. d = hostsFile.verifyHostKey(
  761. ui, b"sample-host.example.com", b"4.3.2.1", ecObj)
  762. d.addBoth(l.append)
  763. self.assertEqual([], l)
  764. self.assertEqual(
  765. ui.promptText,
  766. b"The authenticity of host 'sample-host.example.com (4.3.2.1)' "
  767. b"can't be established.\n"
  768. b"ECDSA key fingerprint is "
  769. b"SHA256:fJnSpgCcYoYYsaBbnWj1YBghGh/QTDgfe4w4U5M5tEo=.\n"
  770. b"Are you sure you want to continue connecting (yes/no)? ")
  771. def test_verifyHostIPMismatch(self):
  772. """
  773. Verifying a key where the host is present (and correct), but the IP is
  774. present and different, should result the deferred firing in a
  775. HostKeyChanged failure.
  776. """
  777. hostsFile = self.loadSampleHostsFile()
  778. wrongKey = Key.fromString(thirdSampleKey)
  779. ui = FakeUI()
  780. d = hostsFile.verifyHostKey(
  781. ui, b"www.twistedmatrix.com", b"4.3.2.1", wrongKey)
  782. return self.assertFailure(d, HostKeyChanged)
  783. def test_verifyKeyForHostAndIP(self):
  784. """
  785. Verifying a key where the hostname is present but the IP is not should
  786. result in the key being added for the IP and the user being warned
  787. about the change.
  788. """
  789. ui = FakeUI()
  790. hostsFile = self.loadSampleHostsFile()
  791. expectedKey = Key.fromString(sampleKey)
  792. hostsFile.verifyHostKey(
  793. ui, b"www.twistedmatrix.com", b"5.4.3.2", expectedKey)
  794. self.assertEqual(
  795. True, KnownHostsFile.fromPath(hostsFile.savePath).hasHostKey(
  796. b"5.4.3.2", expectedKey))
  797. self.assertEqual(
  798. ["Warning: Permanently added the RSA host key for IP address "
  799. "'5.4.3.2' to the list of known hosts."],
  800. ui.userWarnings)
  801. def test_getHostKeyAlgorithms(self):
  802. """
  803. For a given host, get the host key algorithms for that
  804. host in the known_hosts file.
  805. """
  806. hostsFile = self.loadSampleHostsFile()
  807. hostsFile.addHostKey(
  808. b"www.twistedmatrix.com", Key.fromString(otherSampleKey))
  809. hostsFile.addHostKey(
  810. b"www.twistedmatrix.com", Key.fromString(ecdsaSampleKey))
  811. hostsFile.save()
  812. options = {}
  813. options['known-hosts'] = hostsFile.savePath.path
  814. algorithms = default.getHostKeyAlgorithms(
  815. b"www.twistedmatrix.com", options)
  816. expectedAlgorithms = [b'ssh-rsa', b'ecdsa-sha2-nistp256']
  817. self.assertEqual(algorithms, expectedAlgorithms)
  818. class FakeFile(object):
  819. """
  820. A fake file-like object that acts enough like a file for
  821. L{ConsoleUI.prompt}.
  822. """
  823. def __init__(self):
  824. self.inlines = []
  825. self.outchunks = []
  826. self.closed = False
  827. def readline(self):
  828. """
  829. Return a line from the 'inlines' list.
  830. """
  831. return self.inlines.pop(0)
  832. def write(self, chunk):
  833. """
  834. Append the given item to the 'outchunks' list.
  835. """
  836. if self.closed:
  837. raise IOError("the file was closed")
  838. self.outchunks.append(chunk)
  839. def close(self):
  840. """
  841. Set the 'closed' flag to True, explicitly marking that it has been
  842. closed.
  843. """
  844. self.closed = True
  845. class ConsoleUITests(TestCase):
  846. """
  847. Test cases for L{ConsoleUI}.
  848. """
  849. def setUp(self):
  850. """
  851. Create a L{ConsoleUI} pointed at a L{FakeFile}.
  852. """
  853. self.fakeFile = FakeFile()
  854. self.ui = ConsoleUI(self.openFile)
  855. def openFile(self):
  856. """
  857. Return the current fake file.
  858. """
  859. return self.fakeFile
  860. def newFile(self, lines):
  861. """
  862. Create a new fake file (the next file that self.ui will open) with the
  863. given list of lines to be returned from readline().
  864. """
  865. self.fakeFile = FakeFile()
  866. self.fakeFile.inlines = lines
  867. def test_promptYes(self):
  868. """
  869. L{ConsoleUI.prompt} writes a message to the console, then reads a line.
  870. If that line is 'yes', then it returns a L{Deferred} that fires with
  871. True.
  872. """
  873. for okYes in [b'yes', b'Yes', b'yes\n']:
  874. self.newFile([okYes])
  875. l = []
  876. self.ui.prompt("Hello, world!").addCallback(l.append)
  877. self.assertEqual(["Hello, world!"], self.fakeFile.outchunks)
  878. self.assertEqual([True], l)
  879. self.assertTrue(self.fakeFile.closed)
  880. def test_promptNo(self):
  881. """
  882. L{ConsoleUI.prompt} writes a message to the console, then reads a line.
  883. If that line is 'no', then it returns a L{Deferred} that fires with
  884. False.
  885. """
  886. for okNo in [b'no', b'No', b'no\n']:
  887. self.newFile([okNo])
  888. l = []
  889. self.ui.prompt("Goodbye, world!").addCallback(l.append)
  890. self.assertEqual(["Goodbye, world!"], self.fakeFile.outchunks)
  891. self.assertEqual([False], l)
  892. self.assertTrue(self.fakeFile.closed)
  893. def test_promptRepeatedly(self):
  894. """
  895. L{ConsoleUI.prompt} writes a message to the console, then reads a line.
  896. If that line is neither 'yes' nor 'no', then it says "Please enter
  897. 'yes' or 'no'" until it gets a 'yes' or a 'no', at which point it
  898. returns a Deferred that answers either True or False.
  899. """
  900. self.newFile([b'what', b'uh', b'okay', b'yes'])
  901. l = []
  902. self.ui.prompt(b"Please say something useful.").addCallback(l.append)
  903. self.assertEqual([True], l)
  904. self.assertEqual(self.fakeFile.outchunks,
  905. [b"Please say something useful."] +
  906. [b"Please type 'yes' or 'no': "] * 3)
  907. self.assertTrue(self.fakeFile.closed)
  908. self.newFile([b'blah', b'stuff', b'feh', b'no'])
  909. l = []
  910. self.ui.prompt(b"Please say something negative.").addCallback(l.append)
  911. self.assertEqual([False], l)
  912. self.assertEqual(self.fakeFile.outchunks,
  913. [b"Please say something negative."] +
  914. [b"Please type 'yes' or 'no': "] * 3)
  915. self.assertTrue(self.fakeFile.closed)
  916. def test_promptOpenFailed(self):
  917. """
  918. If the C{opener} passed to L{ConsoleUI} raises an exception, that
  919. exception will fail the L{Deferred} returned from L{ConsoleUI.prompt}.
  920. """
  921. def raiseIt():
  922. raise IOError()
  923. ui = ConsoleUI(raiseIt)
  924. d = ui.prompt("This is a test.")
  925. return self.assertFailure(d, IOError)
  926. def test_warn(self):
  927. """
  928. L{ConsoleUI.warn} should output a message to the console object.
  929. """
  930. self.ui.warn("Test message.")
  931. self.assertEqual(["Test message."], self.fakeFile.outchunks)
  932. self.assertTrue(self.fakeFile.closed)
  933. def test_warnOpenFailed(self):
  934. """
  935. L{ConsoleUI.warn} should log a traceback if the output can't be opened.
  936. """
  937. def raiseIt():
  938. 1 / 0
  939. ui = ConsoleUI(raiseIt)
  940. ui.warn("This message never makes it.")
  941. self.assertEqual(len(self.flushLoggedErrors(ZeroDivisionError)), 1)
  942. class FakeUI(object):
  943. """
  944. A fake UI object, adhering to the interface expected by
  945. L{KnownHostsFile.verifyHostKey}
  946. @ivar userWarnings: inputs provided to 'warn'.
  947. @ivar promptDeferred: last result returned from 'prompt'.
  948. @ivar promptText: the last input provided to 'prompt'.
  949. """
  950. def __init__(self):
  951. self.userWarnings = []
  952. self.promptDeferred = None
  953. self.promptText = None
  954. def prompt(self, text):
  955. """
  956. Issue the user an interactive prompt, which they can accept or deny.
  957. """
  958. self.promptText = text
  959. self.promptDeferred = Deferred()
  960. return self.promptDeferred
  961. def warn(self, text):
  962. """
  963. Issue a non-interactive warning to the user.
  964. """
  965. self.userWarnings.append(text)
  966. class FakeObject(object):
  967. """
  968. A fake object that can have some attributes. Used to fake
  969. L{SSHClientTransport} and L{SSHClientFactory}.
  970. """
  971. class DefaultAPITests(TestCase):
  972. """
  973. The API in L{twisted.conch.client.default.verifyHostKey} is the integration
  974. point between the code in the rest of conch and L{KnownHostsFile}.
  975. """
  976. def patchedOpen(self, fname, mode):
  977. """
  978. The patched version of 'open'; this returns a L{FakeFile} that the
  979. instantiated L{ConsoleUI} can use.
  980. """
  981. self.assertEqual(fname, "/dev/tty")
  982. self.assertEqual(mode, "r+b")
  983. return self.fakeFile
  984. def setUp(self):
  985. """
  986. Patch 'open' in verifyHostKey.
  987. """
  988. self.fakeFile = FakeFile()
  989. self.patch(default, "_open", self.patchedOpen)
  990. self.hostsOption = self.mktemp()
  991. self.hashedEntries = {}
  992. knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
  993. for host in (b"exists.example.com", b"4.3.2.1"):
  994. entry = knownHostsFile.addHostKey(host, Key.fromString(sampleKey))
  995. self.hashedEntries[host] = entry
  996. knownHostsFile.save()
  997. self.fakeTransport = FakeObject()
  998. self.fakeTransport.factory = FakeObject()
  999. self.options = self.fakeTransport.factory.options = {
  1000. 'host': b"exists.example.com",
  1001. 'known-hosts': self.hostsOption
  1002. }
  1003. def test_verifyOKKey(self):
  1004. """
  1005. L{default.verifyHostKey} should return a L{Deferred} which fires with
  1006. C{1} when passed a host, IP, and key which already match the
  1007. known_hosts file it is supposed to check.
  1008. """
  1009. l = []
  1010. default.verifyHostKey(self.fakeTransport, b"4.3.2.1", sampleKey,
  1011. b"I don't care.").addCallback(l.append)
  1012. self.assertEqual([1], l)
  1013. def replaceHome(self, tempHome):
  1014. """
  1015. Replace the HOME environment variable until the end of the current
  1016. test, with the given new home-directory, so that L{os.path.expanduser}
  1017. will yield controllable, predictable results.
  1018. @param tempHome: the pathname to replace the HOME variable with.
  1019. @type tempHome: L{str}
  1020. """
  1021. oldHome = os.environ.get('HOME')
  1022. def cleanupHome():
  1023. if oldHome is None:
  1024. del os.environ['HOME']
  1025. else:
  1026. os.environ['HOME'] = oldHome
  1027. self.addCleanup(cleanupHome)
  1028. os.environ['HOME'] = tempHome
  1029. def test_noKnownHostsOption(self):
  1030. """
  1031. L{default.verifyHostKey} should find your known_hosts file in
  1032. ~/.ssh/known_hosts if you don't specify one explicitly on the command
  1033. line.
  1034. """
  1035. l = []
  1036. tmpdir = self.mktemp()
  1037. oldHostsOption = self.hostsOption
  1038. hostsNonOption = FilePath(tmpdir).child(".ssh").child("known_hosts")
  1039. hostsNonOption.parent().makedirs()
  1040. FilePath(oldHostsOption).moveTo(hostsNonOption)
  1041. self.replaceHome(tmpdir)
  1042. self.options['known-hosts'] = None
  1043. default.verifyHostKey(self.fakeTransport, b"4.3.2.1", sampleKey,
  1044. b"I don't care.").addCallback(l.append)
  1045. self.assertEqual([1], l)
  1046. def test_verifyHostButNotIP(self):
  1047. """
  1048. L{default.verifyHostKey} should return a L{Deferred} which fires with
  1049. C{1} when passed a host which matches with an IP is not present in its
  1050. known_hosts file, and should also warn the user that it has added the
  1051. IP address.
  1052. """
  1053. l = []
  1054. default.verifyHostKey(self.fakeTransport, b"8.7.6.5", sampleKey,
  1055. b"Fingerprint not required.").addCallback(l.append)
  1056. self.assertEqual(
  1057. ["Warning: Permanently added the RSA host key for IP address "
  1058. "'8.7.6.5' to the list of known hosts."],
  1059. self.fakeFile.outchunks)
  1060. self.assertEqual([1], l)
  1061. knownHostsFile = KnownHostsFile.fromPath(FilePath(self.hostsOption))
  1062. self.assertTrue(knownHostsFile.hasHostKey(b"8.7.6.5",
  1063. Key.fromString(sampleKey)))
  1064. def test_verifyQuestion(self):
  1065. """
  1066. L{default.verifyHostKey} should return a L{Default} which fires with
  1067. C{0} when passed an unknown host that the user refuses to acknowledge.
  1068. """
  1069. self.fakeTransport.factory.options['host'] = b'fake.example.com'
  1070. self.fakeFile.inlines.append(b"no")
  1071. d = default.verifyHostKey(
  1072. self.fakeTransport, b"9.8.7.6", otherSampleKey,
  1073. b"No fingerprint!")
  1074. self.assertEqual(
  1075. [b"The authenticity of host 'fake.example.com (9.8.7.6)' "
  1076. b"can't be established.\n"
  1077. b"RSA key fingerprint is "
  1078. b"SHA256:vD0YydsNIUYJa7yLZl3tIL8h0vZvQ8G+HPG7JLmQV0s=.\n"
  1079. b"Are you sure you want to continue connecting (yes/no)? "],
  1080. self.fakeFile.outchunks)
  1081. return self.assertFailure(d, UserRejectedKey)
  1082. def test_verifyBadKey(self):
  1083. """
  1084. L{default.verifyHostKey} should return a L{Deferred} which fails with
  1085. L{HostKeyChanged} if the host key is incorrect.
  1086. """
  1087. d = default.verifyHostKey(
  1088. self.fakeTransport, b"4.3.2.1", otherSampleKey,
  1089. "Again, not required.")
  1090. return self.assertFailure(d, HostKeyChanged)
  1091. def test_inKnownHosts(self):
  1092. """
  1093. L{default.isInKnownHosts} should return C{1} when a host with a key
  1094. is in the known hosts file.
  1095. """
  1096. host = self.hashedEntries[b"4.3.2.1"].toString().split()[0]
  1097. r = default.isInKnownHosts(
  1098. host, Key.fromString(sampleKey).blob(),
  1099. {"known-hosts": FilePath(self.hostsOption).path})
  1100. self.assertEqual(1, r)
  1101. def test_notInKnownHosts(self):
  1102. """
  1103. L{default.isInKnownHosts} should return C{0} when a host with a key
  1104. is not in the known hosts file.
  1105. """
  1106. r = default.isInKnownHosts(
  1107. "not.there", b"irrelevant",
  1108. {"known-hosts": FilePath(self.hostsOption).path})
  1109. self.assertEqual(0, r)
  1110. def test_inKnownHostsKeyChanged(self):
  1111. """
  1112. L{default.isInKnownHosts} should return C{2} when a host with a key
  1113. other than the given one is in the known hosts file.
  1114. """
  1115. host = self.hashedEntries[b"4.3.2.1"].toString().split()[0]
  1116. r = default.isInKnownHosts(
  1117. host, Key.fromString(otherSampleKey).blob(),
  1118. {"known-hosts": FilePath(self.hostsOption).path})
  1119. self.assertEqual(2, r)