You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

385 lines
13 KiB

7 years ago
  1. # Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. import binascii
  19. import os
  20. from collections import MutableMapping
  21. from hashlib import sha1
  22. from hmac import HMAC
  23. from paramiko.py3compat import b, u, encodebytes, decodebytes
  24. from paramiko.dsskey import DSSKey
  25. from paramiko.rsakey import RSAKey
  26. from paramiko.util import get_logger, constant_time_bytes_eq
  27. from paramiko.ecdsakey import ECDSAKey
  28. from paramiko.ed25519key import Ed25519Key
  29. from paramiko.ssh_exception import SSHException
  30. class HostKeys (MutableMapping):
  31. """
  32. Representation of an OpenSSH-style "known hosts" file. Host keys can be
  33. read from one or more files, and then individual hosts can be looked up to
  34. verify server keys during SSH negotiation.
  35. A `.HostKeys` object can be treated like a dict; any dict lookup is
  36. equivalent to calling `lookup`.
  37. .. versionadded:: 1.5.3
  38. """
  39. def __init__(self, filename=None):
  40. """
  41. Create a new HostKeys object, optionally loading keys from an OpenSSH
  42. style host-key file.
  43. :param str filename: filename to load host keys from, or ``None``
  44. """
  45. # emulate a dict of { hostname: { keytype: PKey } }
  46. self._entries = []
  47. if filename is not None:
  48. self.load(filename)
  49. def add(self, hostname, keytype, key):
  50. """
  51. Add a host key entry to the table. Any existing entry for a
  52. ``(hostname, keytype)`` pair will be replaced.
  53. :param str hostname: the hostname (or IP) to add
  54. :param str keytype: key type (``"ssh-rsa"`` or ``"ssh-dss"``)
  55. :param .PKey key: the key to add
  56. """
  57. for e in self._entries:
  58. if (hostname in e.hostnames) and (e.key.get_name() == keytype):
  59. e.key = key
  60. return
  61. self._entries.append(HostKeyEntry([hostname], key))
  62. def load(self, filename):
  63. """
  64. Read a file of known SSH host keys, in the format used by OpenSSH.
  65. This type of file unfortunately doesn't exist on Windows, but on
  66. posix, it will usually be stored in
  67. ``os.path.expanduser("~/.ssh/known_hosts")``.
  68. If this method is called multiple times, the host keys are merged,
  69. not cleared. So multiple calls to `load` will just call `add`,
  70. replacing any existing entries and adding new ones.
  71. :param str filename: name of the file to read host keys from
  72. :raises: ``IOError`` -- if there was an error reading the file
  73. """
  74. with open(filename, 'r') as f:
  75. for lineno, line in enumerate(f, 1):
  76. line = line.strip()
  77. if (len(line) == 0) or (line[0] == '#'):
  78. continue
  79. try:
  80. e = HostKeyEntry.from_line(line, lineno)
  81. except SSHException:
  82. continue
  83. if e is not None:
  84. _hostnames = e.hostnames
  85. for h in _hostnames:
  86. if self.check(h, e.key):
  87. e.hostnames.remove(h)
  88. if len(e.hostnames):
  89. self._entries.append(e)
  90. def save(self, filename):
  91. """
  92. Save host keys into a file, in the format used by OpenSSH. The order
  93. of keys in the file will be preserved when possible (if these keys were
  94. loaded from a file originally). The single exception is that combined
  95. lines will be split into individual key lines, which is arguably a bug.
  96. :param str filename: name of the file to write
  97. :raises: ``IOError`` -- if there was an error writing the file
  98. .. versionadded:: 1.6.1
  99. """
  100. with open(filename, 'w') as f:
  101. for e in self._entries:
  102. line = e.to_line()
  103. if line:
  104. f.write(line)
  105. def lookup(self, hostname):
  106. """
  107. Find a hostkey entry for a given hostname or IP. If no entry is found,
  108. ``None`` is returned. Otherwise a dictionary of keytype to key is
  109. returned. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``.
  110. :param str hostname: the hostname (or IP) to lookup
  111. :return: dict of `str` -> `.PKey` keys associated with this host
  112. (or ``None``)
  113. """
  114. class SubDict (MutableMapping):
  115. def __init__(self, hostname, entries, hostkeys):
  116. self._hostname = hostname
  117. self._entries = entries
  118. self._hostkeys = hostkeys
  119. def __iter__(self):
  120. for k in self.keys():
  121. yield k
  122. def __len__(self):
  123. return len(self.keys())
  124. def __delitem__(self, key):
  125. for e in list(self._entries):
  126. if e.key.get_name() == key:
  127. self._entries.remove(e)
  128. else:
  129. raise KeyError(key)
  130. def __getitem__(self, key):
  131. for e in self._entries:
  132. if e.key.get_name() == key:
  133. return e.key
  134. raise KeyError(key)
  135. def __setitem__(self, key, val):
  136. for e in self._entries:
  137. if e.key is None:
  138. continue
  139. if e.key.get_name() == key:
  140. # replace
  141. e.key = val
  142. break
  143. else:
  144. # add a new one
  145. e = HostKeyEntry([hostname], val)
  146. self._entries.append(e)
  147. self._hostkeys._entries.append(e)
  148. def keys(self):
  149. return [
  150. e.key.get_name() for e in self._entries
  151. if e.key is not None
  152. ]
  153. entries = []
  154. for e in self._entries:
  155. if self._hostname_matches(hostname, e):
  156. entries.append(e)
  157. if len(entries) == 0:
  158. return None
  159. return SubDict(hostname, entries, self)
  160. def _hostname_matches(self, hostname, entry):
  161. """
  162. Tests whether ``hostname`` string matches given SubDict ``entry``.
  163. :returns bool:
  164. """
  165. for h in entry.hostnames:
  166. if (
  167. h == hostname or
  168. h.startswith('|1|') and
  169. not hostname.startswith('|1|') and
  170. constant_time_bytes_eq(self.hash_host(hostname, h), h)
  171. ):
  172. return True
  173. return False
  174. def check(self, hostname, key):
  175. """
  176. Return True if the given key is associated with the given hostname
  177. in this dictionary.
  178. :param str hostname: hostname (or IP) of the SSH server
  179. :param .PKey key: the key to check
  180. :return:
  181. ``True`` if the key is associated with the hostname; else ``False``
  182. """
  183. k = self.lookup(hostname)
  184. if k is None:
  185. return False
  186. host_key = k.get(key.get_name(), None)
  187. if host_key is None:
  188. return False
  189. return host_key.asbytes() == key.asbytes()
  190. def clear(self):
  191. """
  192. Remove all host keys from the dictionary.
  193. """
  194. self._entries = []
  195. def __iter__(self):
  196. for k in self.keys():
  197. yield k
  198. def __len__(self):
  199. return len(self.keys())
  200. def __getitem__(self, key):
  201. ret = self.lookup(key)
  202. if ret is None:
  203. raise KeyError(key)
  204. return ret
  205. def __delitem__(self, key):
  206. index = None
  207. for i, entry in enumerate(self._entries):
  208. if self._hostname_matches(key, entry):
  209. index = i
  210. break
  211. if index is None:
  212. raise KeyError(key)
  213. self._entries.pop(index)
  214. def __setitem__(self, hostname, entry):
  215. # don't use this please.
  216. if len(entry) == 0:
  217. self._entries.append(HostKeyEntry([hostname], None))
  218. return
  219. for key_type in entry.keys():
  220. found = False
  221. for e in self._entries:
  222. if (hostname in e.hostnames) and e.key.get_name() == key_type:
  223. # replace
  224. e.key = entry[key_type]
  225. found = True
  226. if not found:
  227. self._entries.append(HostKeyEntry([hostname], entry[key_type]))
  228. def keys(self):
  229. # Python 2.4 sets would be nice here.
  230. ret = []
  231. for e in self._entries:
  232. for h in e.hostnames:
  233. if h not in ret:
  234. ret.append(h)
  235. return ret
  236. def values(self):
  237. ret = []
  238. for k in self.keys():
  239. ret.append(self.lookup(k))
  240. return ret
  241. @staticmethod
  242. def hash_host(hostname, salt=None):
  243. """
  244. Return a "hashed" form of the hostname, as used by OpenSSH when storing
  245. hashed hostnames in the known_hosts file.
  246. :param str hostname: the hostname to hash
  247. :param str salt: optional salt to use when hashing
  248. (must be 20 bytes long)
  249. :return: the hashed hostname as a `str`
  250. """
  251. if salt is None:
  252. salt = os.urandom(sha1().digest_size)
  253. else:
  254. if salt.startswith('|1|'):
  255. salt = salt.split('|')[2]
  256. salt = decodebytes(b(salt))
  257. assert len(salt) == sha1().digest_size
  258. hmac = HMAC(salt, b(hostname), sha1).digest()
  259. hostkey = '|1|{}|{}'.format(u(encodebytes(salt)), u(encodebytes(hmac)))
  260. return hostkey.replace('\n', '')
  261. class InvalidHostKey(Exception):
  262. def __init__(self, line, exc):
  263. self.line = line
  264. self.exc = exc
  265. self.args = (line, exc)
  266. class HostKeyEntry:
  267. """
  268. Representation of a line in an OpenSSH-style "known hosts" file.
  269. """
  270. def __init__(self, hostnames=None, key=None):
  271. self.valid = (hostnames is not None) and (key is not None)
  272. self.hostnames = hostnames
  273. self.key = key
  274. @classmethod
  275. def from_line(cls, line, lineno=None):
  276. """
  277. Parses the given line of text to find the names for the host,
  278. the type of key, and the key data. The line is expected to be in the
  279. format used by the OpenSSH known_hosts file.
  280. Lines are expected to not have leading or trailing whitespace.
  281. We don't bother to check for comments or empty lines. All of
  282. that should be taken care of before sending the line to us.
  283. :param str line: a line from an OpenSSH known_hosts file
  284. """
  285. log = get_logger('paramiko.hostkeys')
  286. fields = line.split(' ')
  287. if len(fields) < 3:
  288. # Bad number of fields
  289. msg = "Not enough fields found in known_hosts in line {} ({!r})"
  290. log.info(msg.format(lineno, line))
  291. return None
  292. fields = fields[:3]
  293. names, keytype, key = fields
  294. names = names.split(',')
  295. # Decide what kind of key we're looking at and create an object
  296. # to hold it accordingly.
  297. try:
  298. key = b(key)
  299. if keytype == 'ssh-rsa':
  300. key = RSAKey(data=decodebytes(key))
  301. elif keytype == 'ssh-dss':
  302. key = DSSKey(data=decodebytes(key))
  303. elif keytype in ECDSAKey.supported_key_format_identifiers():
  304. key = ECDSAKey(data=decodebytes(key), validate_point=False)
  305. elif keytype == 'ssh-ed25519':
  306. key = Ed25519Key(data=decodebytes(key))
  307. else:
  308. log.info("Unable to handle key of type {}".format(keytype))
  309. return None
  310. except binascii.Error as e:
  311. raise InvalidHostKey(line, e)
  312. return cls(names, key)
  313. def to_line(self):
  314. """
  315. Returns a string in OpenSSH known_hosts file format, or None if
  316. the object is not in a valid state. A trailing newline is
  317. included.
  318. """
  319. if self.valid:
  320. return '{} {} {}\n'.format(
  321. ','.join(self.hostnames),
  322. self.key.get_name(),
  323. self.key.get_base64(),
  324. )
  325. return None
  326. def __repr__(self):
  327. return '<HostKeyEntry {!r}: {!r}>'.format(self.hostnames, self.key)

Powered by TurnKey Linux.