keys.py 64 KB

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