backend.py 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import collections
  5. import contextlib
  6. import itertools
  7. import typing
  8. import warnings
  9. from contextlib import contextmanager
  10. from cryptography import utils, x509
  11. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  12. from cryptography.hazmat.backends.interfaces import Backend as BackendInterface
  13. from cryptography.hazmat.backends.openssl import aead
  14. from cryptography.hazmat.backends.openssl.ciphers import _CipherContext
  15. from cryptography.hazmat.backends.openssl.cmac import _CMACContext
  16. from cryptography.hazmat.backends.openssl.decode_asn1 import (
  17. _CRL_ENTRY_REASON_ENUM_TO_CODE,
  18. )
  19. from cryptography.hazmat.backends.openssl.dh import (
  20. _DHParameters,
  21. _DHPrivateKey,
  22. _DHPublicKey,
  23. _dh_params_dup,
  24. )
  25. from cryptography.hazmat.backends.openssl.dsa import (
  26. _DSAParameters,
  27. _DSAPrivateKey,
  28. _DSAPublicKey,
  29. )
  30. from cryptography.hazmat.backends.openssl.ec import (
  31. _EllipticCurvePrivateKey,
  32. _EllipticCurvePublicKey,
  33. )
  34. from cryptography.hazmat.backends.openssl.ed25519 import (
  35. _Ed25519PrivateKey,
  36. _Ed25519PublicKey,
  37. )
  38. from cryptography.hazmat.backends.openssl.ed448 import (
  39. _ED448_KEY_SIZE,
  40. _Ed448PrivateKey,
  41. _Ed448PublicKey,
  42. )
  43. from cryptography.hazmat.backends.openssl.encode_asn1 import (
  44. _CRL_ENTRY_EXTENSION_ENCODE_HANDLERS,
  45. _CRL_EXTENSION_ENCODE_HANDLERS,
  46. _EXTENSION_ENCODE_HANDLERS,
  47. _OCSP_BASICRESP_EXTENSION_ENCODE_HANDLERS,
  48. _OCSP_REQUEST_EXTENSION_ENCODE_HANDLERS,
  49. _encode_asn1_int_gc,
  50. _encode_asn1_str_gc,
  51. _encode_name_gc,
  52. _txt2obj_gc,
  53. )
  54. from cryptography.hazmat.backends.openssl.hashes import _HashContext
  55. from cryptography.hazmat.backends.openssl.hmac import _HMACContext
  56. from cryptography.hazmat.backends.openssl.poly1305 import (
  57. _POLY1305_KEY_SIZE,
  58. _Poly1305Context,
  59. )
  60. from cryptography.hazmat.backends.openssl.rsa import (
  61. _RSAPrivateKey,
  62. _RSAPublicKey,
  63. )
  64. from cryptography.hazmat.backends.openssl.x25519 import (
  65. _X25519PrivateKey,
  66. _X25519PublicKey,
  67. )
  68. from cryptography.hazmat.backends.openssl.x448 import (
  69. _X448PrivateKey,
  70. _X448PublicKey,
  71. )
  72. from cryptography.hazmat.backends.openssl.x509 import (
  73. _RawRevokedCertificate,
  74. )
  75. from cryptography.hazmat.bindings._rust import (
  76. asn1,
  77. x509 as rust_x509,
  78. )
  79. from cryptography.hazmat.bindings.openssl import binding
  80. from cryptography.hazmat.primitives import hashes, serialization
  81. from cryptography.hazmat.primitives.asymmetric import (
  82. dh,
  83. dsa,
  84. ec,
  85. ed25519,
  86. ed448,
  87. rsa,
  88. )
  89. from cryptography.hazmat.primitives.asymmetric.padding import (
  90. MGF1,
  91. OAEP,
  92. PKCS1v15,
  93. PSS,
  94. )
  95. from cryptography.hazmat.primitives.asymmetric.types import PRIVATE_KEY_TYPES
  96. from cryptography.hazmat.primitives.ciphers.algorithms import (
  97. AES,
  98. ARC4,
  99. Blowfish,
  100. CAST5,
  101. Camellia,
  102. ChaCha20,
  103. IDEA,
  104. SEED,
  105. SM4,
  106. TripleDES,
  107. )
  108. from cryptography.hazmat.primitives.ciphers.modes import (
  109. CBC,
  110. CFB,
  111. CFB8,
  112. CTR,
  113. ECB,
  114. GCM,
  115. OFB,
  116. XTS,
  117. )
  118. from cryptography.hazmat.primitives.kdf import scrypt
  119. from cryptography.hazmat.primitives.serialization import pkcs7, ssh
  120. from cryptography.x509 import ocsp
  121. from cryptography.x509.base import PUBLIC_KEY_TYPES
  122. from cryptography.x509.name import Name
  123. _MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"])
  124. # Not actually supported, just used as a marker for some serialization tests.
  125. class _RC2(object):
  126. pass
  127. class Backend(BackendInterface):
  128. """
  129. OpenSSL API binding interfaces.
  130. """
  131. name = "openssl"
  132. # FIPS has opinions about acceptable algorithms and key sizes, but the
  133. # disallowed algorithms are still present in OpenSSL. They just error if
  134. # you try to use them. To avoid that we allowlist the algorithms in
  135. # FIPS 140-3. This isn't ideal, but FIPS 140-3 is trash so here we are.
  136. _fips_aead = {
  137. b"aes-128-ccm",
  138. b"aes-192-ccm",
  139. b"aes-256-ccm",
  140. b"aes-128-gcm",
  141. b"aes-192-gcm",
  142. b"aes-256-gcm",
  143. }
  144. _fips_ciphers = (AES, TripleDES)
  145. # Sometimes SHA1 is still permissible. That logic is contained
  146. # within the various *_supported methods.
  147. _fips_hashes = (
  148. hashes.SHA224,
  149. hashes.SHA256,
  150. hashes.SHA384,
  151. hashes.SHA512,
  152. hashes.SHA512_224,
  153. hashes.SHA512_256,
  154. hashes.SHA3_224,
  155. hashes.SHA3_256,
  156. hashes.SHA3_384,
  157. hashes.SHA3_512,
  158. hashes.SHAKE128,
  159. hashes.SHAKE256,
  160. )
  161. _fips_ecdh_curves = (
  162. ec.SECP224R1,
  163. ec.SECP256R1,
  164. ec.SECP384R1,
  165. ec.SECP521R1,
  166. )
  167. _fips_rsa_min_key_size = 2048
  168. _fips_rsa_min_public_exponent = 65537
  169. _fips_dsa_min_modulus = 1 << 2048
  170. _fips_dh_min_key_size = 2048
  171. _fips_dh_min_modulus = 1 << _fips_dh_min_key_size
  172. def __init__(self):
  173. self._binding = binding.Binding()
  174. self._ffi = self._binding.ffi
  175. self._lib = self._binding.lib
  176. self._rsa_skip_check_key = False
  177. self._fips_enabled = self._is_fips_enabled()
  178. self._cipher_registry = {}
  179. self._register_default_ciphers()
  180. self._register_x509_encoders()
  181. if self._fips_enabled and self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
  182. warnings.warn(
  183. "OpenSSL FIPS mode is enabled. Can't enable DRBG fork safety.",
  184. UserWarning,
  185. )
  186. else:
  187. self.activate_osrandom_engine()
  188. self._dh_types = [self._lib.EVP_PKEY_DH]
  189. if self._lib.Cryptography_HAS_EVP_PKEY_DHX:
  190. self._dh_types.append(self._lib.EVP_PKEY_DHX)
  191. def __repr__(self):
  192. return "<OpenSSLBackend(version: {}, FIPS: {})>".format(
  193. self.openssl_version_text(), self._fips_enabled
  194. )
  195. def openssl_assert(self, ok, errors=None):
  196. return binding._openssl_assert(self._lib, ok, errors=errors)
  197. def _is_fips_enabled(self):
  198. if self._lib.Cryptography_HAS_300_FIPS:
  199. mode = self._lib.EVP_default_properties_is_fips_enabled(
  200. self._ffi.NULL
  201. )
  202. else:
  203. mode = getattr(self._lib, "FIPS_mode", lambda: 0)()
  204. if mode == 0:
  205. # OpenSSL without FIPS pushes an error on the error stack
  206. self._lib.ERR_clear_error()
  207. return bool(mode)
  208. def _enable_fips(self):
  209. # This function enables FIPS mode for OpenSSL 3.0.0 on installs that
  210. # have the FIPS provider installed properly.
  211. self._binding._enable_fips()
  212. assert self._is_fips_enabled()
  213. self._fips_enabled = self._is_fips_enabled()
  214. def activate_builtin_random(self):
  215. if self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
  216. # Obtain a new structural reference.
  217. e = self._lib.ENGINE_get_default_RAND()
  218. if e != self._ffi.NULL:
  219. self._lib.ENGINE_unregister_RAND(e)
  220. # Reset the RNG to use the built-in.
  221. res = self._lib.RAND_set_rand_method(self._ffi.NULL)
  222. self.openssl_assert(res == 1)
  223. # decrement the structural reference from get_default_RAND
  224. res = self._lib.ENGINE_finish(e)
  225. self.openssl_assert(res == 1)
  226. @contextlib.contextmanager
  227. def _get_osurandom_engine(self):
  228. # Fetches an engine by id and returns it. This creates a structural
  229. # reference.
  230. e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id)
  231. self.openssl_assert(e != self._ffi.NULL)
  232. # Initialize the engine for use. This adds a functional reference.
  233. res = self._lib.ENGINE_init(e)
  234. self.openssl_assert(res == 1)
  235. try:
  236. yield e
  237. finally:
  238. # Decrement the structural ref incremented by ENGINE_by_id.
  239. res = self._lib.ENGINE_free(e)
  240. self.openssl_assert(res == 1)
  241. # Decrement the functional ref incremented by ENGINE_init.
  242. res = self._lib.ENGINE_finish(e)
  243. self.openssl_assert(res == 1)
  244. def activate_osrandom_engine(self):
  245. if self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
  246. # Unregister and free the current engine.
  247. self.activate_builtin_random()
  248. with self._get_osurandom_engine() as e:
  249. # Set the engine as the default RAND provider.
  250. res = self._lib.ENGINE_set_default_RAND(e)
  251. self.openssl_assert(res == 1)
  252. # Reset the RNG to use the engine
  253. res = self._lib.RAND_set_rand_method(self._ffi.NULL)
  254. self.openssl_assert(res == 1)
  255. def osrandom_engine_implementation(self):
  256. buf = self._ffi.new("char[]", 64)
  257. with self._get_osurandom_engine() as e:
  258. res = self._lib.ENGINE_ctrl_cmd(
  259. e, b"get_implementation", len(buf), buf, self._ffi.NULL, 0
  260. )
  261. self.openssl_assert(res > 0)
  262. return self._ffi.string(buf).decode("ascii")
  263. def openssl_version_text(self):
  264. """
  265. Friendly string name of the loaded OpenSSL library. This is not
  266. necessarily the same version as it was compiled against.
  267. Example: OpenSSL 1.1.1d 10 Sep 2019
  268. """
  269. return self._ffi.string(
  270. self._lib.OpenSSL_version(self._lib.OPENSSL_VERSION)
  271. ).decode("ascii")
  272. def openssl_version_number(self):
  273. return self._lib.OpenSSL_version_num()
  274. def create_hmac_ctx(self, key, algorithm):
  275. return _HMACContext(self, key, algorithm)
  276. def _evp_md_from_algorithm(self, algorithm):
  277. if algorithm.name == "blake2b" or algorithm.name == "blake2s":
  278. alg = "{}{}".format(
  279. algorithm.name, algorithm.digest_size * 8
  280. ).encode("ascii")
  281. else:
  282. alg = algorithm.name.encode("ascii")
  283. evp_md = self._lib.EVP_get_digestbyname(alg)
  284. return evp_md
  285. def _evp_md_non_null_from_algorithm(self, algorithm):
  286. evp_md = self._evp_md_from_algorithm(algorithm)
  287. self.openssl_assert(evp_md != self._ffi.NULL)
  288. return evp_md
  289. def hash_supported(self, algorithm):
  290. if self._fips_enabled and not isinstance(algorithm, self._fips_hashes):
  291. return False
  292. evp_md = self._evp_md_from_algorithm(algorithm)
  293. return evp_md != self._ffi.NULL
  294. def scrypt_supported(self):
  295. if self._fips_enabled:
  296. return False
  297. else:
  298. return self._lib.Cryptography_HAS_SCRYPT == 1
  299. def hmac_supported(self, algorithm):
  300. # FIPS mode still allows SHA1 for HMAC
  301. if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
  302. return True
  303. return self.hash_supported(algorithm)
  304. def create_hash_ctx(self, algorithm):
  305. return _HashContext(self, algorithm)
  306. def cipher_supported(self, cipher, mode):
  307. if self._fips_enabled:
  308. # FIPS mode requires AES or TripleDES, but only CBC/ECB allowed
  309. # in TripleDES mode.
  310. if not isinstance(cipher, self._fips_ciphers) or (
  311. isinstance(cipher, TripleDES)
  312. and not isinstance(mode, (CBC, ECB))
  313. ):
  314. return False
  315. try:
  316. adapter = self._cipher_registry[type(cipher), type(mode)]
  317. except KeyError:
  318. return False
  319. evp_cipher = adapter(self, cipher, mode)
  320. return self._ffi.NULL != evp_cipher
  321. def register_cipher_adapter(self, cipher_cls, mode_cls, adapter):
  322. if (cipher_cls, mode_cls) in self._cipher_registry:
  323. raise ValueError(
  324. "Duplicate registration for: {} {}.".format(
  325. cipher_cls, mode_cls
  326. )
  327. )
  328. self._cipher_registry[cipher_cls, mode_cls] = adapter
  329. def _register_default_ciphers(self):
  330. for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8, GCM]:
  331. self.register_cipher_adapter(
  332. AES,
  333. mode_cls,
  334. GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"),
  335. )
  336. for mode_cls in [CBC, CTR, ECB, OFB, CFB]:
  337. self.register_cipher_adapter(
  338. Camellia,
  339. mode_cls,
  340. GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"),
  341. )
  342. for mode_cls in [CBC, CFB, CFB8, OFB]:
  343. self.register_cipher_adapter(
  344. TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}")
  345. )
  346. self.register_cipher_adapter(
  347. TripleDES, ECB, GetCipherByName("des-ede3")
  348. )
  349. for mode_cls in [CBC, CFB, OFB, ECB]:
  350. self.register_cipher_adapter(
  351. Blowfish, mode_cls, GetCipherByName("bf-{mode.name}")
  352. )
  353. for mode_cls in [CBC, CFB, OFB, ECB]:
  354. self.register_cipher_adapter(
  355. SEED, mode_cls, GetCipherByName("seed-{mode.name}")
  356. )
  357. for cipher_cls, mode_cls in itertools.product(
  358. [CAST5, IDEA],
  359. [CBC, OFB, CFB, ECB],
  360. ):
  361. self.register_cipher_adapter(
  362. cipher_cls,
  363. mode_cls,
  364. GetCipherByName("{cipher.name}-{mode.name}"),
  365. )
  366. self.register_cipher_adapter(ARC4, type(None), GetCipherByName("rc4"))
  367. # We don't actually support RC2, this is just used by some tests.
  368. self.register_cipher_adapter(_RC2, type(None), GetCipherByName("rc2"))
  369. self.register_cipher_adapter(
  370. ChaCha20, type(None), GetCipherByName("chacha20")
  371. )
  372. self.register_cipher_adapter(AES, XTS, _get_xts_cipher)
  373. for mode_cls in [ECB, CBC, OFB, CFB, CTR]:
  374. self.register_cipher_adapter(
  375. SM4, mode_cls, GetCipherByName("sm4-{mode.name}")
  376. )
  377. def _register_x509_encoders(self):
  378. self._extension_encode_handlers = _EXTENSION_ENCODE_HANDLERS.copy()
  379. self._crl_extension_encode_handlers = (
  380. _CRL_EXTENSION_ENCODE_HANDLERS.copy()
  381. )
  382. self._crl_entry_extension_encode_handlers = (
  383. _CRL_ENTRY_EXTENSION_ENCODE_HANDLERS.copy()
  384. )
  385. self._ocsp_request_extension_encode_handlers = (
  386. _OCSP_REQUEST_EXTENSION_ENCODE_HANDLERS.copy()
  387. )
  388. self._ocsp_basicresp_extension_encode_handlers = (
  389. _OCSP_BASICRESP_EXTENSION_ENCODE_HANDLERS.copy()
  390. )
  391. def create_symmetric_encryption_ctx(self, cipher, mode):
  392. return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
  393. def create_symmetric_decryption_ctx(self, cipher, mode):
  394. return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)
  395. def pbkdf2_hmac_supported(self, algorithm):
  396. return self.hmac_supported(algorithm)
  397. def derive_pbkdf2_hmac(
  398. self, algorithm, length, salt, iterations, key_material
  399. ):
  400. buf = self._ffi.new("unsigned char[]", length)
  401. evp_md = self._evp_md_non_null_from_algorithm(algorithm)
  402. key_material_ptr = self._ffi.from_buffer(key_material)
  403. res = self._lib.PKCS5_PBKDF2_HMAC(
  404. key_material_ptr,
  405. len(key_material),
  406. salt,
  407. len(salt),
  408. iterations,
  409. evp_md,
  410. length,
  411. buf,
  412. )
  413. self.openssl_assert(res == 1)
  414. return self._ffi.buffer(buf)[:]
  415. def _consume_errors(self):
  416. return binding._consume_errors(self._lib)
  417. def _consume_errors_with_text(self):
  418. return binding._consume_errors_with_text(self._lib)
  419. def _bn_to_int(self, bn):
  420. assert bn != self._ffi.NULL
  421. self.openssl_assert(not self._lib.BN_is_negative(bn))
  422. bn_num_bytes = self._lib.BN_num_bytes(bn)
  423. bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes)
  424. bin_len = self._lib.BN_bn2bin(bn, bin_ptr)
  425. # A zero length means the BN has value 0
  426. self.openssl_assert(bin_len >= 0)
  427. val = int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big")
  428. return val
  429. def _int_to_bn(self, num, bn=None):
  430. """
  431. Converts a python integer to a BIGNUM. The returned BIGNUM will not
  432. be garbage collected (to support adding them to structs that take
  433. ownership of the object). Be sure to register it for GC if it will
  434. be discarded after use.
  435. """
  436. assert bn is None or bn != self._ffi.NULL
  437. if bn is None:
  438. bn = self._ffi.NULL
  439. binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big")
  440. bn_ptr = self._lib.BN_bin2bn(binary, len(binary), bn)
  441. self.openssl_assert(bn_ptr != self._ffi.NULL)
  442. return bn_ptr
  443. def generate_rsa_private_key(self, public_exponent, key_size):
  444. rsa._verify_rsa_parameters(public_exponent, key_size)
  445. rsa_cdata = self._lib.RSA_new()
  446. self.openssl_assert(rsa_cdata != self._ffi.NULL)
  447. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  448. bn = self._int_to_bn(public_exponent)
  449. bn = self._ffi.gc(bn, self._lib.BN_free)
  450. res = self._lib.RSA_generate_key_ex(
  451. rsa_cdata, key_size, bn, self._ffi.NULL
  452. )
  453. self.openssl_assert(res == 1)
  454. evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
  455. return _RSAPrivateKey(
  456. self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
  457. )
  458. def generate_rsa_parameters_supported(self, public_exponent, key_size):
  459. return (
  460. public_exponent >= 3
  461. and public_exponent & 1 != 0
  462. and key_size >= 512
  463. )
  464. def load_rsa_private_numbers(self, numbers):
  465. rsa._check_private_key_components(
  466. numbers.p,
  467. numbers.q,
  468. numbers.d,
  469. numbers.dmp1,
  470. numbers.dmq1,
  471. numbers.iqmp,
  472. numbers.public_numbers.e,
  473. numbers.public_numbers.n,
  474. )
  475. rsa_cdata = self._lib.RSA_new()
  476. self.openssl_assert(rsa_cdata != self._ffi.NULL)
  477. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  478. p = self._int_to_bn(numbers.p)
  479. q = self._int_to_bn(numbers.q)
  480. d = self._int_to_bn(numbers.d)
  481. dmp1 = self._int_to_bn(numbers.dmp1)
  482. dmq1 = self._int_to_bn(numbers.dmq1)
  483. iqmp = self._int_to_bn(numbers.iqmp)
  484. e = self._int_to_bn(numbers.public_numbers.e)
  485. n = self._int_to_bn(numbers.public_numbers.n)
  486. res = self._lib.RSA_set0_factors(rsa_cdata, p, q)
  487. self.openssl_assert(res == 1)
  488. res = self._lib.RSA_set0_key(rsa_cdata, n, e, d)
  489. self.openssl_assert(res == 1)
  490. res = self._lib.RSA_set0_crt_params(rsa_cdata, dmp1, dmq1, iqmp)
  491. self.openssl_assert(res == 1)
  492. evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
  493. return _RSAPrivateKey(
  494. self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
  495. )
  496. def load_rsa_public_numbers(self, numbers):
  497. rsa._check_public_key_components(numbers.e, numbers.n)
  498. rsa_cdata = self._lib.RSA_new()
  499. self.openssl_assert(rsa_cdata != self._ffi.NULL)
  500. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  501. e = self._int_to_bn(numbers.e)
  502. n = self._int_to_bn(numbers.n)
  503. res = self._lib.RSA_set0_key(rsa_cdata, n, e, self._ffi.NULL)
  504. self.openssl_assert(res == 1)
  505. evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
  506. return _RSAPublicKey(self, rsa_cdata, evp_pkey)
  507. def _create_evp_pkey_gc(self):
  508. evp_pkey = self._lib.EVP_PKEY_new()
  509. self.openssl_assert(evp_pkey != self._ffi.NULL)
  510. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  511. return evp_pkey
  512. def _rsa_cdata_to_evp_pkey(self, rsa_cdata):
  513. evp_pkey = self._create_evp_pkey_gc()
  514. res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata)
  515. self.openssl_assert(res == 1)
  516. return evp_pkey
  517. def _bytes_to_bio(self, data):
  518. """
  519. Return a _MemoryBIO namedtuple of (BIO, char*).
  520. The char* is the storage for the BIO and it must stay alive until the
  521. BIO is finished with.
  522. """
  523. data_ptr = self._ffi.from_buffer(data)
  524. bio = self._lib.BIO_new_mem_buf(data_ptr, len(data))
  525. self.openssl_assert(bio != self._ffi.NULL)
  526. return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_ptr)
  527. def _create_mem_bio_gc(self):
  528. """
  529. Creates an empty memory BIO.
  530. """
  531. bio_method = self._lib.BIO_s_mem()
  532. self.openssl_assert(bio_method != self._ffi.NULL)
  533. bio = self._lib.BIO_new(bio_method)
  534. self.openssl_assert(bio != self._ffi.NULL)
  535. bio = self._ffi.gc(bio, self._lib.BIO_free)
  536. return bio
  537. def _read_mem_bio(self, bio):
  538. """
  539. Reads a memory BIO. This only works on memory BIOs.
  540. """
  541. buf = self._ffi.new("char **")
  542. buf_len = self._lib.BIO_get_mem_data(bio, buf)
  543. self.openssl_assert(buf_len > 0)
  544. self.openssl_assert(buf[0] != self._ffi.NULL)
  545. bio_data = self._ffi.buffer(buf[0], buf_len)[:]
  546. return bio_data
  547. def _evp_pkey_to_private_key(self, evp_pkey):
  548. """
  549. Return the appropriate type of PrivateKey given an evp_pkey cdata
  550. pointer.
  551. """
  552. key_type = self._lib.EVP_PKEY_id(evp_pkey)
  553. if key_type == self._lib.EVP_PKEY_RSA:
  554. rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
  555. self.openssl_assert(rsa_cdata != self._ffi.NULL)
  556. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  557. return _RSAPrivateKey(
  558. self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
  559. )
  560. elif key_type == self._lib.EVP_PKEY_DSA:
  561. dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
  562. self.openssl_assert(dsa_cdata != self._ffi.NULL)
  563. dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
  564. return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
  565. elif key_type == self._lib.EVP_PKEY_EC:
  566. ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
  567. self.openssl_assert(ec_cdata != self._ffi.NULL)
  568. ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
  569. return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
  570. elif key_type in self._dh_types:
  571. dh_cdata = self._lib.EVP_PKEY_get1_DH(evp_pkey)
  572. self.openssl_assert(dh_cdata != self._ffi.NULL)
  573. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  574. return _DHPrivateKey(self, dh_cdata, evp_pkey)
  575. elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None):
  576. # EVP_PKEY_ED25519 is not present in OpenSSL < 1.1.1
  577. return _Ed25519PrivateKey(self, evp_pkey)
  578. elif key_type == getattr(self._lib, "EVP_PKEY_X448", None):
  579. # EVP_PKEY_X448 is not present in OpenSSL < 1.1.1
  580. return _X448PrivateKey(self, evp_pkey)
  581. elif key_type == getattr(self._lib, "EVP_PKEY_X25519", None):
  582. # EVP_PKEY_X25519 is not present in OpenSSL < 1.1.0
  583. return _X25519PrivateKey(self, evp_pkey)
  584. elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None):
  585. # EVP_PKEY_ED448 is not present in OpenSSL < 1.1.1
  586. return _Ed448PrivateKey(self, evp_pkey)
  587. else:
  588. raise UnsupportedAlgorithm("Unsupported key type.")
  589. def _evp_pkey_to_public_key(self, evp_pkey):
  590. """
  591. Return the appropriate type of PublicKey given an evp_pkey cdata
  592. pointer.
  593. """
  594. key_type = self._lib.EVP_PKEY_id(evp_pkey)
  595. if key_type == self._lib.EVP_PKEY_RSA:
  596. rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
  597. self.openssl_assert(rsa_cdata != self._ffi.NULL)
  598. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  599. return _RSAPublicKey(self, rsa_cdata, evp_pkey)
  600. elif key_type == self._lib.EVP_PKEY_DSA:
  601. dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
  602. self.openssl_assert(dsa_cdata != self._ffi.NULL)
  603. dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
  604. return _DSAPublicKey(self, dsa_cdata, evp_pkey)
  605. elif key_type == self._lib.EVP_PKEY_EC:
  606. ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
  607. self.openssl_assert(ec_cdata != self._ffi.NULL)
  608. ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
  609. return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
  610. elif key_type in self._dh_types:
  611. dh_cdata = self._lib.EVP_PKEY_get1_DH(evp_pkey)
  612. self.openssl_assert(dh_cdata != self._ffi.NULL)
  613. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  614. return _DHPublicKey(self, dh_cdata, evp_pkey)
  615. elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None):
  616. # EVP_PKEY_ED25519 is not present in OpenSSL < 1.1.1
  617. return _Ed25519PublicKey(self, evp_pkey)
  618. elif key_type == getattr(self._lib, "EVP_PKEY_X448", None):
  619. # EVP_PKEY_X448 is not present in OpenSSL < 1.1.1
  620. return _X448PublicKey(self, evp_pkey)
  621. elif key_type == getattr(self._lib, "EVP_PKEY_X25519", None):
  622. # EVP_PKEY_X25519 is not present in OpenSSL < 1.1.0
  623. return _X25519PublicKey(self, evp_pkey)
  624. elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None):
  625. # EVP_PKEY_X25519 is not present in OpenSSL < 1.1.1
  626. return _Ed448PublicKey(self, evp_pkey)
  627. else:
  628. raise UnsupportedAlgorithm("Unsupported key type.")
  629. def _oaep_hash_supported(self, algorithm):
  630. if self._lib.Cryptography_HAS_RSA_OAEP_MD:
  631. return isinstance(
  632. algorithm,
  633. (
  634. hashes.SHA1,
  635. hashes.SHA224,
  636. hashes.SHA256,
  637. hashes.SHA384,
  638. hashes.SHA512,
  639. ),
  640. )
  641. else:
  642. return isinstance(algorithm, hashes.SHA1)
  643. def rsa_padding_supported(self, padding):
  644. if isinstance(padding, PKCS1v15):
  645. return True
  646. elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
  647. # SHA1 is permissible in MGF1 in FIPS
  648. if self._fips_enabled and isinstance(
  649. padding._mgf._algorithm, hashes.SHA1
  650. ):
  651. return True
  652. else:
  653. return self.hash_supported(padding._mgf._algorithm)
  654. elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
  655. return (
  656. self._oaep_hash_supported(padding._mgf._algorithm)
  657. and self._oaep_hash_supported(padding._algorithm)
  658. and (
  659. (padding._label is None or len(padding._label) == 0)
  660. or self._lib.Cryptography_HAS_RSA_OAEP_LABEL == 1
  661. )
  662. )
  663. else:
  664. return False
  665. def generate_dsa_parameters(self, key_size):
  666. if key_size not in (1024, 2048, 3072, 4096):
  667. raise ValueError(
  668. "Key size must be 1024, 2048, 3072, or 4096 bits."
  669. )
  670. ctx = self._lib.DSA_new()
  671. self.openssl_assert(ctx != self._ffi.NULL)
  672. ctx = self._ffi.gc(ctx, self._lib.DSA_free)
  673. res = self._lib.DSA_generate_parameters_ex(
  674. ctx,
  675. key_size,
  676. self._ffi.NULL,
  677. 0,
  678. self._ffi.NULL,
  679. self._ffi.NULL,
  680. self._ffi.NULL,
  681. )
  682. self.openssl_assert(res == 1)
  683. return _DSAParameters(self, ctx)
  684. def generate_dsa_private_key(self, parameters):
  685. ctx = self._lib.DSAparams_dup(parameters._dsa_cdata)
  686. self.openssl_assert(ctx != self._ffi.NULL)
  687. ctx = self._ffi.gc(ctx, self._lib.DSA_free)
  688. self._lib.DSA_generate_key(ctx)
  689. evp_pkey = self._dsa_cdata_to_evp_pkey(ctx)
  690. return _DSAPrivateKey(self, ctx, evp_pkey)
  691. def generate_dsa_private_key_and_parameters(self, key_size):
  692. parameters = self.generate_dsa_parameters(key_size)
  693. return self.generate_dsa_private_key(parameters)
  694. def _dsa_cdata_set_values(self, dsa_cdata, p, q, g, pub_key, priv_key):
  695. res = self._lib.DSA_set0_pqg(dsa_cdata, p, q, g)
  696. self.openssl_assert(res == 1)
  697. res = self._lib.DSA_set0_key(dsa_cdata, pub_key, priv_key)
  698. self.openssl_assert(res == 1)
  699. def load_dsa_private_numbers(self, numbers):
  700. dsa._check_dsa_private_numbers(numbers)
  701. parameter_numbers = numbers.public_numbers.parameter_numbers
  702. dsa_cdata = self._lib.DSA_new()
  703. self.openssl_assert(dsa_cdata != self._ffi.NULL)
  704. dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
  705. p = self._int_to_bn(parameter_numbers.p)
  706. q = self._int_to_bn(parameter_numbers.q)
  707. g = self._int_to_bn(parameter_numbers.g)
  708. pub_key = self._int_to_bn(numbers.public_numbers.y)
  709. priv_key = self._int_to_bn(numbers.x)
  710. self._dsa_cdata_set_values(dsa_cdata, p, q, g, pub_key, priv_key)
  711. evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
  712. return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
  713. def load_dsa_public_numbers(self, numbers):
  714. dsa._check_dsa_parameters(numbers.parameter_numbers)
  715. dsa_cdata = self._lib.DSA_new()
  716. self.openssl_assert(dsa_cdata != self._ffi.NULL)
  717. dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
  718. p = self._int_to_bn(numbers.parameter_numbers.p)
  719. q = self._int_to_bn(numbers.parameter_numbers.q)
  720. g = self._int_to_bn(numbers.parameter_numbers.g)
  721. pub_key = self._int_to_bn(numbers.y)
  722. priv_key = self._ffi.NULL
  723. self._dsa_cdata_set_values(dsa_cdata, p, q, g, pub_key, priv_key)
  724. evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
  725. return _DSAPublicKey(self, dsa_cdata, evp_pkey)
  726. def load_dsa_parameter_numbers(self, numbers):
  727. dsa._check_dsa_parameters(numbers)
  728. dsa_cdata = self._lib.DSA_new()
  729. self.openssl_assert(dsa_cdata != self._ffi.NULL)
  730. dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
  731. p = self._int_to_bn(numbers.p)
  732. q = self._int_to_bn(numbers.q)
  733. g = self._int_to_bn(numbers.g)
  734. res = self._lib.DSA_set0_pqg(dsa_cdata, p, q, g)
  735. self.openssl_assert(res == 1)
  736. return _DSAParameters(self, dsa_cdata)
  737. def _dsa_cdata_to_evp_pkey(self, dsa_cdata):
  738. evp_pkey = self._create_evp_pkey_gc()
  739. res = self._lib.EVP_PKEY_set1_DSA(evp_pkey, dsa_cdata)
  740. self.openssl_assert(res == 1)
  741. return evp_pkey
  742. def dsa_hash_supported(self, algorithm):
  743. return self.hash_supported(algorithm)
  744. def dsa_parameters_supported(self, p, q, g):
  745. return True
  746. def cmac_algorithm_supported(self, algorithm):
  747. return self.cipher_supported(
  748. algorithm, CBC(b"\x00" * algorithm.block_size)
  749. )
  750. def create_cmac_ctx(self, algorithm):
  751. return _CMACContext(self, algorithm)
  752. def _x509_check_signature_params(self, private_key, algorithm):
  753. if isinstance(
  754. private_key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)
  755. ):
  756. if algorithm is not None:
  757. raise ValueError(
  758. "algorithm must be None when signing via ed25519 or ed448"
  759. )
  760. elif not isinstance(
  761. private_key,
  762. (rsa.RSAPrivateKey, dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey),
  763. ):
  764. raise TypeError(
  765. "Key must be an rsa, dsa, ec, ed25519, or ed448 private key."
  766. )
  767. elif not isinstance(algorithm, hashes.HashAlgorithm):
  768. raise TypeError("Algorithm must be a registered hash algorithm.")
  769. elif isinstance(algorithm, hashes.MD5) and not isinstance(
  770. private_key, rsa.RSAPrivateKey
  771. ):
  772. raise ValueError(
  773. "MD5 hash algorithm is only supported with RSA keys"
  774. )
  775. def create_x509_csr(
  776. self,
  777. builder: x509.CertificateSigningRequestBuilder,
  778. private_key: PRIVATE_KEY_TYPES,
  779. algorithm: typing.Optional[hashes.HashAlgorithm],
  780. ) -> x509.CertificateSigningRequest:
  781. if not isinstance(builder, x509.CertificateSigningRequestBuilder):
  782. raise TypeError("Builder type mismatch.")
  783. self._x509_check_signature_params(private_key, algorithm)
  784. # Resolve the signature algorithm.
  785. evp_md = self._evp_md_x509_null_if_eddsa(private_key, algorithm)
  786. # Create an empty request.
  787. x509_req = self._lib.X509_REQ_new()
  788. self.openssl_assert(x509_req != self._ffi.NULL)
  789. x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
  790. # Set x509 version.
  791. res = self._lib.X509_REQ_set_version(x509_req, x509.Version.v1.value)
  792. self.openssl_assert(res == 1)
  793. # Set subject name.
  794. res = self._lib.X509_REQ_set_subject_name(
  795. x509_req, _encode_name_gc(self, builder._subject_name)
  796. )
  797. self.openssl_assert(res == 1)
  798. # Set subject public key.
  799. public_key = private_key.public_key()
  800. res = self._lib.X509_REQ_set_pubkey(
  801. x509_req, public_key._evp_pkey # type: ignore[union-attr]
  802. )
  803. self.openssl_assert(res == 1)
  804. # Add extensions.
  805. sk_extension = self._lib.sk_X509_EXTENSION_new_null()
  806. self.openssl_assert(sk_extension != self._ffi.NULL)
  807. sk_extension = self._ffi.gc(
  808. sk_extension,
  809. lambda x: self._lib.sk_X509_EXTENSION_pop_free(
  810. x,
  811. self._ffi.addressof(
  812. self._lib._original_lib, "X509_EXTENSION_free"
  813. ),
  814. ),
  815. )
  816. # Don't GC individual extensions because the memory is owned by
  817. # sk_extensions and will be freed along with it.
  818. self._create_x509_extensions(
  819. extensions=builder._extensions,
  820. handlers=self._extension_encode_handlers,
  821. x509_obj=sk_extension,
  822. add_func=self._lib.sk_X509_EXTENSION_insert,
  823. gc=False,
  824. )
  825. res = self._lib.X509_REQ_add_extensions(x509_req, sk_extension)
  826. self.openssl_assert(res == 1)
  827. # Add attributes (all bytes encoded as ASN1 UTF8_STRING)
  828. for attr_oid, attr_val in builder._attributes:
  829. obj = _txt2obj_gc(self, attr_oid.dotted_string)
  830. res = self._lib.X509_REQ_add1_attr_by_OBJ(
  831. x509_req,
  832. obj,
  833. x509.name._ASN1Type.UTF8String.value,
  834. attr_val,
  835. len(attr_val),
  836. )
  837. self.openssl_assert(res == 1)
  838. # Sign the request using the requester's private key.
  839. res = self._lib.X509_REQ_sign(
  840. x509_req, private_key._evp_pkey, evp_md # type: ignore[union-attr]
  841. )
  842. if res == 0:
  843. errors = self._consume_errors_with_text()
  844. raise ValueError("Signing failed", errors)
  845. return self._ossl2csr(x509_req)
  846. def create_x509_certificate(
  847. self,
  848. builder: x509.CertificateBuilder,
  849. private_key: PRIVATE_KEY_TYPES,
  850. algorithm: typing.Optional[hashes.HashAlgorithm],
  851. ) -> x509.Certificate:
  852. if not isinstance(builder, x509.CertificateBuilder):
  853. raise TypeError("Builder type mismatch.")
  854. if builder._public_key is None:
  855. raise TypeError("Builder has no public key.")
  856. self._x509_check_signature_params(private_key, algorithm)
  857. # Resolve the signature algorithm.
  858. evp_md = self._evp_md_x509_null_if_eddsa(private_key, algorithm)
  859. # Create an empty certificate.
  860. x509_cert = self._lib.X509_new()
  861. x509_cert = self._ffi.gc(x509_cert, self._lib.X509_free)
  862. # Set the x509 version.
  863. res = self._lib.X509_set_version(x509_cert, builder._version.value)
  864. self.openssl_assert(res == 1)
  865. # Set the subject's name.
  866. res = self._lib.X509_set_subject_name(
  867. x509_cert, _encode_name_gc(self, builder._subject_name)
  868. )
  869. self.openssl_assert(res == 1)
  870. # Set the subject's public key.
  871. res = self._lib.X509_set_pubkey(
  872. x509_cert,
  873. builder._public_key._evp_pkey, # type: ignore[union-attr]
  874. )
  875. self.openssl_assert(res == 1)
  876. # Set the certificate serial number.
  877. serial_number = _encode_asn1_int_gc(self, builder._serial_number)
  878. res = self._lib.X509_set_serialNumber(x509_cert, serial_number)
  879. self.openssl_assert(res == 1)
  880. # Set the "not before" time.
  881. self._set_asn1_time(
  882. self._lib.X509_getm_notBefore(x509_cert), builder._not_valid_before
  883. )
  884. # Set the "not after" time.
  885. self._set_asn1_time(
  886. self._lib.X509_getm_notAfter(x509_cert), builder._not_valid_after
  887. )
  888. # Add extensions.
  889. self._create_x509_extensions(
  890. extensions=builder._extensions,
  891. handlers=self._extension_encode_handlers,
  892. x509_obj=x509_cert,
  893. add_func=self._lib.X509_add_ext,
  894. gc=True,
  895. )
  896. # Set the issuer name.
  897. res = self._lib.X509_set_issuer_name(
  898. x509_cert, _encode_name_gc(self, builder._issuer_name)
  899. )
  900. self.openssl_assert(res == 1)
  901. # Sign the certificate with the issuer's private key.
  902. res = self._lib.X509_sign(
  903. x509_cert,
  904. private_key._evp_pkey, # type: ignore[union-attr]
  905. evp_md,
  906. )
  907. if res == 0:
  908. errors = self._consume_errors_with_text()
  909. raise ValueError("Signing failed", errors)
  910. return self._ossl2cert(x509_cert)
  911. def _evp_md_x509_null_if_eddsa(self, private_key, algorithm):
  912. if isinstance(
  913. private_key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)
  914. ):
  915. # OpenSSL requires us to pass NULL for EVP_MD for ed25519/ed448
  916. return self._ffi.NULL
  917. else:
  918. return self._evp_md_non_null_from_algorithm(algorithm)
  919. def _set_asn1_time(self, asn1_time, time):
  920. if time.year >= 2050:
  921. asn1_str = time.strftime("%Y%m%d%H%M%SZ").encode("ascii")
  922. else:
  923. asn1_str = time.strftime("%y%m%d%H%M%SZ").encode("ascii")
  924. res = self._lib.ASN1_TIME_set_string(asn1_time, asn1_str)
  925. self.openssl_assert(res == 1)
  926. def _create_asn1_time_gc(self, time):
  927. asn1_time = self._lib.ASN1_TIME_new()
  928. self.openssl_assert(asn1_time != self._ffi.NULL)
  929. asn1_time = self._ffi.gc(asn1_time, self._lib.ASN1_TIME_free)
  930. self._set_asn1_time(asn1_time, time)
  931. return asn1_time
  932. def create_x509_crl(
  933. self,
  934. builder: x509.CertificateRevocationListBuilder,
  935. private_key: PRIVATE_KEY_TYPES,
  936. algorithm: typing.Optional[hashes.HashAlgorithm],
  937. ) -> x509.CertificateRevocationList:
  938. if not isinstance(builder, x509.CertificateRevocationListBuilder):
  939. raise TypeError("Builder type mismatch.")
  940. self._x509_check_signature_params(private_key, algorithm)
  941. evp_md = self._evp_md_x509_null_if_eddsa(private_key, algorithm)
  942. # Create an empty CRL.
  943. x509_crl = self._lib.X509_CRL_new()
  944. x509_crl = self._ffi.gc(x509_crl, self._lib.X509_CRL_free)
  945. # Set the x509 CRL version. We only support v2 (integer value 1).
  946. res = self._lib.X509_CRL_set_version(x509_crl, 1)
  947. self.openssl_assert(res == 1)
  948. # Set the issuer name.
  949. res = self._lib.X509_CRL_set_issuer_name(
  950. x509_crl, _encode_name_gc(self, builder._issuer_name)
  951. )
  952. self.openssl_assert(res == 1)
  953. # Set the last update time.
  954. last_update = self._create_asn1_time_gc(builder._last_update)
  955. res = self._lib.X509_CRL_set1_lastUpdate(x509_crl, last_update)
  956. self.openssl_assert(res == 1)
  957. # Set the next update time.
  958. next_update = self._create_asn1_time_gc(builder._next_update)
  959. res = self._lib.X509_CRL_set1_nextUpdate(x509_crl, next_update)
  960. self.openssl_assert(res == 1)
  961. # Add extensions.
  962. self._create_x509_extensions(
  963. extensions=builder._extensions,
  964. handlers=self._crl_extension_encode_handlers,
  965. x509_obj=x509_crl,
  966. add_func=self._lib.X509_CRL_add_ext,
  967. gc=True,
  968. )
  969. # add revoked certificates
  970. for revoked_cert in builder._revoked_certificates:
  971. x509_revoked = self._lib.X509_REVOKED_new()
  972. self.openssl_assert(x509_revoked != self._ffi.NULL)
  973. serial_number = _encode_asn1_int_gc(
  974. self, revoked_cert.serial_number
  975. )
  976. res = self._lib.X509_REVOKED_set_serialNumber(
  977. x509_revoked, serial_number
  978. )
  979. self.openssl_assert(res == 1)
  980. rev_date = self._create_asn1_time_gc(revoked_cert.revocation_date)
  981. res = self._lib.X509_REVOKED_set_revocationDate(
  982. x509_revoked, rev_date
  983. )
  984. self.openssl_assert(res == 1)
  985. # add CRL entry extensions
  986. self._create_x509_extensions(
  987. extensions=revoked_cert.extensions,
  988. handlers=self._crl_entry_extension_encode_handlers,
  989. x509_obj=x509_revoked,
  990. add_func=self._lib.X509_REVOKED_add_ext,
  991. gc=True,
  992. )
  993. res = self._lib.X509_CRL_add0_revoked(x509_crl, x509_revoked)
  994. self.openssl_assert(res == 1)
  995. res = self._lib.X509_CRL_sign(
  996. x509_crl, private_key._evp_pkey, evp_md # type: ignore[union-attr]
  997. )
  998. if res == 0:
  999. errors = self._consume_errors_with_text()
  1000. raise ValueError("Signing failed", errors)
  1001. return self._ossl2crl(x509_crl)
  1002. def _create_x509_extensions(
  1003. self, extensions, handlers, x509_obj, add_func, gc
  1004. ):
  1005. for i, extension in enumerate(extensions):
  1006. x509_extension = self._create_x509_extension(handlers, extension)
  1007. self.openssl_assert(x509_extension != self._ffi.NULL)
  1008. if gc:
  1009. x509_extension = self._ffi.gc(
  1010. x509_extension, self._lib.X509_EXTENSION_free
  1011. )
  1012. res = add_func(x509_obj, x509_extension, i)
  1013. self.openssl_assert(res >= 1)
  1014. def _create_raw_x509_extension(self, extension, value):
  1015. obj = _txt2obj_gc(self, extension.oid.dotted_string)
  1016. return self._lib.X509_EXTENSION_create_by_OBJ(
  1017. self._ffi.NULL, obj, 1 if extension.critical else 0, value
  1018. )
  1019. def _create_x509_extension(self, handlers, extension):
  1020. if isinstance(extension.value, x509.UnrecognizedExtension):
  1021. value = _encode_asn1_str_gc(self, extension.value.value)
  1022. return self._create_raw_x509_extension(extension, value)
  1023. elif isinstance(extension.value, x509.TLSFeature):
  1024. value = _encode_asn1_str_gc(
  1025. self, asn1.encode_tls_feature(extension.value)
  1026. )
  1027. return self._create_raw_x509_extension(extension, value)
  1028. elif isinstance(extension.value, x509.PrecertPoison):
  1029. value = _encode_asn1_str_gc(
  1030. self, asn1.encode_precert_poison(extension.value)
  1031. )
  1032. return self._create_raw_x509_extension(extension, value)
  1033. elif isinstance(
  1034. extension.value, x509.PrecertificateSignedCertificateTimestamps
  1035. ):
  1036. value = _encode_asn1_str_gc(
  1037. self,
  1038. rust_x509.encode_precertificate_signed_certificate_timestamps(
  1039. extension.value
  1040. ),
  1041. )
  1042. return self._create_raw_x509_extension(extension, value)
  1043. else:
  1044. try:
  1045. encode = handlers[extension.oid]
  1046. except KeyError:
  1047. raise NotImplementedError(
  1048. "Extension not supported: {}".format(extension.oid)
  1049. )
  1050. ext_struct = encode(self, extension.value)
  1051. nid = self._lib.OBJ_txt2nid(
  1052. extension.oid.dotted_string.encode("ascii")
  1053. )
  1054. self.openssl_assert(nid != self._lib.NID_undef)
  1055. return self._lib.X509V3_EXT_i2d(
  1056. nid, 1 if extension.critical else 0, ext_struct
  1057. )
  1058. def create_x509_revoked_certificate(
  1059. self, builder: x509.RevokedCertificateBuilder
  1060. ) -> x509.RevokedCertificate:
  1061. if not isinstance(builder, x509.RevokedCertificateBuilder):
  1062. raise TypeError("Builder type mismatch.")
  1063. serial_number = builder._serial_number
  1064. revocation_date = builder._revocation_date
  1065. assert serial_number is not None
  1066. assert revocation_date is not None
  1067. return _RawRevokedCertificate(
  1068. serial_number,
  1069. revocation_date,
  1070. x509.Extensions(builder._extensions),
  1071. )
  1072. def load_pem_private_key(self, data, password):
  1073. return self._load_key(
  1074. self._lib.PEM_read_bio_PrivateKey,
  1075. self._evp_pkey_to_private_key,
  1076. data,
  1077. password,
  1078. )
  1079. def load_pem_public_key(self, data):
  1080. mem_bio = self._bytes_to_bio(data)
  1081. evp_pkey = self._lib.PEM_read_bio_PUBKEY(
  1082. mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
  1083. )
  1084. if evp_pkey != self._ffi.NULL:
  1085. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  1086. return self._evp_pkey_to_public_key(evp_pkey)
  1087. else:
  1088. # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
  1089. # need to check to see if it is a pure PKCS1 RSA public key (not
  1090. # embedded in a subjectPublicKeyInfo)
  1091. self._consume_errors()
  1092. res = self._lib.BIO_reset(mem_bio.bio)
  1093. self.openssl_assert(res == 1)
  1094. rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey(
  1095. mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
  1096. )
  1097. if rsa_cdata != self._ffi.NULL:
  1098. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  1099. evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
  1100. return _RSAPublicKey(self, rsa_cdata, evp_pkey)
  1101. else:
  1102. self._handle_key_loading_error()
  1103. def load_pem_parameters(self, data):
  1104. mem_bio = self._bytes_to_bio(data)
  1105. # only DH is supported currently
  1106. dh_cdata = self._lib.PEM_read_bio_DHparams(
  1107. mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
  1108. )
  1109. if dh_cdata != self._ffi.NULL:
  1110. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1111. return _DHParameters(self, dh_cdata)
  1112. else:
  1113. self._handle_key_loading_error()
  1114. def load_der_private_key(self, data, password):
  1115. # OpenSSL has a function called d2i_AutoPrivateKey that in theory
  1116. # handles this automatically, however it doesn't handle encrypted
  1117. # private keys. Instead we try to load the key two different ways.
  1118. # First we'll try to load it as a traditional key.
  1119. bio_data = self._bytes_to_bio(data)
  1120. key = self._evp_pkey_from_der_traditional_key(bio_data, password)
  1121. if key:
  1122. return self._evp_pkey_to_private_key(key)
  1123. else:
  1124. # Finally we try to load it with the method that handles encrypted
  1125. # PKCS8 properly.
  1126. return self._load_key(
  1127. self._lib.d2i_PKCS8PrivateKey_bio,
  1128. self._evp_pkey_to_private_key,
  1129. data,
  1130. password,
  1131. )
  1132. def _evp_pkey_from_der_traditional_key(self, bio_data, password):
  1133. key = self._lib.d2i_PrivateKey_bio(bio_data.bio, self._ffi.NULL)
  1134. if key != self._ffi.NULL:
  1135. # In OpenSSL 3.0.0-alpha15 there exist scenarios where the key will
  1136. # successfully load but errors are still put on the stack. Tracked
  1137. # as https://github.com/openssl/openssl/issues/14996
  1138. self._consume_errors()
  1139. key = self._ffi.gc(key, self._lib.EVP_PKEY_free)
  1140. if password is not None:
  1141. raise TypeError(
  1142. "Password was given but private key is not encrypted."
  1143. )
  1144. return key
  1145. else:
  1146. self._consume_errors()
  1147. return None
  1148. def load_der_public_key(self, data):
  1149. mem_bio = self._bytes_to_bio(data)
  1150. evp_pkey = self._lib.d2i_PUBKEY_bio(mem_bio.bio, self._ffi.NULL)
  1151. if evp_pkey != self._ffi.NULL:
  1152. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  1153. return self._evp_pkey_to_public_key(evp_pkey)
  1154. else:
  1155. # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
  1156. # need to check to see if it is a pure PKCS1 RSA public key (not
  1157. # embedded in a subjectPublicKeyInfo)
  1158. self._consume_errors()
  1159. res = self._lib.BIO_reset(mem_bio.bio)
  1160. self.openssl_assert(res == 1)
  1161. rsa_cdata = self._lib.d2i_RSAPublicKey_bio(
  1162. mem_bio.bio, self._ffi.NULL
  1163. )
  1164. if rsa_cdata != self._ffi.NULL:
  1165. rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
  1166. evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
  1167. return _RSAPublicKey(self, rsa_cdata, evp_pkey)
  1168. else:
  1169. self._handle_key_loading_error()
  1170. def load_der_parameters(self, data):
  1171. mem_bio = self._bytes_to_bio(data)
  1172. dh_cdata = self._lib.d2i_DHparams_bio(mem_bio.bio, self._ffi.NULL)
  1173. if dh_cdata != self._ffi.NULL:
  1174. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1175. return _DHParameters(self, dh_cdata)
  1176. elif self._lib.Cryptography_HAS_EVP_PKEY_DHX:
  1177. # We check to see if the is dhx.
  1178. self._consume_errors()
  1179. res = self._lib.BIO_reset(mem_bio.bio)
  1180. self.openssl_assert(res == 1)
  1181. dh_cdata = self._lib.Cryptography_d2i_DHxparams_bio(
  1182. mem_bio.bio, self._ffi.NULL
  1183. )
  1184. if dh_cdata != self._ffi.NULL:
  1185. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1186. return _DHParameters(self, dh_cdata)
  1187. self._handle_key_loading_error()
  1188. def _cert2ossl(self, cert: x509.Certificate) -> typing.Any:
  1189. data = cert.public_bytes(serialization.Encoding.DER)
  1190. mem_bio = self._bytes_to_bio(data)
  1191. x509 = self._lib.d2i_X509_bio(mem_bio.bio, self._ffi.NULL)
  1192. self.openssl_assert(x509 != self._ffi.NULL)
  1193. x509 = self._ffi.gc(x509, self._lib.X509_free)
  1194. return x509
  1195. def _ossl2cert(self, x509: typing.Any) -> x509.Certificate:
  1196. bio = self._create_mem_bio_gc()
  1197. res = self._lib.i2d_X509_bio(bio, x509)
  1198. self.openssl_assert(res == 1)
  1199. return rust_x509.load_der_x509_certificate(self._read_mem_bio(bio))
  1200. def _csr2ossl(self, csr: x509.CertificateSigningRequest) -> typing.Any:
  1201. data = csr.public_bytes(serialization.Encoding.DER)
  1202. mem_bio = self._bytes_to_bio(data)
  1203. x509_req = self._lib.d2i_X509_REQ_bio(mem_bio.bio, self._ffi.NULL)
  1204. self.openssl_assert(x509_req != self._ffi.NULL)
  1205. x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
  1206. return x509_req
  1207. def _ossl2csr(
  1208. self, x509_req: typing.Any
  1209. ) -> x509.CertificateSigningRequest:
  1210. bio = self._create_mem_bio_gc()
  1211. res = self._lib.i2d_X509_REQ_bio(bio, x509_req)
  1212. self.openssl_assert(res == 1)
  1213. return rust_x509.load_der_x509_csr(self._read_mem_bio(bio))
  1214. def _crl2ossl(self, crl: x509.CertificateRevocationList) -> typing.Any:
  1215. data = crl.public_bytes(serialization.Encoding.DER)
  1216. mem_bio = self._bytes_to_bio(data)
  1217. x509_crl = self._lib.d2i_X509_CRL_bio(mem_bio.bio, self._ffi.NULL)
  1218. self.openssl_assert(x509_crl != self._ffi.NULL)
  1219. x509_crl = self._ffi.gc(x509_crl, self._lib.X509_CRL_free)
  1220. return x509_crl
  1221. def _ossl2crl(
  1222. self, x509_crl: typing.Any
  1223. ) -> x509.CertificateRevocationList:
  1224. bio = self._create_mem_bio_gc()
  1225. res = self._lib.i2d_X509_CRL_bio(bio, x509_crl)
  1226. self.openssl_assert(res == 1)
  1227. return rust_x509.load_der_x509_crl(self._read_mem_bio(bio))
  1228. def _crl_is_signature_valid(
  1229. self, crl: x509.CertificateRevocationList, public_key: PUBLIC_KEY_TYPES
  1230. ) -> bool:
  1231. if not isinstance(
  1232. public_key,
  1233. (
  1234. _DSAPublicKey,
  1235. _RSAPublicKey,
  1236. _EllipticCurvePublicKey,
  1237. ),
  1238. ):
  1239. raise TypeError(
  1240. "Expecting one of DSAPublicKey, RSAPublicKey,"
  1241. " or EllipticCurvePublicKey."
  1242. )
  1243. x509_crl = self._crl2ossl(crl)
  1244. res = self._lib.X509_CRL_verify(x509_crl, public_key._evp_pkey)
  1245. if res != 1:
  1246. self._consume_errors()
  1247. return False
  1248. return True
  1249. def _csr_is_signature_valid(
  1250. self, csr: x509.CertificateSigningRequest
  1251. ) -> bool:
  1252. x509_req = self._csr2ossl(csr)
  1253. pkey = self._lib.X509_REQ_get_pubkey(x509_req)
  1254. self.openssl_assert(pkey != self._ffi.NULL)
  1255. pkey = self._ffi.gc(pkey, self._lib.EVP_PKEY_free)
  1256. res = self._lib.X509_REQ_verify(x509_req, pkey)
  1257. if res != 1:
  1258. self._consume_errors()
  1259. return False
  1260. return True
  1261. def _load_key(self, openssl_read_func, convert_func, data, password):
  1262. mem_bio = self._bytes_to_bio(data)
  1263. userdata = self._ffi.new("CRYPTOGRAPHY_PASSWORD_DATA *")
  1264. if password is not None:
  1265. utils._check_byteslike("password", password)
  1266. password_ptr = self._ffi.from_buffer(password)
  1267. userdata.password = password_ptr
  1268. userdata.length = len(password)
  1269. evp_pkey = openssl_read_func(
  1270. mem_bio.bio,
  1271. self._ffi.NULL,
  1272. self._ffi.addressof(
  1273. self._lib._original_lib, "Cryptography_pem_password_cb"
  1274. ),
  1275. userdata,
  1276. )
  1277. if evp_pkey == self._ffi.NULL:
  1278. if userdata.error != 0:
  1279. self._consume_errors()
  1280. if userdata.error == -1:
  1281. raise TypeError(
  1282. "Password was not given but private key is encrypted"
  1283. )
  1284. else:
  1285. assert userdata.error == -2
  1286. raise ValueError(
  1287. "Passwords longer than {} bytes are not supported "
  1288. "by this backend.".format(userdata.maxsize - 1)
  1289. )
  1290. else:
  1291. self._handle_key_loading_error()
  1292. # In OpenSSL 3.0.0-alpha15 there exist scenarios where the key will
  1293. # successfully load but errors are still put on the stack. Tracked
  1294. # as https://github.com/openssl/openssl/issues/14996
  1295. self._consume_errors()
  1296. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  1297. if password is not None and userdata.called == 0:
  1298. raise TypeError(
  1299. "Password was given but private key is not encrypted."
  1300. )
  1301. assert (
  1302. password is not None and userdata.called == 1
  1303. ) or password is None
  1304. return convert_func(evp_pkey)
  1305. def _handle_key_loading_error(self):
  1306. errors = self._consume_errors()
  1307. if not errors:
  1308. raise ValueError(
  1309. "Could not deserialize key data. The data may be in an "
  1310. "incorrect format or it may be encrypted with an unsupported "
  1311. "algorithm."
  1312. )
  1313. elif (
  1314. errors[0]._lib_reason_match(
  1315. self._lib.ERR_LIB_EVP, self._lib.EVP_R_BAD_DECRYPT
  1316. )
  1317. or errors[0]._lib_reason_match(
  1318. self._lib.ERR_LIB_PKCS12,
  1319. self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR,
  1320. )
  1321. or (
  1322. self._lib.Cryptography_HAS_PROVIDERS
  1323. and errors[0]._lib_reason_match(
  1324. self._lib.ERR_LIB_PROV,
  1325. self._lib.PROV_R_BAD_DECRYPT,
  1326. )
  1327. )
  1328. ):
  1329. raise ValueError("Bad decrypt. Incorrect password?")
  1330. elif any(
  1331. error._lib_reason_match(
  1332. self._lib.ERR_LIB_EVP,
  1333. self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM,
  1334. )
  1335. for error in errors
  1336. ):
  1337. raise ValueError("Unsupported public key algorithm.")
  1338. else:
  1339. errors = binding._errors_with_text(errors)
  1340. raise ValueError(
  1341. "Could not deserialize key data. The data may be in an "
  1342. "incorrect format or it may be encrypted with an unsupported "
  1343. "algorithm.",
  1344. errors,
  1345. )
  1346. def elliptic_curve_supported(self, curve):
  1347. try:
  1348. curve_nid = self._elliptic_curve_to_nid(curve)
  1349. except UnsupportedAlgorithm:
  1350. curve_nid = self._lib.NID_undef
  1351. group = self._lib.EC_GROUP_new_by_curve_name(curve_nid)
  1352. if group == self._ffi.NULL:
  1353. self._consume_errors()
  1354. return False
  1355. else:
  1356. self.openssl_assert(curve_nid != self._lib.NID_undef)
  1357. self._lib.EC_GROUP_free(group)
  1358. return True
  1359. def elliptic_curve_signature_algorithm_supported(
  1360. self, signature_algorithm, curve
  1361. ):
  1362. # We only support ECDSA right now.
  1363. if not isinstance(signature_algorithm, ec.ECDSA):
  1364. return False
  1365. return self.elliptic_curve_supported(curve)
  1366. def generate_elliptic_curve_private_key(self, curve):
  1367. """
  1368. Generate a new private key on the named curve.
  1369. """
  1370. if self.elliptic_curve_supported(curve):
  1371. ec_cdata = self._ec_key_new_by_curve(curve)
  1372. res = self._lib.EC_KEY_generate_key(ec_cdata)
  1373. self.openssl_assert(res == 1)
  1374. evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
  1375. return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
  1376. else:
  1377. raise UnsupportedAlgorithm(
  1378. "Backend object does not support {}.".format(curve.name),
  1379. _Reasons.UNSUPPORTED_ELLIPTIC_CURVE,
  1380. )
  1381. def load_elliptic_curve_private_numbers(self, numbers):
  1382. public = numbers.public_numbers
  1383. ec_cdata = self._ec_key_new_by_curve(public.curve)
  1384. private_value = self._ffi.gc(
  1385. self._int_to_bn(numbers.private_value), self._lib.BN_clear_free
  1386. )
  1387. res = self._lib.EC_KEY_set_private_key(ec_cdata, private_value)
  1388. self.openssl_assert(res == 1)
  1389. ec_cdata = self._ec_key_set_public_key_affine_coordinates(
  1390. ec_cdata, public.x, public.y
  1391. )
  1392. evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
  1393. return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
  1394. def load_elliptic_curve_public_numbers(self, numbers):
  1395. ec_cdata = self._ec_key_new_by_curve(numbers.curve)
  1396. ec_cdata = self._ec_key_set_public_key_affine_coordinates(
  1397. ec_cdata, numbers.x, numbers.y
  1398. )
  1399. evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
  1400. return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
  1401. def load_elliptic_curve_public_bytes(self, curve, point_bytes):
  1402. ec_cdata = self._ec_key_new_by_curve(curve)
  1403. group = self._lib.EC_KEY_get0_group(ec_cdata)
  1404. self.openssl_assert(group != self._ffi.NULL)
  1405. point = self._lib.EC_POINT_new(group)
  1406. self.openssl_assert(point != self._ffi.NULL)
  1407. point = self._ffi.gc(point, self._lib.EC_POINT_free)
  1408. with self._tmp_bn_ctx() as bn_ctx:
  1409. res = self._lib.EC_POINT_oct2point(
  1410. group, point, point_bytes, len(point_bytes), bn_ctx
  1411. )
  1412. if res != 1:
  1413. self._consume_errors()
  1414. raise ValueError("Invalid public bytes for the given curve")
  1415. res = self._lib.EC_KEY_set_public_key(ec_cdata, point)
  1416. self.openssl_assert(res == 1)
  1417. evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
  1418. return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
  1419. def derive_elliptic_curve_private_key(self, private_value, curve):
  1420. ec_cdata = self._ec_key_new_by_curve(curve)
  1421. get_func, group = self._ec_key_determine_group_get_func(ec_cdata)
  1422. point = self._lib.EC_POINT_new(group)
  1423. self.openssl_assert(point != self._ffi.NULL)
  1424. point = self._ffi.gc(point, self._lib.EC_POINT_free)
  1425. value = self._int_to_bn(private_value)
  1426. value = self._ffi.gc(value, self._lib.BN_clear_free)
  1427. with self._tmp_bn_ctx() as bn_ctx:
  1428. res = self._lib.EC_POINT_mul(
  1429. group, point, value, self._ffi.NULL, self._ffi.NULL, bn_ctx
  1430. )
  1431. self.openssl_assert(res == 1)
  1432. bn_x = self._lib.BN_CTX_get(bn_ctx)
  1433. bn_y = self._lib.BN_CTX_get(bn_ctx)
  1434. res = get_func(group, point, bn_x, bn_y, bn_ctx)
  1435. self.openssl_assert(res == 1)
  1436. res = self._lib.EC_KEY_set_public_key(ec_cdata, point)
  1437. self.openssl_assert(res == 1)
  1438. private = self._int_to_bn(private_value)
  1439. private = self._ffi.gc(private, self._lib.BN_clear_free)
  1440. res = self._lib.EC_KEY_set_private_key(ec_cdata, private)
  1441. self.openssl_assert(res == 1)
  1442. evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata)
  1443. return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
  1444. def _ec_key_new_by_curve(self, curve):
  1445. curve_nid = self._elliptic_curve_to_nid(curve)
  1446. return self._ec_key_new_by_curve_nid(curve_nid)
  1447. def _ec_key_new_by_curve_nid(self, curve_nid):
  1448. ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid)
  1449. self.openssl_assert(ec_cdata != self._ffi.NULL)
  1450. return self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
  1451. def create_ocsp_request(self, builder):
  1452. ocsp_req = self._lib.OCSP_REQUEST_new()
  1453. self.openssl_assert(ocsp_req != self._ffi.NULL)
  1454. ocsp_req = self._ffi.gc(ocsp_req, self._lib.OCSP_REQUEST_free)
  1455. cert, issuer, algorithm = builder._request
  1456. evp_md = self._evp_md_non_null_from_algorithm(algorithm)
  1457. ossl_cert = self._cert2ossl(cert)
  1458. ossl_issuer = self._cert2ossl(issuer)
  1459. certid = self._lib.OCSP_cert_to_id(evp_md, ossl_cert, ossl_issuer)
  1460. self.openssl_assert(certid != self._ffi.NULL)
  1461. onereq = self._lib.OCSP_request_add0_id(ocsp_req, certid)
  1462. self.openssl_assert(onereq != self._ffi.NULL)
  1463. self._create_x509_extensions(
  1464. extensions=builder._extensions,
  1465. handlers=self._ocsp_request_extension_encode_handlers,
  1466. x509_obj=ocsp_req,
  1467. add_func=self._lib.OCSP_REQUEST_add_ext,
  1468. gc=True,
  1469. )
  1470. bio = self._create_mem_bio_gc()
  1471. res = self._lib.i2d_OCSP_REQUEST_bio(bio, ocsp_req)
  1472. self.openssl_assert(res > 0)
  1473. return ocsp.load_der_ocsp_request(self._read_mem_bio(bio))
  1474. def _create_ocsp_basic_response(self, builder, private_key, algorithm):
  1475. self._x509_check_signature_params(private_key, algorithm)
  1476. basic = self._lib.OCSP_BASICRESP_new()
  1477. self.openssl_assert(basic != self._ffi.NULL)
  1478. basic = self._ffi.gc(basic, self._lib.OCSP_BASICRESP_free)
  1479. evp_md = self._evp_md_non_null_from_algorithm(
  1480. builder._response._algorithm
  1481. )
  1482. ossl_cert = self._cert2ossl(builder._response._cert)
  1483. ossl_issuer = self._cert2ossl(builder._response._issuer)
  1484. certid = self._lib.OCSP_cert_to_id(
  1485. evp_md,
  1486. ossl_cert,
  1487. ossl_issuer,
  1488. )
  1489. self.openssl_assert(certid != self._ffi.NULL)
  1490. certid = self._ffi.gc(certid, self._lib.OCSP_CERTID_free)
  1491. if builder._response._revocation_reason is None:
  1492. reason = -1
  1493. else:
  1494. reason = _CRL_ENTRY_REASON_ENUM_TO_CODE[
  1495. builder._response._revocation_reason
  1496. ]
  1497. if builder._response._revocation_time is None:
  1498. rev_time = self._ffi.NULL
  1499. else:
  1500. rev_time = self._create_asn1_time_gc(
  1501. builder._response._revocation_time
  1502. )
  1503. next_update = self._ffi.NULL
  1504. if builder._response._next_update is not None:
  1505. next_update = self._create_asn1_time_gc(
  1506. builder._response._next_update
  1507. )
  1508. this_update = self._create_asn1_time_gc(builder._response._this_update)
  1509. res = self._lib.OCSP_basic_add1_status(
  1510. basic,
  1511. certid,
  1512. builder._response._cert_status.value,
  1513. reason,
  1514. rev_time,
  1515. this_update,
  1516. next_update,
  1517. )
  1518. self.openssl_assert(res != self._ffi.NULL)
  1519. # okay, now sign the basic structure
  1520. evp_md = self._evp_md_x509_null_if_eddsa(private_key, algorithm)
  1521. responder_cert, responder_encoding = builder._responder_id
  1522. flags = self._lib.OCSP_NOCERTS
  1523. if responder_encoding is ocsp.OCSPResponderEncoding.HASH:
  1524. flags |= self._lib.OCSP_RESPID_KEY
  1525. # This list is to keep the x509 values alive until end of function
  1526. ossl_certs = []
  1527. if builder._certs is not None:
  1528. for cert in builder._certs:
  1529. ossl_cert = self._cert2ossl(cert)
  1530. ossl_certs.append(ossl_cert)
  1531. res = self._lib.OCSP_basic_add1_cert(basic, ossl_cert)
  1532. self.openssl_assert(res == 1)
  1533. self._create_x509_extensions(
  1534. extensions=builder._extensions,
  1535. handlers=self._ocsp_basicresp_extension_encode_handlers,
  1536. x509_obj=basic,
  1537. add_func=self._lib.OCSP_BASICRESP_add_ext,
  1538. gc=True,
  1539. )
  1540. ossl_cert = self._cert2ossl(responder_cert)
  1541. res = self._lib.OCSP_basic_sign(
  1542. basic,
  1543. ossl_cert,
  1544. private_key._evp_pkey,
  1545. evp_md,
  1546. self._ffi.NULL,
  1547. flags,
  1548. )
  1549. if res != 1:
  1550. errors = self._consume_errors_with_text()
  1551. raise ValueError(
  1552. "Error while signing. responder_cert must be signed "
  1553. "by private_key",
  1554. errors,
  1555. )
  1556. return basic
  1557. def create_ocsp_response(
  1558. self, response_status, builder, private_key, algorithm
  1559. ):
  1560. if response_status is ocsp.OCSPResponseStatus.SUCCESSFUL:
  1561. basic = self._create_ocsp_basic_response(
  1562. builder, private_key, algorithm
  1563. )
  1564. else:
  1565. basic = self._ffi.NULL
  1566. ocsp_resp = self._lib.OCSP_response_create(
  1567. response_status.value, basic
  1568. )
  1569. self.openssl_assert(ocsp_resp != self._ffi.NULL)
  1570. ocsp_resp = self._ffi.gc(ocsp_resp, self._lib.OCSP_RESPONSE_free)
  1571. bio = self._create_mem_bio_gc()
  1572. res = self._lib.i2d_OCSP_RESPONSE_bio(bio, ocsp_resp)
  1573. self.openssl_assert(res > 0)
  1574. data = self._read_mem_bio(bio)
  1575. return ocsp.load_der_ocsp_response(data)
  1576. def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve):
  1577. if self._fips_enabled and not isinstance(
  1578. curve, self._fips_ecdh_curves
  1579. ):
  1580. return False
  1581. return self.elliptic_curve_supported(curve) and isinstance(
  1582. algorithm, ec.ECDH
  1583. )
  1584. def _ec_cdata_to_evp_pkey(self, ec_cdata):
  1585. evp_pkey = self._create_evp_pkey_gc()
  1586. res = self._lib.EVP_PKEY_set1_EC_KEY(evp_pkey, ec_cdata)
  1587. self.openssl_assert(res == 1)
  1588. return evp_pkey
  1589. def _elliptic_curve_to_nid(self, curve):
  1590. """
  1591. Get the NID for a curve name.
  1592. """
  1593. curve_aliases = {"secp192r1": "prime192v1", "secp256r1": "prime256v1"}
  1594. curve_name = curve_aliases.get(curve.name, curve.name)
  1595. curve_nid = self._lib.OBJ_sn2nid(curve_name.encode())
  1596. if curve_nid == self._lib.NID_undef:
  1597. raise UnsupportedAlgorithm(
  1598. "{} is not a supported elliptic curve".format(curve.name),
  1599. _Reasons.UNSUPPORTED_ELLIPTIC_CURVE,
  1600. )
  1601. return curve_nid
  1602. @contextmanager
  1603. def _tmp_bn_ctx(self):
  1604. bn_ctx = self._lib.BN_CTX_new()
  1605. self.openssl_assert(bn_ctx != self._ffi.NULL)
  1606. bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free)
  1607. self._lib.BN_CTX_start(bn_ctx)
  1608. try:
  1609. yield bn_ctx
  1610. finally:
  1611. self._lib.BN_CTX_end(bn_ctx)
  1612. def _ec_key_determine_group_get_func(self, ctx):
  1613. """
  1614. Given an EC_KEY determine the group and what function is required to
  1615. get point coordinates.
  1616. """
  1617. self.openssl_assert(ctx != self._ffi.NULL)
  1618. nid_two_field = self._lib.OBJ_sn2nid(b"characteristic-two-field")
  1619. self.openssl_assert(nid_two_field != self._lib.NID_undef)
  1620. group = self._lib.EC_KEY_get0_group(ctx)
  1621. self.openssl_assert(group != self._ffi.NULL)
  1622. method = self._lib.EC_GROUP_method_of(group)
  1623. self.openssl_assert(method != self._ffi.NULL)
  1624. nid = self._lib.EC_METHOD_get_field_type(method)
  1625. self.openssl_assert(nid != self._lib.NID_undef)
  1626. if nid == nid_two_field and self._lib.Cryptography_HAS_EC2M:
  1627. get_func = self._lib.EC_POINT_get_affine_coordinates_GF2m
  1628. else:
  1629. get_func = self._lib.EC_POINT_get_affine_coordinates_GFp
  1630. assert get_func
  1631. return get_func, group
  1632. def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y):
  1633. """
  1634. Sets the public key point in the EC_KEY context to the affine x and y
  1635. values.
  1636. """
  1637. if x < 0 or y < 0:
  1638. raise ValueError(
  1639. "Invalid EC key. Both x and y must be non-negative."
  1640. )
  1641. x = self._ffi.gc(self._int_to_bn(x), self._lib.BN_free)
  1642. y = self._ffi.gc(self._int_to_bn(y), self._lib.BN_free)
  1643. res = self._lib.EC_KEY_set_public_key_affine_coordinates(ctx, x, y)
  1644. if res != 1:
  1645. self._consume_errors()
  1646. raise ValueError("Invalid EC key.")
  1647. return ctx
  1648. def _private_key_bytes(
  1649. self, encoding, format, encryption_algorithm, key, evp_pkey, cdata
  1650. ):
  1651. # validate argument types
  1652. if not isinstance(encoding, serialization.Encoding):
  1653. raise TypeError("encoding must be an item from the Encoding enum")
  1654. if not isinstance(format, serialization.PrivateFormat):
  1655. raise TypeError(
  1656. "format must be an item from the PrivateFormat enum"
  1657. )
  1658. if not isinstance(
  1659. encryption_algorithm, serialization.KeySerializationEncryption
  1660. ):
  1661. raise TypeError(
  1662. "Encryption algorithm must be a KeySerializationEncryption "
  1663. "instance"
  1664. )
  1665. # validate password
  1666. if isinstance(encryption_algorithm, serialization.NoEncryption):
  1667. password = b""
  1668. elif isinstance(
  1669. encryption_algorithm, serialization.BestAvailableEncryption
  1670. ):
  1671. password = encryption_algorithm.password
  1672. if len(password) > 1023:
  1673. raise ValueError(
  1674. "Passwords longer than 1023 bytes are not supported by "
  1675. "this backend"
  1676. )
  1677. else:
  1678. raise ValueError("Unsupported encryption type")
  1679. # PKCS8 + PEM/DER
  1680. if format is serialization.PrivateFormat.PKCS8:
  1681. if encoding is serialization.Encoding.PEM:
  1682. write_bio = self._lib.PEM_write_bio_PKCS8PrivateKey
  1683. elif encoding is serialization.Encoding.DER:
  1684. write_bio = self._lib.i2d_PKCS8PrivateKey_bio
  1685. else:
  1686. raise ValueError("Unsupported encoding for PKCS8")
  1687. return self._private_key_bytes_via_bio(
  1688. write_bio, evp_pkey, password
  1689. )
  1690. # TraditionalOpenSSL + PEM/DER
  1691. if format is serialization.PrivateFormat.TraditionalOpenSSL:
  1692. if self._fips_enabled and not isinstance(
  1693. encryption_algorithm, serialization.NoEncryption
  1694. ):
  1695. raise ValueError(
  1696. "Encrypted traditional OpenSSL format is not "
  1697. "supported in FIPS mode."
  1698. )
  1699. key_type = self._lib.EVP_PKEY_id(evp_pkey)
  1700. if encoding is serialization.Encoding.PEM:
  1701. if key_type == self._lib.EVP_PKEY_RSA:
  1702. write_bio = self._lib.PEM_write_bio_RSAPrivateKey
  1703. elif key_type == self._lib.EVP_PKEY_DSA:
  1704. write_bio = self._lib.PEM_write_bio_DSAPrivateKey
  1705. elif key_type == self._lib.EVP_PKEY_EC:
  1706. write_bio = self._lib.PEM_write_bio_ECPrivateKey
  1707. else:
  1708. raise ValueError(
  1709. "Unsupported key type for TraditionalOpenSSL"
  1710. )
  1711. return self._private_key_bytes_via_bio(
  1712. write_bio, cdata, password
  1713. )
  1714. if encoding is serialization.Encoding.DER:
  1715. if password:
  1716. raise ValueError(
  1717. "Encryption is not supported for DER encoded "
  1718. "traditional OpenSSL keys"
  1719. )
  1720. if key_type == self._lib.EVP_PKEY_RSA:
  1721. write_bio = self._lib.i2d_RSAPrivateKey_bio
  1722. elif key_type == self._lib.EVP_PKEY_EC:
  1723. write_bio = self._lib.i2d_ECPrivateKey_bio
  1724. elif key_type == self._lib.EVP_PKEY_DSA:
  1725. write_bio = self._lib.i2d_DSAPrivateKey_bio
  1726. else:
  1727. raise ValueError(
  1728. "Unsupported key type for TraditionalOpenSSL"
  1729. )
  1730. return self._bio_func_output(write_bio, cdata)
  1731. raise ValueError("Unsupported encoding for TraditionalOpenSSL")
  1732. # OpenSSH + PEM
  1733. if format is serialization.PrivateFormat.OpenSSH:
  1734. if encoding is serialization.Encoding.PEM:
  1735. return ssh.serialize_ssh_private_key(key, password)
  1736. raise ValueError(
  1737. "OpenSSH private key format can only be used"
  1738. " with PEM encoding"
  1739. )
  1740. # Anything that key-specific code was supposed to handle earlier,
  1741. # like Raw.
  1742. raise ValueError("format is invalid with this key")
  1743. def _private_key_bytes_via_bio(self, write_bio, evp_pkey, password):
  1744. if not password:
  1745. evp_cipher = self._ffi.NULL
  1746. else:
  1747. # This is a curated value that we will update over time.
  1748. evp_cipher = self._lib.EVP_get_cipherbyname(b"aes-256-cbc")
  1749. return self._bio_func_output(
  1750. write_bio,
  1751. evp_pkey,
  1752. evp_cipher,
  1753. password,
  1754. len(password),
  1755. self._ffi.NULL,
  1756. self._ffi.NULL,
  1757. )
  1758. def _bio_func_output(self, write_bio, *args):
  1759. bio = self._create_mem_bio_gc()
  1760. res = write_bio(bio, *args)
  1761. self.openssl_assert(res == 1)
  1762. return self._read_mem_bio(bio)
  1763. def _public_key_bytes(self, encoding, format, key, evp_pkey, cdata):
  1764. if not isinstance(encoding, serialization.Encoding):
  1765. raise TypeError("encoding must be an item from the Encoding enum")
  1766. if not isinstance(format, serialization.PublicFormat):
  1767. raise TypeError(
  1768. "format must be an item from the PublicFormat enum"
  1769. )
  1770. # SubjectPublicKeyInfo + PEM/DER
  1771. if format is serialization.PublicFormat.SubjectPublicKeyInfo:
  1772. if encoding is serialization.Encoding.PEM:
  1773. write_bio = self._lib.PEM_write_bio_PUBKEY
  1774. elif encoding is serialization.Encoding.DER:
  1775. write_bio = self._lib.i2d_PUBKEY_bio
  1776. else:
  1777. raise ValueError(
  1778. "SubjectPublicKeyInfo works only with PEM or DER encoding"
  1779. )
  1780. return self._bio_func_output(write_bio, evp_pkey)
  1781. # PKCS1 + PEM/DER
  1782. if format is serialization.PublicFormat.PKCS1:
  1783. # Only RSA is supported here.
  1784. key_type = self._lib.EVP_PKEY_id(evp_pkey)
  1785. if key_type != self._lib.EVP_PKEY_RSA:
  1786. raise ValueError("PKCS1 format is supported only for RSA keys")
  1787. if encoding is serialization.Encoding.PEM:
  1788. write_bio = self._lib.PEM_write_bio_RSAPublicKey
  1789. elif encoding is serialization.Encoding.DER:
  1790. write_bio = self._lib.i2d_RSAPublicKey_bio
  1791. else:
  1792. raise ValueError("PKCS1 works only with PEM or DER encoding")
  1793. return self._bio_func_output(write_bio, cdata)
  1794. # OpenSSH + OpenSSH
  1795. if format is serialization.PublicFormat.OpenSSH:
  1796. if encoding is serialization.Encoding.OpenSSH:
  1797. return ssh.serialize_ssh_public_key(key)
  1798. raise ValueError(
  1799. "OpenSSH format must be used with OpenSSH encoding"
  1800. )
  1801. # Anything that key-specific code was supposed to handle earlier,
  1802. # like Raw, CompressedPoint, UncompressedPoint
  1803. raise ValueError("format is invalid with this key")
  1804. def _parameter_bytes(self, encoding, format, cdata):
  1805. if encoding is serialization.Encoding.OpenSSH:
  1806. raise TypeError("OpenSSH encoding is not supported")
  1807. # Only DH is supported here currently.
  1808. q = self._ffi.new("BIGNUM **")
  1809. self._lib.DH_get0_pqg(cdata, self._ffi.NULL, q, self._ffi.NULL)
  1810. if encoding is serialization.Encoding.PEM:
  1811. if q[0] != self._ffi.NULL:
  1812. write_bio = self._lib.PEM_write_bio_DHxparams
  1813. else:
  1814. write_bio = self._lib.PEM_write_bio_DHparams
  1815. elif encoding is serialization.Encoding.DER:
  1816. if q[0] != self._ffi.NULL:
  1817. write_bio = self._lib.Cryptography_i2d_DHxparams_bio
  1818. else:
  1819. write_bio = self._lib.i2d_DHparams_bio
  1820. else:
  1821. raise TypeError("encoding must be an item from the Encoding enum")
  1822. bio = self._create_mem_bio_gc()
  1823. res = write_bio(bio, cdata)
  1824. self.openssl_assert(res == 1)
  1825. return self._read_mem_bio(bio)
  1826. def generate_dh_parameters(self, generator, key_size):
  1827. if key_size < dh._MIN_MODULUS_SIZE:
  1828. raise ValueError(
  1829. "DH key_size must be at least {} bits".format(
  1830. dh._MIN_MODULUS_SIZE
  1831. )
  1832. )
  1833. if generator not in (2, 5):
  1834. raise ValueError("DH generator must be 2 or 5")
  1835. dh_param_cdata = self._lib.DH_new()
  1836. self.openssl_assert(dh_param_cdata != self._ffi.NULL)
  1837. dh_param_cdata = self._ffi.gc(dh_param_cdata, self._lib.DH_free)
  1838. res = self._lib.DH_generate_parameters_ex(
  1839. dh_param_cdata, key_size, generator, self._ffi.NULL
  1840. )
  1841. self.openssl_assert(res == 1)
  1842. return _DHParameters(self, dh_param_cdata)
  1843. def _dh_cdata_to_evp_pkey(self, dh_cdata):
  1844. evp_pkey = self._create_evp_pkey_gc()
  1845. res = self._lib.EVP_PKEY_set1_DH(evp_pkey, dh_cdata)
  1846. self.openssl_assert(res == 1)
  1847. return evp_pkey
  1848. def generate_dh_private_key(self, parameters):
  1849. dh_key_cdata = _dh_params_dup(parameters._dh_cdata, self)
  1850. res = self._lib.DH_generate_key(dh_key_cdata)
  1851. self.openssl_assert(res == 1)
  1852. evp_pkey = self._dh_cdata_to_evp_pkey(dh_key_cdata)
  1853. return _DHPrivateKey(self, dh_key_cdata, evp_pkey)
  1854. def generate_dh_private_key_and_parameters(self, generator, key_size):
  1855. return self.generate_dh_private_key(
  1856. self.generate_dh_parameters(generator, key_size)
  1857. )
  1858. def load_dh_private_numbers(self, numbers):
  1859. parameter_numbers = numbers.public_numbers.parameter_numbers
  1860. dh_cdata = self._lib.DH_new()
  1861. self.openssl_assert(dh_cdata != self._ffi.NULL)
  1862. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1863. p = self._int_to_bn(parameter_numbers.p)
  1864. g = self._int_to_bn(parameter_numbers.g)
  1865. if parameter_numbers.q is not None:
  1866. q = self._int_to_bn(parameter_numbers.q)
  1867. else:
  1868. q = self._ffi.NULL
  1869. pub_key = self._int_to_bn(numbers.public_numbers.y)
  1870. priv_key = self._int_to_bn(numbers.x)
  1871. res = self._lib.DH_set0_pqg(dh_cdata, p, q, g)
  1872. self.openssl_assert(res == 1)
  1873. res = self._lib.DH_set0_key(dh_cdata, pub_key, priv_key)
  1874. self.openssl_assert(res == 1)
  1875. codes = self._ffi.new("int[]", 1)
  1876. res = self._lib.Cryptography_DH_check(dh_cdata, codes)
  1877. self.openssl_assert(res == 1)
  1878. # DH_check will return DH_NOT_SUITABLE_GENERATOR if p % 24 does not
  1879. # equal 11 when the generator is 2 (a quadratic nonresidue).
  1880. # We want to ignore that error because p % 24 == 23 is also fine.
  1881. # Specifically, g is then a quadratic residue. Within the context of
  1882. # Diffie-Hellman this means it can only generate half the possible
  1883. # values. That sounds bad, but quadratic nonresidues leak a bit of
  1884. # the key to the attacker in exchange for having the full key space
  1885. # available. See: https://crypto.stackexchange.com/questions/12961
  1886. if codes[0] != 0 and not (
  1887. parameter_numbers.g == 2
  1888. and codes[0] ^ self._lib.DH_NOT_SUITABLE_GENERATOR == 0
  1889. ):
  1890. raise ValueError("DH private numbers did not pass safety checks.")
  1891. evp_pkey = self._dh_cdata_to_evp_pkey(dh_cdata)
  1892. return _DHPrivateKey(self, dh_cdata, evp_pkey)
  1893. def load_dh_public_numbers(self, numbers):
  1894. dh_cdata = self._lib.DH_new()
  1895. self.openssl_assert(dh_cdata != self._ffi.NULL)
  1896. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1897. parameter_numbers = numbers.parameter_numbers
  1898. p = self._int_to_bn(parameter_numbers.p)
  1899. g = self._int_to_bn(parameter_numbers.g)
  1900. if parameter_numbers.q is not None:
  1901. q = self._int_to_bn(parameter_numbers.q)
  1902. else:
  1903. q = self._ffi.NULL
  1904. pub_key = self._int_to_bn(numbers.y)
  1905. res = self._lib.DH_set0_pqg(dh_cdata, p, q, g)
  1906. self.openssl_assert(res == 1)
  1907. res = self._lib.DH_set0_key(dh_cdata, pub_key, self._ffi.NULL)
  1908. self.openssl_assert(res == 1)
  1909. evp_pkey = self._dh_cdata_to_evp_pkey(dh_cdata)
  1910. return _DHPublicKey(self, dh_cdata, evp_pkey)
  1911. def load_dh_parameter_numbers(self, numbers):
  1912. dh_cdata = self._lib.DH_new()
  1913. self.openssl_assert(dh_cdata != self._ffi.NULL)
  1914. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1915. p = self._int_to_bn(numbers.p)
  1916. g = self._int_to_bn(numbers.g)
  1917. if numbers.q is not None:
  1918. q = self._int_to_bn(numbers.q)
  1919. else:
  1920. q = self._ffi.NULL
  1921. res = self._lib.DH_set0_pqg(dh_cdata, p, q, g)
  1922. self.openssl_assert(res == 1)
  1923. return _DHParameters(self, dh_cdata)
  1924. def dh_parameters_supported(self, p, g, q=None):
  1925. dh_cdata = self._lib.DH_new()
  1926. self.openssl_assert(dh_cdata != self._ffi.NULL)
  1927. dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
  1928. p = self._int_to_bn(p)
  1929. g = self._int_to_bn(g)
  1930. if q is not None:
  1931. q = self._int_to_bn(q)
  1932. else:
  1933. q = self._ffi.NULL
  1934. res = self._lib.DH_set0_pqg(dh_cdata, p, q, g)
  1935. self.openssl_assert(res == 1)
  1936. codes = self._ffi.new("int[]", 1)
  1937. res = self._lib.Cryptography_DH_check(dh_cdata, codes)
  1938. self.openssl_assert(res == 1)
  1939. return codes[0] == 0
  1940. def dh_x942_serialization_supported(self):
  1941. return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1
  1942. def x509_name_bytes(self, name: Name) -> bytes:
  1943. x509_name = _encode_name_gc(self, name)
  1944. pp = self._ffi.new("unsigned char **")
  1945. res = self._lib.i2d_X509_NAME(x509_name, pp)
  1946. self.openssl_assert(pp[0] != self._ffi.NULL)
  1947. pp = self._ffi.gc(
  1948. pp, lambda pointer: self._lib.OPENSSL_free(pointer[0])
  1949. )
  1950. self.openssl_assert(res > 0)
  1951. return self._ffi.buffer(pp[0], res)[:]
  1952. def x25519_load_public_bytes(self, data):
  1953. # When we drop support for CRYPTOGRAPHY_OPENSSL_LESS_THAN_111 we can
  1954. # switch this to EVP_PKEY_new_raw_public_key
  1955. if len(data) != 32:
  1956. raise ValueError("An X25519 public key is 32 bytes long")
  1957. evp_pkey = self._create_evp_pkey_gc()
  1958. res = self._lib.EVP_PKEY_set_type(evp_pkey, self._lib.NID_X25519)
  1959. self.openssl_assert(res == 1)
  1960. res = self._lib.EVP_PKEY_set1_tls_encodedpoint(
  1961. evp_pkey, data, len(data)
  1962. )
  1963. self.openssl_assert(res == 1)
  1964. return _X25519PublicKey(self, evp_pkey)
  1965. def x25519_load_private_bytes(self, data):
  1966. # When we drop support for CRYPTOGRAPHY_OPENSSL_LESS_THAN_111 we can
  1967. # switch this to EVP_PKEY_new_raw_private_key and drop the
  1968. # zeroed_bytearray garbage.
  1969. # OpenSSL only has facilities for loading PKCS8 formatted private
  1970. # keys using the algorithm identifiers specified in
  1971. # https://tools.ietf.org/html/draft-ietf-curdle-pkix-09.
  1972. # This is the standard PKCS8 prefix for a 32 byte X25519 key.
  1973. # The form is:
  1974. # 0:d=0 hl=2 l= 46 cons: SEQUENCE
  1975. # 2:d=1 hl=2 l= 1 prim: INTEGER :00
  1976. # 5:d=1 hl=2 l= 5 cons: SEQUENCE
  1977. # 7:d=2 hl=2 l= 3 prim: OBJECT :1.3.101.110
  1978. # 12:d=1 hl=2 l= 34 prim: OCTET STRING (the key)
  1979. # Of course there's a bit more complexity. In reality OCTET STRING
  1980. # contains an OCTET STRING of length 32! So the last two bytes here
  1981. # are \x04\x20, which is an OCTET STRING of length 32.
  1982. if len(data) != 32:
  1983. raise ValueError("An X25519 private key is 32 bytes long")
  1984. pkcs8_prefix = b'0.\x02\x01\x000\x05\x06\x03+en\x04"\x04 '
  1985. with self._zeroed_bytearray(48) as ba:
  1986. ba[0:16] = pkcs8_prefix
  1987. ba[16:] = data
  1988. bio = self._bytes_to_bio(ba)
  1989. evp_pkey = self._lib.d2i_PrivateKey_bio(bio.bio, self._ffi.NULL)
  1990. self.openssl_assert(evp_pkey != self._ffi.NULL)
  1991. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  1992. self.openssl_assert(
  1993. self._lib.EVP_PKEY_id(evp_pkey) == self._lib.EVP_PKEY_X25519
  1994. )
  1995. return _X25519PrivateKey(self, evp_pkey)
  1996. def _evp_pkey_keygen_gc(self, nid):
  1997. evp_pkey_ctx = self._lib.EVP_PKEY_CTX_new_id(nid, self._ffi.NULL)
  1998. self.openssl_assert(evp_pkey_ctx != self._ffi.NULL)
  1999. evp_pkey_ctx = self._ffi.gc(evp_pkey_ctx, self._lib.EVP_PKEY_CTX_free)
  2000. res = self._lib.EVP_PKEY_keygen_init(evp_pkey_ctx)
  2001. self.openssl_assert(res == 1)
  2002. evp_ppkey = self._ffi.new("EVP_PKEY **")
  2003. res = self._lib.EVP_PKEY_keygen(evp_pkey_ctx, evp_ppkey)
  2004. self.openssl_assert(res == 1)
  2005. self.openssl_assert(evp_ppkey[0] != self._ffi.NULL)
  2006. evp_pkey = self._ffi.gc(evp_ppkey[0], self._lib.EVP_PKEY_free)
  2007. return evp_pkey
  2008. def x25519_generate_key(self):
  2009. evp_pkey = self._evp_pkey_keygen_gc(self._lib.NID_X25519)
  2010. return _X25519PrivateKey(self, evp_pkey)
  2011. def x25519_supported(self):
  2012. if self._fips_enabled:
  2013. return False
  2014. return not self._lib.CRYPTOGRAPHY_IS_LIBRESSL
  2015. def x448_load_public_bytes(self, data):
  2016. if len(data) != 56:
  2017. raise ValueError("An X448 public key is 56 bytes long")
  2018. evp_pkey = self._lib.EVP_PKEY_new_raw_public_key(
  2019. self._lib.NID_X448, self._ffi.NULL, data, len(data)
  2020. )
  2021. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2022. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2023. return _X448PublicKey(self, evp_pkey)
  2024. def x448_load_private_bytes(self, data):
  2025. if len(data) != 56:
  2026. raise ValueError("An X448 private key is 56 bytes long")
  2027. data_ptr = self._ffi.from_buffer(data)
  2028. evp_pkey = self._lib.EVP_PKEY_new_raw_private_key(
  2029. self._lib.NID_X448, self._ffi.NULL, data_ptr, len(data)
  2030. )
  2031. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2032. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2033. return _X448PrivateKey(self, evp_pkey)
  2034. def x448_generate_key(self):
  2035. evp_pkey = self._evp_pkey_keygen_gc(self._lib.NID_X448)
  2036. return _X448PrivateKey(self, evp_pkey)
  2037. def x448_supported(self):
  2038. if self._fips_enabled:
  2039. return False
  2040. return not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111
  2041. def ed25519_supported(self):
  2042. if self._fips_enabled:
  2043. return False
  2044. return not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111B
  2045. def ed25519_load_public_bytes(self, data):
  2046. utils._check_bytes("data", data)
  2047. if len(data) != ed25519._ED25519_KEY_SIZE:
  2048. raise ValueError("An Ed25519 public key is 32 bytes long")
  2049. evp_pkey = self._lib.EVP_PKEY_new_raw_public_key(
  2050. self._lib.NID_ED25519, self._ffi.NULL, data, len(data)
  2051. )
  2052. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2053. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2054. return _Ed25519PublicKey(self, evp_pkey)
  2055. def ed25519_load_private_bytes(self, data):
  2056. if len(data) != ed25519._ED25519_KEY_SIZE:
  2057. raise ValueError("An Ed25519 private key is 32 bytes long")
  2058. utils._check_byteslike("data", data)
  2059. data_ptr = self._ffi.from_buffer(data)
  2060. evp_pkey = self._lib.EVP_PKEY_new_raw_private_key(
  2061. self._lib.NID_ED25519, self._ffi.NULL, data_ptr, len(data)
  2062. )
  2063. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2064. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2065. return _Ed25519PrivateKey(self, evp_pkey)
  2066. def ed25519_generate_key(self):
  2067. evp_pkey = self._evp_pkey_keygen_gc(self._lib.NID_ED25519)
  2068. return _Ed25519PrivateKey(self, evp_pkey)
  2069. def ed448_supported(self):
  2070. if self._fips_enabled:
  2071. return False
  2072. return not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111B
  2073. def ed448_load_public_bytes(self, data):
  2074. utils._check_bytes("data", data)
  2075. if len(data) != _ED448_KEY_SIZE:
  2076. raise ValueError("An Ed448 public key is 57 bytes long")
  2077. evp_pkey = self._lib.EVP_PKEY_new_raw_public_key(
  2078. self._lib.NID_ED448, self._ffi.NULL, data, len(data)
  2079. )
  2080. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2081. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2082. return _Ed448PublicKey(self, evp_pkey)
  2083. def ed448_load_private_bytes(self, data):
  2084. utils._check_byteslike("data", data)
  2085. if len(data) != _ED448_KEY_SIZE:
  2086. raise ValueError("An Ed448 private key is 57 bytes long")
  2087. data_ptr = self._ffi.from_buffer(data)
  2088. evp_pkey = self._lib.EVP_PKEY_new_raw_private_key(
  2089. self._lib.NID_ED448, self._ffi.NULL, data_ptr, len(data)
  2090. )
  2091. self.openssl_assert(evp_pkey != self._ffi.NULL)
  2092. evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
  2093. return _Ed448PrivateKey(self, evp_pkey)
  2094. def ed448_generate_key(self):
  2095. evp_pkey = self._evp_pkey_keygen_gc(self._lib.NID_ED448)
  2096. return _Ed448PrivateKey(self, evp_pkey)
  2097. def derive_scrypt(self, key_material, salt, length, n, r, p):
  2098. buf = self._ffi.new("unsigned char[]", length)
  2099. key_material_ptr = self._ffi.from_buffer(key_material)
  2100. res = self._lib.EVP_PBE_scrypt(
  2101. key_material_ptr,
  2102. len(key_material),
  2103. salt,
  2104. len(salt),
  2105. n,
  2106. r,
  2107. p,
  2108. scrypt._MEM_LIMIT,
  2109. buf,
  2110. length,
  2111. )
  2112. if res != 1:
  2113. errors = self._consume_errors_with_text()
  2114. # memory required formula explained here:
  2115. # https://blog.filippo.io/the-scrypt-parameters/
  2116. min_memory = 128 * n * r // (1024 ** 2)
  2117. raise MemoryError(
  2118. "Not enough memory to derive key. These parameters require"
  2119. " {} MB of memory.".format(min_memory),
  2120. errors,
  2121. )
  2122. return self._ffi.buffer(buf)[:]
  2123. def aead_cipher_supported(self, cipher):
  2124. cipher_name = aead._aead_cipher_name(cipher)
  2125. if self._fips_enabled and cipher_name not in self._fips_aead:
  2126. return False
  2127. return self._lib.EVP_get_cipherbyname(cipher_name) != self._ffi.NULL
  2128. @contextlib.contextmanager
  2129. def _zeroed_bytearray(self, length):
  2130. """
  2131. This method creates a bytearray, which we copy data into (hopefully
  2132. also from a mutable buffer that can be dynamically erased!), and then
  2133. zero when we're done.
  2134. """
  2135. ba = bytearray(length)
  2136. try:
  2137. yield ba
  2138. finally:
  2139. self._zero_data(ba, length)
  2140. def _zero_data(self, data, length):
  2141. # We clear things this way because at the moment we're not
  2142. # sure of a better way that can guarantee it overwrites the
  2143. # memory of a bytearray and doesn't just replace the underlying char *.
  2144. for i in range(length):
  2145. data[i] = 0
  2146. @contextlib.contextmanager
  2147. def _zeroed_null_terminated_buf(self, data):
  2148. """
  2149. This method takes bytes, which can be a bytestring or a mutable
  2150. buffer like a bytearray, and yields a null-terminated version of that
  2151. data. This is required because PKCS12_parse doesn't take a length with
  2152. its password char * and ffi.from_buffer doesn't provide null
  2153. termination. So, to support zeroing the data via bytearray we
  2154. need to build this ridiculous construct that copies the memory, but
  2155. zeroes it after use.
  2156. """
  2157. if data is None:
  2158. yield self._ffi.NULL
  2159. else:
  2160. data_len = len(data)
  2161. buf = self._ffi.new("char[]", data_len + 1)
  2162. self._ffi.memmove(buf, data, data_len)
  2163. try:
  2164. yield buf
  2165. finally:
  2166. # Cast to a uint8_t * so we can assign by integer
  2167. self._zero_data(self._ffi.cast("uint8_t *", buf), data_len)
  2168. def load_key_and_certificates_from_pkcs12(self, data, password):
  2169. if password is not None:
  2170. utils._check_byteslike("password", password)
  2171. bio = self._bytes_to_bio(data)
  2172. p12 = self._lib.d2i_PKCS12_bio(bio.bio, self._ffi.NULL)
  2173. if p12 == self._ffi.NULL:
  2174. self._consume_errors()
  2175. raise ValueError("Could not deserialize PKCS12 data")
  2176. p12 = self._ffi.gc(p12, self._lib.PKCS12_free)
  2177. evp_pkey_ptr = self._ffi.new("EVP_PKEY **")
  2178. x509_ptr = self._ffi.new("X509 **")
  2179. sk_x509_ptr = self._ffi.new("Cryptography_STACK_OF_X509 **")
  2180. with self._zeroed_null_terminated_buf(password) as password_buf:
  2181. res = self._lib.PKCS12_parse(
  2182. p12, password_buf, evp_pkey_ptr, x509_ptr, sk_x509_ptr
  2183. )
  2184. # Workaround for
  2185. # https://github.com/libressl-portable/portable/issues/659
  2186. # TODO: Once 3.4.0 is released, add branch.
  2187. if self._lib.CRYPTOGRAPHY_IS_LIBRESSL:
  2188. self._consume_errors()
  2189. if res == 0:
  2190. self._consume_errors()
  2191. raise ValueError("Invalid password or PKCS12 data")
  2192. cert = None
  2193. key = None
  2194. additional_certificates = []
  2195. if evp_pkey_ptr[0] != self._ffi.NULL:
  2196. evp_pkey = self._ffi.gc(evp_pkey_ptr[0], self._lib.EVP_PKEY_free)
  2197. key = self._evp_pkey_to_private_key(evp_pkey)
  2198. if x509_ptr[0] != self._ffi.NULL:
  2199. x509 = self._ffi.gc(x509_ptr[0], self._lib.X509_free)
  2200. cert = self._ossl2cert(x509)
  2201. if sk_x509_ptr[0] != self._ffi.NULL:
  2202. sk_x509 = self._ffi.gc(sk_x509_ptr[0], self._lib.sk_X509_free)
  2203. num = self._lib.sk_X509_num(sk_x509_ptr[0])
  2204. # In OpenSSL < 3.0.0 PKCS12 parsing reverses the order of the
  2205. # certificates.
  2206. indices: typing.Iterable[int]
  2207. if self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER:
  2208. indices = range(num)
  2209. else:
  2210. indices = reversed(range(num))
  2211. for i in indices:
  2212. x509 = self._lib.sk_X509_value(sk_x509, i)
  2213. self.openssl_assert(x509 != self._ffi.NULL)
  2214. x509 = self._ffi.gc(x509, self._lib.X509_free)
  2215. addl_cert = self._ossl2cert(x509)
  2216. additional_certificates.append(addl_cert)
  2217. return (key, cert, additional_certificates)
  2218. def serialize_key_and_certificates_to_pkcs12(
  2219. self, name, key, cert, cas, encryption_algorithm
  2220. ):
  2221. password = None
  2222. if name is not None:
  2223. utils._check_bytes("name", name)
  2224. if isinstance(encryption_algorithm, serialization.NoEncryption):
  2225. nid_cert = -1
  2226. nid_key = -1
  2227. pkcs12_iter = 0
  2228. mac_iter = 0
  2229. elif isinstance(
  2230. encryption_algorithm, serialization.BestAvailableEncryption
  2231. ):
  2232. # PKCS12 encryption is hopeless trash and can never be fixed.
  2233. # This is the least terrible option.
  2234. nid_cert = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC
  2235. nid_key = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC
  2236. # At least we can set this higher than OpenSSL's default
  2237. pkcs12_iter = 20000
  2238. # mac_iter chosen for compatibility reasons, see:
  2239. # https://www.openssl.org/docs/man1.1.1/man3/PKCS12_create.html
  2240. # Did we mention how lousy PKCS12 encryption is?
  2241. mac_iter = 1
  2242. password = encryption_algorithm.password
  2243. else:
  2244. raise ValueError("Unsupported key encryption type")
  2245. if cas is None or len(cas) == 0:
  2246. sk_x509 = self._ffi.NULL
  2247. else:
  2248. sk_x509 = self._lib.sk_X509_new_null()
  2249. sk_x509 = self._ffi.gc(sk_x509, self._lib.sk_X509_free)
  2250. # This list is to keep the x509 values alive until end of function
  2251. ossl_cas = []
  2252. for ca in cas:
  2253. ossl_ca = self._cert2ossl(ca)
  2254. ossl_cas.append(ossl_ca)
  2255. res = self._lib.sk_X509_push(sk_x509, ossl_ca)
  2256. backend.openssl_assert(res >= 1)
  2257. with self._zeroed_null_terminated_buf(password) as password_buf:
  2258. with self._zeroed_null_terminated_buf(name) as name_buf:
  2259. ossl_cert = self._cert2ossl(cert) if cert else self._ffi.NULL
  2260. evp_pkey = key._evp_pkey if key else self._ffi.NULL
  2261. p12 = self._lib.PKCS12_create(
  2262. password_buf,
  2263. name_buf,
  2264. evp_pkey,
  2265. ossl_cert,
  2266. sk_x509,
  2267. nid_key,
  2268. nid_cert,
  2269. pkcs12_iter,
  2270. mac_iter,
  2271. 0,
  2272. )
  2273. self.openssl_assert(p12 != self._ffi.NULL)
  2274. p12 = self._ffi.gc(p12, self._lib.PKCS12_free)
  2275. bio = self._create_mem_bio_gc()
  2276. res = self._lib.i2d_PKCS12_bio(bio, p12)
  2277. self.openssl_assert(res > 0)
  2278. return self._read_mem_bio(bio)
  2279. def poly1305_supported(self):
  2280. if self._fips_enabled:
  2281. return False
  2282. return self._lib.Cryptography_HAS_POLY1305 == 1
  2283. def create_poly1305_ctx(self, key):
  2284. utils._check_byteslike("key", key)
  2285. if len(key) != _POLY1305_KEY_SIZE:
  2286. raise ValueError("A poly1305 key is 32 bytes long")
  2287. return _Poly1305Context(self, key)
  2288. def load_pem_pkcs7_certificates(self, data):
  2289. utils._check_bytes("data", data)
  2290. bio = self._bytes_to_bio(data)
  2291. p7 = self._lib.PEM_read_bio_PKCS7(
  2292. bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
  2293. )
  2294. if p7 == self._ffi.NULL:
  2295. self._consume_errors()
  2296. raise ValueError("Unable to parse PKCS7 data")
  2297. p7 = self._ffi.gc(p7, self._lib.PKCS7_free)
  2298. return self._load_pkcs7_certificates(p7)
  2299. def load_der_pkcs7_certificates(self, data):
  2300. utils._check_bytes("data", data)
  2301. bio = self._bytes_to_bio(data)
  2302. p7 = self._lib.d2i_PKCS7_bio(bio.bio, self._ffi.NULL)
  2303. if p7 == self._ffi.NULL:
  2304. self._consume_errors()
  2305. raise ValueError("Unable to parse PKCS7 data")
  2306. p7 = self._ffi.gc(p7, self._lib.PKCS7_free)
  2307. return self._load_pkcs7_certificates(p7)
  2308. def _load_pkcs7_certificates(self, p7):
  2309. nid = self._lib.OBJ_obj2nid(p7.type)
  2310. self.openssl_assert(nid != self._lib.NID_undef)
  2311. if nid != self._lib.NID_pkcs7_signed:
  2312. raise UnsupportedAlgorithm(
  2313. "Only basic signed structures are currently supported. NID"
  2314. " for this data was {}".format(nid),
  2315. _Reasons.UNSUPPORTED_SERIALIZATION,
  2316. )
  2317. sk_x509 = p7.d.sign.cert
  2318. num = self._lib.sk_X509_num(sk_x509)
  2319. certs = []
  2320. for i in range(num):
  2321. x509 = self._lib.sk_X509_value(sk_x509, i)
  2322. self.openssl_assert(x509 != self._ffi.NULL)
  2323. res = self._lib.X509_up_ref(x509)
  2324. # When OpenSSL is less than 1.1.0 up_ref returns the current
  2325. # refcount. On 1.1.0+ it returns 1 for success.
  2326. self.openssl_assert(res >= 1)
  2327. x509 = self._ffi.gc(x509, self._lib.X509_free)
  2328. cert = self._ossl2cert(x509)
  2329. certs.append(cert)
  2330. return certs
  2331. def pkcs7_sign(self, builder, encoding, options):
  2332. bio = self._bytes_to_bio(builder._data)
  2333. init_flags = self._lib.PKCS7_PARTIAL
  2334. final_flags = 0
  2335. if len(builder._additional_certs) == 0:
  2336. certs = self._ffi.NULL
  2337. else:
  2338. certs = self._lib.sk_X509_new_null()
  2339. certs = self._ffi.gc(certs, self._lib.sk_X509_free)
  2340. # This list is to keep the x509 values alive until end of function
  2341. ossl_certs = []
  2342. for cert in builder._additional_certs:
  2343. ossl_cert = self._cert2ossl(cert)
  2344. ossl_certs.append(ossl_cert)
  2345. res = self._lib.sk_X509_push(certs, ossl_cert)
  2346. self.openssl_assert(res >= 1)
  2347. if pkcs7.PKCS7Options.DetachedSignature in options:
  2348. # Don't embed the data in the PKCS7 structure
  2349. init_flags |= self._lib.PKCS7_DETACHED
  2350. final_flags |= self._lib.PKCS7_DETACHED
  2351. # This just inits a structure for us. However, there
  2352. # are flags we need to set, joy.
  2353. p7 = self._lib.PKCS7_sign(
  2354. self._ffi.NULL,
  2355. self._ffi.NULL,
  2356. certs,
  2357. self._ffi.NULL,
  2358. init_flags,
  2359. )
  2360. self.openssl_assert(p7 != self._ffi.NULL)
  2361. p7 = self._ffi.gc(p7, self._lib.PKCS7_free)
  2362. signer_flags = 0
  2363. # These flags are configurable on a per-signature basis
  2364. # but we've deliberately chosen to make the API only allow
  2365. # setting it across all signatures for now.
  2366. if pkcs7.PKCS7Options.NoCapabilities in options:
  2367. signer_flags |= self._lib.PKCS7_NOSMIMECAP
  2368. elif pkcs7.PKCS7Options.NoAttributes in options:
  2369. signer_flags |= self._lib.PKCS7_NOATTR
  2370. if pkcs7.PKCS7Options.NoCerts in options:
  2371. signer_flags |= self._lib.PKCS7_NOCERTS
  2372. for certificate, private_key, hash_algorithm in builder._signers:
  2373. ossl_cert = self._cert2ossl(certificate)
  2374. md = self._evp_md_non_null_from_algorithm(hash_algorithm)
  2375. p7signerinfo = self._lib.PKCS7_sign_add_signer(
  2376. p7, ossl_cert, private_key._evp_pkey, md, signer_flags
  2377. )
  2378. self.openssl_assert(p7signerinfo != self._ffi.NULL)
  2379. for option in options:
  2380. # DetachedSignature, NoCapabilities, and NoAttributes are already
  2381. # handled so we just need to check these last two options.
  2382. if option is pkcs7.PKCS7Options.Text:
  2383. final_flags |= self._lib.PKCS7_TEXT
  2384. elif option is pkcs7.PKCS7Options.Binary:
  2385. final_flags |= self._lib.PKCS7_BINARY
  2386. bio_out = self._create_mem_bio_gc()
  2387. if encoding is serialization.Encoding.SMIME:
  2388. # This finalizes the structure
  2389. res = self._lib.SMIME_write_PKCS7(
  2390. bio_out, p7, bio.bio, final_flags
  2391. )
  2392. elif encoding is serialization.Encoding.PEM:
  2393. res = self._lib.PKCS7_final(p7, bio.bio, final_flags)
  2394. self.openssl_assert(res == 1)
  2395. res = self._lib.PEM_write_bio_PKCS7_stream(
  2396. bio_out, p7, bio.bio, final_flags
  2397. )
  2398. else:
  2399. assert encoding is serialization.Encoding.DER
  2400. # We need to call finalize here becauase i2d_PKCS7_bio does not
  2401. # finalize.
  2402. res = self._lib.PKCS7_final(p7, bio.bio, final_flags)
  2403. self.openssl_assert(res == 1)
  2404. # OpenSSL 3.0 leaves a random bio error on the stack:
  2405. # https://github.com/openssl/openssl/issues/16681
  2406. if self._lib.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER:
  2407. self._consume_errors()
  2408. res = self._lib.i2d_PKCS7_bio(bio_out, p7)
  2409. self.openssl_assert(res == 1)
  2410. return self._read_mem_bio(bio_out)
  2411. class GetCipherByName(object):
  2412. def __init__(self, fmt):
  2413. self._fmt = fmt
  2414. def __call__(self, backend, cipher, mode):
  2415. cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower()
  2416. return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii"))
  2417. def _get_xts_cipher(backend, cipher, mode):
  2418. cipher_name = "aes-{}-xts".format(cipher.key_size // 2)
  2419. return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii"))
  2420. backend = Backend()