keys.py 59 KB

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