keys.py 53 KB

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