crypto.py 103 KB

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