knownhosts.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. # -*- test-case-name: twisted.conch.test.test_knownhosts -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An implementation of the OpenSSH known_hosts database.
  6. @since: 8.2
  7. """
  8. from __future__ import absolute_import, division
  9. import hmac
  10. from binascii import Error as DecodeError, b2a_base64, a2b_base64
  11. from contextlib import closing
  12. from hashlib import sha1
  13. import sys
  14. from zope.interface import implementer
  15. from twisted.conch.interfaces import IKnownHostEntry
  16. from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
  17. from twisted.conch.ssh.keys import Key, BadKeyError, FingerprintFormats
  18. from twisted.internet import defer
  19. from twisted.python import log
  20. from twisted.python.compat import nativeString, unicode
  21. from twisted.python.randbytes import secureRandom
  22. from twisted.python.util import FancyEqMixin
  23. def _b64encode(s):
  24. """
  25. Encode a binary string as base64 with no trailing newline.
  26. @param s: The string to encode.
  27. @type s: L{bytes}
  28. @return: The base64-encoded string.
  29. @rtype: L{bytes}
  30. """
  31. return b2a_base64(s).strip()
  32. def _extractCommon(string):
  33. """
  34. Extract common elements of base64 keys from an entry in a hosts file.
  35. @param string: A known hosts file entry (a single line).
  36. @type string: L{bytes}
  37. @return: a 4-tuple of hostname data (L{bytes}), ssh key type (L{bytes}), key
  38. (L{Key}), and comment (L{bytes} or L{None}). The hostname data is
  39. simply the beginning of the line up to the first occurrence of
  40. whitespace.
  41. @rtype: L{tuple}
  42. """
  43. elements = string.split(None, 2)
  44. if len(elements) != 3:
  45. raise InvalidEntry()
  46. hostnames, keyType, keyAndComment = elements
  47. splitkey = keyAndComment.split(None, 1)
  48. if len(splitkey) == 2:
  49. keyString, comment = splitkey
  50. comment = comment.rstrip(b"\n")
  51. else:
  52. keyString = splitkey[0]
  53. comment = None
  54. key = Key.fromString(a2b_base64(keyString))
  55. return hostnames, keyType, key, comment
  56. class _BaseEntry(object):
  57. """
  58. Abstract base of both hashed and non-hashed entry objects, since they
  59. represent keys and key types the same way.
  60. @ivar keyType: The type of the key; either ssh-dss or ssh-rsa.
  61. @type keyType: L{bytes}
  62. @ivar publicKey: The server public key indicated by this line.
  63. @type publicKey: L{twisted.conch.ssh.keys.Key}
  64. @ivar comment: Trailing garbage after the key line.
  65. @type comment: L{bytes}
  66. """
  67. def __init__(self, keyType, publicKey, comment):
  68. self.keyType = keyType
  69. self.publicKey = publicKey
  70. self.comment = comment
  71. def matchesKey(self, keyObject):
  72. """
  73. Check to see if this entry matches a given key object.
  74. @param keyObject: A public key object to check.
  75. @type keyObject: L{Key}
  76. @return: C{True} if this entry's key matches C{keyObject}, C{False}
  77. otherwise.
  78. @rtype: L{bool}
  79. """
  80. return self.publicKey == keyObject
  81. @implementer(IKnownHostEntry)
  82. class PlainEntry(_BaseEntry):
  83. """
  84. A L{PlainEntry} is a representation of a plain-text entry in a known_hosts
  85. file.
  86. @ivar _hostnames: the list of all host-names associated with this entry.
  87. @type _hostnames: L{list} of L{bytes}
  88. """
  89. def __init__(self, hostnames, keyType, publicKey, comment):
  90. self._hostnames = hostnames
  91. super(PlainEntry, self).__init__(keyType, publicKey, comment)
  92. @classmethod
  93. def fromString(cls, string):
  94. """
  95. Parse a plain-text entry in a known_hosts file, and return a
  96. corresponding L{PlainEntry}.
  97. @param string: a space-separated string formatted like "hostname
  98. key-type base64-key-data comment".
  99. @type string: L{bytes}
  100. @raise DecodeError: if the key is not valid encoded as valid base64.
  101. @raise InvalidEntry: if the entry does not have the right number of
  102. elements and is therefore invalid.
  103. @raise BadKeyError: if the key, once decoded from base64, is not
  104. actually an SSH key.
  105. @return: an IKnownHostEntry representing the hostname and key in the
  106. input line.
  107. @rtype: L{PlainEntry}
  108. """
  109. hostnames, keyType, key, comment = _extractCommon(string)
  110. self = cls(hostnames.split(b","), keyType, key, comment)
  111. return self
  112. def matchesHost(self, hostname):
  113. """
  114. Check to see if this entry matches a given hostname.
  115. @param hostname: A hostname or IP address literal to check against this
  116. entry.
  117. @type hostname: L{bytes}
  118. @return: C{True} if this entry is for the given hostname or IP address,
  119. C{False} otherwise.
  120. @rtype: L{bool}
  121. """
  122. if isinstance(hostname, unicode):
  123. hostname = hostname.encode("utf-8")
  124. return hostname in self._hostnames
  125. def toString(self):
  126. """
  127. Implement L{IKnownHostEntry.toString} by recording the comma-separated
  128. hostnames, key type, and base-64 encoded key.
  129. @return: The string representation of this entry, with unhashed hostname
  130. information.
  131. @rtype: L{bytes}
  132. """
  133. fields = [b','.join(self._hostnames),
  134. self.keyType,
  135. _b64encode(self.publicKey.blob())]
  136. if self.comment is not None:
  137. fields.append(self.comment)
  138. return b' '.join(fields)
  139. @implementer(IKnownHostEntry)
  140. class UnparsedEntry(object):
  141. """
  142. L{UnparsedEntry} is an entry in a L{KnownHostsFile} which can't actually be
  143. parsed; therefore it matches no keys and no hosts.
  144. """
  145. def __init__(self, string):
  146. """
  147. Create an unparsed entry from a line in a known_hosts file which cannot
  148. otherwise be parsed.
  149. """
  150. self._string = string
  151. def matchesHost(self, hostname):
  152. """
  153. Always returns False.
  154. """
  155. return False
  156. def matchesKey(self, key):
  157. """
  158. Always returns False.
  159. """
  160. return False
  161. def toString(self):
  162. """
  163. Returns the input line, without its newline if one was given.
  164. @return: The string representation of this entry, almost exactly as was
  165. used to initialize this entry but without a trailing newline.
  166. @rtype: L{bytes}
  167. """
  168. return self._string.rstrip(b"\n")
  169. def _hmacedString(key, string):
  170. """
  171. Return the SHA-1 HMAC hash of the given key and string.
  172. @param key: The HMAC key.
  173. @type key: L{bytes}
  174. @param string: The string to be hashed.
  175. @type string: L{bytes}
  176. @return: The keyed hash value.
  177. @rtype: L{bytes}
  178. """
  179. hash = hmac.HMAC(key, digestmod=sha1)
  180. if isinstance(string, unicode):
  181. string = string.encode("utf-8")
  182. hash.update(string)
  183. return hash.digest()
  184. @implementer(IKnownHostEntry)
  185. class HashedEntry(_BaseEntry, FancyEqMixin):
  186. """
  187. A L{HashedEntry} is a representation of an entry in a known_hosts file
  188. where the hostname has been hashed and salted.
  189. @ivar _hostSalt: the salt to combine with a hostname for hashing.
  190. @ivar _hostHash: the hashed representation of the hostname.
  191. @cvar MAGIC: the 'hash magic' string used to identify a hashed line in a
  192. known_hosts file as opposed to a plaintext one.
  193. """
  194. MAGIC = b'|1|'
  195. compareAttributes = (
  196. "_hostSalt", "_hostHash", "keyType", "publicKey", "comment")
  197. def __init__(self, hostSalt, hostHash, keyType, publicKey, comment):
  198. self._hostSalt = hostSalt
  199. self._hostHash = hostHash
  200. super(HashedEntry, self).__init__(keyType, publicKey, comment)
  201. @classmethod
  202. def fromString(cls, string):
  203. """
  204. Load a hashed entry from a string representing a line in a known_hosts
  205. file.
  206. @param string: A complete single line from a I{known_hosts} file,
  207. formatted as defined by OpenSSH.
  208. @type string: L{bytes}
  209. @raise DecodeError: if the key, the hostname, or the is not valid
  210. encoded as valid base64
  211. @raise InvalidEntry: if the entry does not have the right number of
  212. elements and is therefore invalid, or the host/hash portion contains
  213. more items than just the host and hash.
  214. @raise BadKeyError: if the key, once decoded from base64, is not
  215. actually an SSH key.
  216. @return: The newly created L{HashedEntry} instance, initialized with the
  217. information from C{string}.
  218. """
  219. stuff, keyType, key, comment = _extractCommon(string)
  220. saltAndHash = stuff[len(cls.MAGIC):].split(b"|")
  221. if len(saltAndHash) != 2:
  222. raise InvalidEntry()
  223. hostSalt, hostHash = saltAndHash
  224. self = cls(a2b_base64(hostSalt), a2b_base64(hostHash),
  225. keyType, key, comment)
  226. return self
  227. def matchesHost(self, hostname):
  228. """
  229. Implement L{IKnownHostEntry.matchesHost} to compare the hash of the
  230. input to the stored hash.
  231. @param hostname: A hostname or IP address literal to check against this
  232. entry.
  233. @type hostname: L{bytes}
  234. @return: C{True} if this entry is for the given hostname or IP address,
  235. C{False} otherwise.
  236. @rtype: L{bool}
  237. """
  238. return (_hmacedString(self._hostSalt, hostname) == self._hostHash)
  239. def toString(self):
  240. """
  241. Implement L{IKnownHostEntry.toString} by base64-encoding the salt, host
  242. hash, and key.
  243. @return: The string representation of this entry, with the hostname part
  244. hashed.
  245. @rtype: L{bytes}
  246. """
  247. fields = [self.MAGIC + b'|'.join([_b64encode(self._hostSalt),
  248. _b64encode(self._hostHash)]),
  249. self.keyType,
  250. _b64encode(self.publicKey.blob())]
  251. if self.comment is not None:
  252. fields.append(self.comment)
  253. return b' '.join(fields)
  254. class KnownHostsFile(object):
  255. """
  256. A structured representation of an OpenSSH-format ~/.ssh/known_hosts file.
  257. @ivar _added: A list of L{IKnownHostEntry} providers which have been added
  258. to this instance in memory but not yet saved.
  259. @ivar _clobber: A flag indicating whether the current contents of the save
  260. path will be disregarded and potentially overwritten or not. If
  261. C{True}, this will be done. If C{False}, entries in the save path will
  262. be read and new entries will be saved by appending rather than
  263. overwriting.
  264. @type _clobber: L{bool}
  265. @ivar _savePath: See C{savePath} parameter of L{__init__}.
  266. """
  267. def __init__(self, savePath):
  268. """
  269. Create a new, empty KnownHostsFile.
  270. Unless you want to erase the current contents of C{savePath}, you want
  271. to use L{KnownHostsFile.fromPath} instead.
  272. @param savePath: The L{FilePath} to which to save new entries.
  273. @type savePath: L{FilePath}
  274. """
  275. self._added = []
  276. self._savePath = savePath
  277. self._clobber = True
  278. @property
  279. def savePath(self):
  280. """
  281. @see: C{savePath} parameter of L{__init__}
  282. """
  283. return self._savePath
  284. def iterentries(self):
  285. """
  286. Iterate over the host entries in this file.
  287. @return: An iterable the elements of which provide L{IKnownHostEntry}.
  288. There is an element for each entry in the file as well as an element
  289. for each added but not yet saved entry.
  290. @rtype: iterable of L{IKnownHostEntry} providers
  291. """
  292. for entry in self._added:
  293. yield entry
  294. if self._clobber:
  295. return
  296. try:
  297. fp = self._savePath.open()
  298. except IOError:
  299. return
  300. with fp:
  301. for line in fp:
  302. try:
  303. if line.startswith(HashedEntry.MAGIC):
  304. entry = HashedEntry.fromString(line)
  305. else:
  306. entry = PlainEntry.fromString(line)
  307. except (DecodeError, InvalidEntry, BadKeyError):
  308. entry = UnparsedEntry(line)
  309. yield entry
  310. def hasHostKey(self, hostname, key):
  311. """
  312. Check for an entry with matching hostname and key.
  313. @param hostname: A hostname or IP address literal to check for.
  314. @type hostname: L{bytes}
  315. @param key: The public key to check for.
  316. @type key: L{Key}
  317. @return: C{True} if the given hostname and key are present in this file,
  318. C{False} if they are not.
  319. @rtype: L{bool}
  320. @raise HostKeyChanged: if the host key found for the given hostname
  321. does not match the given key.
  322. """
  323. for lineidx, entry in enumerate(self.iterentries(), -len(self._added)):
  324. if entry.matchesHost(hostname) and entry.keyType == key.sshType():
  325. if entry.matchesKey(key):
  326. return True
  327. else:
  328. # Notice that lineidx is 0-based but HostKeyChanged.lineno
  329. # is 1-based.
  330. if lineidx < 0:
  331. line = None
  332. path = None
  333. else:
  334. line = lineidx + 1
  335. path = self._savePath
  336. raise HostKeyChanged(entry, path, line)
  337. return False
  338. def verifyHostKey(self, ui, hostname, ip, key):
  339. """
  340. Verify the given host key for the given IP and host, asking for
  341. confirmation from, and notifying, the given UI about changes to this
  342. file.
  343. @param ui: The user interface to request an IP address from.
  344. @param hostname: The hostname that the user requested to connect to.
  345. @param ip: The string representation of the IP address that is actually
  346. being connected to.
  347. @param key: The public key of the server.
  348. @return: a L{Deferred} that fires with True when the key has been
  349. verified, or fires with an errback when the key either cannot be
  350. verified or has changed.
  351. @rtype: L{Deferred}
  352. """
  353. hhk = defer.maybeDeferred(self.hasHostKey, hostname, key)
  354. def gotHasKey(result):
  355. if result:
  356. if not self.hasHostKey(ip, key):
  357. ui.warn("Warning: Permanently added the %s host key for "
  358. "IP address '%s' to the list of known hosts." %
  359. (key.type(), nativeString(ip)))
  360. self.addHostKey(ip, key)
  361. self.save()
  362. return result
  363. else:
  364. def promptResponse(response):
  365. if response:
  366. self.addHostKey(hostname, key)
  367. self.addHostKey(ip, key)
  368. self.save()
  369. return response
  370. else:
  371. raise UserRejectedKey()
  372. keytype = key.type()
  373. if keytype == "EC":
  374. keytype = "ECDSA"
  375. prompt = (
  376. "The authenticity of host '%s (%s)' "
  377. "can't be established.\n"
  378. "%s key fingerprint is SHA256:%s.\n"
  379. "Are you sure you want to continue connecting (yes/no)? " %
  380. (nativeString(hostname), nativeString(ip), keytype,
  381. key.fingerprint(format=FingerprintFormats.SHA256_BASE64)))
  382. proceed = ui.prompt(prompt.encode(sys.getdefaultencoding()))
  383. return proceed.addCallback(promptResponse)
  384. return hhk.addCallback(gotHasKey)
  385. def addHostKey(self, hostname, key):
  386. """
  387. Add a new L{HashedEntry} to the key database.
  388. Note that you still need to call L{KnownHostsFile.save} if you wish
  389. these changes to be persisted.
  390. @param hostname: A hostname or IP address literal to associate with the
  391. new entry.
  392. @type hostname: L{bytes}
  393. @param key: The public key to associate with the new entry.
  394. @type key: L{Key}
  395. @return: The L{HashedEntry} that was added.
  396. @rtype: L{HashedEntry}
  397. """
  398. salt = secureRandom(20)
  399. keyType = key.sshType()
  400. entry = HashedEntry(salt, _hmacedString(salt, hostname),
  401. keyType, key, None)
  402. self._added.append(entry)
  403. return entry
  404. def save(self):
  405. """
  406. Save this L{KnownHostsFile} to the path it was loaded from.
  407. """
  408. p = self._savePath.parent()
  409. if not p.isdir():
  410. p.makedirs()
  411. if self._clobber:
  412. mode = "wb"
  413. else:
  414. mode = "ab"
  415. with self._savePath.open(mode) as hostsFileObj:
  416. if self._added:
  417. hostsFileObj.write(
  418. b"\n".join([entry.toString() for entry in self._added]) +
  419. b"\n")
  420. self._added = []
  421. self._clobber = False
  422. @classmethod
  423. def fromPath(cls, path):
  424. """
  425. Create a new L{KnownHostsFile}, potentially reading existing known
  426. hosts information from the given file.
  427. @param path: A path object to use for both reading contents from and
  428. later saving to. If no file exists at this path, it is not an
  429. error; a L{KnownHostsFile} with no entries is returned.
  430. @type path: L{FilePath}
  431. @return: A L{KnownHostsFile} initialized with entries from C{path}.
  432. @rtype: L{KnownHostsFile}
  433. """
  434. knownHosts = cls(path)
  435. knownHosts._clobber = False
  436. return knownHosts
  437. class ConsoleUI(object):
  438. """
  439. A UI object that can ask true/false questions and post notifications on the
  440. console, to be used during key verification.
  441. """
  442. def __init__(self, opener):
  443. """
  444. @param opener: A no-argument callable which should open a console
  445. binary-mode file-like object to be used for reading and writing.
  446. This initializes the C{opener} attribute.
  447. @type opener: callable taking no arguments and returning a read/write
  448. file-like object
  449. """
  450. self.opener = opener
  451. def prompt(self, text):
  452. """
  453. Write the given text as a prompt to the console output, then read a
  454. result from the console input.
  455. @param text: Something to present to a user to solicit a yes or no
  456. response.
  457. @type text: L{bytes}
  458. @return: a L{Deferred} which fires with L{True} when the user answers
  459. 'yes' and L{False} when the user answers 'no'. It may errback if
  460. there were any I/O errors.
  461. """
  462. d = defer.succeed(None)
  463. def body(ignored):
  464. with closing(self.opener()) as f:
  465. f.write(text)
  466. while True:
  467. answer = f.readline().strip().lower()
  468. if answer == b'yes':
  469. return True
  470. elif answer == b'no':
  471. return False
  472. else:
  473. f.write(b"Please type 'yes' or 'no': ")
  474. return d.addCallback(body)
  475. def warn(self, text):
  476. """
  477. Notify the user (non-interactively) of the provided text, by writing it
  478. to the console.
  479. @param text: Some information the user is to be made aware of.
  480. @type text: L{bytes}
  481. """
  482. try:
  483. with closing(self.opener()) as f:
  484. f.write(text)
  485. except:
  486. log.err()