keys.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  1. # -*- test-case-name: twisted.conch.test.test_keys -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Handling of RSA, DSA, ECDSA, and Ed25519 keys.
  6. """
  7. from __future__ import annotations
  8. import binascii
  9. import struct
  10. import unicodedata
  11. import warnings
  12. from base64 import b64encode, decodebytes, encodebytes
  13. from hashlib import md5, sha256
  14. from typing import Any
  15. import bcrypt
  16. from cryptography import utils
  17. from cryptography.exceptions import InvalidSignature
  18. from cryptography.hazmat.backends import default_backend
  19. from cryptography.hazmat.primitives import hashes, serialization
  20. from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed25519, padding, rsa
  21. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  22. from cryptography.hazmat.primitives.serialization import (
  23. load_pem_private_key,
  24. load_ssh_public_key,
  25. )
  26. from typing_extensions import Literal
  27. from twisted.conch.ssh import common, sexpy
  28. from twisted.conch.ssh.common import int_to_bytes
  29. from twisted.python import randbytes
  30. from twisted.python.compat import iterbytes, nativeString
  31. from twisted.python.constants import NamedConstant, Names
  32. from twisted.python.deprecate import _mutuallyExclusiveArguments
  33. try:
  34. from cryptography.hazmat.primitives.asymmetric.utils import (
  35. decode_dss_signature,
  36. encode_dss_signature,
  37. )
  38. except ImportError:
  39. from cryptography.hazmat.primitives.asymmetric.utils import ( # type: ignore[no-redef,attr-defined]
  40. decode_rfc6979_signature as decode_dss_signature,
  41. encode_rfc6979_signature as encode_dss_signature,
  42. )
  43. # Curve lookup table
  44. _curveTable = {
  45. b"ecdsa-sha2-nistp256": ec.SECP256R1(),
  46. b"ecdsa-sha2-nistp384": ec.SECP384R1(),
  47. b"ecdsa-sha2-nistp521": ec.SECP521R1(),
  48. }
  49. _secToNist = {
  50. b"secp256r1": b"nistp256",
  51. b"secp384r1": b"nistp384",
  52. b"secp521r1": b"nistp521",
  53. }
  54. Ed25519PublicKey = ed25519.Ed25519PublicKey
  55. Ed25519PrivateKey = ed25519.Ed25519PrivateKey
  56. class BadKeyError(Exception):
  57. """
  58. Raised when a key isn't what we expected from it.
  59. XXX: we really need to check for bad keys
  60. """
  61. class BadSignatureAlgorithmError(Exception):
  62. """
  63. Raised when a public key signature algorithm name isn't defined for this
  64. public key format.
  65. """
  66. class EncryptedKeyError(Exception):
  67. """
  68. Raised when an encrypted key is presented to fromString/fromFile without
  69. a password.
  70. """
  71. class BadFingerPrintFormat(Exception):
  72. """
  73. Raises when unsupported fingerprint formats are presented to fingerprint.
  74. """
  75. class FingerprintFormats(Names):
  76. """
  77. Constants representing the supported formats of key fingerprints.
  78. @cvar MD5_HEX: Named constant representing fingerprint format generated
  79. using md5[RFC1321] algorithm in hexadecimal encoding.
  80. @type MD5_HEX: L{twisted.python.constants.NamedConstant}
  81. @cvar SHA256_BASE64: Named constant representing fingerprint format
  82. generated using sha256[RFC4634] algorithm in base64 encoding
  83. @type SHA256_BASE64: L{twisted.python.constants.NamedConstant}
  84. """
  85. MD5_HEX = NamedConstant()
  86. SHA256_BASE64 = NamedConstant()
  87. class PassphraseNormalizationError(Exception):
  88. """
  89. Raised when a passphrase contains Unicode characters that cannot be
  90. normalized using the available Unicode character database.
  91. """
  92. def _normalizePassphrase(passphrase):
  93. """
  94. Normalize a passphrase, which may be Unicode.
  95. If the passphrase is Unicode, this follows the requirements of U{NIST
  96. 800-63B, section
  97. 5.1.1.2<https://pages.nist.gov/800-63-3/sp800-63b.html#memsecretver>}
  98. for Unicode characters in memorized secrets: it applies the
  99. Normalization Process for Stabilized Strings using NFKC normalization.
  100. The passphrase is then encoded using UTF-8.
  101. @type passphrase: L{bytes} or L{unicode} or L{None}
  102. @param passphrase: The passphrase to normalize.
  103. @return: The normalized passphrase, if any.
  104. @rtype: L{bytes} or L{None}
  105. @raises PassphraseNormalizationError: if the passphrase is Unicode and
  106. cannot be normalized using the available Unicode character database.
  107. """
  108. if isinstance(passphrase, str):
  109. # The Normalization Process for Stabilized Strings requires aborting
  110. # with an error if the string contains any unassigned code point.
  111. if any(unicodedata.category(c) == "Cn" for c in passphrase):
  112. # Perhaps not very helpful, but we don't want to leak any other
  113. # information about the passphrase.
  114. raise PassphraseNormalizationError()
  115. return unicodedata.normalize("NFKC", passphrase).encode("UTF-8")
  116. else:
  117. return passphrase
  118. class Key:
  119. """
  120. An object representing a key. A key can be either a public or
  121. private key. A public key can verify a signature; a private key can
  122. create or verify a signature. To generate a string that can be stored
  123. on disk, use the toString method. If you have a private key, but want
  124. the string representation of the public key, use Key.public().toString().
  125. """
  126. @classmethod
  127. def fromFile(cls, filename, type=None, passphrase=None):
  128. """
  129. Load a key from a file.
  130. @param filename: The path to load key data from.
  131. @type type: L{str} or L{None}
  132. @param type: A string describing the format the key data is in, or
  133. L{None} to attempt detection of the type.
  134. @type passphrase: L{bytes} or L{None}
  135. @param passphrase: The passphrase the key is encrypted with, or L{None}
  136. if there is no encryption.
  137. @rtype: L{Key}
  138. @return: The loaded key.
  139. """
  140. with open(filename, "rb") as f:
  141. return cls.fromString(f.read(), type, passphrase)
  142. @classmethod
  143. def fromString(cls, data, type=None, passphrase=None):
  144. """
  145. Return a Key object corresponding to the string data.
  146. type is optionally the type of string, matching a _fromString_*
  147. method. Otherwise, the _guessStringType() classmethod will be used
  148. to guess a type. If the key is encrypted, passphrase is used as
  149. the decryption key.
  150. @type data: L{bytes}
  151. @param data: The key data.
  152. @type type: L{str} or L{None}
  153. @param type: A string describing the format the key data is in, or
  154. L{None} to attempt detection of the type.
  155. @type passphrase: L{bytes} or L{None}
  156. @param passphrase: The passphrase the key is encrypted with, or L{None}
  157. if there is no encryption.
  158. @rtype: L{Key}
  159. @return: The loaded key.
  160. """
  161. if isinstance(data, str):
  162. data = data.encode("utf-8")
  163. passphrase = _normalizePassphrase(passphrase)
  164. if type is None:
  165. type = cls._guessStringType(data)
  166. if type is None:
  167. raise BadKeyError(f"cannot guess the type of {data!r}")
  168. method = getattr(cls, f"_fromString_{type.upper()}", None)
  169. if method is None:
  170. raise BadKeyError(f"no _fromString method for {type}")
  171. if method.__code__.co_argcount == 2: # No passphrase
  172. if passphrase:
  173. raise BadKeyError("key not encrypted")
  174. return method(data)
  175. else:
  176. return method(data, passphrase)
  177. @classmethod
  178. def _fromString_BLOB(cls, blob):
  179. """
  180. Return a public key object corresponding to this public key blob.
  181. The format of a RSA public key blob is::
  182. string 'ssh-rsa'
  183. integer e
  184. integer n
  185. The format of a DSA public key blob is::
  186. string 'ssh-dss'
  187. integer p
  188. integer q
  189. integer g
  190. integer y
  191. The format of ECDSA-SHA2-* public key blob is::
  192. string 'ecdsa-sha2-[identifier]'
  193. integer x
  194. integer y
  195. identifier is the standard NIST curve name.
  196. The format of an Ed25519 public key blob is::
  197. string 'ssh-ed25519'
  198. string a
  199. @type blob: L{bytes}
  200. @param blob: The key data.
  201. @return: A new key.
  202. @rtype: L{twisted.conch.ssh.keys.Key}
  203. @raises BadKeyError: if the key type (the first string) is unknown.
  204. """
  205. keyType, rest = common.getNS(blob)
  206. if keyType == b"ssh-rsa":
  207. e, n, rest = common.getMP(rest, 2)
  208. return cls(rsa.RSAPublicNumbers(e, n).public_key(default_backend()))
  209. elif keyType == b"ssh-dss":
  210. p, q, g, y, rest = common.getMP(rest, 4)
  211. return cls(
  212. dsa.DSAPublicNumbers(
  213. y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g)
  214. ).public_key(default_backend())
  215. )
  216. elif keyType in _curveTable:
  217. return cls(
  218. ec.EllipticCurvePublicKey.from_encoded_point(
  219. _curveTable[keyType], common.getNS(rest, 2)[1]
  220. )
  221. )
  222. elif keyType == b"ssh-ed25519":
  223. a, rest = common.getNS(rest)
  224. return cls._fromEd25519Components(a)
  225. else:
  226. raise BadKeyError(f"unknown blob type: {keyType}")
  227. @classmethod
  228. def _fromString_PRIVATE_BLOB(cls, blob):
  229. """
  230. Return a private key object corresponding to this private key blob.
  231. The blob formats are as follows:
  232. RSA keys::
  233. string 'ssh-rsa'
  234. integer n
  235. integer e
  236. integer d
  237. integer u
  238. integer p
  239. integer q
  240. DSA keys::
  241. string 'ssh-dss'
  242. integer p
  243. integer q
  244. integer g
  245. integer y
  246. integer x
  247. EC keys::
  248. string 'ecdsa-sha2-[identifier]'
  249. string identifier
  250. string q
  251. integer privateValue
  252. identifier is the standard NIST curve name.
  253. Ed25519 keys::
  254. string 'ssh-ed25519'
  255. string a
  256. string k || a
  257. @type blob: L{bytes}
  258. @param blob: The key data.
  259. @return: A new key.
  260. @rtype: L{twisted.conch.ssh.keys.Key}
  261. @raises BadKeyError: if
  262. * the key type (the first string) is unknown
  263. * the curve name of an ECDSA key does not match the key type
  264. """
  265. keyType, rest = common.getNS(blob)
  266. if keyType == b"ssh-rsa":
  267. n, e, d, u, p, q, rest = common.getMP(rest, 6)
  268. return cls._fromRSAComponents(n=n, e=e, d=d, p=p, q=q)
  269. elif keyType == b"ssh-dss":
  270. p, q, g, y, x, rest = common.getMP(rest, 5)
  271. return cls._fromDSAComponents(y=y, g=g, p=p, q=q, x=x)
  272. elif keyType in _curveTable:
  273. curve = _curveTable[keyType]
  274. curveName, q, rest = common.getNS(rest, 2)
  275. if curveName != _secToNist[curve.name.encode("ascii")]:
  276. raise BadKeyError(
  277. "ECDSA curve name %r does not match key "
  278. "type %r" % (curveName, keyType)
  279. )
  280. privateValue, rest = common.getMP(rest)
  281. return cls._fromECEncodedPoint(
  282. encodedPoint=q, curve=keyType, privateValue=privateValue
  283. )
  284. elif keyType == b"ssh-ed25519":
  285. # OpenSSH's format repeats the public key bytes for some reason.
  286. # We're only interested in the private key here anyway.
  287. a, combined, rest = common.getNS(rest, 2)
  288. k = combined[:32]
  289. return cls._fromEd25519Components(a, k=k)
  290. else:
  291. raise BadKeyError(f"unknown blob type: {keyType}")
  292. @classmethod
  293. def _fromString_PUBLIC_OPENSSH(cls, data):
  294. """
  295. Return a public key object corresponding to this OpenSSH public key
  296. string. The format of an OpenSSH public key string is::
  297. <key type> <base64-encoded public key blob>
  298. @type data: L{bytes}
  299. @param data: The key data.
  300. @return: A new key.
  301. @rtype: L{twisted.conch.ssh.keys.Key}
  302. @raises BadKeyError: if the blob type is unknown.
  303. """
  304. # ECDSA keys don't need base64 decoding which is required
  305. # for RSA or DSA key.
  306. if data.startswith(b"ecdsa-sha2"):
  307. return cls(load_ssh_public_key(data, default_backend()))
  308. blob = decodebytes(data.split()[1])
  309. return cls._fromString_BLOB(blob)
  310. @classmethod
  311. def _fromPrivateOpenSSH_v1(cls, data, passphrase):
  312. """
  313. Return a private key object corresponding to this OpenSSH private key
  314. string, in the "openssh-key-v1" format introduced in OpenSSH 6.5.
  315. The format of an openssh-key-v1 private key string is::
  316. -----BEGIN OPENSSH PRIVATE KEY-----
  317. <base64-encoded SSH protocol string>
  318. -----END OPENSSH PRIVATE KEY-----
  319. The SSH protocol string is as described in
  320. U{PROTOCOL.key<https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.key>}.
  321. @type data: L{bytes}
  322. @param data: The key data.
  323. @type passphrase: L{bytes} or L{None}
  324. @param passphrase: The passphrase the key is encrypted with, or L{None}
  325. if it is not encrypted.
  326. @return: A new key.
  327. @rtype: L{twisted.conch.ssh.keys.Key}
  328. @raises BadKeyError: if
  329. * a passphrase is provided for an unencrypted key
  330. * the SSH protocol encoding is incorrect
  331. @raises EncryptedKeyError: if
  332. * a passphrase is not provided for an encrypted key
  333. """
  334. lines = data.strip().splitlines()
  335. keyList = decodebytes(b"".join(lines[1:-1]))
  336. if not keyList.startswith(b"openssh-key-v1\0"):
  337. raise BadKeyError("unknown OpenSSH private key format")
  338. keyList = keyList[len(b"openssh-key-v1\0") :]
  339. cipher, kdf, kdfOptions, rest = common.getNS(keyList, 3)
  340. n = struct.unpack("!L", rest[:4])[0]
  341. if n != 1:
  342. raise BadKeyError(
  343. "only OpenSSH private key files containing "
  344. "a single key are supported"
  345. )
  346. # Ignore public key
  347. _, encPrivKeyList, _ = common.getNS(rest[4:], 2)
  348. if cipher != b"none":
  349. if not passphrase:
  350. raise EncryptedKeyError(
  351. "Passphrase must be provided " "for an encrypted key"
  352. )
  353. # Determine cipher
  354. if cipher in (b"aes128-ctr", b"aes192-ctr", b"aes256-ctr"):
  355. algorithmClass = algorithms.AES
  356. blockSize = 16
  357. keySize = int(cipher[3:6]) // 8
  358. ivSize = blockSize
  359. else:
  360. raise BadKeyError(f"unknown encryption type {cipher!r}")
  361. if kdf == b"bcrypt":
  362. salt, rest = common.getNS(kdfOptions)
  363. rounds = struct.unpack("!L", rest[:4])[0]
  364. decKey = bcrypt.kdf(
  365. passphrase,
  366. salt,
  367. keySize + ivSize,
  368. rounds,
  369. # We can only use the number of rounds that OpenSSH used.
  370. ignore_few_rounds=True,
  371. )
  372. else:
  373. raise BadKeyError(f"unknown KDF type {kdf!r}")
  374. if (len(encPrivKeyList) % blockSize) != 0:
  375. raise BadKeyError("bad padding")
  376. decryptor = Cipher(
  377. algorithmClass(decKey[:keySize]),
  378. modes.CTR(decKey[keySize : keySize + ivSize]),
  379. backend=default_backend(),
  380. ).decryptor()
  381. privKeyList = decryptor.update(encPrivKeyList) + decryptor.finalize()
  382. else:
  383. if kdf != b"none":
  384. raise BadKeyError(
  385. "private key specifies KDF %r but no " "cipher" % (kdf,)
  386. )
  387. privKeyList = encPrivKeyList
  388. check1 = struct.unpack("!L", privKeyList[:4])[0]
  389. check2 = struct.unpack("!L", privKeyList[4:8])[0]
  390. if check1 != check2:
  391. raise BadKeyError("check values do not match: %d != %d" % (check1, check2))
  392. return cls._fromString_PRIVATE_BLOB(privKeyList[8:])
  393. @classmethod
  394. def _fromPrivateOpenSSH_PEM(cls, data, passphrase):
  395. """
  396. Return a private key object corresponding to this OpenSSH private key
  397. string, in the old PEM-based format.
  398. The format of a PEM-based OpenSSH private key string is::
  399. -----BEGIN <key type> PRIVATE KEY-----
  400. [Proc-Type: 4,ENCRYPTED
  401. DEK-Info: DES-EDE3-CBC,<initialization value>]
  402. <base64-encoded ASN.1 structure>
  403. ------END <key type> PRIVATE KEY------
  404. The ASN.1 structure of a RSA key is::
  405. (0, n, e, d, p, q)
  406. The ASN.1 structure of a DSA key is::
  407. (0, p, q, g, y, x)
  408. The ASN.1 structure of a ECDSA key is::
  409. (ECParameters, OID, NULL)
  410. @type data: L{bytes}
  411. @param data: The key data.
  412. @type passphrase: L{bytes} or L{None}
  413. @param passphrase: The passphrase the key is encrypted with, or L{None}
  414. if it is not encrypted.
  415. @return: A new key.
  416. @rtype: L{twisted.conch.ssh.keys.Key}
  417. @raises BadKeyError: if
  418. * a passphrase is provided for an unencrypted key
  419. * the ASN.1 encoding is incorrect
  420. @raises EncryptedKeyError: if
  421. * a passphrase is not provided for an encrypted key
  422. """
  423. lines = data.strip().splitlines()
  424. kind = lines[0][11:-17]
  425. # cryptography considers an empty byte string a passphrase, but
  426. # twisted considers that to be "no password". So we need to convert
  427. # to None on empty.
  428. if not passphrase:
  429. passphrase = None
  430. if kind in (b"EC", b"RSA", b"DSA"):
  431. try:
  432. key = load_pem_private_key(data, passphrase, default_backend())
  433. except TypeError:
  434. raise EncryptedKeyError(
  435. "Passphrase must be provided for an encrypted key"
  436. )
  437. except ValueError:
  438. raise BadKeyError("Failed to decode key (Bad Passphrase?)")
  439. return cls(key)
  440. else:
  441. raise BadKeyError(f"unknown key type {kind}")
  442. @classmethod
  443. def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
  444. """
  445. Return a private key object corresponding to this OpenSSH private key
  446. string. If the key is encrypted, passphrase MUST be provided.
  447. Providing a passphrase for an unencrypted key is an error.
  448. @type data: L{bytes}
  449. @param data: The key data.
  450. @type passphrase: L{bytes} or L{None}
  451. @param passphrase: The passphrase the key is encrypted with, or L{None}
  452. if it is not encrypted.
  453. @return: A new key.
  454. @rtype: L{twisted.conch.ssh.keys.Key}
  455. @raises BadKeyError: if
  456. * a passphrase is provided for an unencrypted key
  457. * the encoding is incorrect
  458. @raises EncryptedKeyError: if
  459. * a passphrase is not provided for an encrypted key
  460. """
  461. if data.strip().splitlines()[0][11:-17] == b"OPENSSH":
  462. # New-format (openssh-key-v1) key
  463. return cls._fromPrivateOpenSSH_v1(data, passphrase)
  464. else:
  465. # Old-format (PEM) key
  466. return cls._fromPrivateOpenSSH_PEM(data, passphrase)
  467. @classmethod
  468. def _fromString_PUBLIC_LSH(cls, data):
  469. """
  470. Return a public key corresponding to this LSH public key string.
  471. The LSH public key string format is::
  472. <s-expression: ('public-key', (<key type>, (<name, <value>)+))>
  473. The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
  474. The names for a DSA (key type 'dsa') key are: y, g, p, q.
  475. @type data: L{bytes}
  476. @param data: The key data.
  477. @return: A new key.
  478. @rtype: L{twisted.conch.ssh.keys.Key}
  479. @raises BadKeyError: if the key type is unknown
  480. """
  481. sexp = sexpy.parse(decodebytes(data[1:-1]))
  482. assert sexp[0] == b"public-key"
  483. kd = {}
  484. for name, data in sexp[1][1:]:
  485. kd[name] = common.getMP(common.NS(data))[0]
  486. if sexp[1][0] == b"dsa":
  487. return cls._fromDSAComponents(
  488. y=kd[b"y"], g=kd[b"g"], p=kd[b"p"], q=kd[b"q"]
  489. )
  490. elif sexp[1][0] == b"rsa-pkcs1-sha1":
  491. return cls._fromRSAComponents(n=kd[b"n"], e=kd[b"e"])
  492. else:
  493. raise BadKeyError(f"unknown lsh key type {sexp[1][0]}")
  494. @classmethod
  495. def _fromString_PRIVATE_LSH(cls, data):
  496. """
  497. Return a private key corresponding to this LSH private key string.
  498. The LSH private key string format is::
  499. <s-expression: ('private-key', (<key type>, (<name>, <value>)+))>
  500. The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
  501. The names for a DSA (key type 'dsa') key are: y, g, p, q, x.
  502. @type data: L{bytes}
  503. @param data: The key data.
  504. @return: A new key.
  505. @rtype: L{twisted.conch.ssh.keys.Key}
  506. @raises BadKeyError: if the key type is unknown
  507. """
  508. sexp = sexpy.parse(data)
  509. assert sexp[0] == b"private-key"
  510. kd = {}
  511. for name, data in sexp[1][1:]:
  512. kd[name] = common.getMP(common.NS(data))[0]
  513. if sexp[1][0] == b"dsa":
  514. assert len(kd) == 5, len(kd)
  515. return cls._fromDSAComponents(
  516. y=kd[b"y"], g=kd[b"g"], p=kd[b"p"], q=kd[b"q"], x=kd[b"x"]
  517. )
  518. elif sexp[1][0] == b"rsa-pkcs1":
  519. assert len(kd) == 8, len(kd)
  520. if kd[b"p"] > kd[b"q"]: # Make p smaller than q
  521. kd[b"p"], kd[b"q"] = kd[b"q"], kd[b"p"]
  522. return cls._fromRSAComponents(
  523. n=kd[b"n"], e=kd[b"e"], d=kd[b"d"], p=kd[b"p"], q=kd[b"q"]
  524. )
  525. else:
  526. raise BadKeyError(f"unknown lsh key type {sexp[1][0]}")
  527. @classmethod
  528. def _fromString_AGENTV3(cls, data):
  529. """
  530. Return a private key object corresponsing to the Secure Shell Key
  531. Agent v3 format.
  532. The SSH Key Agent v3 format for a RSA key is::
  533. string 'ssh-rsa'
  534. integer e
  535. integer d
  536. integer n
  537. integer u
  538. integer p
  539. integer q
  540. The SSH Key Agent v3 format for a DSA key is::
  541. string 'ssh-dss'
  542. integer p
  543. integer q
  544. integer g
  545. integer y
  546. integer x
  547. @type data: L{bytes}
  548. @param data: The key data.
  549. @return: A new key.
  550. @rtype: L{twisted.conch.ssh.keys.Key}
  551. @raises BadKeyError: if the key type (the first string) is unknown
  552. """
  553. keyType, data = common.getNS(data)
  554. if keyType == b"ssh-dss":
  555. p, data = common.getMP(data)
  556. q, data = common.getMP(data)
  557. g, data = common.getMP(data)
  558. y, data = common.getMP(data)
  559. x, data = common.getMP(data)
  560. return cls._fromDSAComponents(y=y, g=g, p=p, q=q, x=x)
  561. elif keyType == b"ssh-rsa":
  562. e, data = common.getMP(data)
  563. d, data = common.getMP(data)
  564. n, data = common.getMP(data)
  565. u, data = common.getMP(data)
  566. p, data = common.getMP(data)
  567. q, data = common.getMP(data)
  568. return cls._fromRSAComponents(n=n, e=e, d=d, p=p, q=q, u=u)
  569. else:
  570. raise BadKeyError(f"unknown key type {keyType}")
  571. @classmethod
  572. def _guessStringType(cls, data):
  573. """
  574. Guess the type of key in data. The types map to _fromString_*
  575. methods.
  576. @type data: L{bytes}
  577. @param data: The key data.
  578. """
  579. if data.startswith(b"ssh-") or data.startswith(b"ecdsa-sha2-"):
  580. return "public_openssh"
  581. elif data.startswith(b"-----BEGIN"):
  582. return "private_openssh"
  583. elif data.startswith(b"{"):
  584. return "public_lsh"
  585. elif data.startswith(b"("):
  586. return "private_lsh"
  587. elif (
  588. data.startswith(b"\x00\x00\x00\x07ssh-")
  589. or data.startswith(b"\x00\x00\x00\x13ecdsa-")
  590. or data.startswith(b"\x00\x00\x00\x0bssh-ed25519")
  591. ):
  592. ignored, rest = common.getNS(data)
  593. count = 0
  594. while rest:
  595. count += 1
  596. ignored, rest = common.getMP(rest)
  597. if count > 4:
  598. return "agentv3"
  599. else:
  600. return "blob"
  601. @classmethod
  602. def _fromRSAComponents(cls, n, e, d=None, p=None, q=None, u=None):
  603. """
  604. Build a key from RSA numerical components.
  605. @type n: L{int}
  606. @param n: The 'n' RSA variable.
  607. @type e: L{int}
  608. @param e: The 'e' RSA variable.
  609. @type d: L{int} or L{None}
  610. @param d: The 'd' RSA variable (optional for a public key).
  611. @type p: L{int} or L{None}
  612. @param p: The 'p' RSA variable (optional for a public key).
  613. @type q: L{int} or L{None}
  614. @param q: The 'q' RSA variable (optional for a public key).
  615. @type u: L{int} or L{None}
  616. @param u: The 'u' RSA variable. Ignored, as its value is determined by
  617. p and q.
  618. @rtype: L{Key}
  619. @return: An RSA key constructed from the values as given.
  620. """
  621. publicNumbers = rsa.RSAPublicNumbers(e=e, n=n)
  622. if d is None:
  623. # We have public components.
  624. keyObject = publicNumbers.public_key(default_backend())
  625. else:
  626. privateNumbers = rsa.RSAPrivateNumbers(
  627. p=p,
  628. q=q,
  629. d=d,
  630. dmp1=rsa.rsa_crt_dmp1(d, p),
  631. dmq1=rsa.rsa_crt_dmq1(d, q),
  632. iqmp=rsa.rsa_crt_iqmp(p, q),
  633. public_numbers=publicNumbers,
  634. )
  635. keyObject = privateNumbers.private_key(default_backend())
  636. return cls(keyObject)
  637. @classmethod
  638. def _fromDSAComponents(cls, y, p, q, g, x=None):
  639. """
  640. Build a key from DSA numerical components.
  641. @type y: L{int}
  642. @param y: The 'y' DSA variable.
  643. @type p: L{int}
  644. @param p: The 'p' DSA variable.
  645. @type q: L{int}
  646. @param q: The 'q' DSA variable.
  647. @type g: L{int}
  648. @param g: The 'g' DSA variable.
  649. @type x: L{int} or L{None}
  650. @param x: The 'x' DSA variable (optional for a public key)
  651. @rtype: L{Key}
  652. @return: A DSA key constructed from the values as given.
  653. """
  654. publicNumbers = dsa.DSAPublicNumbers(
  655. y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g)
  656. )
  657. if x is None:
  658. # We have public components.
  659. keyObject = publicNumbers.public_key(default_backend())
  660. else:
  661. privateNumbers = dsa.DSAPrivateNumbers(x=x, public_numbers=publicNumbers)
  662. keyObject = privateNumbers.private_key(default_backend())
  663. return cls(keyObject)
  664. @classmethod
  665. def _fromECComponents(cls, x, y, curve, privateValue=None):
  666. """
  667. Build a key from EC components.
  668. @param x: The affine x component of the public point used for verifying.
  669. @type x: L{int}
  670. @param y: The affine y component of the public point used for verifying.
  671. @type y: L{int}
  672. @param curve: NIST name of elliptic curve.
  673. @type curve: L{bytes}
  674. @param privateValue: The private value.
  675. @type privateValue: L{int}
  676. """
  677. publicNumbers = ec.EllipticCurvePublicNumbers(
  678. x=x, y=y, curve=_curveTable[curve]
  679. )
  680. if privateValue is None:
  681. # We have public components.
  682. keyObject = publicNumbers.public_key(default_backend())
  683. else:
  684. privateNumbers = ec.EllipticCurvePrivateNumbers(
  685. private_value=privateValue, public_numbers=publicNumbers
  686. )
  687. keyObject = privateNumbers.private_key(default_backend())
  688. return cls(keyObject)
  689. @classmethod
  690. def _fromECEncodedPoint(cls, encodedPoint, curve, privateValue=None):
  691. """
  692. Build a key from an EC encoded point.
  693. @param encodedPoint: The public point encoded as in SEC 1 v2.0
  694. section 2.3.3.
  695. @type encodedPoint: L{bytes}
  696. @param curve: NIST name of elliptic curve.
  697. @type curve: L{bytes}
  698. @param privateValue: The private value.
  699. @type privateValue: L{int}
  700. """
  701. if privateValue is None:
  702. # We have public components.
  703. keyObject = ec.EllipticCurvePublicKey.from_encoded_point(
  704. _curveTable[curve], encodedPoint
  705. )
  706. else:
  707. keyObject = ec.derive_private_key(
  708. privateValue, _curveTable[curve], default_backend()
  709. )
  710. return cls(keyObject)
  711. @classmethod
  712. def _fromEd25519Components(cls, a, k=None):
  713. """Build a key from Ed25519 components.
  714. @param a: The Ed25519 public key, as defined in RFC 8032 section
  715. 5.1.5.
  716. @type a: L{bytes}
  717. @param k: The Ed25519 private key, as defined in RFC 8032 section
  718. 5.1.5.
  719. @type k: L{bytes}
  720. """
  721. if Ed25519PublicKey is None or Ed25519PrivateKey is None:
  722. raise BadKeyError("Ed25519 keys not supported on this system")
  723. if k is None:
  724. keyObject = Ed25519PublicKey.from_public_bytes(a)
  725. else:
  726. keyObject = Ed25519PrivateKey.from_private_bytes(k)
  727. return cls(keyObject)
  728. def __init__(self, keyObject):
  729. """
  730. Initialize with a private or public
  731. C{cryptography.hazmat.primitives.asymmetric} key.
  732. @param keyObject: Low level key.
  733. @type keyObject: C{cryptography.hazmat.primitives.asymmetric} key.
  734. """
  735. self._keyObject = keyObject
  736. def __eq__(self, other: object) -> bool:
  737. """
  738. Return True if other represents an object with the same key.
  739. """
  740. if isinstance(other, Key):
  741. return self.type() == other.type() and self.data() == other.data()
  742. else:
  743. return NotImplemented
  744. def __repr__(self) -> str:
  745. """
  746. Return a pretty representation of this object.
  747. """
  748. if self.type() == "EC":
  749. data = self.data()
  750. name = data["curve"].decode("utf-8")
  751. if self.isPublic():
  752. out = f"<Elliptic Curve Public Key ({name[-3:]} bits)"
  753. else:
  754. out = f"<Elliptic Curve Private Key ({name[-3:]} bits)"
  755. for k, v in sorted(data.items()):
  756. if k == "curve":
  757. out += f"\ncurve:\n\t{name}"
  758. else:
  759. out += f"\n{k}:\n\t{v}"
  760. return out + ">\n"
  761. else:
  762. lines = [
  763. "<%s %s (%s bits)"
  764. % (
  765. nativeString(self.type()),
  766. self.isPublic() and "Public Key" or "Private Key",
  767. self.size(),
  768. )
  769. ]
  770. for k, v in sorted(self.data().items()):
  771. lines.append(f"attr {k}:")
  772. by = v if self.type() == "Ed25519" else common.MP(v)[4:]
  773. while by:
  774. m = by[:15]
  775. by = by[15:]
  776. o = ""
  777. for c in iterbytes(m):
  778. o = o + f"{ord(c):02x}:"
  779. if len(m) < 15:
  780. o = o[:-1]
  781. lines.append("\t" + o)
  782. lines[-1] = lines[-1] + ">"
  783. return "\n".join(lines)
  784. def isPublic(self):
  785. """
  786. Check if this instance is a public key.
  787. @return: C{True} if this is a public key.
  788. """
  789. return isinstance(
  790. self._keyObject,
  791. (
  792. rsa.RSAPublicKey,
  793. dsa.DSAPublicKey,
  794. ec.EllipticCurvePublicKey,
  795. ed25519.Ed25519PublicKey,
  796. ),
  797. )
  798. def public(self):
  799. """
  800. Returns a version of this key containing only the public key data.
  801. If this is a public key, this may or may not be the same object
  802. as self.
  803. @rtype: L{Key}
  804. @return: A public key.
  805. """
  806. if self.isPublic():
  807. return self
  808. else:
  809. return Key(self._keyObject.public_key())
  810. def fingerprint(self, format=FingerprintFormats.MD5_HEX):
  811. """
  812. The fingerprint of a public key consists of the output of the
  813. message-digest algorithm in the specified format.
  814. Supported formats include L{FingerprintFormats.MD5_HEX} and
  815. L{FingerprintFormats.SHA256_BASE64}
  816. The input to the algorithm is the public key data as specified by [RFC4253].
  817. The output of sha256[RFC4634] algorithm is presented to the
  818. user in the form of base64 encoded sha256 hashes.
  819. Example: C{US5jTUa0kgX5ZxdqaGF0yGRu8EgKXHNmoT8jHKo1StM=}
  820. The output of the MD5[RFC1321](default) algorithm is presented to the user as
  821. a sequence of 16 octets printed as hexadecimal with lowercase letters
  822. and separated by colons.
  823. Example: C{c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87}
  824. @param format: Format for fingerprint generation. Consists
  825. hash function and representation format.
  826. Default is L{FingerprintFormats.MD5_HEX}
  827. @since: 8.2
  828. @return: the user presentation of this L{Key}'s fingerprint, as a
  829. string.
  830. @rtype: L{str}
  831. """
  832. if format is FingerprintFormats.SHA256_BASE64:
  833. return nativeString(b64encode(sha256(self.blob()).digest()))
  834. elif format is FingerprintFormats.MD5_HEX:
  835. return nativeString(
  836. b":".join(
  837. [binascii.hexlify(x) for x in iterbytes(md5(self.blob()).digest())]
  838. )
  839. )
  840. else:
  841. raise BadFingerPrintFormat(f"Unsupported fingerprint format: {format}")
  842. def type(self) -> Literal["RSA", "DSA", "EC", "Ed25519"]:
  843. """
  844. Return the type of the object we wrap. Currently this can only be
  845. 'RSA', 'DSA', 'EC', or 'Ed25519'.
  846. @rtype: L{str}
  847. @raises RuntimeError: If the object type is unknown.
  848. """
  849. if isinstance(self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)):
  850. return "RSA"
  851. elif isinstance(self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)):
  852. return "DSA"
  853. elif isinstance(
  854. self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)
  855. ):
  856. return "EC"
  857. elif isinstance(
  858. self._keyObject, (ed25519.Ed25519PublicKey, ed25519.Ed25519PrivateKey)
  859. ):
  860. return "Ed25519"
  861. else:
  862. raise RuntimeError(f"unknown type of object: {self._keyObject!r}")
  863. def sshType(self):
  864. """
  865. Get the type of the object we wrap as defined in the SSH protocol,
  866. defined in RFC 4253, Section 6.6 and RFC 8332, section 4 (this is a
  867. public key format name, not a public key algorithm name). Currently
  868. this can only be b'ssh-rsa', b'ssh-dss', b'ecdsa-sha2-[identifier]'
  869. or b'ssh-ed25519'.
  870. identifier is the standard NIST curve name
  871. @return: The key type format.
  872. @rtype: L{bytes}
  873. """
  874. if self.type() == "EC":
  875. return (
  876. b"ecdsa-sha2-" + _secToNist[self._keyObject.curve.name.encode("ascii")]
  877. )
  878. else:
  879. return {
  880. "RSA": b"ssh-rsa",
  881. "DSA": b"ssh-dss",
  882. "Ed25519": b"ssh-ed25519",
  883. }[self.type()]
  884. def supportedSignatureAlgorithms(self):
  885. """
  886. Get the public key signature algorithms supported by this key.
  887. @return: A list of supported public key signature algorithm names.
  888. @rtype: L{list} of L{bytes}
  889. """
  890. if self.type() == "RSA":
  891. return [b"rsa-sha2-512", b"rsa-sha2-256", b"ssh-rsa"]
  892. else:
  893. return [self.sshType()]
  894. def _getHashAlgorithm(self, signatureType):
  895. """
  896. Return a hash algorithm for this key type given an SSH signature
  897. algorithm name, or L{None} if no such hash algorithm is defined for
  898. this key type.
  899. """
  900. if self.type() == "EC":
  901. # Hash algorithm depends on key size
  902. if signatureType == self.sshType():
  903. keySize = self.size()
  904. if keySize <= 256:
  905. return hashes.SHA256()
  906. elif keySize <= 384:
  907. return hashes.SHA384()
  908. else:
  909. return hashes.SHA512()
  910. else:
  911. return None
  912. else:
  913. return {
  914. ("RSA", b"ssh-rsa"): hashes.SHA1(),
  915. ("RSA", b"rsa-sha2-256"): hashes.SHA256(),
  916. ("RSA", b"rsa-sha2-512"): hashes.SHA512(),
  917. ("DSA", b"ssh-dss"): hashes.SHA1(),
  918. ("Ed25519", b"ssh-ed25519"): hashes.SHA512(),
  919. }.get((self.type(), signatureType))
  920. def size(self):
  921. """
  922. Return the size of the object we wrap.
  923. @return: The size of the key.
  924. @rtype: L{int}
  925. """
  926. if self._keyObject is None:
  927. return 0
  928. elif self.type() == "EC":
  929. return self._keyObject.curve.key_size
  930. elif self.type() == "Ed25519":
  931. return 256
  932. return self._keyObject.key_size
  933. def data(self) -> dict[str, Any]:
  934. """
  935. Return the values of the public key as a dictionary.
  936. @rtype: L{dict}
  937. """
  938. if isinstance(self._keyObject, rsa.RSAPublicKey):
  939. rsa_pub_numbers = self._keyObject.public_numbers()
  940. return {
  941. "n": rsa_pub_numbers.n,
  942. "e": rsa_pub_numbers.e,
  943. }
  944. elif isinstance(self._keyObject, rsa.RSAPrivateKey):
  945. rsa_priv_numbers = self._keyObject.private_numbers()
  946. return {
  947. "n": rsa_priv_numbers.public_numbers.n,
  948. "e": rsa_priv_numbers.public_numbers.e,
  949. "d": rsa_priv_numbers.d,
  950. "p": rsa_priv_numbers.p,
  951. "q": rsa_priv_numbers.q,
  952. # Use a trick: iqmp is q^-1 % p, u is p^-1 % q
  953. "u": rsa.rsa_crt_iqmp(rsa_priv_numbers.q, rsa_priv_numbers.p),
  954. }
  955. elif isinstance(self._keyObject, dsa.DSAPublicKey):
  956. dsa_pub_numbers = self._keyObject.public_numbers()
  957. return {
  958. "y": dsa_pub_numbers.y,
  959. "g": dsa_pub_numbers.parameter_numbers.g,
  960. "p": dsa_pub_numbers.parameter_numbers.p,
  961. "q": dsa_pub_numbers.parameter_numbers.q,
  962. }
  963. elif isinstance(self._keyObject, dsa.DSAPrivateKey):
  964. dsa_priv_numbers = self._keyObject.private_numbers()
  965. return {
  966. "x": dsa_priv_numbers.x,
  967. "y": dsa_priv_numbers.public_numbers.y,
  968. "g": dsa_priv_numbers.public_numbers.parameter_numbers.g,
  969. "p": dsa_priv_numbers.public_numbers.parameter_numbers.p,
  970. "q": dsa_priv_numbers.public_numbers.parameter_numbers.q,
  971. }
  972. elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
  973. ec_pub_numbers = self._keyObject.public_numbers()
  974. return {
  975. "x": ec_pub_numbers.x,
  976. "y": ec_pub_numbers.y,
  977. "curve": self.sshType(),
  978. }
  979. elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
  980. ec_priv_numbers = self._keyObject.private_numbers()
  981. return {
  982. "x": ec_priv_numbers.public_numbers.x,
  983. "y": ec_priv_numbers.public_numbers.y,
  984. "privateValue": ec_priv_numbers.private_value,
  985. "curve": self.sshType(),
  986. }
  987. elif isinstance(self._keyObject, ed25519.Ed25519PublicKey):
  988. return {
  989. "a": self._keyObject.public_bytes(
  990. serialization.Encoding.Raw, serialization.PublicFormat.Raw
  991. ),
  992. }
  993. elif isinstance(self._keyObject, ed25519.Ed25519PrivateKey):
  994. return {
  995. "a": self._keyObject.public_key().public_bytes(
  996. serialization.Encoding.Raw, serialization.PublicFormat.Raw
  997. ),
  998. "k": self._keyObject.private_bytes(
  999. serialization.Encoding.Raw,
  1000. serialization.PrivateFormat.Raw,
  1001. serialization.NoEncryption(),
  1002. ),
  1003. }
  1004. else:
  1005. raise RuntimeError(f"Unexpected key type: {self._keyObject}")
  1006. def blob(self):
  1007. """
  1008. Return the public key blob for this key. The blob is the
  1009. over-the-wire format for public keys.
  1010. SECSH-TRANS RFC 4253 Section 6.6.
  1011. RSA keys::
  1012. string 'ssh-rsa'
  1013. integer e
  1014. integer n
  1015. DSA keys::
  1016. string 'ssh-dss'
  1017. integer p
  1018. integer q
  1019. integer g
  1020. integer y
  1021. EC keys::
  1022. string 'ecdsa-sha2-[identifier]'
  1023. integer x
  1024. integer y
  1025. identifier is the standard NIST curve name
  1026. Ed25519 keys::
  1027. string 'ssh-ed25519'
  1028. string a
  1029. @rtype: L{bytes}
  1030. """
  1031. type = self.type()
  1032. data = self.data()
  1033. if type == "RSA":
  1034. return common.NS(b"ssh-rsa") + common.MP(data["e"]) + common.MP(data["n"])
  1035. elif type == "DSA":
  1036. return (
  1037. common.NS(b"ssh-dss")
  1038. + common.MP(data["p"])
  1039. + common.MP(data["q"])
  1040. + common.MP(data["g"])
  1041. + common.MP(data["y"])
  1042. )
  1043. elif type == "EC":
  1044. byteLength = (self._keyObject.curve.key_size + 7) // 8
  1045. return (
  1046. common.NS(data["curve"])
  1047. + common.NS(data["curve"][-8:])
  1048. + common.NS(
  1049. b"\x04"
  1050. + utils.int_to_bytes(data["x"], byteLength)
  1051. + utils.int_to_bytes(data["y"], byteLength)
  1052. )
  1053. )
  1054. elif type == "Ed25519":
  1055. return common.NS(b"ssh-ed25519") + common.NS(data["a"])
  1056. else:
  1057. raise BadKeyError(f"unknown key type: {type}")
  1058. def privateBlob(self):
  1059. """
  1060. Return the private key blob for this key. The blob is the
  1061. over-the-wire format for private keys:
  1062. Specification in OpenSSH PROTOCOL.agent
  1063. RSA keys::
  1064. string 'ssh-rsa'
  1065. integer n
  1066. integer e
  1067. integer d
  1068. integer u
  1069. integer p
  1070. integer q
  1071. DSA keys::
  1072. string 'ssh-dss'
  1073. integer p
  1074. integer q
  1075. integer g
  1076. integer y
  1077. integer x
  1078. EC keys::
  1079. string 'ecdsa-sha2-[identifier]'
  1080. integer x
  1081. integer y
  1082. integer privateValue
  1083. identifier is the NIST standard curve name.
  1084. Ed25519 keys::
  1085. string 'ssh-ed25519'
  1086. string a
  1087. string k || a
  1088. """
  1089. type = self.type()
  1090. data = self.data()
  1091. if type == "RSA":
  1092. iqmp = rsa.rsa_crt_iqmp(data["p"], data["q"])
  1093. return (
  1094. common.NS(b"ssh-rsa")
  1095. + common.MP(data["n"])
  1096. + common.MP(data["e"])
  1097. + common.MP(data["d"])
  1098. + common.MP(iqmp)
  1099. + common.MP(data["p"])
  1100. + common.MP(data["q"])
  1101. )
  1102. elif type == "DSA":
  1103. return (
  1104. common.NS(b"ssh-dss")
  1105. + common.MP(data["p"])
  1106. + common.MP(data["q"])
  1107. + common.MP(data["g"])
  1108. + common.MP(data["y"])
  1109. + common.MP(data["x"])
  1110. )
  1111. elif type == "EC":
  1112. encPub = self._keyObject.public_key().public_bytes(
  1113. serialization.Encoding.X962,
  1114. serialization.PublicFormat.UncompressedPoint,
  1115. )
  1116. return (
  1117. common.NS(data["curve"])
  1118. + common.NS(data["curve"][-8:])
  1119. + common.NS(encPub)
  1120. + common.MP(data["privateValue"])
  1121. )
  1122. elif type == "Ed25519":
  1123. return (
  1124. common.NS(b"ssh-ed25519")
  1125. + common.NS(data["a"])
  1126. + common.NS(data["k"] + data["a"])
  1127. )
  1128. else:
  1129. raise BadKeyError(f"unknown key type: {type}")
  1130. @_mutuallyExclusiveArguments(
  1131. [
  1132. ["extra", "comment"],
  1133. ["extra", "passphrase"],
  1134. ]
  1135. )
  1136. def toString(self, type, extra=None, subtype=None, comment=None, passphrase=None):
  1137. """
  1138. Create a string representation of this key. If the key is a private
  1139. key and you want the representation of its public key, use
  1140. C{key.public().toString()}. type maps to a _toString_* method.
  1141. @param type: The type of string to emit. Currently supported values
  1142. are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
  1143. @type type: L{str}
  1144. @param extra: Any extra data supported by the selected format which
  1145. is not part of the key itself. For public OpenSSH keys, this is
  1146. a comment. For private OpenSSH keys, this is a passphrase to
  1147. encrypt with. (Deprecated since Twisted 20.3.0; use C{comment}
  1148. or C{passphrase} as appropriate instead.)
  1149. @type extra: L{bytes} or L{unicode} or L{None}
  1150. @param subtype: A subtype of the requested C{type} to emit. Only
  1151. supported for private OpenSSH keys, for which the currently
  1152. supported subtypes are C{'PEM'} and C{'v1'}. If not given, an
  1153. appropriate default is used.
  1154. @type subtype: L{str} or L{None}
  1155. @param comment: A comment to include with the key. Only supported
  1156. for OpenSSH keys.
  1157. Present since Twisted 20.3.0.
  1158. @type comment: L{bytes} or L{unicode} or L{None}
  1159. @param passphrase: A passphrase to encrypt the key with. Only
  1160. supported for private OpenSSH keys.
  1161. Present since Twisted 20.3.0.
  1162. @type passphrase: L{bytes} or L{unicode} or L{None}
  1163. @rtype: L{bytes}
  1164. """
  1165. if extra is not None:
  1166. # Compatibility with old parameter format.
  1167. warnings.warn(
  1168. "The 'extra' argument to "
  1169. "twisted.conch.ssh.keys.Key.toString was deprecated in "
  1170. "Twisted 20.3.0; use 'comment' or 'passphrase' instead.",
  1171. DeprecationWarning,
  1172. stacklevel=3,
  1173. )
  1174. if self.isPublic():
  1175. comment = extra
  1176. else:
  1177. passphrase = extra
  1178. if isinstance(comment, str):
  1179. comment = comment.encode("utf-8")
  1180. passphrase = _normalizePassphrase(passphrase)
  1181. method = getattr(self, f"_toString_{type.upper()}", None)
  1182. if method is None:
  1183. raise BadKeyError(f"unknown key type: {type}")
  1184. return method(subtype=subtype, comment=comment, passphrase=passphrase)
  1185. def _toPublicOpenSSH(self, comment=None):
  1186. """
  1187. Return a public OpenSSH key string.
  1188. See _fromString_PUBLIC_OPENSSH for the string format.
  1189. @type comment: L{bytes} or L{None}
  1190. @param comment: A comment to include with the key, or L{None} to
  1191. omit the comment.
  1192. """
  1193. if self.type() == "EC":
  1194. if not comment:
  1195. comment = b""
  1196. return (
  1197. self._keyObject.public_bytes(
  1198. serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH
  1199. )
  1200. + b" "
  1201. + comment
  1202. ).strip()
  1203. b64Data = encodebytes(self.blob()).replace(b"\n", b"")
  1204. if not comment:
  1205. comment = b""
  1206. return (self.sshType() + b" " + b64Data + b" " + comment).strip()
  1207. def _toPrivateOpenSSH_v1(self, comment=None, passphrase=None):
  1208. """
  1209. Return a private OpenSSH key string, in the "openssh-key-v1" format
  1210. introduced in OpenSSH 6.5.
  1211. See _fromPrivateOpenSSH_v1 for the string format.
  1212. @type passphrase: L{bytes} or L{None}
  1213. @param passphrase: The passphrase to encrypt the key with, or L{None}
  1214. if it is not encrypted.
  1215. """
  1216. if passphrase:
  1217. # For now we just hardcode the cipher to the one used by
  1218. # OpenSSH. We could make this configurable later if it's
  1219. # needed.
  1220. cipher = algorithms.AES
  1221. cipherName = b"aes256-ctr"
  1222. kdfName = b"bcrypt"
  1223. blockSize = cipher.block_size // 8
  1224. keySize = 32
  1225. ivSize = blockSize
  1226. salt = randbytes.secureRandom(ivSize)
  1227. rounds = 100
  1228. kdfOptions = common.NS(salt) + struct.pack("!L", rounds)
  1229. else:
  1230. cipherName = b"none"
  1231. kdfName = b"none"
  1232. blockSize = 8
  1233. kdfOptions = b""
  1234. check = randbytes.secureRandom(4)
  1235. privKeyList = check + check + self.privateBlob() + common.NS(comment or b"")
  1236. padByte = 0
  1237. while len(privKeyList) % blockSize:
  1238. padByte += 1
  1239. privKeyList += bytes((padByte & 0xFF,))
  1240. if passphrase:
  1241. encKey = bcrypt.kdf(passphrase, salt, keySize + ivSize, 100)
  1242. encryptor = Cipher(
  1243. cipher(encKey[:keySize]),
  1244. modes.CTR(encKey[keySize : keySize + ivSize]),
  1245. backend=default_backend(),
  1246. ).encryptor()
  1247. encPrivKeyList = encryptor.update(privKeyList) + encryptor.finalize()
  1248. else:
  1249. encPrivKeyList = privKeyList
  1250. blob = (
  1251. b"openssh-key-v1\0"
  1252. + common.NS(cipherName)
  1253. + common.NS(kdfName)
  1254. + common.NS(kdfOptions)
  1255. + struct.pack("!L", 1)
  1256. + common.NS(self.blob())
  1257. + common.NS(encPrivKeyList)
  1258. )
  1259. b64Data = encodebytes(blob).replace(b"\n", b"")
  1260. lines = (
  1261. [b"-----BEGIN OPENSSH PRIVATE KEY-----"]
  1262. + [b64Data[i : i + 64] for i in range(0, len(b64Data), 64)]
  1263. + [b"-----END OPENSSH PRIVATE KEY-----"]
  1264. )
  1265. return b"\n".join(lines) + b"\n"
  1266. def _toPrivateOpenSSH_PEM(self, passphrase=None):
  1267. """
  1268. Return a private OpenSSH key string, in the old PEM-based format.
  1269. See _fromPrivateOpenSSH_PEM for the string format.
  1270. @type passphrase: L{bytes} or L{None}
  1271. @param passphrase: The passphrase to encrypt the key with, or L{None}
  1272. if it is not encrypted.
  1273. """
  1274. if not passphrase:
  1275. # unencrypted private key
  1276. encryptor = serialization.NoEncryption()
  1277. else:
  1278. encryptor = serialization.BestAvailableEncryption(passphrase)
  1279. if self.type() != "Ed25519":
  1280. return self._keyObject.private_bytes(
  1281. serialization.Encoding.PEM,
  1282. serialization.PrivateFormat.TraditionalOpenSSL,
  1283. encryptor,
  1284. )
  1285. else:
  1286. # TODO: why not just support serialization here
  1287. assert self.type() == "Ed25519"
  1288. raise ValueError(
  1289. "cannot serialize Ed25519 key to OpenSSH PEM format; use v1 " "instead"
  1290. )
  1291. def _toString_OPENSSH(self, subtype=None, comment=None, passphrase=None):
  1292. """
  1293. Return a public or private OpenSSH string. See
  1294. L{_fromString_PUBLIC_OPENSSH} and L{_fromPrivateOpenSSH_PEM} for the
  1295. string formats.
  1296. @param subtype: A subtype to emit. Only supported for private keys,
  1297. for which the currently supported subtypes are C{'PEM'} and C{'v1'}.
  1298. If not given, an appropriate default is used.
  1299. @type subtype: L{str} or L{None}
  1300. @param comment: Comment for a public key.
  1301. @type comment: L{bytes}
  1302. @param passphrase: Passphrase for a private key.
  1303. @type passphrase: L{bytes}
  1304. @rtype: L{bytes}
  1305. """
  1306. if self.isPublic():
  1307. return self._toPublicOpenSSH(comment=comment)
  1308. # No pre-v1 format is defined for Ed25519 keys.
  1309. elif subtype == "v1" or (subtype is None and self.type() == "Ed25519"):
  1310. return self._toPrivateOpenSSH_v1(comment=comment, passphrase=passphrase)
  1311. elif subtype is None or subtype == "PEM":
  1312. return self._toPrivateOpenSSH_PEM(passphrase=passphrase)
  1313. else:
  1314. raise ValueError(f"unknown subtype {subtype}")
  1315. def _toString_LSH(self, **kwargs):
  1316. """
  1317. Return a public or private LSH key. See _fromString_PUBLIC_LSH and
  1318. _fromString_PRIVATE_LSH for the key formats.
  1319. @rtype: L{bytes}
  1320. """
  1321. data = self.data()
  1322. type = self.type()
  1323. if self.isPublic():
  1324. if type == "RSA":
  1325. keyData = sexpy.pack(
  1326. [
  1327. [
  1328. b"public-key",
  1329. [
  1330. b"rsa-pkcs1-sha1",
  1331. [b"n", common.MP(data["n"])[4:]],
  1332. [b"e", common.MP(data["e"])[4:]],
  1333. ],
  1334. ]
  1335. ]
  1336. )
  1337. elif type == "DSA":
  1338. keyData = sexpy.pack(
  1339. [
  1340. [
  1341. b"public-key",
  1342. [
  1343. b"dsa",
  1344. [b"p", common.MP(data["p"])[4:]],
  1345. [b"q", common.MP(data["q"])[4:]],
  1346. [b"g", common.MP(data["g"])[4:]],
  1347. [b"y", common.MP(data["y"])[4:]],
  1348. ],
  1349. ]
  1350. ]
  1351. )
  1352. else:
  1353. raise BadKeyError(f"unknown key type {type}")
  1354. return b"{" + encodebytes(keyData).replace(b"\n", b"") + b"}"
  1355. else:
  1356. if type == "RSA":
  1357. p, q = data["p"], data["q"]
  1358. iqmp = rsa.rsa_crt_iqmp(p, q)
  1359. return sexpy.pack(
  1360. [
  1361. [
  1362. b"private-key",
  1363. [
  1364. b"rsa-pkcs1",
  1365. [b"n", common.MP(data["n"])[4:]],
  1366. [b"e", common.MP(data["e"])[4:]],
  1367. [b"d", common.MP(data["d"])[4:]],
  1368. [b"p", common.MP(q)[4:]],
  1369. [b"q", common.MP(p)[4:]],
  1370. [b"a", common.MP(data["d"] % (q - 1))[4:]],
  1371. [b"b", common.MP(data["d"] % (p - 1))[4:]],
  1372. [b"c", common.MP(iqmp)[4:]],
  1373. ],
  1374. ]
  1375. ]
  1376. )
  1377. elif type == "DSA":
  1378. return sexpy.pack(
  1379. [
  1380. [
  1381. b"private-key",
  1382. [
  1383. b"dsa",
  1384. [b"p", common.MP(data["p"])[4:]],
  1385. [b"q", common.MP(data["q"])[4:]],
  1386. [b"g", common.MP(data["g"])[4:]],
  1387. [b"y", common.MP(data["y"])[4:]],
  1388. [b"x", common.MP(data["x"])[4:]],
  1389. ],
  1390. ]
  1391. ]
  1392. )
  1393. else:
  1394. raise BadKeyError(f"unknown key type {type}'")
  1395. def _toString_AGENTV3(self, **kwargs):
  1396. """
  1397. Return a private Secure Shell Agent v3 key. See
  1398. _fromString_AGENTV3 for the key format.
  1399. @rtype: L{bytes}
  1400. """
  1401. data = self.data()
  1402. if not self.isPublic():
  1403. if self.type() == "RSA":
  1404. values = (
  1405. data["e"],
  1406. data["d"],
  1407. data["n"],
  1408. data["u"],
  1409. data["p"],
  1410. data["q"],
  1411. )
  1412. elif self.type() == "DSA":
  1413. values = (data["p"], data["q"], data["g"], data["y"], data["x"])
  1414. return common.NS(self.sshType()) + b"".join(map(common.MP, values))
  1415. def sign(self, data, signatureType=None):
  1416. """
  1417. Sign some data with this key.
  1418. SECSH-TRANS RFC 4253 Section 6.6.
  1419. @type data: L{bytes}
  1420. @param data: The data to sign.
  1421. @type signatureType: L{bytes}
  1422. @param signatureType: The SSH public key algorithm name to sign this
  1423. data with, or L{None} to use a reasonable default for the key.
  1424. @rtype: L{bytes}
  1425. @return: A signature for the given data.
  1426. """
  1427. keyType = self.type()
  1428. if signatureType is None:
  1429. # Use the SSH public key type name by default, since for all
  1430. # current key types this can also be used as a public key
  1431. # algorithm name. (This exists for compatibility; new code
  1432. # should explicitly specify a public key algorithm name.)
  1433. signatureType = self.sshType()
  1434. hashAlgorithm = self._getHashAlgorithm(signatureType)
  1435. if hashAlgorithm is None:
  1436. raise BadSignatureAlgorithmError(
  1437. f"public key signature algorithm {signatureType} is not "
  1438. f"defined for {keyType} keys"
  1439. )
  1440. if keyType == "RSA":
  1441. sig = self._keyObject.sign(data, padding.PKCS1v15(), hashAlgorithm)
  1442. ret = common.NS(sig)
  1443. elif keyType == "DSA":
  1444. sig = self._keyObject.sign(data, hashAlgorithm)
  1445. (r, s) = decode_dss_signature(sig)
  1446. # SSH insists that the DSS signature blob be two 160-bit integers
  1447. # concatenated together. The sig[0], [1] numbers from obj.sign
  1448. # are just numbers, and could be any length from 0 to 160 bits.
  1449. # Make sure they are padded out to 160 bits (20 bytes each)
  1450. ret = common.NS(int_to_bytes(r, 20) + int_to_bytes(s, 20))
  1451. elif keyType == "EC": # Pragma: no branch
  1452. signature = self._keyObject.sign(data, ec.ECDSA(hashAlgorithm))
  1453. (r, s) = decode_dss_signature(signature)
  1454. rb = int_to_bytes(r)
  1455. sb = int_to_bytes(s)
  1456. # Int_to_bytes returns rb[0] as a str in python2
  1457. # and an as int in python3
  1458. if type(rb[0]) is str:
  1459. rcomp = ord(rb[0])
  1460. else:
  1461. rcomp = rb[0]
  1462. # If the MSB is set, prepend a null byte for correct formatting.
  1463. if rcomp & 0x80:
  1464. rb = b"\x00" + rb
  1465. if type(sb[0]) is str:
  1466. scomp = ord(sb[0])
  1467. else:
  1468. scomp = sb[0]
  1469. if scomp & 0x80:
  1470. sb = b"\x00" + sb
  1471. ret = common.NS(common.NS(rb) + common.NS(sb))
  1472. elif keyType == "Ed25519":
  1473. ret = common.NS(self._keyObject.sign(data))
  1474. return common.NS(signatureType) + ret
  1475. def verify(self, signature, data):
  1476. """
  1477. Verify a signature using this key.
  1478. @type signature: L{bytes}
  1479. @param signature: The signature to verify.
  1480. @type data: L{bytes}
  1481. @param data: The signed data.
  1482. @rtype: L{bool}
  1483. @return: C{True} if the signature is valid.
  1484. """
  1485. if len(signature) == 40:
  1486. # DSA key with no padding
  1487. signatureType, signature = b"ssh-dss", common.NS(signature)
  1488. else:
  1489. signatureType, signature = common.getNS(signature)
  1490. hashAlgorithm = self._getHashAlgorithm(signatureType)
  1491. if hashAlgorithm is None:
  1492. return False
  1493. keyType = self.type()
  1494. if keyType == "RSA":
  1495. k = self._keyObject
  1496. if not self.isPublic():
  1497. k = k.public_key()
  1498. args = (
  1499. common.getNS(signature)[0],
  1500. data,
  1501. padding.PKCS1v15(),
  1502. hashAlgorithm,
  1503. )
  1504. elif keyType == "DSA":
  1505. concatenatedSignature = common.getNS(signature)[0]
  1506. r = int.from_bytes(concatenatedSignature[:20], "big")
  1507. s = int.from_bytes(concatenatedSignature[20:], "big")
  1508. signature = encode_dss_signature(r, s)
  1509. k = self._keyObject
  1510. if not self.isPublic():
  1511. k = k.public_key()
  1512. args = (signature, data, hashAlgorithm)
  1513. elif keyType == "EC": # Pragma: no branch
  1514. concatenatedSignature = common.getNS(signature)[0]
  1515. rstr, sstr, rest = common.getNS(concatenatedSignature, 2)
  1516. r = int.from_bytes(rstr, "big")
  1517. s = int.from_bytes(sstr, "big")
  1518. signature = encode_dss_signature(r, s)
  1519. k = self._keyObject
  1520. if not self.isPublic():
  1521. k = k.public_key()
  1522. args = (signature, data, ec.ECDSA(hashAlgorithm))
  1523. elif keyType == "Ed25519":
  1524. k = self._keyObject
  1525. if not self.isPublic():
  1526. k = k.public_key()
  1527. args = (common.getNS(signature)[0], data)
  1528. try:
  1529. k.verify(*args)
  1530. except InvalidSignature:
  1531. return False
  1532. else:
  1533. return True
  1534. def _getPersistentRSAKey(location, keySize=4096):
  1535. """
  1536. This function returns a persistent L{Key}.
  1537. The key is loaded from a PEM file in C{location}. If it does not exist, a
  1538. key with the key size of C{keySize} is generated and saved.
  1539. @param location: Where the key is stored.
  1540. @type location: L{twisted.python.filepath.FilePath}
  1541. @param keySize: The size of the key, if it needs to be generated.
  1542. @type keySize: L{int}
  1543. @returns: A persistent key.
  1544. @rtype: L{Key}
  1545. """
  1546. location.parent().makedirs(ignoreExistingDirectory=True)
  1547. # If it doesn't exist, we want to generate a new key and save it
  1548. if not location.exists():
  1549. privateKey = rsa.generate_private_key(
  1550. public_exponent=65537, key_size=keySize, backend=default_backend()
  1551. )
  1552. pem = privateKey.private_bytes(
  1553. encoding=serialization.Encoding.PEM,
  1554. format=serialization.PrivateFormat.TraditionalOpenSSL,
  1555. encryption_algorithm=serialization.NoEncryption(),
  1556. )
  1557. location.setContent(pem)
  1558. # By this point (save any hilarious race conditions) we should have a
  1559. # working PEM file. Load it!
  1560. # (Future archaeological readers: I chose not to short circuit above,
  1561. # because then there's two exit paths to this code!)
  1562. with location.open("rb") as keyFile:
  1563. privateKey = serialization.load_pem_private_key(
  1564. keyFile.read(), password=None, backend=default_backend()
  1565. )
  1566. return Key(privateKey)