pkey.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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
  31. from paramiko.ssh_exception import SSHException, PasswordRequiredException
  32. class PKey(object):
  33. """
  34. Base class for public keys.
  35. """
  36. # known encryption types for private key files:
  37. _CIPHER_TABLE = {
  38. 'AES-128-CBC': {
  39. 'cipher': algorithms.AES,
  40. 'keysize': 16,
  41. 'blocksize': 16,
  42. 'mode': modes.CBC
  43. },
  44. 'AES-256-CBC': {
  45. 'cipher': algorithms.AES,
  46. 'keysize': 32,
  47. 'blocksize': 16,
  48. 'mode': modes.CBC
  49. },
  50. 'DES-EDE3-CBC': {
  51. 'cipher': algorithms.TripleDES,
  52. 'keysize': 24,
  53. 'blocksize': 8,
  54. 'mode': modes.CBC
  55. },
  56. }
  57. def __init__(self, msg=None, data=None):
  58. """
  59. Create a new instance of this public key type. If ``msg`` is given,
  60. the key's public part(s) will be filled in from the message. If
  61. ``data`` is given, the key's public part(s) will be filled in from
  62. the string.
  63. :param .Message msg:
  64. an optional SSH `.Message` containing a public key of this type.
  65. :param str data: an optional string containing a public key
  66. of this type
  67. :raises: `.SSHException` --
  68. if a key cannot be created from the ``data`` or ``msg`` given, or
  69. no key was passed in.
  70. """
  71. pass
  72. def asbytes(self):
  73. """
  74. Return a string of an SSH `.Message` made up of the public part(s) of
  75. this key. This string is suitable for passing to `__init__` to
  76. re-create the key object later.
  77. """
  78. return bytes()
  79. def __str__(self):
  80. return self.asbytes()
  81. # noinspection PyUnresolvedReferences
  82. # TODO: The comparison functions should be removed as per:
  83. # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
  84. def __cmp__(self, other):
  85. """
  86. Compare this key to another. Returns 0 if this key is equivalent to
  87. the given key, or non-0 if they are different. Only the public parts
  88. of the key are compared, so a public key will compare equal to its
  89. corresponding private key.
  90. :param .PKey other: key to compare to.
  91. """
  92. hs = hash(self)
  93. ho = hash(other)
  94. if hs != ho:
  95. return cmp(hs, ho) # noqa
  96. return cmp(self.asbytes(), other.asbytes()) # noqa
  97. def __eq__(self, other):
  98. return hash(self) == hash(other)
  99. def get_name(self):
  100. """
  101. Return the name of this private key implementation.
  102. :return:
  103. name of this private key type, in SSH terminology, as a `str` (for
  104. example, ``"ssh-rsa"``).
  105. """
  106. return ''
  107. def get_bits(self):
  108. """
  109. Return the number of significant bits in this key. This is useful
  110. for judging the relative security of a key.
  111. :return: bits in the key (as an `int`)
  112. """
  113. return 0
  114. def can_sign(self):
  115. """
  116. Return ``True`` if this key has the private part necessary for signing
  117. data.
  118. """
  119. return False
  120. def get_fingerprint(self):
  121. """
  122. Return an MD5 fingerprint of the public part of this key. Nothing
  123. secret is revealed.
  124. :return:
  125. a 16-byte `string <str>` (binary) of the MD5 fingerprint, in SSH
  126. format.
  127. """
  128. return md5(self.asbytes()).digest()
  129. def get_base64(self):
  130. """
  131. Return a base64 string containing the public part of this key. Nothing
  132. secret is revealed. This format is compatible with that used to store
  133. public key files or recognized host keys.
  134. :return: a base64 `string <str>` containing the public part of the key.
  135. """
  136. return u(encodebytes(self.asbytes())).replace('\n', '')
  137. def sign_ssh_data(self, data):
  138. """
  139. Sign a blob of data with this private key, and return a `.Message`
  140. representing an SSH signature message.
  141. :param str data: the data to sign.
  142. :return: an SSH signature `message <.Message>`.
  143. """
  144. return bytes()
  145. def verify_ssh_sig(self, data, msg):
  146. """
  147. Given a blob of data, and an SSH message representing a signature of
  148. that data, verify that it was signed with this key.
  149. :param str data: the data that was signed.
  150. :param .Message msg: an SSH signature message
  151. :return:
  152. ``True`` if the signature verifies correctly; ``False`` otherwise.
  153. """
  154. return False
  155. @classmethod
  156. def from_private_key_file(cls, filename, password=None):
  157. """
  158. Create a key object by reading a private key file. If the private
  159. key is encrypted and ``password`` is not ``None``, the given password
  160. will be used to decrypt the key (otherwise `.PasswordRequiredException`
  161. is thrown). Through the magic of Python, this factory method will
  162. exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
  163. is useless on the abstract PKey class.
  164. :param str filename: name of the file to read
  165. :param str password:
  166. an optional password to use to decrypt the key file, if it's
  167. encrypted
  168. :return: a new `.PKey` based on the given private key
  169. :raises: ``IOError`` -- if there was an error reading the file
  170. :raises: `.PasswordRequiredException` -- if the private key file is
  171. encrypted, and ``password`` is ``None``
  172. :raises: `.SSHException` -- if the key file is invalid
  173. """
  174. key = cls(filename=filename, password=password)
  175. return key
  176. @classmethod
  177. def from_private_key(cls, file_obj, password=None):
  178. """
  179. Create a key object by reading a private key from a file (or file-like)
  180. object. If the private key is encrypted and ``password`` is not
  181. ``None``, the given password will be used to decrypt the key (otherwise
  182. `.PasswordRequiredException` is thrown).
  183. :param file_obj: the file-like object to read from
  184. :param str password:
  185. an optional password to use to decrypt the key, if it's encrypted
  186. :return: a new `.PKey` based on the given private key
  187. :raises: ``IOError`` -- if there was an error reading the key
  188. :raises: `.PasswordRequiredException` --
  189. if the private key file is encrypted, and ``password`` is ``None``
  190. :raises: `.SSHException` -- if the key file is invalid
  191. """
  192. key = cls(file_obj=file_obj, password=password)
  193. return key
  194. def write_private_key_file(self, filename, password=None):
  195. """
  196. Write private key contents into a file. If the password is not
  197. ``None``, the key is encrypted before writing.
  198. :param str filename: name of the file to write
  199. :param str password:
  200. an optional password to use to encrypt the key file
  201. :raises: ``IOError`` -- if there was an error writing the file
  202. :raises: `.SSHException` -- if the key is invalid
  203. """
  204. raise Exception('Not implemented in PKey')
  205. def write_private_key(self, file_obj, password=None):
  206. """
  207. Write private key contents into a file (or file-like) object. If the
  208. password is not ``None``, the key is encrypted before writing.
  209. :param file_obj: the file-like object to write into
  210. :param str password: an optional password to use to encrypt the key
  211. :raises: ``IOError`` -- if there was an error writing to the file
  212. :raises: `.SSHException` -- if the key is invalid
  213. """
  214. raise Exception('Not implemented in PKey')
  215. def _read_private_key_file(self, tag, filename, password=None):
  216. """
  217. Read an SSH2-format private key file, looking for a string of the type
  218. ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we
  219. find, and return it as a string. If the private key is encrypted and
  220. ``password`` is not ``None``, the given password will be used to
  221. decrypt the key (otherwise `.PasswordRequiredException` is thrown).
  222. :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the
  223. data block.
  224. :param str filename: name of the file to read.
  225. :param str password:
  226. an optional password to use to decrypt the key file, if it's
  227. encrypted.
  228. :return: data blob (`str`) that makes up the private key.
  229. :raises: ``IOError`` -- if there was an error reading the file.
  230. :raises: `.PasswordRequiredException` -- if the private key file is
  231. encrypted, and ``password`` is ``None``.
  232. :raises: `.SSHException` -- if the key file is invalid.
  233. """
  234. with open(filename, 'r') as f:
  235. data = self._read_private_key(tag, f, password)
  236. return data
  237. def _read_private_key(self, tag, f, password=None):
  238. lines = f.readlines()
  239. start = 0
  240. beginning_of_key = '-----BEGIN ' + tag + ' PRIVATE KEY-----'
  241. while start < len(lines) and lines[start].strip() != beginning_of_key:
  242. start += 1
  243. if start >= len(lines):
  244. raise SSHException('not a valid ' + tag + ' private key file')
  245. # parse any headers first
  246. headers = {}
  247. start += 1
  248. while start < len(lines):
  249. l = lines[start].split(': ')
  250. if len(l) == 1:
  251. break
  252. headers[l[0].lower()] = l[1].strip()
  253. start += 1
  254. # find end
  255. end = start
  256. ending_of_key = '-----END ' + tag + ' PRIVATE KEY-----'
  257. while end < len(lines) and lines[end].strip() != ending_of_key:
  258. end += 1
  259. # if we trudged to the end of the file, just try to cope.
  260. try:
  261. data = decodebytes(b(''.join(lines[start:end])))
  262. except base64.binascii.Error as e:
  263. raise SSHException('base64 decoding error: ' + str(e))
  264. if 'proc-type' not in headers:
  265. # unencryped: done
  266. return data
  267. # encrypted keyfile: will need a password
  268. if headers['proc-type'] != '4,ENCRYPTED':
  269. raise SSHException(
  270. 'Unknown private key structure "%s"' % headers['proc-type'])
  271. try:
  272. encryption_type, saltstr = headers['dek-info'].split(',')
  273. except:
  274. raise SSHException("Can't parse DEK-info in private key file")
  275. if encryption_type not in self._CIPHER_TABLE:
  276. raise SSHException(
  277. 'Unknown private key cipher "%s"' % encryption_type)
  278. # if no password was passed in,
  279. # raise an exception pointing out that we need one
  280. if password is None:
  281. raise PasswordRequiredException('Private key file is encrypted')
  282. cipher = self._CIPHER_TABLE[encryption_type]['cipher']
  283. keysize = self._CIPHER_TABLE[encryption_type]['keysize']
  284. mode = self._CIPHER_TABLE[encryption_type]['mode']
  285. salt = unhexlify(b(saltstr))
  286. key = util.generate_key_bytes(md5, salt, password, keysize)
  287. decryptor = Cipher(
  288. cipher(key), mode(salt), backend=default_backend()
  289. ).decryptor()
  290. return decryptor.update(data) + decryptor.finalize()
  291. def _write_private_key_file(self, filename, key, format, password=None):
  292. """
  293. Write an SSH2-format private key file in a form that can be read by
  294. paramiko or openssh. If no password is given, the key is written in
  295. a trivially-encoded format (base64) which is completely insecure. If
  296. a password is given, DES-EDE3-CBC is used.
  297. :param str tag:
  298. ``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
  299. :param filename: name of the file to write.
  300. :param str data: data blob that makes up the private key.
  301. :param str password: an optional password to use to encrypt the file.
  302. :raises: ``IOError`` -- if there was an error writing the file.
  303. """
  304. with open(filename, 'w') as f:
  305. os.chmod(filename, o600)
  306. self._write_private_key(f, key, format, password=password)
  307. def _write_private_key(self, f, key, format, password=None):
  308. if password is None:
  309. encryption = serialization.NoEncryption()
  310. else:
  311. encryption = serialization.BestAvailableEncryption(b(password))
  312. f.write(key.private_bytes(
  313. serialization.Encoding.PEM,
  314. format,
  315. encryption
  316. ).decode())