pkey.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. import re
  26. import struct
  27. import six
  28. import bcrypt
  29. from cryptography.hazmat.backends import default_backend
  30. from cryptography.hazmat.primitives import serialization
  31. from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher
  32. from paramiko import util
  33. from paramiko.common import o600
  34. from paramiko.py3compat import u, b, encodebytes, decodebytes, string_types
  35. from paramiko.ssh_exception import SSHException, PasswordRequiredException
  36. from paramiko.message import Message
  37. OPENSSH_AUTH_MAGIC = b"openssh-key-v1\x00"
  38. def _unpad_openssh(data):
  39. # At the moment, this is only used for unpadding private keys on disk. This
  40. # really ought to be made constant time (possibly by upstreaming this logic
  41. # into pyca/cryptography).
  42. padding_length = six.indexbytes(data, -1)
  43. if 0x20 <= padding_length < 0x7f:
  44. return data # no padding, last byte part comment (printable ascii)
  45. if padding_length > 15:
  46. raise SSHException("Invalid key")
  47. for i in range(padding_length):
  48. if six.indexbytes(data, i - padding_length) != i + 1:
  49. raise SSHException("Invalid key")
  50. return data[:-padding_length]
  51. class PKey(object):
  52. """
  53. Base class for public keys.
  54. """
  55. # known encryption types for private key files:
  56. _CIPHER_TABLE = {
  57. "AES-128-CBC": {
  58. "cipher": algorithms.AES,
  59. "keysize": 16,
  60. "blocksize": 16,
  61. "mode": modes.CBC,
  62. },
  63. "AES-256-CBC": {
  64. "cipher": algorithms.AES,
  65. "keysize": 32,
  66. "blocksize": 16,
  67. "mode": modes.CBC,
  68. },
  69. "DES-EDE3-CBC": {
  70. "cipher": algorithms.TripleDES,
  71. "keysize": 24,
  72. "blocksize": 8,
  73. "mode": modes.CBC,
  74. },
  75. }
  76. _PRIVATE_KEY_FORMAT_ORIGINAL = 1
  77. _PRIVATE_KEY_FORMAT_OPENSSH = 2
  78. BEGIN_TAG = re.compile(
  79. r"^-{5}BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$"
  80. )
  81. END_TAG = re.compile(r"^-{5}END (RSA|DSA|EC|OPENSSH) PRIVATE KEY-{5}\s*$")
  82. def __init__(self, msg=None, data=None):
  83. """
  84. Create a new instance of this public key type. If ``msg`` is given,
  85. the key's public part(s) will be filled in from the message. If
  86. ``data`` is given, the key's public part(s) will be filled in from
  87. the string.
  88. :param .Message msg:
  89. an optional SSH `.Message` containing a public key of this type.
  90. :param str data: an optional string containing a public key
  91. of this type
  92. :raises: `.SSHException` --
  93. if a key cannot be created from the ``data`` or ``msg`` given, or
  94. no key was passed in.
  95. """
  96. pass
  97. def asbytes(self):
  98. """
  99. Return a string of an SSH `.Message` made up of the public part(s) of
  100. this key. This string is suitable for passing to `__init__` to
  101. re-create the key object later.
  102. """
  103. return bytes()
  104. def __str__(self):
  105. return self.asbytes()
  106. # noinspection PyUnresolvedReferences
  107. # TODO: The comparison functions should be removed as per:
  108. # https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons
  109. def __cmp__(self, other):
  110. """
  111. Compare this key to another. Returns 0 if this key is equivalent to
  112. the given key, or non-0 if they are different. Only the public parts
  113. of the key are compared, so a public key will compare equal to its
  114. corresponding private key.
  115. :param .PKey other: key to compare to.
  116. """
  117. hs = hash(self)
  118. ho = hash(other)
  119. if hs != ho:
  120. return cmp(hs, ho) # noqa
  121. return cmp(self.asbytes(), other.asbytes()) # noqa
  122. def __eq__(self, other):
  123. return isinstance(other, PKey) and self._fields == other._fields
  124. def __hash__(self):
  125. return hash(self._fields)
  126. @property
  127. def _fields(self):
  128. raise NotImplementedError
  129. def get_name(self):
  130. """
  131. Return the name of this private key implementation.
  132. :return:
  133. name of this private key type, in SSH terminology, as a `str` (for
  134. example, ``"ssh-rsa"``).
  135. """
  136. return ""
  137. def get_bits(self):
  138. """
  139. Return the number of significant bits in this key. This is useful
  140. for judging the relative security of a key.
  141. :return: bits in the key (as an `int`)
  142. """
  143. return 0
  144. def can_sign(self):
  145. """
  146. Return ``True`` if this key has the private part necessary for signing
  147. data.
  148. """
  149. return False
  150. def get_fingerprint(self):
  151. """
  152. Return an MD5 fingerprint of the public part of this key. Nothing
  153. secret is revealed.
  154. :return:
  155. a 16-byte `string <str>` (binary) of the MD5 fingerprint, in SSH
  156. format.
  157. """
  158. return md5(self.asbytes()).digest()
  159. def get_base64(self):
  160. """
  161. Return a base64 string containing the public part of this key. Nothing
  162. secret is revealed. This format is compatible with that used to store
  163. public key files or recognized host keys.
  164. :return: a base64 `string <str>` containing the public part of the key.
  165. """
  166. return u(encodebytes(self.asbytes())).replace("\n", "")
  167. def sign_ssh_data(self, data, algorithm=None):
  168. """
  169. Sign a blob of data with this private key, and return a `.Message`
  170. representing an SSH signature message.
  171. :param str data:
  172. the data to sign.
  173. :param str algorithm:
  174. the signature algorithm to use, if different from the key's
  175. internal name. Default: ``None``.
  176. :return: an SSH signature `message <.Message>`.
  177. .. versionchanged:: 2.9
  178. Added the ``algorithm`` kwarg.
  179. """
  180. return bytes()
  181. def verify_ssh_sig(self, data, msg):
  182. """
  183. Given a blob of data, and an SSH message representing a signature of
  184. that data, verify that it was signed with this key.
  185. :param str data: the data that was signed.
  186. :param .Message msg: an SSH signature message
  187. :return:
  188. ``True`` if the signature verifies correctly; ``False`` otherwise.
  189. """
  190. return False
  191. @classmethod
  192. def from_private_key_file(cls, filename, password=None):
  193. """
  194. Create a key object by reading a private key file. If the private
  195. key is encrypted and ``password`` is not ``None``, the given password
  196. will be used to decrypt the key (otherwise `.PasswordRequiredException`
  197. is thrown). Through the magic of Python, this factory method will
  198. exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
  199. is useless on the abstract PKey class.
  200. :param str filename: name of the file to read
  201. :param str password:
  202. an optional password to use to decrypt the key file, if it's
  203. encrypted
  204. :return: a new `.PKey` based on the given private key
  205. :raises: ``IOError`` -- if there was an error reading the file
  206. :raises: `.PasswordRequiredException` -- if the private key file is
  207. encrypted, and ``password`` is ``None``
  208. :raises: `.SSHException` -- if the key file is invalid
  209. """
  210. key = cls(filename=filename, password=password)
  211. return key
  212. @classmethod
  213. def from_private_key(cls, file_obj, password=None):
  214. """
  215. Create a key object by reading a private key from a file (or file-like)
  216. object. If the private key is encrypted and ``password`` is not
  217. ``None``, the given password will be used to decrypt the key (otherwise
  218. `.PasswordRequiredException` is thrown).
  219. :param file_obj: the file-like object to read from
  220. :param str password:
  221. an optional password to use to decrypt the key, if it's encrypted
  222. :return: a new `.PKey` based on the given private key
  223. :raises: ``IOError`` -- if there was an error reading the key
  224. :raises: `.PasswordRequiredException` --
  225. if the private key file is encrypted, and ``password`` is ``None``
  226. :raises: `.SSHException` -- if the key file is invalid
  227. """
  228. key = cls(file_obj=file_obj, password=password)
  229. return key
  230. def write_private_key_file(self, filename, password=None):
  231. """
  232. Write private key contents into a file. If the password is not
  233. ``None``, the key is encrypted before writing.
  234. :param str filename: name of the file to write
  235. :param str password:
  236. an optional password to use to encrypt the key file
  237. :raises: ``IOError`` -- if there was an error writing the file
  238. :raises: `.SSHException` -- if the key is invalid
  239. """
  240. raise Exception("Not implemented in PKey")
  241. def write_private_key(self, file_obj, password=None):
  242. """
  243. Write private key contents into a file (or file-like) object. If the
  244. password is not ``None``, the key is encrypted before writing.
  245. :param file_obj: the file-like object to write into
  246. :param str password: an optional password to use to encrypt the key
  247. :raises: ``IOError`` -- if there was an error writing to the file
  248. :raises: `.SSHException` -- if the key is invalid
  249. """
  250. raise Exception("Not implemented in PKey")
  251. def _read_private_key_file(self, tag, filename, password=None):
  252. """
  253. Read an SSH2-format private key file, looking for a string of the type
  254. ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we
  255. find, and return it as a string. If the private key is encrypted and
  256. ``password`` is not ``None``, the given password will be used to
  257. decrypt the key (otherwise `.PasswordRequiredException` is thrown).
  258. :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the
  259. data block.
  260. :param str filename: name of the file to read.
  261. :param str password:
  262. an optional password to use to decrypt the key file, if it's
  263. encrypted.
  264. :return: data blob (`str`) that makes up the private key.
  265. :raises: ``IOError`` -- if there was an error reading the file.
  266. :raises: `.PasswordRequiredException` -- if the private key file is
  267. encrypted, and ``password`` is ``None``.
  268. :raises: `.SSHException` -- if the key file is invalid.
  269. """
  270. with open(filename, "r") as f:
  271. data = self._read_private_key(tag, f, password)
  272. return data
  273. def _read_private_key(self, tag, f, password=None):
  274. lines = f.readlines()
  275. # find the BEGIN tag
  276. start = 0
  277. m = self.BEGIN_TAG.match(lines[start])
  278. line_range = len(lines) - 1
  279. while start < line_range and not m:
  280. start += 1
  281. m = self.BEGIN_TAG.match(lines[start])
  282. start += 1
  283. keytype = m.group(1) if m else None
  284. if start >= len(lines) or keytype is None:
  285. raise SSHException("not a valid {} private key file".format(tag))
  286. # find the END tag
  287. end = start
  288. m = self.END_TAG.match(lines[end])
  289. while end < line_range and not m:
  290. end += 1
  291. m = self.END_TAG.match(lines[end])
  292. if keytype == tag:
  293. data = self._read_private_key_pem(lines, end, password)
  294. pkformat = self._PRIVATE_KEY_FORMAT_ORIGINAL
  295. elif keytype == "OPENSSH":
  296. data = self._read_private_key_openssh(lines[start:end], password)
  297. pkformat = self._PRIVATE_KEY_FORMAT_OPENSSH
  298. else:
  299. raise SSHException(
  300. "encountered {} key, expected {} key".format(keytype, tag)
  301. )
  302. return pkformat, data
  303. def _got_bad_key_format_id(self, id_):
  304. err = "{}._read_private_key() spat out an unknown key format id '{}'"
  305. raise SSHException(err.format(self.__class__.__name__, id_))
  306. def _read_private_key_pem(self, lines, end, password):
  307. start = 0
  308. # parse any headers first
  309. headers = {}
  310. start += 1
  311. while start < len(lines):
  312. line = lines[start].split(": ")
  313. if len(line) == 1:
  314. break
  315. headers[line[0].lower()] = line[1].strip()
  316. start += 1
  317. # if we trudged to the end of the file, just try to cope.
  318. try:
  319. data = decodebytes(b("".join(lines[start:end])))
  320. except base64.binascii.Error as e:
  321. raise SSHException("base64 decoding error: {}".format(e))
  322. if "proc-type" not in headers:
  323. # unencryped: done
  324. return data
  325. # encrypted keyfile: will need a password
  326. proc_type = headers["proc-type"]
  327. if proc_type != "4,ENCRYPTED":
  328. raise SSHException(
  329. 'Unknown private key structure "{}"'.format(proc_type)
  330. )
  331. try:
  332. encryption_type, saltstr = headers["dek-info"].split(",")
  333. except:
  334. raise SSHException("Can't parse DEK-info in private key file")
  335. if encryption_type not in self._CIPHER_TABLE:
  336. raise SSHException(
  337. 'Unknown private key cipher "{}"'.format(encryption_type)
  338. )
  339. # if no password was passed in,
  340. # raise an exception pointing out that we need one
  341. if password is None:
  342. raise PasswordRequiredException("Private key file is encrypted")
  343. cipher = self._CIPHER_TABLE[encryption_type]["cipher"]
  344. keysize = self._CIPHER_TABLE[encryption_type]["keysize"]
  345. mode = self._CIPHER_TABLE[encryption_type]["mode"]
  346. salt = unhexlify(b(saltstr))
  347. key = util.generate_key_bytes(md5, salt, password, keysize)
  348. decryptor = Cipher(
  349. cipher(key), mode(salt), backend=default_backend()
  350. ).decryptor()
  351. return decryptor.update(data) + decryptor.finalize()
  352. def _read_private_key_openssh(self, lines, password):
  353. """
  354. Read the new OpenSSH SSH2 private key format available
  355. since OpenSSH version 6.5
  356. Reference:
  357. https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
  358. """
  359. try:
  360. data = decodebytes(b("".join(lines)))
  361. except base64.binascii.Error as e:
  362. raise SSHException("base64 decoding error: {}".format(e))
  363. # read data struct
  364. auth_magic = data[:15]
  365. if auth_magic != OPENSSH_AUTH_MAGIC:
  366. raise SSHException("unexpected OpenSSH key header encountered")
  367. cstruct = self._uint32_cstruct_unpack(data[15:], "sssur")
  368. cipher, kdfname, kdf_options, num_pubkeys, remainder = cstruct
  369. # For now, just support 1 key.
  370. if num_pubkeys > 1:
  371. raise SSHException(
  372. "unsupported: private keyfile has multiple keys"
  373. )
  374. pubkey, privkey_blob = self._uint32_cstruct_unpack(remainder, "ss")
  375. if kdfname == b("bcrypt"):
  376. if cipher == b("aes256-cbc"):
  377. mode = modes.CBC
  378. elif cipher == b("aes256-ctr"):
  379. mode = modes.CTR
  380. else:
  381. raise SSHException(
  382. "unknown cipher `{}` used in private key file".format(
  383. cipher.decode("utf-8")
  384. )
  385. )
  386. # Encrypted private key.
  387. # If no password was passed in, raise an exception pointing
  388. # out that we need one
  389. if password is None:
  390. raise PasswordRequiredException(
  391. "private key file is encrypted"
  392. )
  393. # Unpack salt and rounds from kdfoptions
  394. salt, rounds = self._uint32_cstruct_unpack(kdf_options, "su")
  395. # run bcrypt kdf to derive key and iv/nonce (32 + 16 bytes)
  396. key_iv = bcrypt.kdf(
  397. b(password),
  398. b(salt),
  399. 48,
  400. rounds,
  401. # We can't control how many rounds are on disk, so no sense
  402. # warning about it.
  403. ignore_few_rounds=True,
  404. )
  405. key = key_iv[:32]
  406. iv = key_iv[32:]
  407. # decrypt private key blob
  408. decryptor = Cipher(
  409. algorithms.AES(key), mode(iv), default_backend()
  410. ).decryptor()
  411. decrypted_privkey = decryptor.update(privkey_blob)
  412. decrypted_privkey += decryptor.finalize()
  413. elif cipher == b("none") and kdfname == b("none"):
  414. # Unencrypted private key
  415. decrypted_privkey = privkey_blob
  416. else:
  417. raise SSHException(
  418. "unknown cipher or kdf used in private key file"
  419. )
  420. # Unpack private key and verify checkints
  421. cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr")
  422. checkint1, checkint2, keytype, keydata = cstruct
  423. if checkint1 != checkint2:
  424. raise SSHException(
  425. "OpenSSH private key file checkints do not match"
  426. )
  427. return _unpad_openssh(keydata)
  428. def _uint32_cstruct_unpack(self, data, strformat):
  429. """
  430. Used to read new OpenSSH private key format.
  431. Unpacks a c data structure containing a mix of 32-bit uints and
  432. variable length strings prefixed by 32-bit uint size field,
  433. according to the specified format. Returns the unpacked vars
  434. in a tuple.
  435. Format strings:
  436. s - denotes a string
  437. i - denotes a long integer, encoded as a byte string
  438. u - denotes a 32-bit unsigned integer
  439. r - the remainder of the input string, returned as a string
  440. """
  441. arr = []
  442. idx = 0
  443. try:
  444. for f in strformat:
  445. if f == "s":
  446. # string
  447. s_size = struct.unpack(">L", data[idx : idx + 4])[0]
  448. idx += 4
  449. s = data[idx : idx + s_size]
  450. idx += s_size
  451. arr.append(s)
  452. if f == "i":
  453. # long integer
  454. s_size = struct.unpack(">L", data[idx : idx + 4])[0]
  455. idx += 4
  456. s = data[idx : idx + s_size]
  457. idx += s_size
  458. i = util.inflate_long(s, True)
  459. arr.append(i)
  460. elif f == "u":
  461. # 32-bit unsigned int
  462. u = struct.unpack(">L", data[idx : idx + 4])[0]
  463. idx += 4
  464. arr.append(u)
  465. elif f == "r":
  466. # remainder as string
  467. s = data[idx:]
  468. arr.append(s)
  469. break
  470. except Exception as e:
  471. # PKey-consuming code frequently wants to save-and-skip-over issues
  472. # with loading keys, and uses SSHException as the (really friggin
  473. # awful) signal for this. So for now...we do this.
  474. raise SSHException(str(e))
  475. return tuple(arr)
  476. def _write_private_key_file(self, filename, key, format, password=None):
  477. """
  478. Write an SSH2-format private key file in a form that can be read by
  479. paramiko or openssh. If no password is given, the key is written in
  480. a trivially-encoded format (base64) which is completely insecure. If
  481. a password is given, DES-EDE3-CBC is used.
  482. :param str tag:
  483. ``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
  484. :param filename: name of the file to write.
  485. :param str data: data blob that makes up the private key.
  486. :param str password: an optional password to use to encrypt the file.
  487. :raises: ``IOError`` -- if there was an error writing the file.
  488. """
  489. # Ensure that we create new key files directly with a user-only mode,
  490. # instead of opening, writing, then chmodding, which leaves us open to
  491. # CVE-2022-24302.
  492. # NOTE: O_TRUNC is a noop on new files, and O_CREAT is a noop on
  493. # existing files, so using all 3 in both cases is fine. Ditto the use
  494. # of the 'mode' argument; it should be safe to give even for existing
  495. # files (though it will not act like a chmod in that case).
  496. # TODO 3.0: turn into kwargs again
  497. args = [os.O_WRONLY | os.O_TRUNC | os.O_CREAT, o600]
  498. # NOTE: yea, you still gotta inform the FLO that it is in "write" mode
  499. with os.fdopen(os.open(filename, *args), "w") as f:
  500. # TODO 3.0: remove the now redundant chmod
  501. os.chmod(filename, o600)
  502. self._write_private_key(f, key, format, password=password)
  503. def _write_private_key(self, f, key, format, password=None):
  504. if password is None:
  505. encryption = serialization.NoEncryption()
  506. else:
  507. encryption = serialization.BestAvailableEncryption(b(password))
  508. f.write(
  509. key.private_bytes(
  510. serialization.Encoding.PEM, format, encryption
  511. ).decode()
  512. )
  513. def _check_type_and_load_cert(self, msg, key_type, cert_type):
  514. """
  515. Perform message type-checking & optional certificate loading.
  516. This includes fast-forwarding cert ``msg`` objects past the nonce, so
  517. that the subsequent fields are the key numbers; thus the caller may
  518. expect to treat the message as key material afterwards either way.
  519. The obtained key type is returned for classes which need to know what
  520. it was (e.g. ECDSA.)
  521. """
  522. # Normalization; most classes have a single key type and give a string,
  523. # but eg ECDSA is a 1:N mapping.
  524. key_types = key_type
  525. cert_types = cert_type
  526. if isinstance(key_type, string_types):
  527. key_types = [key_types]
  528. if isinstance(cert_types, string_types):
  529. cert_types = [cert_types]
  530. # Can't do much with no message, that should've been handled elsewhere
  531. if msg is None:
  532. raise SSHException("Key object may not be empty")
  533. # First field is always key type, in either kind of object. (make sure
  534. # we rewind before grabbing it - sometimes caller had to do their own
  535. # introspection first!)
  536. msg.rewind()
  537. type_ = msg.get_text()
  538. # Regular public key - nothing special to do besides the implicit
  539. # type check.
  540. if type_ in key_types:
  541. pass
  542. # OpenSSH-compatible certificate - store full copy as .public_blob
  543. # (so signing works correctly) and then fast-forward past the
  544. # nonce.
  545. elif type_ in cert_types:
  546. # This seems the cleanest way to 'clone' an already-being-read
  547. # message; they're *IO objects at heart and their .getvalue()
  548. # always returns the full value regardless of pointer position.
  549. self.load_certificate(Message(msg.asbytes()))
  550. # Read out nonce as it comes before the public numbers.
  551. # TODO: usefully interpret it & other non-public-number fields
  552. # (requires going back into per-type subclasses.)
  553. msg.get_string()
  554. else:
  555. err = "Invalid key (class: {}, data type: {}"
  556. raise SSHException(err.format(self.__class__.__name__, type_))
  557. def load_certificate(self, value):
  558. """
  559. Supplement the private key contents with data loaded from an OpenSSH
  560. public key (``.pub``) or certificate (``-cert.pub``) file, a string
  561. containing such a file, or a `.Message` object.
  562. The .pub contents adds no real value, since the private key
  563. file includes sufficient information to derive the public
  564. key info. For certificates, however, this can be used on
  565. the client side to offer authentication requests to the server
  566. based on certificate instead of raw public key.
  567. See:
  568. https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
  569. Note: very little effort is made to validate the certificate contents,
  570. that is for the server to decide if it is good enough to authenticate
  571. successfully.
  572. """
  573. if isinstance(value, Message):
  574. constructor = "from_message"
  575. elif os.path.isfile(value):
  576. constructor = "from_file"
  577. else:
  578. constructor = "from_string"
  579. blob = getattr(PublicBlob, constructor)(value)
  580. if not blob.key_type.startswith(self.get_name()):
  581. err = "PublicBlob type {} incompatible with key type {}"
  582. raise ValueError(err.format(blob.key_type, self.get_name()))
  583. self.public_blob = blob
  584. # General construct for an OpenSSH style Public Key blob
  585. # readable from a one-line file of the format:
  586. # <key-name> <base64-blob> [<comment>]
  587. # Of little value in the case of standard public keys
  588. # {ssh-rsa, ssh-dss, ssh-ecdsa, ssh-ed25519}, but should
  589. # provide rudimentary support for {*-cert.v01}
  590. class PublicBlob(object):
  591. """
  592. OpenSSH plain public key or OpenSSH signed public key (certificate).
  593. Tries to be as dumb as possible and barely cares about specific
  594. per-key-type data.
  595. .. note::
  596. Most of the time you'll want to call `from_file`, `from_string` or
  597. `from_message` for useful instantiation, the main constructor is
  598. basically "I should be using ``attrs`` for this."
  599. """
  600. def __init__(self, type_, blob, comment=None):
  601. """
  602. Create a new public blob of given type and contents.
  603. :param str type_: Type indicator, eg ``ssh-rsa``.
  604. :param blob: The blob bytes themselves.
  605. :param str comment: A comment, if one was given (e.g. file-based.)
  606. """
  607. self.key_type = type_
  608. self.key_blob = blob
  609. self.comment = comment
  610. @classmethod
  611. def from_file(cls, filename):
  612. """
  613. Create a public blob from a ``-cert.pub``-style file on disk.
  614. """
  615. with open(filename) as f:
  616. string = f.read()
  617. return cls.from_string(string)
  618. @classmethod
  619. def from_string(cls, string):
  620. """
  621. Create a public blob from a ``-cert.pub``-style string.
  622. """
  623. fields = string.split(None, 2)
  624. if len(fields) < 2:
  625. msg = "Not enough fields for public blob: {}"
  626. raise ValueError(msg.format(fields))
  627. key_type = fields[0]
  628. key_blob = decodebytes(b(fields[1]))
  629. try:
  630. comment = fields[2].strip()
  631. except IndexError:
  632. comment = None
  633. # Verify that the blob message first (string) field matches the
  634. # key_type
  635. m = Message(key_blob)
  636. blob_type = m.get_text()
  637. if blob_type != key_type:
  638. deets = "key type={!r}, but blob type={!r}".format(
  639. key_type, blob_type
  640. )
  641. raise ValueError("Invalid PublicBlob contents: {}".format(deets))
  642. # All good? All good.
  643. return cls(type_=key_type, blob=key_blob, comment=comment)
  644. @classmethod
  645. def from_message(cls, message):
  646. """
  647. Create a public blob from a network `.Message`.
  648. Specifically, a cert-bearing pubkey auth packet, because by definition
  649. OpenSSH-style certificates 'are' their own network representation."
  650. """
  651. type_ = message.get_text()
  652. return cls(type_=type_, blob=message.asbytes())
  653. def __str__(self):
  654. ret = "{} public key/certificate".format(self.key_type)
  655. if self.comment:
  656. ret += "- {}".format(self.comment)
  657. return ret
  658. def __eq__(self, other):
  659. # Just piggyback on Message/BytesIO, since both of these should be one.
  660. return self and other and self.key_blob == other.key_blob
  661. def __ne__(self, other):
  662. return not self == other