Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

keys.py 67KB

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