Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

crypto.py 107KB

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