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.

535 lines
20 KiB

7 years ago
  1. # Copyright (C) 2003-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. """
  19. Common API for all public keys.
  20. """
  21. import base64
  22. from binascii import unhexlify
  23. import os
  24. from hashlib import md5
  25. from cryptography.hazmat.backends import default_backend
  26. from cryptography.hazmat.primitives import serialization
  27. from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher
  28. from paramiko import util
  29. from paramiko.common import o600
  30. from paramiko.py3compat import u, encodebytes, decodebytes, b, string_types
  31. from paramiko.ssh_exception import SSHException, PasswordRequiredException
  32. from paramiko.message import Message
  33. class PKey(object):
  34. """
  35. Base class for public keys.
  36. """
  37. # known encryption types for private key files:
  38. _CIPHER_TABLE = {
  39. 'AES-128-CBC': {
  40. 'cipher': algorithms.AES,
  41. 'keysize': 16,
  42. 'blocksize': 16,
  43. 'mode': modes.CBC
  44. },
  45. 'AES-256-CBC': {
  46. 'cipher': algorithms.AES,
  47. 'keysize': 32,
  48. 'blocksize': 16,
  49. 'mode': modes.CBC
  50. },
  51. 'DES-EDE3-CBC': {
  52. 'cipher': algorithms.TripleDES,
  53. 'keysize': 24,
  54. 'blocksize': 8,
  55. 'mode': modes.CBC
  56. },
  57. }
  58. def __init__(self, msg=None, data=None):
  59. """
  60. Create a new instance of this public key type. If ``msg`` is given,
  61. the key's public part(s) will be filled in from the message. If
  62. ``data`` is given, the key's public part(s) will be filled in from
  63. the string.
  64. :param .Message msg:
  65. an optional SSH `.Message` containing a public key of this type.
  66. :param str data: an optional string containing a public key
  67. of this type
  68. :raises: `.SSHException` --
  69. if a key cannot be created from the ``data`` or ``msg`` given, or
  70. no key was passed in.
  71. """
  72. pass
  73. def asbytes(self):
  74. """
  75. Return a string of an SSH `.Message` made up of the public part(s) of
  76. this key. This string is suitable for passing to `__init__` to
  77. re-create the key object later.
  78. """
  79. return bytes()
  80. def __str__(self):
  81. return self.asbytes()
  82. # noinspection PyUnresolvedReferences
  83. # TODO: The comparison functions should be removed as per:
  84. # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
  85. def __cmp__(self, other):
  86. """
  87. Compare this key to another. Returns 0 if this key is equivalent to
  88. the given key, or non-0 if they are different. Only the public parts
  89. of the key are compared, so a public key will compare equal to its
  90. corresponding private key.
  91. :param .PKey other: key to compare to.
  92. """
  93. hs = hash(self)
  94. ho = hash(other)
  95. if hs != ho:
  96. return cmp(hs, ho) # noqa
  97. return cmp(self.asbytes(), other.asbytes()) # noqa
  98. def __eq__(self, other):
  99. return hash(self) == hash(other)
  100. def get_name(self):
  101. """
  102. Return the name of this private key implementation.
  103. :return:
  104. name of this private key type, in SSH terminology, as a `str` (for
  105. example, ``"ssh-rsa"``).
  106. """
  107. return ''
  108. def get_bits(self):
  109. """
  110. Return the number of significant bits in this key. This is useful
  111. for judging the relative security of a key.
  112. :return: bits in the key (as an `int`)
  113. """
  114. return 0
  115. def can_sign(self):
  116. """
  117. Return ``True`` if this key has the private part necessary for signing
  118. data.
  119. """
  120. return False
  121. def get_fingerprint(self):
  122. """
  123. Return an MD5 fingerprint of the public part of this key. Nothing
  124. secret is revealed.
  125. :return:
  126. a 16-byte `string <str>` (binary) of the MD5 fingerprint, in SSH
  127. format.
  128. """
  129. return md5(self.asbytes()).digest()
  130. def get_base64(self):
  131. """
  132. Return a base64 string containing the public part of this key. Nothing
  133. secret is revealed. This format is compatible with that used to store
  134. public key files or recognized host keys.
  135. :return: a base64 `string <str>` containing the public part of the key.
  136. """
  137. return u(encodebytes(self.asbytes())).replace('\n', '')
  138. def sign_ssh_data(self, data):
  139. """
  140. Sign a blob of data with this private key, and return a `.Message`
  141. representing an SSH signature message.
  142. :param str data: the data to sign.
  143. :return: an SSH signature `message <.Message>`.
  144. """
  145. return bytes()
  146. def verify_ssh_sig(self, data, msg):
  147. """
  148. Given a blob of data, and an SSH message representing a signature of
  149. that data, verify that it was signed with this key.
  150. :param str data: the data that was signed.
  151. :param .Message msg: an SSH signature message
  152. :return:
  153. ``True`` if the signature verifies correctly; ``False`` otherwise.
  154. """
  155. return False
  156. @classmethod
  157. def from_private_key_file(cls, filename, password=None):
  158. """
  159. Create a key object by reading a private key file. If the private
  160. key is encrypted and ``password`` is not ``None``, the given password
  161. will be used to decrypt the key (otherwise `.PasswordRequiredException`
  162. is thrown). Through the magic of Python, this factory method will
  163. exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
  164. is useless on the abstract PKey class.
  165. :param str filename: name of the file to read
  166. :param str password:
  167. an optional password to use to decrypt the key file, if it's
  168. encrypted
  169. :return: a new `.PKey` based on the given private key
  170. :raises: ``IOError`` -- if there was an error reading the file
  171. :raises: `.PasswordRequiredException` -- if the private key file is
  172. encrypted, and ``password`` is ``None``
  173. :raises: `.SSHException` -- if the key file is invalid
  174. """
  175. key = cls(filename=filename, password=password)
  176. return key
  177. @classmethod
  178. def from_private_key(cls, file_obj, password=None):
  179. """
  180. Create a key object by reading a private key from a file (or file-like)
  181. object. If the private key is encrypted and ``password`` is not
  182. ``None``, the given password will be used to decrypt the key (otherwise
  183. `.PasswordRequiredException` is thrown).
  184. :param file_obj: the file-like object to read from
  185. :param str password:
  186. an optional password to use to decrypt the key, if it's encrypted
  187. :return: a new `.PKey` based on the given private key
  188. :raises: ``IOError`` -- if there was an error reading the key
  189. :raises: `.PasswordRequiredException` --
  190. if the private key file is encrypted, and ``password`` is ``None``
  191. :raises: `.SSHException` -- if the key file is invalid
  192. """
  193. key = cls(file_obj=file_obj, password=password)
  194. return key
  195. def write_private_key_file(self, filename, password=None):
  196. """
  197. Write private key contents into a file. If the password is not
  198. ``None``, the key is encrypted before writing.
  199. :param str filename: name of the file to write
  200. :param str password:
  201. an optional password to use to encrypt the key file
  202. :raises: ``IOError`` -- if there was an error writing the file
  203. :raises: `.SSHException` -- if the key is invalid
  204. """
  205. raise Exception('Not implemented in PKey')
  206. def write_private_key(self, file_obj, password=None):
  207. """
  208. Write private key contents into a file (or file-like) object. If the
  209. password is not ``None``, the key is encrypted before writing.
  210. :param file_obj: the file-like object to write into
  211. :param str password: an optional password to use to encrypt the key
  212. :raises: ``IOError`` -- if there was an error writing to the file
  213. :raises: `.SSHException` -- if the key is invalid
  214. """
  215. raise Exception('Not implemented in PKey')
  216. def _read_private_key_file(self, tag, filename, password=None):
  217. """
  218. Read an SSH2-format private key file, looking for a string of the type
  219. ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we
  220. find, and return it as a string. If the private key is encrypted and
  221. ``password`` is not ``None``, the given password will be used to
  222. decrypt the key (otherwise `.PasswordRequiredException` is thrown).
  223. :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the
  224. data block.
  225. :param str filename: name of the file to read.
  226. :param str password:
  227. an optional password to use to decrypt the key file, if it's
  228. encrypted.
  229. :return: data blob (`str`) that makes up the private key.
  230. :raises: ``IOError`` -- if there was an error reading the file.
  231. :raises: `.PasswordRequiredException` -- if the private key file is
  232. encrypted, and ``password`` is ``None``.
  233. :raises: `.SSHException` -- if the key file is invalid.
  234. """
  235. with open(filename, 'r') as f:
  236. data = self._read_private_key(tag, f, password)
  237. return data
  238. def _read_private_key(self, tag, f, password=None):
  239. lines = f.readlines()
  240. start = 0
  241. beginning_of_key = '-----BEGIN ' + tag + ' PRIVATE KEY-----'
  242. while start < len(lines) and lines[start].strip() != beginning_of_key:
  243. start += 1
  244. if start >= len(lines):
  245. raise SSHException('not a valid ' + tag + ' private key file')
  246. # parse any headers first
  247. headers = {}
  248. start += 1
  249. while start < len(lines):
  250. l = lines[start].split(': ')
  251. if len(l) == 1:
  252. break
  253. headers[l[0].lower()] = l[1].strip()
  254. start += 1
  255. # find end
  256. end = start
  257. ending_of_key = '-----END ' + tag + ' PRIVATE KEY-----'
  258. while end < len(lines) and lines[end].strip() != ending_of_key:
  259. end += 1
  260. # if we trudged to the end of the file, just try to cope.
  261. try:
  262. data = decodebytes(b(''.join(lines[start:end])))
  263. except base64.binascii.Error as e:
  264. raise SSHException('base64 decoding error: ' + str(e))
  265. if 'proc-type' not in headers:
  266. # unencryped: done
  267. return data
  268. # encrypted keyfile: will need a password
  269. proc_type = headers['proc-type']
  270. if proc_type != '4,ENCRYPTED':
  271. raise SSHException(
  272. 'Unknown private key structure "{}"'.format(proc_type)
  273. )
  274. try:
  275. encryption_type, saltstr = headers['dek-info'].split(',')
  276. except:
  277. raise SSHException("Can't parse DEK-info in private key file")
  278. if encryption_type not in self._CIPHER_TABLE:
  279. raise SSHException(
  280. 'Unknown private key cipher "{}"'.format(encryption_type))
  281. # if no password was passed in,
  282. # raise an exception pointing out that we need one
  283. if password is None:
  284. raise PasswordRequiredException('Private key file is encrypted')
  285. cipher = self._CIPHER_TABLE[encryption_type]['cipher']
  286. keysize = self._CIPHER_TABLE[encryption_type]['keysize']
  287. mode = self._CIPHER_TABLE[encryption_type]['mode']
  288. salt = unhexlify(b(saltstr))
  289. key = util.generate_key_bytes(md5, salt, password, keysize)
  290. decryptor = Cipher(
  291. cipher(key), mode(salt), backend=default_backend()
  292. ).decryptor()
  293. return decryptor.update(data) + decryptor.finalize()
  294. def _write_private_key_file(self, filename, key, format, password=None):
  295. """
  296. Write an SSH2-format private key file in a form that can be read by
  297. paramiko or openssh. If no password is given, the key is written in
  298. a trivially-encoded format (base64) which is completely insecure. If
  299. a password is given, DES-EDE3-CBC is used.
  300. :param str tag:
  301. ``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
  302. :param filename: name of the file to write.
  303. :param str data: data blob that makes up the private key.
  304. :param str password: an optional password to use to encrypt the file.
  305. :raises: ``IOError`` -- if there was an error writing the file.
  306. """
  307. with open(filename, 'w') as f:
  308. os.chmod(filename, o600)
  309. self._write_private_key(f, key, format, password=password)
  310. def _write_private_key(self, f, key, format, password=None):
  311. if password is None:
  312. encryption = serialization.NoEncryption()
  313. else:
  314. encryption = serialization.BestAvailableEncryption(b(password))
  315. f.write(key.private_bytes(
  316. serialization.Encoding.PEM,
  317. format,
  318. encryption
  319. ).decode())
  320. def _check_type_and_load_cert(self, msg, key_type, cert_type):
  321. """
  322. Perform message type-checking & optional certificate loading.
  323. This includes fast-forwarding cert ``msg`` objects past the nonce, so
  324. that the subsequent fields are the key numbers; thus the caller may
  325. expect to treat the message as key material afterwards either way.
  326. The obtained key type is returned for classes which need to know what
  327. it was (e.g. ECDSA.)
  328. """
  329. # Normalization; most classes have a single key type and give a string,
  330. # but eg ECDSA is a 1:N mapping.
  331. key_types = key_type
  332. cert_types = cert_type
  333. if isinstance(key_type, string_types):
  334. key_types = [key_types]
  335. if isinstance(cert_types, string_types):
  336. cert_types = [cert_types]
  337. # Can't do much with no message, that should've been handled elsewhere
  338. if msg is None:
  339. raise SSHException('Key object may not be empty')
  340. # First field is always key type, in either kind of object. (make sure
  341. # we rewind before grabbing it - sometimes caller had to do their own
  342. # introspection first!)
  343. msg.rewind()
  344. type_ = msg.get_text()
  345. # Regular public key - nothing special to do besides the implicit
  346. # type check.
  347. if type_ in key_types:
  348. pass
  349. # OpenSSH-compatible certificate - store full copy as .public_blob
  350. # (so signing works correctly) and then fast-forward past the
  351. # nonce.
  352. elif type_ in cert_types:
  353. # This seems the cleanest way to 'clone' an already-being-read
  354. # message; they're *IO objects at heart and their .getvalue()
  355. # always returns the full value regardless of pointer position.
  356. self.load_certificate(Message(msg.asbytes()))
  357. # Read out nonce as it comes before the public numbers.
  358. # TODO: usefully interpret it & other non-public-number fields
  359. # (requires going back into per-type subclasses.)
  360. msg.get_string()
  361. else:
  362. err = 'Invalid key (class: {}, data type: {}'
  363. raise SSHException(err.format(self.__class__.__name__, type_))
  364. def load_certificate(self, value):
  365. """
  366. Supplement the private key contents with data loaded from an OpenSSH
  367. public key (``.pub``) or certificate (``-cert.pub``) file, a string
  368. containing such a file, or a `.Message` object.
  369. The .pub contents adds no real value, since the private key
  370. file includes sufficient information to derive the public
  371. key info. For certificates, however, this can be used on
  372. the client side to offer authentication requests to the server
  373. based on certificate instead of raw public key.
  374. See:
  375. https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
  376. Note: very little effort is made to validate the certificate contents,
  377. that is for the server to decide if it is good enough to authenticate
  378. successfully.
  379. """
  380. if isinstance(value, Message):
  381. constructor = 'from_message'
  382. elif os.path.isfile(value):
  383. constructor = 'from_file'
  384. else:
  385. constructor = 'from_string'
  386. blob = getattr(PublicBlob, constructor)(value)
  387. if not blob.key_type.startswith(self.get_name()):
  388. err = "PublicBlob type {} incompatible with key type {}"
  389. raise ValueError(err.format(blob.key_type, self.get_name()))
  390. self.public_blob = blob
  391. # General construct for an OpenSSH style Public Key blob
  392. # readable from a one-line file of the format:
  393. # <key-name> <base64-blob> [<comment>]
  394. # Of little value in the case of standard public keys
  395. # {ssh-rsa, ssh-dss, ssh-ecdsa, ssh-ed25519}, but should
  396. # provide rudimentary support for {*-cert.v01}
  397. class PublicBlob(object):
  398. """
  399. OpenSSH plain public key or OpenSSH signed public key (certificate).
  400. Tries to be as dumb as possible and barely cares about specific
  401. per-key-type data.
  402. ..note::
  403. Most of the time you'll want to call `from_file`, `from_string` or
  404. `from_message` for useful instantiation, the main constructor is
  405. basically "I should be using ``attrs`` for this."
  406. """
  407. def __init__(self, type_, blob, comment=None):
  408. """
  409. Create a new public blob of given type and contents.
  410. :param str type_: Type indicator, eg ``ssh-rsa``.
  411. :param blob: The blob bytes themselves.
  412. :param str comment: A comment, if one was given (e.g. file-based.)
  413. """
  414. self.key_type = type_
  415. self.key_blob = blob
  416. self.comment = comment
  417. @classmethod
  418. def from_file(cls, filename):
  419. """
  420. Create a public blob from a ``-cert.pub``-style file on disk.
  421. """
  422. with open(filename) as f:
  423. string = f.read()
  424. return cls.from_string(string)
  425. @classmethod
  426. def from_string(cls, string):
  427. """
  428. Create a public blob from a ``-cert.pub``-style string.
  429. """
  430. fields = string.split(None, 2)
  431. if len(fields) < 2:
  432. msg = "Not enough fields for public blob: {}"
  433. raise ValueError(msg.format(fields))
  434. key_type = fields[0]
  435. key_blob = decodebytes(b(fields[1]))
  436. try:
  437. comment = fields[2].strip()
  438. except IndexError:
  439. comment = None
  440. # Verify that the blob message first (string) field matches the
  441. # key_type
  442. m = Message(key_blob)
  443. blob_type = m.get_text()
  444. if blob_type != key_type:
  445. msg = "Invalid PublicBlob contents: key type={!r}, but blob type={!r}" # noqa
  446. raise ValueError(msg.format(key_type, blob_type))
  447. # All good? All good.
  448. return cls(type_=key_type, blob=key_blob, comment=comment)
  449. @classmethod
  450. def from_message(cls, message):
  451. """
  452. Create a public blob from a network `.Message`.
  453. Specifically, a cert-bearing pubkey auth packet, because by definition
  454. OpenSSH-style certificates 'are' their own network representation."
  455. """
  456. type_ = message.get_text()
  457. return cls(type_=type_, blob=message.asbytes())
  458. def __str__(self):
  459. ret = '{} public key/certificate'.format(self.key_type)
  460. if self.comment:
  461. ret += "- {}".format(self.comment)
  462. return ret
  463. def __eq__(self, other):
  464. # Just piggyback on Message/BytesIO, since both of these should be one.
  465. return self and other and self.key_blob == other.key_blob
  466. def __ne__(self, other):
  467. return not self == other

Powered by TurnKey Linux.