crypto.py 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277
  1. import calendar
  2. import datetime
  3. from base64 import b16encode
  4. from functools import partial
  5. from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
  6. from cryptography import utils, x509
  7. from cryptography.hazmat.primitives.asymmetric import dsa, rsa
  8. from OpenSSL._util import (
  9. ffi as _ffi,
  10. lib as _lib,
  11. exception_from_error_queue as _exception_from_error_queue,
  12. byte_string as _byte_string,
  13. path_bytes as _path_bytes,
  14. UNSPECIFIED as _UNSPECIFIED,
  15. text_to_bytes_and_warn as _text_to_bytes_and_warn,
  16. make_assert as _make_assert,
  17. )
  18. __all__ = [
  19. "FILETYPE_PEM",
  20. "FILETYPE_ASN1",
  21. "FILETYPE_TEXT",
  22. "TYPE_RSA",
  23. "TYPE_DSA",
  24. "Error",
  25. "PKey",
  26. "get_elliptic_curves",
  27. "get_elliptic_curve",
  28. "X509Name",
  29. "X509Extension",
  30. "X509Req",
  31. "X509",
  32. "X509StoreFlags",
  33. "X509Store",
  34. "X509StoreContextError",
  35. "X509StoreContext",
  36. "load_certificate",
  37. "dump_certificate",
  38. "dump_publickey",
  39. "dump_privatekey",
  40. "Revoked",
  41. "CRL",
  42. "PKCS7",
  43. "PKCS12",
  44. "NetscapeSPKI",
  45. "load_publickey",
  46. "load_privatekey",
  47. "dump_certificate_request",
  48. "load_certificate_request",
  49. "sign",
  50. "verify",
  51. "dump_crl",
  52. "load_crl",
  53. "load_pkcs7_data",
  54. "load_pkcs12",
  55. ]
  56. FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
  57. FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
  58. # TODO This was an API mistake. OpenSSL has no such constant.
  59. FILETYPE_TEXT = 2 ** 16 - 1
  60. TYPE_RSA = _lib.EVP_PKEY_RSA
  61. TYPE_DSA = _lib.EVP_PKEY_DSA
  62. TYPE_DH = _lib.EVP_PKEY_DH
  63. TYPE_EC = _lib.EVP_PKEY_EC
  64. class Error(Exception):
  65. """
  66. An error occurred in an `OpenSSL.crypto` API.
  67. """
  68. _raise_current_error = partial(_exception_from_error_queue, Error)
  69. _openssl_assert = _make_assert(Error)
  70. def _get_backend():
  71. """
  72. Importing the backend from cryptography has the side effect of activating
  73. the osrandom engine. This mutates the global state of OpenSSL in the
  74. process and causes issues for various programs that use subinterpreters or
  75. embed Python. By putting the import in this function we can avoid
  76. triggering this side effect unless _get_backend is called.
  77. """
  78. from cryptography.hazmat.backends.openssl.backend import backend
  79. return backend
  80. def _untested_error(where):
  81. """
  82. An OpenSSL API failed somehow. Additionally, the failure which was
  83. encountered isn't one that's exercised by the test suite so future behavior
  84. of pyOpenSSL is now somewhat less predictable.
  85. """
  86. raise RuntimeError("Unknown %s failure" % (where,))
  87. def _new_mem_buf(buffer=None):
  88. """
  89. Allocate a new OpenSSL memory BIO.
  90. Arrange for the garbage collector to clean it up automatically.
  91. :param buffer: None or some bytes to use to put into the BIO so that they
  92. can be read out.
  93. """
  94. if buffer is None:
  95. bio = _lib.BIO_new(_lib.BIO_s_mem())
  96. free = _lib.BIO_free
  97. else:
  98. data = _ffi.new("char[]", buffer)
  99. bio = _lib.BIO_new_mem_buf(data, len(buffer))
  100. # Keep the memory alive as long as the bio is alive!
  101. def free(bio, ref=data):
  102. return _lib.BIO_free(bio)
  103. _openssl_assert(bio != _ffi.NULL)
  104. bio = _ffi.gc(bio, free)
  105. return bio
  106. def _bio_to_string(bio):
  107. """
  108. Copy the contents of an OpenSSL BIO object into a Python byte string.
  109. """
  110. result_buffer = _ffi.new("char**")
  111. buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
  112. return _ffi.buffer(result_buffer[0], buffer_length)[:]
  113. def _set_asn1_time(boundary, when):
  114. """
  115. The the time value of an ASN1 time object.
  116. @param boundary: An ASN1_TIME pointer (or an object safely
  117. castable to that type) which will have its value set.
  118. @param when: A string representation of the desired time value.
  119. @raise TypeError: If C{when} is not a L{bytes} string.
  120. @raise ValueError: If C{when} does not represent a time in the required
  121. format.
  122. @raise RuntimeError: If the time value cannot be set for some other
  123. (unspecified) reason.
  124. """
  125. if not isinstance(when, bytes):
  126. raise TypeError("when must be a byte string")
  127. set_result = _lib.ASN1_TIME_set_string(boundary, when)
  128. if set_result == 0:
  129. raise ValueError("Invalid string")
  130. def _get_asn1_time(timestamp):
  131. """
  132. Retrieve the time value of an ASN1 time object.
  133. @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
  134. that type) from which the time value will be retrieved.
  135. @return: The time value from C{timestamp} as a L{bytes} string in a certain
  136. format. Or C{None} if the object contains no time value.
  137. """
  138. string_timestamp = _ffi.cast("ASN1_STRING*", timestamp)
  139. if _lib.ASN1_STRING_length(string_timestamp) == 0:
  140. return None
  141. elif (
  142. _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
  143. ):
  144. return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
  145. else:
  146. generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
  147. _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
  148. if generalized_timestamp[0] == _ffi.NULL:
  149. # This may happen:
  150. # - if timestamp was not an ASN1_TIME
  151. # - if allocating memory for the ASN1_GENERALIZEDTIME failed
  152. # - if a copy of the time data from timestamp cannot be made for
  153. # the newly allocated ASN1_GENERALIZEDTIME
  154. #
  155. # These are difficult to test. cffi enforces the ASN1_TIME type.
  156. # Memory allocation failures are a pain to trigger
  157. # deterministically.
  158. _untested_error("ASN1_TIME_to_generalizedtime")
  159. else:
  160. string_timestamp = _ffi.cast(
  161. "ASN1_STRING*", generalized_timestamp[0]
  162. )
  163. string_data = _lib.ASN1_STRING_data(string_timestamp)
  164. string_result = _ffi.string(string_data)
  165. _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
  166. return string_result
  167. class _X509NameInvalidator(object):
  168. def __init__(self):
  169. self._names = []
  170. def add(self, name):
  171. self._names.append(name)
  172. def clear(self):
  173. for name in self._names:
  174. # Breaks the object, but also prevents UAF!
  175. del name._name
  176. class PKey(object):
  177. """
  178. A class representing an DSA or RSA public key or key pair.
  179. """
  180. _only_public = False
  181. _initialized = True
  182. def __init__(self):
  183. pkey = _lib.EVP_PKEY_new()
  184. self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
  185. self._initialized = False
  186. def to_cryptography_key(self):
  187. """
  188. Export as a ``cryptography`` key.
  189. :rtype: One of ``cryptography``'s `key interfaces`_.
  190. .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
  191. primitives/asymmetric/rsa/#key-interfaces
  192. .. versionadded:: 16.1.0
  193. """
  194. from cryptography.hazmat.primitives.serialization import (
  195. load_der_private_key,
  196. load_der_public_key,
  197. )
  198. backend = _get_backend()
  199. if self._only_public:
  200. der = dump_publickey(FILETYPE_ASN1, self)
  201. return load_der_public_key(der, backend)
  202. else:
  203. der = dump_privatekey(FILETYPE_ASN1, self)
  204. return load_der_private_key(der, None, backend)
  205. @classmethod
  206. def from_cryptography_key(cls, crypto_key):
  207. """
  208. Construct based on a ``cryptography`` *crypto_key*.
  209. :param crypto_key: A ``cryptography`` key.
  210. :type crypto_key: One of ``cryptography``'s `key interfaces`_.
  211. :rtype: PKey
  212. .. versionadded:: 16.1.0
  213. """
  214. if not isinstance(
  215. crypto_key,
  216. (
  217. rsa.RSAPublicKey,
  218. rsa.RSAPrivateKey,
  219. dsa.DSAPublicKey,
  220. dsa.DSAPrivateKey,
  221. ),
  222. ):
  223. raise TypeError("Unsupported key type")
  224. from cryptography.hazmat.primitives.serialization import (
  225. Encoding,
  226. NoEncryption,
  227. PrivateFormat,
  228. PublicFormat,
  229. )
  230. if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
  231. return load_publickey(
  232. FILETYPE_ASN1,
  233. crypto_key.public_bytes(
  234. Encoding.DER, PublicFormat.SubjectPublicKeyInfo
  235. ),
  236. )
  237. else:
  238. der = crypto_key.private_bytes(
  239. Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
  240. )
  241. return load_privatekey(FILETYPE_ASN1, der)
  242. def generate_key(self, type, bits):
  243. """
  244. Generate a key pair of the given type, with the given number of bits.
  245. This generates a key "into" the this object.
  246. :param type: The key type.
  247. :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
  248. :param bits: The number of bits.
  249. :type bits: :py:data:`int` ``>= 0``
  250. :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
  251. of the appropriate type.
  252. :raises ValueError: If the number of bits isn't an integer of
  253. the appropriate size.
  254. :return: ``None``
  255. """
  256. if not isinstance(type, int):
  257. raise TypeError("type must be an integer")
  258. if not isinstance(bits, int):
  259. raise TypeError("bits must be an integer")
  260. if type == TYPE_RSA:
  261. if bits <= 0:
  262. raise ValueError("Invalid number of bits")
  263. # TODO Check error return
  264. exponent = _lib.BN_new()
  265. exponent = _ffi.gc(exponent, _lib.BN_free)
  266. _lib.BN_set_word(exponent, _lib.RSA_F4)
  267. rsa = _lib.RSA_new()
  268. result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
  269. _openssl_assert(result == 1)
  270. result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
  271. _openssl_assert(result == 1)
  272. elif type == TYPE_DSA:
  273. dsa = _lib.DSA_new()
  274. _openssl_assert(dsa != _ffi.NULL)
  275. dsa = _ffi.gc(dsa, _lib.DSA_free)
  276. res = _lib.DSA_generate_parameters_ex(
  277. dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
  278. )
  279. _openssl_assert(res == 1)
  280. _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
  281. _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
  282. else:
  283. raise Error("No such key type")
  284. self._initialized = True
  285. def check(self):
  286. """
  287. Check the consistency of an RSA private key.
  288. This is the Python equivalent of OpenSSL's ``RSA_check_key``.
  289. :return: ``True`` if key is consistent.
  290. :raise OpenSSL.crypto.Error: if the key is inconsistent.
  291. :raise TypeError: if the key is of a type which cannot be checked.
  292. Only RSA keys can currently be checked.
  293. """
  294. if self._only_public:
  295. raise TypeError("public key only")
  296. if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
  297. raise TypeError("key type unsupported")
  298. rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
  299. rsa = _ffi.gc(rsa, _lib.RSA_free)
  300. result = _lib.RSA_check_key(rsa)
  301. if result == 1:
  302. return True
  303. _raise_current_error()
  304. def type(self):
  305. """
  306. Returns the type of the key
  307. :return: The type of the key.
  308. """
  309. return _lib.EVP_PKEY_id(self._pkey)
  310. def bits(self):
  311. """
  312. Returns the number of bits of the key
  313. :return: The number of bits of the key.
  314. """
  315. return _lib.EVP_PKEY_bits(self._pkey)
  316. class _EllipticCurve(object):
  317. """
  318. A representation of a supported elliptic curve.
  319. @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
  320. Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
  321. instances each of which represents one curve supported by the system.
  322. @type _curves: :py:type:`NoneType` or :py:type:`set`
  323. """
  324. _curves = None
  325. def __ne__(self, other):
  326. """
  327. Implement cooperation with the right-hand side argument of ``!=``.
  328. Python 3 seems to have dropped this cooperation in this very narrow
  329. circumstance.
  330. """
  331. if isinstance(other, _EllipticCurve):
  332. return super(_EllipticCurve, self).__ne__(other)
  333. return NotImplemented
  334. @classmethod
  335. def _load_elliptic_curves(cls, lib):
  336. """
  337. Get the curves supported by OpenSSL.
  338. :param lib: The OpenSSL library binding object.
  339. :return: A :py:type:`set` of ``cls`` instances giving the names of the
  340. elliptic curves the underlying library supports.
  341. """
  342. num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
  343. builtin_curves = _ffi.new("EC_builtin_curve[]", num_curves)
  344. # The return value on this call should be num_curves again. We
  345. # could check it to make sure but if it *isn't* then.. what could
  346. # we do? Abort the whole process, I suppose...? -exarkun
  347. lib.EC_get_builtin_curves(builtin_curves, num_curves)
  348. return set(cls.from_nid(lib, c.nid) for c in builtin_curves)
  349. @classmethod
  350. def _get_elliptic_curves(cls, lib):
  351. """
  352. Get, cache, and return the curves supported by OpenSSL.
  353. :param lib: The OpenSSL library binding object.
  354. :return: A :py:type:`set` of ``cls`` instances giving the names of the
  355. elliptic curves the underlying library supports.
  356. """
  357. if cls._curves is None:
  358. cls._curves = cls._load_elliptic_curves(lib)
  359. return cls._curves
  360. @classmethod
  361. def from_nid(cls, lib, nid):
  362. """
  363. Instantiate a new :py:class:`_EllipticCurve` associated with the given
  364. OpenSSL NID.
  365. :param lib: The OpenSSL library binding object.
  366. :param nid: The OpenSSL NID the resulting curve object will represent.
  367. This must be a curve NID (and not, for example, a hash NID) or
  368. subsequent operations will fail in unpredictable ways.
  369. :type nid: :py:class:`int`
  370. :return: The curve object.
  371. """
  372. return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
  373. def __init__(self, lib, nid, name):
  374. """
  375. :param _lib: The :py:mod:`cryptography` binding instance used to
  376. interface with OpenSSL.
  377. :param _nid: The OpenSSL NID identifying the curve this object
  378. represents.
  379. :type _nid: :py:class:`int`
  380. :param name: The OpenSSL short name identifying the curve this object
  381. represents.
  382. :type name: :py:class:`unicode`
  383. """
  384. self._lib = lib
  385. self._nid = nid
  386. self.name = name
  387. def __repr__(self):
  388. return "<Curve %r>" % (self.name,)
  389. def _to_EC_KEY(self):
  390. """
  391. Create a new OpenSSL EC_KEY structure initialized to use this curve.
  392. The structure is automatically garbage collected when the Python object
  393. is garbage collected.
  394. """
  395. key = self._lib.EC_KEY_new_by_curve_name(self._nid)
  396. return _ffi.gc(key, _lib.EC_KEY_free)
  397. def get_elliptic_curves():
  398. """
  399. Return a set of objects representing the elliptic curves supported in the
  400. OpenSSL build in use.
  401. The curve objects have a :py:class:`unicode` ``name`` attribute by which
  402. they identify themselves.
  403. The curve objects are useful as values for the argument accepted by
  404. :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
  405. used for ECDHE key exchange.
  406. """
  407. return _EllipticCurve._get_elliptic_curves(_lib)
  408. def get_elliptic_curve(name):
  409. """
  410. Return a single curve object selected by name.
  411. See :py:func:`get_elliptic_curves` for information about curve objects.
  412. :param name: The OpenSSL short name identifying the curve object to
  413. retrieve.
  414. :type name: :py:class:`unicode`
  415. If the named curve is not supported then :py:class:`ValueError` is raised.
  416. """
  417. for curve in get_elliptic_curves():
  418. if curve.name == name:
  419. return curve
  420. raise ValueError("unknown curve name", name)
  421. class X509Name(object):
  422. """
  423. An X.509 Distinguished Name.
  424. :ivar countryName: The country of the entity.
  425. :ivar C: Alias for :py:attr:`countryName`.
  426. :ivar stateOrProvinceName: The state or province of the entity.
  427. :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
  428. :ivar localityName: The locality of the entity.
  429. :ivar L: Alias for :py:attr:`localityName`.
  430. :ivar organizationName: The organization name of the entity.
  431. :ivar O: Alias for :py:attr:`organizationName`.
  432. :ivar organizationalUnitName: The organizational unit of the entity.
  433. :ivar OU: Alias for :py:attr:`organizationalUnitName`
  434. :ivar commonName: The common name of the entity.
  435. :ivar CN: Alias for :py:attr:`commonName`.
  436. :ivar emailAddress: The e-mail address of the entity.
  437. """
  438. def __init__(self, name):
  439. """
  440. Create a new X509Name, copying the given X509Name instance.
  441. :param name: The name to copy.
  442. :type name: :py:class:`X509Name`
  443. """
  444. name = _lib.X509_NAME_dup(name._name)
  445. self._name = _ffi.gc(name, _lib.X509_NAME_free)
  446. def __setattr__(self, name, value):
  447. if name.startswith("_"):
  448. return super(X509Name, self).__setattr__(name, value)
  449. # Note: we really do not want str subclasses here, so we do not use
  450. # isinstance.
  451. if type(name) is not str:
  452. raise TypeError(
  453. "attribute name must be string, not '%.200s'"
  454. % (type(value).__name__,)
  455. )
  456. nid = _lib.OBJ_txt2nid(_byte_string(name))
  457. if nid == _lib.NID_undef:
  458. try:
  459. _raise_current_error()
  460. except Error:
  461. pass
  462. raise AttributeError("No such attribute")
  463. # If there's an old entry for this NID, remove it
  464. for i in range(_lib.X509_NAME_entry_count(self._name)):
  465. ent = _lib.X509_NAME_get_entry(self._name, i)
  466. ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
  467. ent_nid = _lib.OBJ_obj2nid(ent_obj)
  468. if nid == ent_nid:
  469. ent = _lib.X509_NAME_delete_entry(self._name, i)
  470. _lib.X509_NAME_ENTRY_free(ent)
  471. break
  472. if isinstance(value, str):
  473. value = value.encode("utf-8")
  474. add_result = _lib.X509_NAME_add_entry_by_NID(
  475. self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0
  476. )
  477. if not add_result:
  478. _raise_current_error()
  479. def __getattr__(self, name):
  480. """
  481. Find attribute. An X509Name object has the following attributes:
  482. countryName (alias C), stateOrProvince (alias ST), locality (alias L),
  483. organization (alias O), organizationalUnit (alias OU), commonName
  484. (alias CN) and more...
  485. """
  486. nid = _lib.OBJ_txt2nid(_byte_string(name))
  487. if nid == _lib.NID_undef:
  488. # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
  489. # a lower level function, a2d_ASN1_OBJECT, also feels the need to
  490. # push something onto the error queue. If we don't clean that up
  491. # now, someone else will bump into it later and be quite confused.
  492. # See lp#314814.
  493. try:
  494. _raise_current_error()
  495. except Error:
  496. pass
  497. return super(X509Name, self).__getattr__(name)
  498. entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
  499. if entry_index == -1:
  500. return None
  501. entry = _lib.X509_NAME_get_entry(self._name, entry_index)
  502. data = _lib.X509_NAME_ENTRY_get_data(entry)
  503. result_buffer = _ffi.new("unsigned char**")
  504. data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
  505. _openssl_assert(data_length >= 0)
  506. try:
  507. result = _ffi.buffer(result_buffer[0], data_length)[:].decode(
  508. "utf-8"
  509. )
  510. finally:
  511. # XXX untested
  512. _lib.OPENSSL_free(result_buffer[0])
  513. return result
  514. def _cmp(op):
  515. def f(self, other):
  516. if not isinstance(other, X509Name):
  517. return NotImplemented
  518. result = _lib.X509_NAME_cmp(self._name, other._name)
  519. return op(result, 0)
  520. return f
  521. __eq__ = _cmp(__eq__)
  522. __ne__ = _cmp(__ne__)
  523. __lt__ = _cmp(__lt__)
  524. __le__ = _cmp(__le__)
  525. __gt__ = _cmp(__gt__)
  526. __ge__ = _cmp(__ge__)
  527. def __repr__(self):
  528. """
  529. String representation of an X509Name
  530. """
  531. result_buffer = _ffi.new("char[]", 512)
  532. format_result = _lib.X509_NAME_oneline(
  533. self._name, result_buffer, len(result_buffer)
  534. )
  535. _openssl_assert(format_result != _ffi.NULL)
  536. return "<X509Name object '%s'>" % (
  537. _ffi.string(result_buffer).decode("utf-8"),
  538. )
  539. def hash(self):
  540. """
  541. Return an integer representation of the first four bytes of the
  542. MD5 digest of the DER representation of the name.
  543. This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
  544. :return: The (integer) hash of this name.
  545. :rtype: :py:class:`int`
  546. """
  547. return _lib.X509_NAME_hash(self._name)
  548. def der(self):
  549. """
  550. Return the DER encoding of this name.
  551. :return: The DER encoded form of this name.
  552. :rtype: :py:class:`bytes`
  553. """
  554. result_buffer = _ffi.new("unsigned char**")
  555. encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
  556. _openssl_assert(encode_result >= 0)
  557. string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
  558. _lib.OPENSSL_free(result_buffer[0])
  559. return string_result
  560. def get_components(self):
  561. """
  562. Returns the components of this name, as a sequence of 2-tuples.
  563. :return: The components of this name.
  564. :rtype: :py:class:`list` of ``name, value`` tuples.
  565. """
  566. result = []
  567. for i in range(_lib.X509_NAME_entry_count(self._name)):
  568. ent = _lib.X509_NAME_get_entry(self._name, i)
  569. fname = _lib.X509_NAME_ENTRY_get_object(ent)
  570. fval = _lib.X509_NAME_ENTRY_get_data(ent)
  571. nid = _lib.OBJ_obj2nid(fname)
  572. name = _lib.OBJ_nid2sn(nid)
  573. # ffi.string does not handle strings containing NULL bytes
  574. # (which may have been generated by old, broken software)
  575. value = _ffi.buffer(
  576. _lib.ASN1_STRING_data(fval), _lib.ASN1_STRING_length(fval)
  577. )[:]
  578. result.append((_ffi.string(name), value))
  579. return result
  580. class X509Extension(object):
  581. """
  582. An X.509 v3 certificate extension.
  583. """
  584. def __init__(self, type_name, critical, value, subject=None, issuer=None):
  585. """
  586. Initializes an X509 extension.
  587. :param type_name: The name of the type of extension_ to create.
  588. :type type_name: :py:data:`bytes`
  589. :param bool critical: A flag indicating whether this is a critical
  590. extension.
  591. :param value: The value of the extension.
  592. :type value: :py:data:`bytes`
  593. :param subject: Optional X509 certificate to use as subject.
  594. :type subject: :py:class:`X509`
  595. :param issuer: Optional X509 certificate to use as issuer.
  596. :type issuer: :py:class:`X509`
  597. .. _extension: https://www.openssl.org/docs/manmaster/man5/
  598. x509v3_config.html#STANDARD-EXTENSIONS
  599. """
  600. ctx = _ffi.new("X509V3_CTX*")
  601. # A context is necessary for any extension which uses the r2i
  602. # conversion method. That is, X509V3_EXT_nconf may segfault if passed
  603. # a NULL ctx. Start off by initializing most of the fields to NULL.
  604. _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
  605. # We have no configuration database - but perhaps we should (some
  606. # extensions may require it).
  607. _lib.X509V3_set_ctx_nodb(ctx)
  608. # Initialize the subject and issuer, if appropriate. ctx is a local,
  609. # and as far as I can tell none of the X509V3_* APIs invoked here steal
  610. # any references, so no need to mess with reference counts or
  611. # duplicates.
  612. if issuer is not None:
  613. if not isinstance(issuer, X509):
  614. raise TypeError("issuer must be an X509 instance")
  615. ctx.issuer_cert = issuer._x509
  616. if subject is not None:
  617. if not isinstance(subject, X509):
  618. raise TypeError("subject must be an X509 instance")
  619. ctx.subject_cert = subject._x509
  620. if critical:
  621. # There are other OpenSSL APIs which would let us pass in critical
  622. # separately, but they're harder to use, and since value is already
  623. # a pile of crappy junk smuggling a ton of utterly important
  624. # structured data, what's the point of trying to avoid nasty stuff
  625. # with strings? (However, X509V3_EXT_i2d in particular seems like
  626. # it would be a better API to invoke. I do not know where to get
  627. # the ext_struc it desires for its last parameter, though.)
  628. value = b"critical," + value
  629. extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
  630. if extension == _ffi.NULL:
  631. _raise_current_error()
  632. self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
  633. @property
  634. def _nid(self):
  635. return _lib.OBJ_obj2nid(
  636. _lib.X509_EXTENSION_get_object(self._extension)
  637. )
  638. _prefixes = {
  639. _lib.GEN_EMAIL: "email",
  640. _lib.GEN_DNS: "DNS",
  641. _lib.GEN_URI: "URI",
  642. }
  643. def _subjectAltNameString(self):
  644. names = _ffi.cast(
  645. "GENERAL_NAMES*", _lib.X509V3_EXT_d2i(self._extension)
  646. )
  647. names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
  648. parts = []
  649. for i in range(_lib.sk_GENERAL_NAME_num(names)):
  650. name = _lib.sk_GENERAL_NAME_value(names, i)
  651. try:
  652. label = self._prefixes[name.type]
  653. except KeyError:
  654. bio = _new_mem_buf()
  655. _lib.GENERAL_NAME_print(bio, name)
  656. parts.append(_bio_to_string(bio).decode("utf-8"))
  657. else:
  658. value = _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[
  659. :
  660. ].decode("utf-8")
  661. parts.append(label + ":" + value)
  662. return ", ".join(parts)
  663. def __str__(self):
  664. """
  665. :return: a nice text representation of the extension
  666. """
  667. if _lib.NID_subject_alt_name == self._nid:
  668. return self._subjectAltNameString()
  669. bio = _new_mem_buf()
  670. print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
  671. _openssl_assert(print_result != 0)
  672. return _bio_to_string(bio).decode("utf-8")
  673. def get_critical(self):
  674. """
  675. Returns the critical field of this X.509 extension.
  676. :return: The critical field.
  677. """
  678. return _lib.X509_EXTENSION_get_critical(self._extension)
  679. def get_short_name(self):
  680. """
  681. Returns the short type name of this X.509 extension.
  682. The result is a byte string such as :py:const:`b"basicConstraints"`.
  683. :return: The short type name.
  684. :rtype: :py:data:`bytes`
  685. .. versionadded:: 0.12
  686. """
  687. obj = _lib.X509_EXTENSION_get_object(self._extension)
  688. nid = _lib.OBJ_obj2nid(obj)
  689. return _ffi.string(_lib.OBJ_nid2sn(nid))
  690. def get_data(self):
  691. """
  692. Returns the data of the X509 extension, encoded as ASN.1.
  693. :return: The ASN.1 encoded data of this X509 extension.
  694. :rtype: :py:data:`bytes`
  695. .. versionadded:: 0.12
  696. """
  697. octet_result = _lib.X509_EXTENSION_get_data(self._extension)
  698. string_result = _ffi.cast("ASN1_STRING*", octet_result)
  699. char_result = _lib.ASN1_STRING_data(string_result)
  700. result_length = _lib.ASN1_STRING_length(string_result)
  701. return _ffi.buffer(char_result, result_length)[:]
  702. class X509Req(object):
  703. """
  704. An X.509 certificate signing requests.
  705. """
  706. def __init__(self):
  707. req = _lib.X509_REQ_new()
  708. self._req = _ffi.gc(req, _lib.X509_REQ_free)
  709. # Default to version 0.
  710. self.set_version(0)
  711. def to_cryptography(self):
  712. """
  713. Export as a ``cryptography`` certificate signing request.
  714. :rtype: ``cryptography.x509.CertificateSigningRequest``
  715. .. versionadded:: 17.1.0
  716. """
  717. from cryptography.x509 import load_der_x509_csr
  718. der = dump_certificate_request(FILETYPE_ASN1, self)
  719. backend = _get_backend()
  720. return load_der_x509_csr(der, backend)
  721. @classmethod
  722. def from_cryptography(cls, crypto_req):
  723. """
  724. Construct based on a ``cryptography`` *crypto_req*.
  725. :param crypto_req: A ``cryptography`` X.509 certificate signing request
  726. :type crypto_req: ``cryptography.x509.CertificateSigningRequest``
  727. :rtype: X509Req
  728. .. versionadded:: 17.1.0
  729. """
  730. if not isinstance(crypto_req, x509.CertificateSigningRequest):
  731. raise TypeError("Must be a certificate signing request")
  732. from cryptography.hazmat.primitives.serialization import Encoding
  733. der = crypto_req.public_bytes(Encoding.DER)
  734. return load_certificate_request(FILETYPE_ASN1, der)
  735. def set_pubkey(self, pkey):
  736. """
  737. Set the public key of the certificate signing request.
  738. :param pkey: The public key to use.
  739. :type pkey: :py:class:`PKey`
  740. :return: ``None``
  741. """
  742. set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
  743. _openssl_assert(set_result == 1)
  744. def get_pubkey(self):
  745. """
  746. Get the public key of the certificate signing request.
  747. :return: The public key.
  748. :rtype: :py:class:`PKey`
  749. """
  750. pkey = PKey.__new__(PKey)
  751. pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
  752. _openssl_assert(pkey._pkey != _ffi.NULL)
  753. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  754. pkey._only_public = True
  755. return pkey
  756. def set_version(self, version):
  757. """
  758. Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
  759. request.
  760. :param int version: The version number.
  761. :return: ``None``
  762. """
  763. set_result = _lib.X509_REQ_set_version(self._req, version)
  764. _openssl_assert(set_result == 1)
  765. def get_version(self):
  766. """
  767. Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
  768. request.
  769. :return: The value of the version subfield.
  770. :rtype: :py:class:`int`
  771. """
  772. return _lib.X509_REQ_get_version(self._req)
  773. def get_subject(self):
  774. """
  775. Return the subject of this certificate signing request.
  776. This creates a new :class:`X509Name` that wraps the underlying subject
  777. name field on the certificate signing request. Modifying it will modify
  778. the underlying signing request, and will have the effect of modifying
  779. any other :class:`X509Name` that refers to this subject.
  780. :return: The subject of this certificate signing request.
  781. :rtype: :class:`X509Name`
  782. """
  783. name = X509Name.__new__(X509Name)
  784. name._name = _lib.X509_REQ_get_subject_name(self._req)
  785. _openssl_assert(name._name != _ffi.NULL)
  786. # The name is owned by the X509Req structure. As long as the X509Name
  787. # Python object is alive, keep the X509Req Python object alive.
  788. name._owner = self
  789. return name
  790. def add_extensions(self, extensions):
  791. """
  792. Add extensions to the certificate signing request.
  793. :param extensions: The X.509 extensions to add.
  794. :type extensions: iterable of :py:class:`X509Extension`
  795. :return: ``None``
  796. """
  797. stack = _lib.sk_X509_EXTENSION_new_null()
  798. _openssl_assert(stack != _ffi.NULL)
  799. stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
  800. for ext in extensions:
  801. if not isinstance(ext, X509Extension):
  802. raise ValueError("One of the elements is not an X509Extension")
  803. # TODO push can fail (here and elsewhere)
  804. _lib.sk_X509_EXTENSION_push(stack, ext._extension)
  805. add_result = _lib.X509_REQ_add_extensions(self._req, stack)
  806. _openssl_assert(add_result == 1)
  807. def get_extensions(self):
  808. """
  809. Get X.509 extensions in the certificate signing request.
  810. :return: The X.509 extensions in this request.
  811. :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
  812. .. versionadded:: 0.15
  813. """
  814. exts = []
  815. native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
  816. native_exts_obj = _ffi.gc(
  817. native_exts_obj,
  818. lambda x: _lib.sk_X509_EXTENSION_pop_free(
  819. x,
  820. _ffi.addressof(_lib._original_lib, "X509_EXTENSION_free"),
  821. ),
  822. )
  823. for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
  824. ext = X509Extension.__new__(X509Extension)
  825. extension = _lib.X509_EXTENSION_dup(
  826. _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
  827. )
  828. ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
  829. exts.append(ext)
  830. return exts
  831. def sign(self, pkey, digest):
  832. """
  833. Sign the certificate signing request with this key and digest type.
  834. :param pkey: The key pair to sign with.
  835. :type pkey: :py:class:`PKey`
  836. :param digest: The name of the message digest to use for the signature,
  837. e.g. :py:data:`"sha256"`.
  838. :type digest: :py:class:`str`
  839. :return: ``None``
  840. """
  841. if pkey._only_public:
  842. raise ValueError("Key has only public part")
  843. if not pkey._initialized:
  844. raise ValueError("Key is uninitialized")
  845. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  846. if digest_obj == _ffi.NULL:
  847. raise ValueError("No such digest method")
  848. sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
  849. _openssl_assert(sign_result > 0)
  850. def verify(self, pkey):
  851. """
  852. Verifies the signature on this certificate signing request.
  853. :param PKey key: A public key.
  854. :return: ``True`` if the signature is correct.
  855. :rtype: bool
  856. :raises OpenSSL.crypto.Error: If the signature is invalid or there is a
  857. problem verifying the signature.
  858. """
  859. if not isinstance(pkey, PKey):
  860. raise TypeError("pkey must be a PKey instance")
  861. result = _lib.X509_REQ_verify(self._req, pkey._pkey)
  862. if result <= 0:
  863. _raise_current_error()
  864. return result
  865. class X509(object):
  866. """
  867. An X.509 certificate.
  868. """
  869. def __init__(self):
  870. x509 = _lib.X509_new()
  871. _openssl_assert(x509 != _ffi.NULL)
  872. self._x509 = _ffi.gc(x509, _lib.X509_free)
  873. self._issuer_invalidator = _X509NameInvalidator()
  874. self._subject_invalidator = _X509NameInvalidator()
  875. @classmethod
  876. def _from_raw_x509_ptr(cls, x509):
  877. cert = cls.__new__(cls)
  878. cert._x509 = _ffi.gc(x509, _lib.X509_free)
  879. cert._issuer_invalidator = _X509NameInvalidator()
  880. cert._subject_invalidator = _X509NameInvalidator()
  881. return cert
  882. def to_cryptography(self):
  883. """
  884. Export as a ``cryptography`` certificate.
  885. :rtype: ``cryptography.x509.Certificate``
  886. .. versionadded:: 17.1.0
  887. """
  888. from cryptography.x509 import load_der_x509_certificate
  889. der = dump_certificate(FILETYPE_ASN1, self)
  890. backend = _get_backend()
  891. return load_der_x509_certificate(der, backend)
  892. @classmethod
  893. def from_cryptography(cls, crypto_cert):
  894. """
  895. Construct based on a ``cryptography`` *crypto_cert*.
  896. :param crypto_key: A ``cryptography`` X.509 certificate.
  897. :type crypto_key: ``cryptography.x509.Certificate``
  898. :rtype: X509
  899. .. versionadded:: 17.1.0
  900. """
  901. if not isinstance(crypto_cert, x509.Certificate):
  902. raise TypeError("Must be a certificate")
  903. from cryptography.hazmat.primitives.serialization import Encoding
  904. der = crypto_cert.public_bytes(Encoding.DER)
  905. return load_certificate(FILETYPE_ASN1, der)
  906. def set_version(self, version):
  907. """
  908. Set the version number of the certificate. Note that the
  909. version value is zero-based, eg. a value of 0 is V1.
  910. :param version: The version number of the certificate.
  911. :type version: :py:class:`int`
  912. :return: ``None``
  913. """
  914. if not isinstance(version, int):
  915. raise TypeError("version must be an integer")
  916. _lib.X509_set_version(self._x509, version)
  917. def get_version(self):
  918. """
  919. Return the version number of the certificate.
  920. :return: The version number of the certificate.
  921. :rtype: :py:class:`int`
  922. """
  923. return _lib.X509_get_version(self._x509)
  924. def get_pubkey(self):
  925. """
  926. Get the public key of the certificate.
  927. :return: The public key.
  928. :rtype: :py:class:`PKey`
  929. """
  930. pkey = PKey.__new__(PKey)
  931. pkey._pkey = _lib.X509_get_pubkey(self._x509)
  932. if pkey._pkey == _ffi.NULL:
  933. _raise_current_error()
  934. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  935. pkey._only_public = True
  936. return pkey
  937. def set_pubkey(self, pkey):
  938. """
  939. Set the public key of the certificate.
  940. :param pkey: The public key.
  941. :type pkey: :py:class:`PKey`
  942. :return: :py:data:`None`
  943. """
  944. if not isinstance(pkey, PKey):
  945. raise TypeError("pkey must be a PKey instance")
  946. set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
  947. _openssl_assert(set_result == 1)
  948. def sign(self, pkey, digest):
  949. """
  950. Sign the certificate with this key and digest type.
  951. :param pkey: The key to sign with.
  952. :type pkey: :py:class:`PKey`
  953. :param digest: The name of the message digest to use.
  954. :type digest: :py:class:`str`
  955. :return: :py:data:`None`
  956. """
  957. if not isinstance(pkey, PKey):
  958. raise TypeError("pkey must be a PKey instance")
  959. if pkey._only_public:
  960. raise ValueError("Key only has public part")
  961. if not pkey._initialized:
  962. raise ValueError("Key is uninitialized")
  963. evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
  964. if evp_md == _ffi.NULL:
  965. raise ValueError("No such digest method")
  966. sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
  967. _openssl_assert(sign_result > 0)
  968. def get_signature_algorithm(self):
  969. """
  970. Return the signature algorithm used in the certificate.
  971. :return: The name of the algorithm.
  972. :rtype: :py:class:`bytes`
  973. :raises ValueError: If the signature algorithm is undefined.
  974. .. versionadded:: 0.13
  975. """
  976. algor = _lib.X509_get0_tbs_sigalg(self._x509)
  977. nid = _lib.OBJ_obj2nid(algor.algorithm)
  978. if nid == _lib.NID_undef:
  979. raise ValueError("Undefined signature algorithm")
  980. return _ffi.string(_lib.OBJ_nid2ln(nid))
  981. def digest(self, digest_name):
  982. """
  983. Return the digest of the X509 object.
  984. :param digest_name: The name of the digest algorithm to use.
  985. :type digest_name: :py:class:`str`
  986. :return: The digest of the object, formatted as
  987. :py:const:`b":"`-delimited hex pairs.
  988. :rtype: :py:class:`bytes`
  989. """
  990. digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
  991. if digest == _ffi.NULL:
  992. raise ValueError("No such digest method")
  993. result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
  994. result_length = _ffi.new("unsigned int[]", 1)
  995. result_length[0] = len(result_buffer)
  996. digest_result = _lib.X509_digest(
  997. self._x509, digest, result_buffer, result_length
  998. )
  999. _openssl_assert(digest_result == 1)
  1000. return b":".join(
  1001. [
  1002. b16encode(ch).upper()
  1003. for ch in _ffi.buffer(result_buffer, result_length[0])
  1004. ]
  1005. )
  1006. def subject_name_hash(self):
  1007. """
  1008. Return the hash of the X509 subject.
  1009. :return: The hash of the subject.
  1010. :rtype: :py:class:`bytes`
  1011. """
  1012. return _lib.X509_subject_name_hash(self._x509)
  1013. def set_serial_number(self, serial):
  1014. """
  1015. Set the serial number of the certificate.
  1016. :param serial: The new serial number.
  1017. :type serial: :py:class:`int`
  1018. :return: :py:data`None`
  1019. """
  1020. if not isinstance(serial, int):
  1021. raise TypeError("serial must be an integer")
  1022. hex_serial = hex(serial)[2:]
  1023. if not isinstance(hex_serial, bytes):
  1024. hex_serial = hex_serial.encode("ascii")
  1025. bignum_serial = _ffi.new("BIGNUM**")
  1026. # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
  1027. # it. If bignum is still NULL after this call, then the return value
  1028. # is actually the result. I hope. -exarkun
  1029. small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
  1030. if bignum_serial[0] == _ffi.NULL:
  1031. set_result = _lib.ASN1_INTEGER_set(
  1032. _lib.X509_get_serialNumber(self._x509), small_serial
  1033. )
  1034. if set_result:
  1035. # TODO Not tested
  1036. _raise_current_error()
  1037. else:
  1038. asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
  1039. _lib.BN_free(bignum_serial[0])
  1040. if asn1_serial == _ffi.NULL:
  1041. # TODO Not tested
  1042. _raise_current_error()
  1043. asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
  1044. set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
  1045. _openssl_assert(set_result == 1)
  1046. def get_serial_number(self):
  1047. """
  1048. Return the serial number of this certificate.
  1049. :return: The serial number.
  1050. :rtype: int
  1051. """
  1052. asn1_serial = _lib.X509_get_serialNumber(self._x509)
  1053. bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
  1054. try:
  1055. hex_serial = _lib.BN_bn2hex(bignum_serial)
  1056. try:
  1057. hexstring_serial = _ffi.string(hex_serial)
  1058. serial = int(hexstring_serial, 16)
  1059. return serial
  1060. finally:
  1061. _lib.OPENSSL_free(hex_serial)
  1062. finally:
  1063. _lib.BN_free(bignum_serial)
  1064. def gmtime_adj_notAfter(self, amount):
  1065. """
  1066. Adjust the time stamp on which the certificate stops being valid.
  1067. :param int amount: The number of seconds by which to adjust the
  1068. timestamp.
  1069. :return: ``None``
  1070. """
  1071. if not isinstance(amount, int):
  1072. raise TypeError("amount must be an integer")
  1073. notAfter = _lib.X509_getm_notAfter(self._x509)
  1074. _lib.X509_gmtime_adj(notAfter, amount)
  1075. def gmtime_adj_notBefore(self, amount):
  1076. """
  1077. Adjust the timestamp on which the certificate starts being valid.
  1078. :param amount: The number of seconds by which to adjust the timestamp.
  1079. :return: ``None``
  1080. """
  1081. if not isinstance(amount, int):
  1082. raise TypeError("amount must be an integer")
  1083. notBefore = _lib.X509_getm_notBefore(self._x509)
  1084. _lib.X509_gmtime_adj(notBefore, amount)
  1085. def has_expired(self):
  1086. """
  1087. Check whether the certificate has expired.
  1088. :return: ``True`` if the certificate has expired, ``False`` otherwise.
  1089. :rtype: bool
  1090. """
  1091. time_string = self.get_notAfter().decode("utf-8")
  1092. not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
  1093. return not_after < datetime.datetime.utcnow()
  1094. def _get_boundary_time(self, which):
  1095. return _get_asn1_time(which(self._x509))
  1096. def get_notBefore(self):
  1097. """
  1098. Get the timestamp at which the certificate starts being valid.
  1099. The timestamp is formatted as an ASN.1 TIME::
  1100. YYYYMMDDhhmmssZ
  1101. :return: A timestamp string, or ``None`` if there is none.
  1102. :rtype: bytes or NoneType
  1103. """
  1104. return self._get_boundary_time(_lib.X509_getm_notBefore)
  1105. def _set_boundary_time(self, which, when):
  1106. return _set_asn1_time(which(self._x509), when)
  1107. def set_notBefore(self, when):
  1108. """
  1109. Set the timestamp at which the certificate starts being valid.
  1110. The timestamp is formatted as an ASN.1 TIME::
  1111. YYYYMMDDhhmmssZ
  1112. :param bytes when: A timestamp string.
  1113. :return: ``None``
  1114. """
  1115. return self._set_boundary_time(_lib.X509_getm_notBefore, when)
  1116. def get_notAfter(self):
  1117. """
  1118. Get the timestamp at which the certificate stops being valid.
  1119. The timestamp is formatted as an ASN.1 TIME::
  1120. YYYYMMDDhhmmssZ
  1121. :return: A timestamp string, or ``None`` if there is none.
  1122. :rtype: bytes or NoneType
  1123. """
  1124. return self._get_boundary_time(_lib.X509_getm_notAfter)
  1125. def set_notAfter(self, when):
  1126. """
  1127. Set the timestamp at which the certificate stops being valid.
  1128. The timestamp is formatted as an ASN.1 TIME::
  1129. YYYYMMDDhhmmssZ
  1130. :param bytes when: A timestamp string.
  1131. :return: ``None``
  1132. """
  1133. return self._set_boundary_time(_lib.X509_getm_notAfter, when)
  1134. def _get_name(self, which):
  1135. name = X509Name.__new__(X509Name)
  1136. name._name = which(self._x509)
  1137. _openssl_assert(name._name != _ffi.NULL)
  1138. # The name is owned by the X509 structure. As long as the X509Name
  1139. # Python object is alive, keep the X509 Python object alive.
  1140. name._owner = self
  1141. return name
  1142. def _set_name(self, which, name):
  1143. if not isinstance(name, X509Name):
  1144. raise TypeError("name must be an X509Name")
  1145. set_result = which(self._x509, name._name)
  1146. _openssl_assert(set_result == 1)
  1147. def get_issuer(self):
  1148. """
  1149. Return the issuer of this certificate.
  1150. This creates a new :class:`X509Name` that wraps the underlying issuer
  1151. name field on the certificate. Modifying it will modify the underlying
  1152. certificate, and will have the effect of modifying any other
  1153. :class:`X509Name` that refers to this issuer.
  1154. :return: The issuer of this certificate.
  1155. :rtype: :class:`X509Name`
  1156. """
  1157. name = self._get_name(_lib.X509_get_issuer_name)
  1158. self._issuer_invalidator.add(name)
  1159. return name
  1160. def set_issuer(self, issuer):
  1161. """
  1162. Set the issuer of this certificate.
  1163. :param issuer: The issuer.
  1164. :type issuer: :py:class:`X509Name`
  1165. :return: ``None``
  1166. """
  1167. self._set_name(_lib.X509_set_issuer_name, issuer)
  1168. self._issuer_invalidator.clear()
  1169. def get_subject(self):
  1170. """
  1171. Return the subject of this certificate.
  1172. This creates a new :class:`X509Name` that wraps the underlying subject
  1173. name field on the certificate. Modifying it will modify the underlying
  1174. certificate, and will have the effect of modifying any other
  1175. :class:`X509Name` that refers to this subject.
  1176. :return: The subject of this certificate.
  1177. :rtype: :class:`X509Name`
  1178. """
  1179. name = self._get_name(_lib.X509_get_subject_name)
  1180. self._subject_invalidator.add(name)
  1181. return name
  1182. def set_subject(self, subject):
  1183. """
  1184. Set the subject of this certificate.
  1185. :param subject: The subject.
  1186. :type subject: :py:class:`X509Name`
  1187. :return: ``None``
  1188. """
  1189. self._set_name(_lib.X509_set_subject_name, subject)
  1190. self._subject_invalidator.clear()
  1191. def get_extension_count(self):
  1192. """
  1193. Get the number of extensions on this certificate.
  1194. :return: The number of extensions.
  1195. :rtype: :py:class:`int`
  1196. .. versionadded:: 0.12
  1197. """
  1198. return _lib.X509_get_ext_count(self._x509)
  1199. def add_extensions(self, extensions):
  1200. """
  1201. Add extensions to the certificate.
  1202. :param extensions: The extensions to add.
  1203. :type extensions: An iterable of :py:class:`X509Extension` objects.
  1204. :return: ``None``
  1205. """
  1206. for ext in extensions:
  1207. if not isinstance(ext, X509Extension):
  1208. raise ValueError("One of the elements is not an X509Extension")
  1209. add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
  1210. if not add_result:
  1211. _raise_current_error()
  1212. def get_extension(self, index):
  1213. """
  1214. Get a specific extension of the certificate by index.
  1215. Extensions on a certificate are kept in order. The index
  1216. parameter selects which extension will be returned.
  1217. :param int index: The index of the extension to retrieve.
  1218. :return: The extension at the specified index.
  1219. :rtype: :py:class:`X509Extension`
  1220. :raises IndexError: If the extension index was out of bounds.
  1221. .. versionadded:: 0.12
  1222. """
  1223. ext = X509Extension.__new__(X509Extension)
  1224. ext._extension = _lib.X509_get_ext(self._x509, index)
  1225. if ext._extension == _ffi.NULL:
  1226. raise IndexError("extension index out of bounds")
  1227. extension = _lib.X509_EXTENSION_dup(ext._extension)
  1228. ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
  1229. return ext
  1230. class X509StoreFlags(object):
  1231. """
  1232. Flags for X509 verification, used to change the behavior of
  1233. :class:`X509Store`.
  1234. See `OpenSSL Verification Flags`_ for details.
  1235. .. _OpenSSL Verification Flags:
  1236. https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html
  1237. """
  1238. CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
  1239. CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
  1240. IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
  1241. X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
  1242. ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
  1243. POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
  1244. EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
  1245. INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
  1246. NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
  1247. CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
  1248. class X509Store(object):
  1249. """
  1250. An X.509 store.
  1251. An X.509 store is used to describe a context in which to verify a
  1252. certificate. A description of a context may include a set of certificates
  1253. to trust, a set of certificate revocation lists, verification flags and
  1254. more.
  1255. An X.509 store, being only a description, cannot be used by itself to
  1256. verify a certificate. To carry out the actual verification process, see
  1257. :class:`X509StoreContext`.
  1258. """
  1259. def __init__(self):
  1260. store = _lib.X509_STORE_new()
  1261. self._store = _ffi.gc(store, _lib.X509_STORE_free)
  1262. def add_cert(self, cert):
  1263. """
  1264. Adds a trusted certificate to this store.
  1265. Adding a certificate with this method adds this certificate as a
  1266. *trusted* certificate.
  1267. :param X509 cert: The certificate to add to this store.
  1268. :raises TypeError: If the certificate is not an :class:`X509`.
  1269. :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your
  1270. certificate.
  1271. :return: ``None`` if the certificate was added successfully.
  1272. """
  1273. if not isinstance(cert, X509):
  1274. raise TypeError()
  1275. res = _lib.X509_STORE_add_cert(self._store, cert._x509)
  1276. _openssl_assert(res == 1)
  1277. def add_crl(self, crl):
  1278. """
  1279. Add a certificate revocation list to this store.
  1280. The certificate revocation lists added to a store will only be used if
  1281. the associated flags are configured to check certificate revocation
  1282. lists.
  1283. .. versionadded:: 16.1.0
  1284. :param CRL crl: The certificate revocation list to add to this store.
  1285. :return: ``None`` if the certificate revocation list was added
  1286. successfully.
  1287. """
  1288. _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
  1289. def set_flags(self, flags):
  1290. """
  1291. Set verification flags to this store.
  1292. Verification flags can be combined by oring them together.
  1293. .. note::
  1294. Setting a verification flag sometimes requires clients to add
  1295. additional information to the store, otherwise a suitable error will
  1296. be raised.
  1297. For example, in setting flags to enable CRL checking a
  1298. suitable CRL must be added to the store otherwise an error will be
  1299. raised.
  1300. .. versionadded:: 16.1.0
  1301. :param int flags: The verification flags to set on this store.
  1302. See :class:`X509StoreFlags` for available constants.
  1303. :return: ``None`` if the verification flags were successfully set.
  1304. """
  1305. _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
  1306. def set_time(self, vfy_time):
  1307. """
  1308. Set the time against which the certificates are verified.
  1309. Normally the current time is used.
  1310. .. note::
  1311. For example, you can determine if a certificate was valid at a given
  1312. time.
  1313. .. versionadded:: 17.0.0
  1314. :param datetime vfy_time: The verification time to set on this store.
  1315. :return: ``None`` if the verification time was successfully set.
  1316. """
  1317. param = _lib.X509_VERIFY_PARAM_new()
  1318. param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
  1319. _lib.X509_VERIFY_PARAM_set_time(
  1320. param, calendar.timegm(vfy_time.timetuple())
  1321. )
  1322. _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
  1323. def load_locations(self, cafile, capath=None):
  1324. """
  1325. Let X509Store know where we can find trusted certificates for the
  1326. certificate chain. Note that the certificates have to be in PEM
  1327. format.
  1328. If *capath* is passed, it must be a directory prepared using the
  1329. ``c_rehash`` tool included with OpenSSL. Either, but not both, of
  1330. *cafile* or *capath* may be ``None``.
  1331. .. note::
  1332. Both *cafile* and *capath* may be set simultaneously.
  1333. Call this method multiple times to add more than one location.
  1334. For example, CA certificates, and certificate revocation list bundles
  1335. may be passed in *cafile* in subsequent calls to this method.
  1336. .. versionadded:: 20.0
  1337. :param cafile: In which file we can find the certificates (``bytes`` or
  1338. ``unicode``).
  1339. :param capath: In which directory we can find the certificates
  1340. (``bytes`` or ``unicode``).
  1341. :return: ``None`` if the locations were set successfully.
  1342. :raises OpenSSL.crypto.Error: If both *cafile* and *capath* is ``None``
  1343. or the locations could not be set for any reason.
  1344. """
  1345. if cafile is None:
  1346. cafile = _ffi.NULL
  1347. else:
  1348. cafile = _path_bytes(cafile)
  1349. if capath is None:
  1350. capath = _ffi.NULL
  1351. else:
  1352. capath = _path_bytes(capath)
  1353. load_result = _lib.X509_STORE_load_locations(
  1354. self._store, cafile, capath
  1355. )
  1356. if not load_result:
  1357. _raise_current_error()
  1358. class X509StoreContextError(Exception):
  1359. """
  1360. An exception raised when an error occurred while verifying a certificate
  1361. using `OpenSSL.X509StoreContext.verify_certificate`.
  1362. :ivar certificate: The certificate which caused verificate failure.
  1363. :type certificate: :class:`X509`
  1364. """
  1365. def __init__(self, message, certificate):
  1366. super(X509StoreContextError, self).__init__(message)
  1367. self.certificate = certificate
  1368. class X509StoreContext(object):
  1369. """
  1370. An X.509 store context.
  1371. An X.509 store context is used to carry out the actual verification process
  1372. of a certificate in a described context. For describing such a context, see
  1373. :class:`X509Store`.
  1374. :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
  1375. instance. It is dynamically allocated and automatically garbage
  1376. collected.
  1377. :ivar _store: See the ``store`` ``__init__`` parameter.
  1378. :ivar _cert: See the ``certificate`` ``__init__`` parameter.
  1379. :ivar _chain: See the ``chain`` ``__init__`` parameter.
  1380. :param X509Store store: The certificates which will be trusted for the
  1381. purposes of any verifications.
  1382. :param X509 certificate: The certificate to be verified.
  1383. :param chain: List of untrusted certificates that may be used for building
  1384. the certificate chain. May be ``None``.
  1385. :type chain: :class:`list` of :class:`X509`
  1386. """
  1387. def __init__(self, store, certificate, chain=None):
  1388. store_ctx = _lib.X509_STORE_CTX_new()
  1389. self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
  1390. self._store = store
  1391. self._cert = certificate
  1392. self._chain = self._build_certificate_stack(chain)
  1393. # Make the store context available for use after instantiating this
  1394. # class by initializing it now. Per testing, subsequent calls to
  1395. # :meth:`_init` have no adverse affect.
  1396. self._init()
  1397. @staticmethod
  1398. def _build_certificate_stack(certificates):
  1399. def cleanup(s):
  1400. # Equivalent to sk_X509_pop_free, but we don't
  1401. # currently have a CFFI binding for that available
  1402. for i in range(_lib.sk_X509_num(s)):
  1403. x = _lib.sk_X509_value(s, i)
  1404. _lib.X509_free(x)
  1405. _lib.sk_X509_free(s)
  1406. if certificates is None or len(certificates) == 0:
  1407. return _ffi.NULL
  1408. stack = _lib.sk_X509_new_null()
  1409. _openssl_assert(stack != _ffi.NULL)
  1410. stack = _ffi.gc(stack, cleanup)
  1411. for cert in certificates:
  1412. if not isinstance(cert, X509):
  1413. raise TypeError("One of the elements is not an X509 instance")
  1414. _openssl_assert(_lib.X509_up_ref(cert._x509) > 0)
  1415. if _lib.sk_X509_push(stack, cert._x509) <= 0:
  1416. _lib.X509_free(cert._x509)
  1417. _raise_current_error()
  1418. return stack
  1419. def _init(self):
  1420. """
  1421. Set up the store context for a subsequent verification operation.
  1422. Calling this method more than once without first calling
  1423. :meth:`_cleanup` will leak memory.
  1424. """
  1425. ret = _lib.X509_STORE_CTX_init(
  1426. self._store_ctx, self._store._store, self._cert._x509, self._chain
  1427. )
  1428. if ret <= 0:
  1429. _raise_current_error()
  1430. def _cleanup(self):
  1431. """
  1432. Internally cleans up the store context.
  1433. The store context can then be reused with a new call to :meth:`_init`.
  1434. """
  1435. _lib.X509_STORE_CTX_cleanup(self._store_ctx)
  1436. def _exception_from_context(self):
  1437. """
  1438. Convert an OpenSSL native context error failure into a Python
  1439. exception.
  1440. When a call to native OpenSSL X509_verify_cert fails, additional
  1441. information about the failure can be obtained from the store context.
  1442. """
  1443. errors = [
  1444. _lib.X509_STORE_CTX_get_error(self._store_ctx),
  1445. _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
  1446. _ffi.string(
  1447. _lib.X509_verify_cert_error_string(
  1448. _lib.X509_STORE_CTX_get_error(self._store_ctx)
  1449. )
  1450. ).decode("utf-8"),
  1451. ]
  1452. # A context error should always be associated with a certificate, so we
  1453. # expect this call to never return :class:`None`.
  1454. _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
  1455. _cert = _lib.X509_dup(_x509)
  1456. pycert = X509._from_raw_x509_ptr(_cert)
  1457. return X509StoreContextError(errors, pycert)
  1458. def set_store(self, store):
  1459. """
  1460. Set the context's X.509 store.
  1461. .. versionadded:: 0.15
  1462. :param X509Store store: The store description which will be used for
  1463. the purposes of any *future* verifications.
  1464. """
  1465. self._store = store
  1466. def verify_certificate(self):
  1467. """
  1468. Verify a certificate in a context.
  1469. .. versionadded:: 0.15
  1470. :raises X509StoreContextError: If an error occurred when validating a
  1471. certificate in the context. Sets ``certificate`` attribute to
  1472. indicate which certificate caused the error.
  1473. """
  1474. # Always re-initialize the store context in case
  1475. # :meth:`verify_certificate` is called multiple times.
  1476. #
  1477. # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
  1478. # before _init to ensure memory is not leaked.
  1479. self._cleanup()
  1480. self._init()
  1481. ret = _lib.X509_verify_cert(self._store_ctx)
  1482. self._cleanup()
  1483. if ret <= 0:
  1484. raise self._exception_from_context()
  1485. def get_verified_chain(self):
  1486. """
  1487. Verify a certificate in a context and return the complete validated
  1488. chain.
  1489. :raises X509StoreContextError: If an error occurred when validating a
  1490. certificate in the context. Sets ``certificate`` attribute to
  1491. indicate which certificate caused the error.
  1492. .. versionadded:: 20.0
  1493. """
  1494. # Always re-initialize the store context in case
  1495. # :meth:`verify_certificate` is called multiple times.
  1496. #
  1497. # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
  1498. # before _init to ensure memory is not leaked.
  1499. self._cleanup()
  1500. self._init()
  1501. ret = _lib.X509_verify_cert(self._store_ctx)
  1502. if ret <= 0:
  1503. self._cleanup()
  1504. raise self._exception_from_context()
  1505. # Note: X509_STORE_CTX_get1_chain returns a deep copy of the chain.
  1506. cert_stack = _lib.X509_STORE_CTX_get1_chain(self._store_ctx)
  1507. _openssl_assert(cert_stack != _ffi.NULL)
  1508. result = []
  1509. for i in range(_lib.sk_X509_num(cert_stack)):
  1510. cert = _lib.sk_X509_value(cert_stack, i)
  1511. _openssl_assert(cert != _ffi.NULL)
  1512. pycert = X509._from_raw_x509_ptr(cert)
  1513. result.append(pycert)
  1514. # Free the stack but not the members which are freed by the X509 class.
  1515. _lib.sk_X509_free(cert_stack)
  1516. self._cleanup()
  1517. return result
  1518. def load_certificate(type, buffer):
  1519. """
  1520. Load a certificate (X509) from the string *buffer* encoded with the
  1521. type *type*.
  1522. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1523. :param bytes buffer: The buffer the certificate is stored in
  1524. :return: The X509 object
  1525. """
  1526. if isinstance(buffer, str):
  1527. buffer = buffer.encode("ascii")
  1528. bio = _new_mem_buf(buffer)
  1529. if type == FILETYPE_PEM:
  1530. x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  1531. elif type == FILETYPE_ASN1:
  1532. x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
  1533. else:
  1534. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1535. if x509 == _ffi.NULL:
  1536. _raise_current_error()
  1537. return X509._from_raw_x509_ptr(x509)
  1538. def dump_certificate(type, cert):
  1539. """
  1540. Dump the certificate *cert* into a buffer string encoded with the type
  1541. *type*.
  1542. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
  1543. FILETYPE_TEXT)
  1544. :param cert: The certificate to dump
  1545. :return: The buffer with the dumped certificate in
  1546. """
  1547. bio = _new_mem_buf()
  1548. if type == FILETYPE_PEM:
  1549. result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
  1550. elif type == FILETYPE_ASN1:
  1551. result_code = _lib.i2d_X509_bio(bio, cert._x509)
  1552. elif type == FILETYPE_TEXT:
  1553. result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
  1554. else:
  1555. raise ValueError(
  1556. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  1557. "FILETYPE_TEXT"
  1558. )
  1559. _openssl_assert(result_code == 1)
  1560. return _bio_to_string(bio)
  1561. def dump_publickey(type, pkey):
  1562. """
  1563. Dump a public key to a buffer.
  1564. :param type: The file type (one of :data:`FILETYPE_PEM` or
  1565. :data:`FILETYPE_ASN1`).
  1566. :param PKey pkey: The public key to dump
  1567. :return: The buffer with the dumped key in it.
  1568. :rtype: bytes
  1569. """
  1570. bio = _new_mem_buf()
  1571. if type == FILETYPE_PEM:
  1572. write_bio = _lib.PEM_write_bio_PUBKEY
  1573. elif type == FILETYPE_ASN1:
  1574. write_bio = _lib.i2d_PUBKEY_bio
  1575. else:
  1576. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1577. result_code = write_bio(bio, pkey._pkey)
  1578. if result_code != 1: # pragma: no cover
  1579. _raise_current_error()
  1580. return _bio_to_string(bio)
  1581. def dump_privatekey(type, pkey, cipher=None, passphrase=None):
  1582. """
  1583. Dump the private key *pkey* into a buffer string encoded with the type
  1584. *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
  1585. using *cipher* and *passphrase*.
  1586. :param type: The file type (one of :const:`FILETYPE_PEM`,
  1587. :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
  1588. :param PKey pkey: The PKey to dump
  1589. :param cipher: (optional) if encrypted PEM format, the cipher to use
  1590. :param passphrase: (optional) if encrypted PEM format, this can be either
  1591. the passphrase to use, or a callback for providing the passphrase.
  1592. :return: The buffer with the dumped key in
  1593. :rtype: bytes
  1594. """
  1595. bio = _new_mem_buf()
  1596. if not isinstance(pkey, PKey):
  1597. raise TypeError("pkey must be a PKey")
  1598. if cipher is not None:
  1599. if passphrase is None:
  1600. raise TypeError(
  1601. "if a value is given for cipher "
  1602. "one must also be given for passphrase"
  1603. )
  1604. cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
  1605. if cipher_obj == _ffi.NULL:
  1606. raise ValueError("Invalid cipher name")
  1607. else:
  1608. cipher_obj = _ffi.NULL
  1609. helper = _PassphraseHelper(type, passphrase)
  1610. if type == FILETYPE_PEM:
  1611. result_code = _lib.PEM_write_bio_PrivateKey(
  1612. bio,
  1613. pkey._pkey,
  1614. cipher_obj,
  1615. _ffi.NULL,
  1616. 0,
  1617. helper.callback,
  1618. helper.callback_args,
  1619. )
  1620. helper.raise_if_problem()
  1621. elif type == FILETYPE_ASN1:
  1622. result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
  1623. elif type == FILETYPE_TEXT:
  1624. if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:
  1625. raise TypeError("Only RSA keys are supported for FILETYPE_TEXT")
  1626. rsa = _ffi.gc(_lib.EVP_PKEY_get1_RSA(pkey._pkey), _lib.RSA_free)
  1627. result_code = _lib.RSA_print(bio, rsa, 0)
  1628. else:
  1629. raise ValueError(
  1630. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  1631. "FILETYPE_TEXT"
  1632. )
  1633. _openssl_assert(result_code != 0)
  1634. return _bio_to_string(bio)
  1635. class Revoked(object):
  1636. """
  1637. A certificate revocation.
  1638. """
  1639. # https://www.openssl.org/docs/manmaster/man5/x509v3_config.html#CRL-distribution-points
  1640. # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
  1641. # OCSP_crl_reason_str. We use the latter, just like the command line
  1642. # program.
  1643. _crl_reasons = [
  1644. b"unspecified",
  1645. b"keyCompromise",
  1646. b"CACompromise",
  1647. b"affiliationChanged",
  1648. b"superseded",
  1649. b"cessationOfOperation",
  1650. b"certificateHold",
  1651. # b"removeFromCRL",
  1652. ]
  1653. def __init__(self):
  1654. revoked = _lib.X509_REVOKED_new()
  1655. self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
  1656. def set_serial(self, hex_str):
  1657. """
  1658. Set the serial number.
  1659. The serial number is formatted as a hexadecimal number encoded in
  1660. ASCII.
  1661. :param bytes hex_str: The new serial number.
  1662. :return: ``None``
  1663. """
  1664. bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
  1665. bignum_ptr = _ffi.new("BIGNUM**")
  1666. bignum_ptr[0] = bignum_serial
  1667. bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
  1668. if not bn_result:
  1669. raise ValueError("bad hex string")
  1670. asn1_serial = _ffi.gc(
  1671. _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
  1672. _lib.ASN1_INTEGER_free,
  1673. )
  1674. _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
  1675. def get_serial(self):
  1676. """
  1677. Get the serial number.
  1678. The serial number is formatted as a hexadecimal number encoded in
  1679. ASCII.
  1680. :return: The serial number.
  1681. :rtype: bytes
  1682. """
  1683. bio = _new_mem_buf()
  1684. asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
  1685. _openssl_assert(asn1_int != _ffi.NULL)
  1686. result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
  1687. _openssl_assert(result >= 0)
  1688. return _bio_to_string(bio)
  1689. def _delete_reason(self):
  1690. for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
  1691. ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
  1692. obj = _lib.X509_EXTENSION_get_object(ext)
  1693. if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
  1694. _lib.X509_EXTENSION_free(ext)
  1695. _lib.X509_REVOKED_delete_ext(self._revoked, i)
  1696. break
  1697. def set_reason(self, reason):
  1698. """
  1699. Set the reason of this revocation.
  1700. If :data:`reason` is ``None``, delete the reason instead.
  1701. :param reason: The reason string.
  1702. :type reason: :class:`bytes` or :class:`NoneType`
  1703. :return: ``None``
  1704. .. seealso::
  1705. :meth:`all_reasons`, which gives you a list of all supported
  1706. reasons which you might pass to this method.
  1707. """
  1708. if reason is None:
  1709. self._delete_reason()
  1710. elif not isinstance(reason, bytes):
  1711. raise TypeError("reason must be None or a byte string")
  1712. else:
  1713. reason = reason.lower().replace(b" ", b"")
  1714. reason_code = [r.lower() for r in self._crl_reasons].index(reason)
  1715. new_reason_ext = _lib.ASN1_ENUMERATED_new()
  1716. _openssl_assert(new_reason_ext != _ffi.NULL)
  1717. new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
  1718. set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
  1719. _openssl_assert(set_result != _ffi.NULL)
  1720. self._delete_reason()
  1721. add_result = _lib.X509_REVOKED_add1_ext_i2d(
  1722. self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0
  1723. )
  1724. _openssl_assert(add_result == 1)
  1725. def get_reason(self):
  1726. """
  1727. Get the reason of this revocation.
  1728. :return: The reason, or ``None`` if there is none.
  1729. :rtype: bytes or NoneType
  1730. .. seealso::
  1731. :meth:`all_reasons`, which gives you a list of all supported
  1732. reasons this method might return.
  1733. """
  1734. for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
  1735. ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
  1736. obj = _lib.X509_EXTENSION_get_object(ext)
  1737. if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
  1738. bio = _new_mem_buf()
  1739. print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
  1740. if not print_result:
  1741. print_result = _lib.M_ASN1_OCTET_STRING_print(
  1742. bio, _lib.X509_EXTENSION_get_data(ext)
  1743. )
  1744. _openssl_assert(print_result != 0)
  1745. return _bio_to_string(bio)
  1746. def all_reasons(self):
  1747. """
  1748. Return a list of all the supported reason strings.
  1749. This list is a copy; modifying it does not change the supported reason
  1750. strings.
  1751. :return: A list of reason strings.
  1752. :rtype: :class:`list` of :class:`bytes`
  1753. """
  1754. return self._crl_reasons[:]
  1755. def set_rev_date(self, when):
  1756. """
  1757. Set the revocation timestamp.
  1758. :param bytes when: The timestamp of the revocation,
  1759. as ASN.1 TIME.
  1760. :return: ``None``
  1761. """
  1762. dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
  1763. return _set_asn1_time(dt, when)
  1764. def get_rev_date(self):
  1765. """
  1766. Get the revocation timestamp.
  1767. :return: The timestamp of the revocation, as ASN.1 TIME.
  1768. :rtype: bytes
  1769. """
  1770. dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
  1771. return _get_asn1_time(dt)
  1772. class CRL(object):
  1773. """
  1774. A certificate revocation list.
  1775. """
  1776. def __init__(self):
  1777. crl = _lib.X509_CRL_new()
  1778. self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
  1779. def to_cryptography(self):
  1780. """
  1781. Export as a ``cryptography`` CRL.
  1782. :rtype: ``cryptography.x509.CertificateRevocationList``
  1783. .. versionadded:: 17.1.0
  1784. """
  1785. from cryptography.x509 import load_der_x509_crl
  1786. der = dump_crl(FILETYPE_ASN1, self)
  1787. backend = _get_backend()
  1788. return load_der_x509_crl(der, backend)
  1789. @classmethod
  1790. def from_cryptography(cls, crypto_crl):
  1791. """
  1792. Construct based on a ``cryptography`` *crypto_crl*.
  1793. :param crypto_crl: A ``cryptography`` certificate revocation list
  1794. :type crypto_crl: ``cryptography.x509.CertificateRevocationList``
  1795. :rtype: CRL
  1796. .. versionadded:: 17.1.0
  1797. """
  1798. if not isinstance(crypto_crl, x509.CertificateRevocationList):
  1799. raise TypeError("Must be a certificate revocation list")
  1800. from cryptography.hazmat.primitives.serialization import Encoding
  1801. der = crypto_crl.public_bytes(Encoding.DER)
  1802. return load_crl(FILETYPE_ASN1, der)
  1803. def get_revoked(self):
  1804. """
  1805. Return the revocations in this certificate revocation list.
  1806. These revocations will be provided by value, not by reference.
  1807. That means it's okay to mutate them: it won't affect this CRL.
  1808. :return: The revocations in this CRL.
  1809. :rtype: :class:`tuple` of :class:`Revocation`
  1810. """
  1811. results = []
  1812. revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
  1813. for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
  1814. revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
  1815. revoked_copy = _lib.X509_REVOKED_dup(revoked)
  1816. pyrev = Revoked.__new__(Revoked)
  1817. pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
  1818. results.append(pyrev)
  1819. if results:
  1820. return tuple(results)
  1821. def add_revoked(self, revoked):
  1822. """
  1823. Add a revoked (by value not reference) to the CRL structure
  1824. This revocation will be added by value, not by reference. That
  1825. means it's okay to mutate it after adding: it won't affect
  1826. this CRL.
  1827. :param Revoked revoked: The new revocation.
  1828. :return: ``None``
  1829. """
  1830. copy = _lib.X509_REVOKED_dup(revoked._revoked)
  1831. _openssl_assert(copy != _ffi.NULL)
  1832. add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
  1833. _openssl_assert(add_result != 0)
  1834. def get_issuer(self):
  1835. """
  1836. Get the CRL's issuer.
  1837. .. versionadded:: 16.1.0
  1838. :rtype: X509Name
  1839. """
  1840. _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
  1841. _openssl_assert(_issuer != _ffi.NULL)
  1842. _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
  1843. issuer = X509Name.__new__(X509Name)
  1844. issuer._name = _issuer
  1845. return issuer
  1846. def set_version(self, version):
  1847. """
  1848. Set the CRL version.
  1849. .. versionadded:: 16.1.0
  1850. :param int version: The version of the CRL.
  1851. :return: ``None``
  1852. """
  1853. _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
  1854. def _set_boundary_time(self, which, when):
  1855. return _set_asn1_time(which(self._crl), when)
  1856. def set_lastUpdate(self, when):
  1857. """
  1858. Set when the CRL was last updated.
  1859. The timestamp is formatted as an ASN.1 TIME::
  1860. YYYYMMDDhhmmssZ
  1861. .. versionadded:: 16.1.0
  1862. :param bytes when: A timestamp string.
  1863. :return: ``None``
  1864. """
  1865. return self._set_boundary_time(_lib.X509_CRL_get0_lastUpdate, when)
  1866. def set_nextUpdate(self, when):
  1867. """
  1868. Set when the CRL will next be updated.
  1869. The timestamp is formatted as an ASN.1 TIME::
  1870. YYYYMMDDhhmmssZ
  1871. .. versionadded:: 16.1.0
  1872. :param bytes when: A timestamp string.
  1873. :return: ``None``
  1874. """
  1875. return self._set_boundary_time(_lib.X509_CRL_get0_nextUpdate, when)
  1876. def sign(self, issuer_cert, issuer_key, digest):
  1877. """
  1878. Sign the CRL.
  1879. Signing a CRL enables clients to associate the CRL itself with an
  1880. issuer. Before a CRL is meaningful to other OpenSSL functions, it must
  1881. be signed by an issuer.
  1882. This method implicitly sets the issuer's name based on the issuer
  1883. certificate and private key used to sign the CRL.
  1884. .. versionadded:: 16.1.0
  1885. :param X509 issuer_cert: The issuer's certificate.
  1886. :param PKey issuer_key: The issuer's private key.
  1887. :param bytes digest: The digest method to sign the CRL with.
  1888. """
  1889. digest_obj = _lib.EVP_get_digestbyname(digest)
  1890. _openssl_assert(digest_obj != _ffi.NULL)
  1891. _lib.X509_CRL_set_issuer_name(
  1892. self._crl, _lib.X509_get_subject_name(issuer_cert._x509)
  1893. )
  1894. _lib.X509_CRL_sort(self._crl)
  1895. result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
  1896. _openssl_assert(result != 0)
  1897. def export(
  1898. self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED
  1899. ):
  1900. """
  1901. Export the CRL as a string.
  1902. :param X509 cert: The certificate used to sign the CRL.
  1903. :param PKey key: The key used to sign the CRL.
  1904. :param int type: The export format, either :data:`FILETYPE_PEM`,
  1905. :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
  1906. :param int days: The number of days until the next update of this CRL.
  1907. :param bytes digest: The name of the message digest to use (eg
  1908. ``b"sha256"``).
  1909. :rtype: bytes
  1910. """
  1911. if not isinstance(cert, X509):
  1912. raise TypeError("cert must be an X509 instance")
  1913. if not isinstance(key, PKey):
  1914. raise TypeError("key must be a PKey instance")
  1915. if not isinstance(type, int):
  1916. raise TypeError("type must be an integer")
  1917. if digest is _UNSPECIFIED:
  1918. raise TypeError("digest must be provided")
  1919. digest_obj = _lib.EVP_get_digestbyname(digest)
  1920. if digest_obj == _ffi.NULL:
  1921. raise ValueError("No such digest method")
  1922. bio = _lib.BIO_new(_lib.BIO_s_mem())
  1923. _openssl_assert(bio != _ffi.NULL)
  1924. # A scratch time object to give different values to different CRL
  1925. # fields
  1926. sometime = _lib.ASN1_TIME_new()
  1927. _openssl_assert(sometime != _ffi.NULL)
  1928. _lib.X509_gmtime_adj(sometime, 0)
  1929. _lib.X509_CRL_set1_lastUpdate(self._crl, sometime)
  1930. _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
  1931. _lib.X509_CRL_set1_nextUpdate(self._crl, sometime)
  1932. _lib.X509_CRL_set_issuer_name(
  1933. self._crl, _lib.X509_get_subject_name(cert._x509)
  1934. )
  1935. sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
  1936. if not sign_result:
  1937. _raise_current_error()
  1938. return dump_crl(type, self)
  1939. class PKCS7(object):
  1940. def type_is_signed(self):
  1941. """
  1942. Check if this NID_pkcs7_signed object
  1943. :return: True if the PKCS7 is of type signed
  1944. """
  1945. return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
  1946. def type_is_enveloped(self):
  1947. """
  1948. Check if this NID_pkcs7_enveloped object
  1949. :returns: True if the PKCS7 is of type enveloped
  1950. """
  1951. return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
  1952. def type_is_signedAndEnveloped(self):
  1953. """
  1954. Check if this NID_pkcs7_signedAndEnveloped object
  1955. :returns: True if the PKCS7 is of type signedAndEnveloped
  1956. """
  1957. return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
  1958. def type_is_data(self):
  1959. """
  1960. Check if this NID_pkcs7_data object
  1961. :return: True if the PKCS7 is of type data
  1962. """
  1963. return bool(_lib.PKCS7_type_is_data(self._pkcs7))
  1964. def get_type_name(self):
  1965. """
  1966. Returns the type name of the PKCS7 structure
  1967. :return: A string with the typename
  1968. """
  1969. nid = _lib.OBJ_obj2nid(self._pkcs7.type)
  1970. string_type = _lib.OBJ_nid2sn(nid)
  1971. return _ffi.string(string_type)
  1972. class PKCS12(object):
  1973. """
  1974. A PKCS #12 archive.
  1975. """
  1976. def __init__(self):
  1977. self._pkey = None
  1978. self._cert = None
  1979. self._cacerts = None
  1980. self._friendlyname = None
  1981. def get_certificate(self):
  1982. """
  1983. Get the certificate in the PKCS #12 structure.
  1984. :return: The certificate, or :py:const:`None` if there is none.
  1985. :rtype: :py:class:`X509` or :py:const:`None`
  1986. """
  1987. return self._cert
  1988. def set_certificate(self, cert):
  1989. """
  1990. Set the certificate in the PKCS #12 structure.
  1991. :param cert: The new certificate, or :py:const:`None` to unset it.
  1992. :type cert: :py:class:`X509` or :py:const:`None`
  1993. :return: ``None``
  1994. """
  1995. if not isinstance(cert, X509):
  1996. raise TypeError("cert must be an X509 instance")
  1997. self._cert = cert
  1998. def get_privatekey(self):
  1999. """
  2000. Get the private key in the PKCS #12 structure.
  2001. :return: The private key, or :py:const:`None` if there is none.
  2002. :rtype: :py:class:`PKey`
  2003. """
  2004. return self._pkey
  2005. def set_privatekey(self, pkey):
  2006. """
  2007. Set the certificate portion of the PKCS #12 structure.
  2008. :param pkey: The new private key, or :py:const:`None` to unset it.
  2009. :type pkey: :py:class:`PKey` or :py:const:`None`
  2010. :return: ``None``
  2011. """
  2012. if not isinstance(pkey, PKey):
  2013. raise TypeError("pkey must be a PKey instance")
  2014. self._pkey = pkey
  2015. def get_ca_certificates(self):
  2016. """
  2017. Get the CA certificates in the PKCS #12 structure.
  2018. :return: A tuple with the CA certificates in the chain, or
  2019. :py:const:`None` if there are none.
  2020. :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
  2021. """
  2022. if self._cacerts is not None:
  2023. return tuple(self._cacerts)
  2024. def set_ca_certificates(self, cacerts):
  2025. """
  2026. Replace or set the CA certificates within the PKCS12 object.
  2027. :param cacerts: The new CA certificates, or :py:const:`None` to unset
  2028. them.
  2029. :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
  2030. :return: ``None``
  2031. """
  2032. if cacerts is None:
  2033. self._cacerts = None
  2034. else:
  2035. cacerts = list(cacerts)
  2036. for cert in cacerts:
  2037. if not isinstance(cert, X509):
  2038. raise TypeError(
  2039. "iterable must only contain X509 instances"
  2040. )
  2041. self._cacerts = cacerts
  2042. def set_friendlyname(self, name):
  2043. """
  2044. Set the friendly name in the PKCS #12 structure.
  2045. :param name: The new friendly name, or :py:const:`None` to unset.
  2046. :type name: :py:class:`bytes` or :py:const:`None`
  2047. :return: ``None``
  2048. """
  2049. if name is None:
  2050. self._friendlyname = None
  2051. elif not isinstance(name, bytes):
  2052. raise TypeError(
  2053. "name must be a byte string or None (not %r)" % (name,)
  2054. )
  2055. self._friendlyname = name
  2056. def get_friendlyname(self):
  2057. """
  2058. Get the friendly name in the PKCS# 12 structure.
  2059. :returns: The friendly name, or :py:const:`None` if there is none.
  2060. :rtype: :py:class:`bytes` or :py:const:`None`
  2061. """
  2062. return self._friendlyname
  2063. def export(self, passphrase=None, iter=2048, maciter=1):
  2064. """
  2065. Dump a PKCS12 object as a string.
  2066. For more information, see the :c:func:`PKCS12_create` man page.
  2067. :param passphrase: The passphrase used to encrypt the structure. Unlike
  2068. some other passphrase arguments, this *must* be a string, not a
  2069. callback.
  2070. :type passphrase: :py:data:`bytes`
  2071. :param iter: Number of times to repeat the encryption step.
  2072. :type iter: :py:data:`int`
  2073. :param maciter: Number of times to repeat the MAC step.
  2074. :type maciter: :py:data:`int`
  2075. :return: The string representation of the PKCS #12 structure.
  2076. :rtype:
  2077. """
  2078. passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
  2079. if self._cacerts is None:
  2080. cacerts = _ffi.NULL
  2081. else:
  2082. cacerts = _lib.sk_X509_new_null()
  2083. cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
  2084. for cert in self._cacerts:
  2085. _lib.sk_X509_push(cacerts, cert._x509)
  2086. if passphrase is None:
  2087. passphrase = _ffi.NULL
  2088. friendlyname = self._friendlyname
  2089. if friendlyname is None:
  2090. friendlyname = _ffi.NULL
  2091. if self._pkey is None:
  2092. pkey = _ffi.NULL
  2093. else:
  2094. pkey = self._pkey._pkey
  2095. if self._cert is None:
  2096. cert = _ffi.NULL
  2097. else:
  2098. cert = self._cert._x509
  2099. pkcs12 = _lib.PKCS12_create(
  2100. passphrase,
  2101. friendlyname,
  2102. pkey,
  2103. cert,
  2104. cacerts,
  2105. _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  2106. _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  2107. iter,
  2108. maciter,
  2109. 0,
  2110. )
  2111. if pkcs12 == _ffi.NULL:
  2112. _raise_current_error()
  2113. pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
  2114. bio = _new_mem_buf()
  2115. _lib.i2d_PKCS12_bio(bio, pkcs12)
  2116. return _bio_to_string(bio)
  2117. class NetscapeSPKI(object):
  2118. """
  2119. A Netscape SPKI object.
  2120. """
  2121. def __init__(self):
  2122. spki = _lib.NETSCAPE_SPKI_new()
  2123. self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
  2124. def sign(self, pkey, digest):
  2125. """
  2126. Sign the certificate request with this key and digest type.
  2127. :param pkey: The private key to sign with.
  2128. :type pkey: :py:class:`PKey`
  2129. :param digest: The message digest to use.
  2130. :type digest: :py:class:`str`
  2131. :return: ``None``
  2132. """
  2133. if pkey._only_public:
  2134. raise ValueError("Key has only public part")
  2135. if not pkey._initialized:
  2136. raise ValueError("Key is uninitialized")
  2137. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  2138. if digest_obj == _ffi.NULL:
  2139. raise ValueError("No such digest method")
  2140. sign_result = _lib.NETSCAPE_SPKI_sign(
  2141. self._spki, pkey._pkey, digest_obj
  2142. )
  2143. _openssl_assert(sign_result > 0)
  2144. def verify(self, key):
  2145. """
  2146. Verifies a signature on a certificate request.
  2147. :param PKey key: The public key that signature is supposedly from.
  2148. :return: ``True`` if the signature is correct.
  2149. :rtype: bool
  2150. :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
  2151. a problem verifying the signature.
  2152. """
  2153. answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
  2154. if answer <= 0:
  2155. _raise_current_error()
  2156. return True
  2157. def b64_encode(self):
  2158. """
  2159. Generate a base64 encoded representation of this SPKI object.
  2160. :return: The base64 encoded string.
  2161. :rtype: :py:class:`bytes`
  2162. """
  2163. encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
  2164. result = _ffi.string(encoded)
  2165. _lib.OPENSSL_free(encoded)
  2166. return result
  2167. def get_pubkey(self):
  2168. """
  2169. Get the public key of this certificate.
  2170. :return: The public key.
  2171. :rtype: :py:class:`PKey`
  2172. """
  2173. pkey = PKey.__new__(PKey)
  2174. pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
  2175. _openssl_assert(pkey._pkey != _ffi.NULL)
  2176. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  2177. pkey._only_public = True
  2178. return pkey
  2179. def set_pubkey(self, pkey):
  2180. """
  2181. Set the public key of the certificate
  2182. :param pkey: The public key
  2183. :return: ``None``
  2184. """
  2185. set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
  2186. _openssl_assert(set_result == 1)
  2187. class _PassphraseHelper(object):
  2188. def __init__(self, type, passphrase, more_args=False, truncate=False):
  2189. if type != FILETYPE_PEM and passphrase is not None:
  2190. raise ValueError(
  2191. "only FILETYPE_PEM key format supports encryption"
  2192. )
  2193. self._passphrase = passphrase
  2194. self._more_args = more_args
  2195. self._truncate = truncate
  2196. self._problems = []
  2197. @property
  2198. def callback(self):
  2199. if self._passphrase is None:
  2200. return _ffi.NULL
  2201. elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
  2202. return _ffi.callback("pem_password_cb", self._read_passphrase)
  2203. else:
  2204. raise TypeError(
  2205. "Last argument must be a byte string or a callable."
  2206. )
  2207. @property
  2208. def callback_args(self):
  2209. if self._passphrase is None:
  2210. return _ffi.NULL
  2211. elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
  2212. return _ffi.NULL
  2213. else:
  2214. raise TypeError(
  2215. "Last argument must be a byte string or a callable."
  2216. )
  2217. def raise_if_problem(self, exceptionType=Error):
  2218. if self._problems:
  2219. # Flush the OpenSSL error queue
  2220. try:
  2221. _exception_from_error_queue(exceptionType)
  2222. except exceptionType:
  2223. pass
  2224. raise self._problems.pop(0)
  2225. def _read_passphrase(self, buf, size, rwflag, userdata):
  2226. try:
  2227. if callable(self._passphrase):
  2228. if self._more_args:
  2229. result = self._passphrase(size, rwflag, userdata)
  2230. else:
  2231. result = self._passphrase(rwflag)
  2232. else:
  2233. result = self._passphrase
  2234. if not isinstance(result, bytes):
  2235. raise ValueError("Bytes expected")
  2236. if len(result) > size:
  2237. if self._truncate:
  2238. result = result[:size]
  2239. else:
  2240. raise ValueError(
  2241. "passphrase returned by callback is too long"
  2242. )
  2243. for i in range(len(result)):
  2244. buf[i] = result[i : i + 1]
  2245. return len(result)
  2246. except Exception as e:
  2247. self._problems.append(e)
  2248. return 0
  2249. def load_publickey(type, buffer):
  2250. """
  2251. Load a public key from a buffer.
  2252. :param type: The file type (one of :data:`FILETYPE_PEM`,
  2253. :data:`FILETYPE_ASN1`).
  2254. :param buffer: The buffer the key is stored in.
  2255. :type buffer: A Python string object, either unicode or bytestring.
  2256. :return: The PKey object.
  2257. :rtype: :class:`PKey`
  2258. """
  2259. if isinstance(buffer, str):
  2260. buffer = buffer.encode("ascii")
  2261. bio = _new_mem_buf(buffer)
  2262. if type == FILETYPE_PEM:
  2263. evp_pkey = _lib.PEM_read_bio_PUBKEY(
  2264. bio, _ffi.NULL, _ffi.NULL, _ffi.NULL
  2265. )
  2266. elif type == FILETYPE_ASN1:
  2267. evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
  2268. else:
  2269. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  2270. if evp_pkey == _ffi.NULL:
  2271. _raise_current_error()
  2272. pkey = PKey.__new__(PKey)
  2273. pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
  2274. pkey._only_public = True
  2275. return pkey
  2276. def load_privatekey(type, buffer, passphrase=None):
  2277. """
  2278. Load a private key (PKey) from the string *buffer* encoded with the type
  2279. *type*.
  2280. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  2281. :param buffer: The buffer the key is stored in
  2282. :param passphrase: (optional) if encrypted PEM format, this can be
  2283. either the passphrase to use, or a callback for
  2284. providing the passphrase.
  2285. :return: The PKey object
  2286. """
  2287. if isinstance(buffer, str):
  2288. buffer = buffer.encode("ascii")
  2289. bio = _new_mem_buf(buffer)
  2290. helper = _PassphraseHelper(type, passphrase)
  2291. if type == FILETYPE_PEM:
  2292. evp_pkey = _lib.PEM_read_bio_PrivateKey(
  2293. bio, _ffi.NULL, helper.callback, helper.callback_args
  2294. )
  2295. helper.raise_if_problem()
  2296. elif type == FILETYPE_ASN1:
  2297. evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
  2298. else:
  2299. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  2300. if evp_pkey == _ffi.NULL:
  2301. _raise_current_error()
  2302. pkey = PKey.__new__(PKey)
  2303. pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
  2304. return pkey
  2305. def dump_certificate_request(type, req):
  2306. """
  2307. Dump the certificate request *req* into a buffer string encoded with the
  2308. type *type*.
  2309. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  2310. :param req: The certificate request to dump
  2311. :return: The buffer with the dumped certificate request in
  2312. """
  2313. bio = _new_mem_buf()
  2314. if type == FILETYPE_PEM:
  2315. result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
  2316. elif type == FILETYPE_ASN1:
  2317. result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
  2318. elif type == FILETYPE_TEXT:
  2319. result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
  2320. else:
  2321. raise ValueError(
  2322. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  2323. "FILETYPE_TEXT"
  2324. )
  2325. _openssl_assert(result_code != 0)
  2326. return _bio_to_string(bio)
  2327. def load_certificate_request(type, buffer):
  2328. """
  2329. Load a certificate request (X509Req) from the string *buffer* encoded with
  2330. the type *type*.
  2331. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  2332. :param buffer: The buffer the certificate request is stored in
  2333. :return: The X509Req object
  2334. """
  2335. if isinstance(buffer, str):
  2336. buffer = buffer.encode("ascii")
  2337. bio = _new_mem_buf(buffer)
  2338. if type == FILETYPE_PEM:
  2339. req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  2340. elif type == FILETYPE_ASN1:
  2341. req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
  2342. else:
  2343. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  2344. _openssl_assert(req != _ffi.NULL)
  2345. x509req = X509Req.__new__(X509Req)
  2346. x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
  2347. return x509req
  2348. def sign(pkey, data, digest):
  2349. """
  2350. Sign a data string using the given key and message digest.
  2351. :param pkey: PKey to sign with
  2352. :param data: data to be signed
  2353. :param digest: message digest to use
  2354. :return: signature
  2355. .. versionadded:: 0.11
  2356. """
  2357. data = _text_to_bytes_and_warn("data", data)
  2358. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  2359. if digest_obj == _ffi.NULL:
  2360. raise ValueError("No such digest method")
  2361. md_ctx = _lib.EVP_MD_CTX_new()
  2362. md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_free)
  2363. _lib.EVP_SignInit(md_ctx, digest_obj)
  2364. _lib.EVP_SignUpdate(md_ctx, data, len(data))
  2365. length = _lib.EVP_PKEY_size(pkey._pkey)
  2366. _openssl_assert(length > 0)
  2367. signature_buffer = _ffi.new("unsigned char[]", length)
  2368. signature_length = _ffi.new("unsigned int *")
  2369. final_result = _lib.EVP_SignFinal(
  2370. md_ctx, signature_buffer, signature_length, pkey._pkey
  2371. )
  2372. _openssl_assert(final_result == 1)
  2373. return _ffi.buffer(signature_buffer, signature_length[0])[:]
  2374. def verify(cert, signature, data, digest):
  2375. """
  2376. Verify the signature for a data string.
  2377. :param cert: signing certificate (X509 object) corresponding to the
  2378. private key which generated the signature.
  2379. :param signature: signature returned by sign function
  2380. :param data: data to be verified
  2381. :param digest: message digest to use
  2382. :return: ``None`` if the signature is correct, raise exception otherwise.
  2383. .. versionadded:: 0.11
  2384. """
  2385. data = _text_to_bytes_and_warn("data", data)
  2386. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  2387. if digest_obj == _ffi.NULL:
  2388. raise ValueError("No such digest method")
  2389. pkey = _lib.X509_get_pubkey(cert._x509)
  2390. _openssl_assert(pkey != _ffi.NULL)
  2391. pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
  2392. md_ctx = _lib.EVP_MD_CTX_new()
  2393. md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_free)
  2394. _lib.EVP_VerifyInit(md_ctx, digest_obj)
  2395. _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
  2396. verify_result = _lib.EVP_VerifyFinal(
  2397. md_ctx, signature, len(signature), pkey
  2398. )
  2399. if verify_result != 1:
  2400. _raise_current_error()
  2401. def dump_crl(type, crl):
  2402. """
  2403. Dump a certificate revocation list to a buffer.
  2404. :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
  2405. ``FILETYPE_TEXT``).
  2406. :param CRL crl: The CRL to dump.
  2407. :return: The buffer with the CRL.
  2408. :rtype: bytes
  2409. """
  2410. bio = _new_mem_buf()
  2411. if type == FILETYPE_PEM:
  2412. ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
  2413. elif type == FILETYPE_ASN1:
  2414. ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
  2415. elif type == FILETYPE_TEXT:
  2416. ret = _lib.X509_CRL_print(bio, crl._crl)
  2417. else:
  2418. raise ValueError(
  2419. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  2420. "FILETYPE_TEXT"
  2421. )
  2422. _openssl_assert(ret == 1)
  2423. return _bio_to_string(bio)
  2424. def load_crl(type, buffer):
  2425. """
  2426. Load Certificate Revocation List (CRL) data from a string *buffer*.
  2427. *buffer* encoded with the type *type*.
  2428. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  2429. :param buffer: The buffer the CRL is stored in
  2430. :return: The PKey object
  2431. """
  2432. if isinstance(buffer, str):
  2433. buffer = buffer.encode("ascii")
  2434. bio = _new_mem_buf(buffer)
  2435. if type == FILETYPE_PEM:
  2436. crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  2437. elif type == FILETYPE_ASN1:
  2438. crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
  2439. else:
  2440. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  2441. if crl == _ffi.NULL:
  2442. _raise_current_error()
  2443. result = CRL.__new__(CRL)
  2444. result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
  2445. return result
  2446. def load_pkcs7_data(type, buffer):
  2447. """
  2448. Load pkcs7 data from the string *buffer* encoded with the type
  2449. *type*.
  2450. :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
  2451. :param buffer: The buffer with the pkcs7 data.
  2452. :return: The PKCS7 object
  2453. """
  2454. if isinstance(buffer, str):
  2455. buffer = buffer.encode("ascii")
  2456. bio = _new_mem_buf(buffer)
  2457. if type == FILETYPE_PEM:
  2458. pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  2459. elif type == FILETYPE_ASN1:
  2460. pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
  2461. else:
  2462. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  2463. if pkcs7 == _ffi.NULL:
  2464. _raise_current_error()
  2465. pypkcs7 = PKCS7.__new__(PKCS7)
  2466. pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
  2467. return pypkcs7
  2468. load_pkcs7_data = utils.deprecated(
  2469. load_pkcs7_data,
  2470. __name__,
  2471. (
  2472. "PKCS#7 support in pyOpenSSL is deprecated. You should use the APIs "
  2473. "in cryptography."
  2474. ),
  2475. DeprecationWarning,
  2476. )
  2477. def load_pkcs12(buffer, passphrase=None):
  2478. """
  2479. Load pkcs12 data from the string *buffer*. If the pkcs12 structure is
  2480. encrypted, a *passphrase* must be included. The MAC is always
  2481. checked and thus required.
  2482. See also the man page for the C function :py:func:`PKCS12_parse`.
  2483. :param buffer: The buffer the certificate is stored in
  2484. :param passphrase: (Optional) The password to decrypt the PKCS12 lump
  2485. :returns: The PKCS12 object
  2486. """
  2487. passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
  2488. if isinstance(buffer, str):
  2489. buffer = buffer.encode("ascii")
  2490. bio = _new_mem_buf(buffer)
  2491. # Use null passphrase if passphrase is None or empty string. With PKCS#12
  2492. # password based encryption no password and a zero length password are two
  2493. # different things, but OpenSSL implementation will try both to figure out
  2494. # which one works.
  2495. if not passphrase:
  2496. passphrase = _ffi.NULL
  2497. p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
  2498. if p12 == _ffi.NULL:
  2499. _raise_current_error()
  2500. p12 = _ffi.gc(p12, _lib.PKCS12_free)
  2501. pkey = _ffi.new("EVP_PKEY**")
  2502. cert = _ffi.new("X509**")
  2503. cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
  2504. parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
  2505. if not parse_result:
  2506. _raise_current_error()
  2507. cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
  2508. # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
  2509. # queue for no particular reason. This error isn't interesting to anyone
  2510. # outside this function. It's not even interesting to us. Get rid of it.
  2511. try:
  2512. _raise_current_error()
  2513. except Error:
  2514. pass
  2515. if pkey[0] == _ffi.NULL:
  2516. pykey = None
  2517. else:
  2518. pykey = PKey.__new__(PKey)
  2519. pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
  2520. if cert[0] == _ffi.NULL:
  2521. pycert = None
  2522. friendlyname = None
  2523. else:
  2524. pycert = X509._from_raw_x509_ptr(cert[0])
  2525. friendlyname_length = _ffi.new("int*")
  2526. friendlyname_buffer = _lib.X509_alias_get0(
  2527. cert[0], friendlyname_length
  2528. )
  2529. friendlyname = _ffi.buffer(
  2530. friendlyname_buffer, friendlyname_length[0]
  2531. )[:]
  2532. if friendlyname_buffer == _ffi.NULL:
  2533. friendlyname = None
  2534. pycacerts = []
  2535. for i in range(_lib.sk_X509_num(cacerts)):
  2536. x509 = _lib.sk_X509_value(cacerts, i)
  2537. pycacert = X509._from_raw_x509_ptr(x509)
  2538. pycacerts.append(pycacert)
  2539. if not pycacerts:
  2540. pycacerts = None
  2541. pkcs12 = PKCS12.__new__(PKCS12)
  2542. pkcs12._pkey = pykey
  2543. pkcs12._cert = pycert
  2544. pkcs12._cacerts = pycacerts
  2545. pkcs12._friendlyname = friendlyname
  2546. return pkcs12
  2547. load_pkcs12 = utils.deprecated(
  2548. load_pkcs12,
  2549. __name__,
  2550. (
  2551. "PKCS#12 support in pyOpenSSL is deprecated. You should use the APIs "
  2552. "in cryptography."
  2553. ),
  2554. DeprecationWarning,
  2555. )
  2556. # There are no direct unit tests for this initialization. It is tested
  2557. # indirectly since it is necessary for functions like dump_privatekey when
  2558. # using encryption.
  2559. #
  2560. # Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
  2561. # and some other similar tests may fail without this (though they may not if
  2562. # the Python runtime has already done some initialization of the underlying
  2563. # OpenSSL library (and is linked against the same one that cryptography is
  2564. # using)).
  2565. _lib.OpenSSL_add_all_algorithms()
  2566. # This is similar but exercised mainly by exception_from_error_queue. It calls
  2567. # both ERR_load_crypto_strings() and ERR_load_SSL_strings().
  2568. _lib.SSL_load_error_strings()
  2569. # Set the default string mask to match OpenSSL upstream (since 2005) and
  2570. # RFC5280 recommendations.
  2571. _lib.ASN1_STRING_set_default_mask_asc(b"utf8only")