crypto.py 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639
  1. from time import time
  2. from base64 import b16encode
  3. from functools import partial
  4. from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
  5. from warnings import warn as _warn
  6. from six import (
  7. integer_types as _integer_types,
  8. text_type as _text_type,
  9. PY3 as _PY3)
  10. from OpenSSL._util import (
  11. ffi as _ffi,
  12. lib as _lib,
  13. exception_from_error_queue as _exception_from_error_queue,
  14. byte_string as _byte_string,
  15. native as _native,
  16. UNSPECIFIED as _UNSPECIFIED,
  17. text_to_bytes_and_warn as _text_to_bytes_and_warn,
  18. )
  19. FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
  20. FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
  21. # TODO This was an API mistake. OpenSSL has no such constant.
  22. FILETYPE_TEXT = 2 ** 16 - 1
  23. TYPE_RSA = _lib.EVP_PKEY_RSA
  24. TYPE_DSA = _lib.EVP_PKEY_DSA
  25. class Error(Exception):
  26. """
  27. An error occurred in an `OpenSSL.crypto` API.
  28. """
  29. _raise_current_error = partial(_exception_from_error_queue, Error)
  30. def _untested_error(where):
  31. """
  32. An OpenSSL API failed somehow. Additionally, the failure which was
  33. encountered isn't one that's exercised by the test suite so future behavior
  34. of pyOpenSSL is now somewhat less predictable.
  35. """
  36. raise RuntimeError("Unknown %s failure" % (where,))
  37. def _new_mem_buf(buffer=None):
  38. """
  39. Allocate a new OpenSSL memory BIO.
  40. Arrange for the garbage collector to clean it up automatically.
  41. :param buffer: None or some bytes to use to put into the BIO so that they
  42. can be read out.
  43. """
  44. if buffer is None:
  45. bio = _lib.BIO_new(_lib.BIO_s_mem())
  46. free = _lib.BIO_free
  47. else:
  48. data = _ffi.new("char[]", buffer)
  49. bio = _lib.BIO_new_mem_buf(data, len(buffer))
  50. # Keep the memory alive as long as the bio is alive!
  51. def free(bio, ref=data):
  52. return _lib.BIO_free(bio)
  53. if bio == _ffi.NULL:
  54. # TODO: This is untested.
  55. _raise_current_error()
  56. bio = _ffi.gc(bio, free)
  57. return bio
  58. def _bio_to_string(bio):
  59. """
  60. Copy the contents of an OpenSSL BIO object into a Python byte string.
  61. """
  62. result_buffer = _ffi.new('char**')
  63. buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
  64. return _ffi.buffer(result_buffer[0], buffer_length)[:]
  65. def _set_asn1_time(boundary, when):
  66. """
  67. The the time value of an ASN1 time object.
  68. @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
  69. castable to that type) which will have its value set.
  70. @param when: A string representation of the desired time value.
  71. @raise TypeError: If C{when} is not a L{bytes} string.
  72. @raise ValueError: If C{when} does not represent a time in the required
  73. format.
  74. @raise RuntimeError: If the time value cannot be set for some other
  75. (unspecified) reason.
  76. """
  77. if not isinstance(when, bytes):
  78. raise TypeError("when must be a byte string")
  79. set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
  80. _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
  81. if set_result == 0:
  82. dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
  83. _lib.ASN1_STRING_set(dummy, when, len(when))
  84. check_result = _lib.ASN1_GENERALIZEDTIME_check(
  85. _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
  86. if not check_result:
  87. raise ValueError("Invalid string")
  88. else:
  89. _untested_error()
  90. def _get_asn1_time(timestamp):
  91. """
  92. Retrieve the time value of an ASN1 time object.
  93. @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
  94. that type) from which the time value will be retrieved.
  95. @return: The time value from C{timestamp} as a L{bytes} string in a certain
  96. format. Or C{None} if the object contains no time value.
  97. """
  98. string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
  99. if _lib.ASN1_STRING_length(string_timestamp) == 0:
  100. return None
  101. elif _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME:
  102. return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
  103. else:
  104. generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
  105. _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
  106. if generalized_timestamp[0] == _ffi.NULL:
  107. # This may happen:
  108. # - if timestamp was not an ASN1_TIME
  109. # - if allocating memory for the ASN1_GENERALIZEDTIME failed
  110. # - if a copy of the time data from timestamp cannot be made for
  111. # the newly allocated ASN1_GENERALIZEDTIME
  112. #
  113. # These are difficult to test. cffi enforces the ASN1_TIME type.
  114. # Memory allocation failures are a pain to trigger
  115. # deterministically.
  116. _untested_error("ASN1_TIME_to_generalizedtime")
  117. else:
  118. string_timestamp = _ffi.cast(
  119. "ASN1_STRING*", generalized_timestamp[0])
  120. string_data = _lib.ASN1_STRING_data(string_timestamp)
  121. string_result = _ffi.string(string_data)
  122. _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
  123. return string_result
  124. class PKey(object):
  125. _only_public = False
  126. _initialized = True
  127. def __init__(self):
  128. pkey = _lib.EVP_PKEY_new()
  129. self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
  130. self._initialized = False
  131. def generate_key(self, type, bits):
  132. """
  133. Generate a key of a given type, with a given number of a bits
  134. :param type: The key type (TYPE_RSA or TYPE_DSA)
  135. :param bits: The number of bits
  136. :return: None
  137. """
  138. if not isinstance(type, int):
  139. raise TypeError("type must be an integer")
  140. if not isinstance(bits, int):
  141. raise TypeError("bits must be an integer")
  142. # TODO Check error return
  143. exponent = _lib.BN_new()
  144. exponent = _ffi.gc(exponent, _lib.BN_free)
  145. _lib.BN_set_word(exponent, _lib.RSA_F4)
  146. if type == TYPE_RSA:
  147. if bits <= 0:
  148. raise ValueError("Invalid number of bits")
  149. rsa = _lib.RSA_new()
  150. result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
  151. if result == 0:
  152. # TODO: The test for this case is commented out. Different
  153. # builds of OpenSSL appear to have different failure modes that
  154. # make it hard to test. Visual inspection of the OpenSSL
  155. # source reveals that a return value of 0 signals an error.
  156. # Manual testing on a particular build of OpenSSL suggests that
  157. # this is probably the appropriate way to handle those errors.
  158. _raise_current_error()
  159. result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
  160. if not result:
  161. # TODO: It appears as though this can fail if an engine is in
  162. # use which does not support RSA.
  163. _raise_current_error()
  164. elif type == TYPE_DSA:
  165. dsa = _lib.DSA_generate_parameters(
  166. bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  167. if dsa == _ffi.NULL:
  168. # TODO: This is untested.
  169. _raise_current_error()
  170. if not _lib.DSA_generate_key(dsa):
  171. # TODO: This is untested.
  172. _raise_current_error()
  173. if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):
  174. # TODO: This is untested.
  175. _raise_current_error()
  176. else:
  177. raise Error("No such key type")
  178. self._initialized = True
  179. def check(self):
  180. """
  181. Check the consistency of an RSA private key.
  182. :return: True if key is consistent.
  183. :raise Error: if the key is inconsistent.
  184. :raise TypeError: if the key is of a type which cannot be checked.
  185. Only RSA keys can currently be checked.
  186. """
  187. if self._only_public:
  188. raise TypeError("public key only")
  189. if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:
  190. raise TypeError("key type unsupported")
  191. rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
  192. rsa = _ffi.gc(rsa, _lib.RSA_free)
  193. result = _lib.RSA_check_key(rsa)
  194. if result:
  195. return True
  196. _raise_current_error()
  197. def type(self):
  198. """
  199. Returns the type of the key
  200. :return: The type of the key.
  201. """
  202. return self._pkey.type
  203. def bits(self):
  204. """
  205. Returns the number of bits of the key
  206. :return: The number of bits of the key.
  207. """
  208. return _lib.EVP_PKEY_bits(self._pkey)
  209. PKeyType = PKey
  210. class _EllipticCurve(object):
  211. """
  212. A representation of a supported elliptic curve.
  213. @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
  214. Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
  215. instances each of which represents one curve supported by the system.
  216. @type _curves: :py:type:`NoneType` or :py:type:`set`
  217. """
  218. _curves = None
  219. if _PY3:
  220. # This only necessary on Python 3. Morever, it is broken on Python 2.
  221. def __ne__(self, other):
  222. """
  223. Implement cooperation with the right-hand side argument of ``!=``.
  224. Python 3 seems to have dropped this cooperation in this very narrow
  225. circumstance.
  226. """
  227. if isinstance(other, _EllipticCurve):
  228. return super(_EllipticCurve, self).__ne__(other)
  229. return NotImplemented
  230. @classmethod
  231. def _load_elliptic_curves(cls, lib):
  232. """
  233. Get the curves supported by OpenSSL.
  234. :param lib: The OpenSSL library binding object.
  235. :return: A :py:type:`set` of ``cls`` instances giving the names of the
  236. elliptic curves the underlying library supports.
  237. """
  238. if lib.Cryptography_HAS_EC:
  239. num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
  240. builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
  241. # The return value on this call should be num_curves again. We could
  242. # check it to make sure but if it *isn't* then.. what could we do?
  243. # Abort the whole process, I suppose...? -exarkun
  244. lib.EC_get_builtin_curves(builtin_curves, num_curves)
  245. return set(
  246. cls.from_nid(lib, c.nid)
  247. for c in builtin_curves)
  248. return set()
  249. @classmethod
  250. def _get_elliptic_curves(cls, lib):
  251. """
  252. Get, cache, and return the curves supported by OpenSSL.
  253. :param lib: The OpenSSL library binding object.
  254. :return: A :py:type:`set` of ``cls`` instances giving the names of the
  255. elliptic curves the underlying library supports.
  256. """
  257. if cls._curves is None:
  258. cls._curves = cls._load_elliptic_curves(lib)
  259. return cls._curves
  260. @classmethod
  261. def from_nid(cls, lib, nid):
  262. """
  263. Instantiate a new :py:class:`_EllipticCurve` associated with the given
  264. OpenSSL NID.
  265. :param lib: The OpenSSL library binding object.
  266. :param nid: The OpenSSL NID the resulting curve object will represent.
  267. This must be a curve NID (and not, for example, a hash NID) or
  268. subsequent operations will fail in unpredictable ways.
  269. :type nid: :py:class:`int`
  270. :return: The curve object.
  271. """
  272. return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
  273. def __init__(self, lib, nid, name):
  274. """
  275. :param _lib: The :py:mod:`cryptography` binding instance used to
  276. interface with OpenSSL.
  277. :param _nid: The OpenSSL NID identifying the curve this object
  278. represents.
  279. :type _nid: :py:class:`int`
  280. :param name: The OpenSSL short name identifying the curve this object
  281. represents.
  282. :type name: :py:class:`unicode`
  283. """
  284. self._lib = lib
  285. self._nid = nid
  286. self.name = name
  287. def __repr__(self):
  288. return "<Curve %r>" % (self.name,)
  289. def _to_EC_KEY(self):
  290. """
  291. Create a new OpenSSL EC_KEY structure initialized to use this curve.
  292. The structure is automatically garbage collected when the Python object
  293. is garbage collected.
  294. """
  295. key = self._lib.EC_KEY_new_by_curve_name(self._nid)
  296. return _ffi.gc(key, _lib.EC_KEY_free)
  297. def get_elliptic_curves():
  298. """
  299. Return a set of objects representing the elliptic curves supported in the
  300. OpenSSL build in use.
  301. The curve objects have a :py:class:`unicode` ``name`` attribute by which
  302. they identify themselves.
  303. The curve objects are useful as values for the argument accepted by
  304. :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
  305. used for ECDHE key exchange.
  306. """
  307. return _EllipticCurve._get_elliptic_curves(_lib)
  308. def get_elliptic_curve(name):
  309. """
  310. Return a single curve object selected by name.
  311. See :py:func:`get_elliptic_curves` for information about curve objects.
  312. :param name: The OpenSSL short name identifying the curve object to
  313. retrieve.
  314. :type name: :py:class:`unicode`
  315. If the named curve is not supported then :py:class:`ValueError` is raised.
  316. """
  317. for curve in get_elliptic_curves():
  318. if curve.name == name:
  319. return curve
  320. raise ValueError("unknown curve name", name)
  321. class X509Name(object):
  322. def __init__(self, name):
  323. """
  324. Create a new X509Name, copying the given X509Name instance.
  325. :param name: An X509Name object to copy
  326. """
  327. name = _lib.X509_NAME_dup(name._name)
  328. self._name = _ffi.gc(name, _lib.X509_NAME_free)
  329. def __setattr__(self, name, value):
  330. if name.startswith('_'):
  331. return super(X509Name, self).__setattr__(name, value)
  332. # Note: we really do not want str subclasses here, so we do not use
  333. # isinstance.
  334. if type(name) is not str:
  335. raise TypeError("attribute name must be string, not '%.200s'" % (
  336. type(value).__name__,))
  337. nid = _lib.OBJ_txt2nid(_byte_string(name))
  338. if nid == _lib.NID_undef:
  339. try:
  340. _raise_current_error()
  341. except Error:
  342. pass
  343. raise AttributeError("No such attribute")
  344. # If there's an old entry for this NID, remove it
  345. for i in range(_lib.X509_NAME_entry_count(self._name)):
  346. ent = _lib.X509_NAME_get_entry(self._name, i)
  347. ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
  348. ent_nid = _lib.OBJ_obj2nid(ent_obj)
  349. if nid == ent_nid:
  350. ent = _lib.X509_NAME_delete_entry(self._name, i)
  351. _lib.X509_NAME_ENTRY_free(ent)
  352. break
  353. if isinstance(value, _text_type):
  354. value = value.encode('utf-8')
  355. add_result = _lib.X509_NAME_add_entry_by_NID(
  356. self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
  357. if not add_result:
  358. _raise_current_error()
  359. def __getattr__(self, name):
  360. """
  361. Find attribute. An X509Name object has the following attributes:
  362. countryName (alias C), stateOrProvince (alias ST), locality (alias L),
  363. organization (alias O), organizationalUnit (alias OU), commonName (alias
  364. CN) and more...
  365. """
  366. nid = _lib.OBJ_txt2nid(_byte_string(name))
  367. if nid == _lib.NID_undef:
  368. # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
  369. # a lower level function, a2d_ASN1_OBJECT, also feels the need to
  370. # push something onto the error queue. If we don't clean that up
  371. # now, someone else will bump into it later and be quite confused.
  372. # See lp#314814.
  373. try:
  374. _raise_current_error()
  375. except Error:
  376. pass
  377. return super(X509Name, self).__getattr__(name)
  378. entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
  379. if entry_index == -1:
  380. return None
  381. entry = _lib.X509_NAME_get_entry(self._name, entry_index)
  382. data = _lib.X509_NAME_ENTRY_get_data(entry)
  383. result_buffer = _ffi.new("unsigned char**")
  384. data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
  385. if data_length < 0:
  386. # TODO: This is untested.
  387. _raise_current_error()
  388. try:
  389. result = _ffi.buffer(result_buffer[0], data_length)[:].decode('utf-8')
  390. finally:
  391. # XXX untested
  392. _lib.OPENSSL_free(result_buffer[0])
  393. return result
  394. def _cmp(op):
  395. def f(self, other):
  396. if not isinstance(other, X509Name):
  397. return NotImplemented
  398. result = _lib.X509_NAME_cmp(self._name, other._name)
  399. return op(result, 0)
  400. return f
  401. __eq__ = _cmp(__eq__)
  402. __ne__ = _cmp(__ne__)
  403. __lt__ = _cmp(__lt__)
  404. __le__ = _cmp(__le__)
  405. __gt__ = _cmp(__gt__)
  406. __ge__ = _cmp(__ge__)
  407. def __repr__(self):
  408. """
  409. String representation of an X509Name
  410. """
  411. result_buffer = _ffi.new("char[]", 512);
  412. format_result = _lib.X509_NAME_oneline(
  413. self._name, result_buffer, len(result_buffer))
  414. if format_result == _ffi.NULL:
  415. # TODO: This is untested.
  416. _raise_current_error()
  417. return "<X509Name object '%s'>" % (
  418. _native(_ffi.string(result_buffer)),)
  419. def hash(self):
  420. """
  421. Return the hash value of this name
  422. :return: None
  423. """
  424. return _lib.X509_NAME_hash(self._name)
  425. def der(self):
  426. """
  427. Return the DER encoding of this name
  428. :return: A :py:class:`bytes` instance giving the DER encoded form of
  429. this name.
  430. """
  431. result_buffer = _ffi.new('unsigned char**')
  432. encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
  433. if encode_result < 0:
  434. # TODO: This is untested.
  435. _raise_current_error()
  436. string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
  437. _lib.OPENSSL_free(result_buffer[0])
  438. return string_result
  439. def get_components(self):
  440. """
  441. Returns the split-up components of this name.
  442. :return: List of tuples (name, value).
  443. """
  444. result = []
  445. for i in range(_lib.X509_NAME_entry_count(self._name)):
  446. ent = _lib.X509_NAME_get_entry(self._name, i)
  447. fname = _lib.X509_NAME_ENTRY_get_object(ent)
  448. fval = _lib.X509_NAME_ENTRY_get_data(ent)
  449. nid = _lib.OBJ_obj2nid(fname)
  450. name = _lib.OBJ_nid2sn(nid)
  451. result.append((
  452. _ffi.string(name),
  453. _ffi.string(
  454. _lib.ASN1_STRING_data(fval),
  455. _lib.ASN1_STRING_length(fval))))
  456. return result
  457. X509NameType = X509Name
  458. class X509Extension(object):
  459. def __init__(self, type_name, critical, value, subject=None, issuer=None):
  460. """
  461. :param typename: The name of the extension to create.
  462. :type typename: :py:data:`str`
  463. :param critical: A flag indicating whether this is a critical extension.
  464. :param value: The value of the extension.
  465. :type value: :py:data:`str`
  466. :param subject: Optional X509 cert to use as subject.
  467. :type subject: :py:class:`X509`
  468. :param issuer: Optional X509 cert to use as issuer.
  469. :type issuer: :py:class:`X509`
  470. :return: The X509Extension object
  471. """
  472. ctx = _ffi.new("X509V3_CTX*")
  473. # A context is necessary for any extension which uses the r2i conversion
  474. # method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx.
  475. # Start off by initializing most of the fields to NULL.
  476. _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
  477. # We have no configuration database - but perhaps we should (some
  478. # extensions may require it).
  479. _lib.X509V3_set_ctx_nodb(ctx)
  480. # Initialize the subject and issuer, if appropriate. ctx is a local,
  481. # and as far as I can tell none of the X509V3_* APIs invoked here steal
  482. # any references, so no need to mess with reference counts or duplicates.
  483. if issuer is not None:
  484. if not isinstance(issuer, X509):
  485. raise TypeError("issuer must be an X509 instance")
  486. ctx.issuer_cert = issuer._x509
  487. if subject is not None:
  488. if not isinstance(subject, X509):
  489. raise TypeError("subject must be an X509 instance")
  490. ctx.subject_cert = subject._x509
  491. if critical:
  492. # There are other OpenSSL APIs which would let us pass in critical
  493. # separately, but they're harder to use, and since value is already
  494. # a pile of crappy junk smuggling a ton of utterly important
  495. # structured data, what's the point of trying to avoid nasty stuff
  496. # with strings? (However, X509V3_EXT_i2d in particular seems like it
  497. # would be a better API to invoke. I do not know where to get the
  498. # ext_struc it desires for its last parameter, though.)
  499. value = b"critical," + value
  500. extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
  501. if extension == _ffi.NULL:
  502. _raise_current_error()
  503. self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
  504. @property
  505. def _nid(self):
  506. return _lib.OBJ_obj2nid(self._extension.object)
  507. _prefixes = {
  508. _lib.GEN_EMAIL: "email",
  509. _lib.GEN_DNS: "DNS",
  510. _lib.GEN_URI: "URI",
  511. }
  512. def _subjectAltNameString(self):
  513. method = _lib.X509V3_EXT_get(self._extension)
  514. if method == _ffi.NULL:
  515. # TODO: This is untested.
  516. _raise_current_error()
  517. payload = self._extension.value.data
  518. length = self._extension.value.length
  519. payloadptr = _ffi.new("unsigned char**")
  520. payloadptr[0] = payload
  521. if method.it != _ffi.NULL:
  522. ptr = _lib.ASN1_ITEM_ptr(method.it)
  523. data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
  524. names = _ffi.cast("GENERAL_NAMES*", data)
  525. else:
  526. names = _ffi.cast(
  527. "GENERAL_NAMES*",
  528. method.d2i(_ffi.NULL, payloadptr, length))
  529. parts = []
  530. for i in range(_lib.sk_GENERAL_NAME_num(names)):
  531. name = _lib.sk_GENERAL_NAME_value(names, i)
  532. try:
  533. label = self._prefixes[name.type]
  534. except KeyError:
  535. bio = _new_mem_buf()
  536. _lib.GENERAL_NAME_print(bio, name)
  537. parts.append(_native(_bio_to_string(bio)))
  538. else:
  539. value = _native(
  540. _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
  541. parts.append(label + ":" + value)
  542. return ", ".join(parts)
  543. def __str__(self):
  544. """
  545. :return: a nice text representation of the extension
  546. """
  547. if _lib.NID_subject_alt_name == self._nid:
  548. return self._subjectAltNameString()
  549. bio = _new_mem_buf()
  550. print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
  551. if not print_result:
  552. # TODO: This is untested.
  553. _raise_current_error()
  554. return _native(_bio_to_string(bio))
  555. def get_critical(self):
  556. """
  557. Returns the critical field of the X509Extension
  558. :return: The critical field.
  559. """
  560. return _lib.X509_EXTENSION_get_critical(self._extension)
  561. def get_short_name(self):
  562. """
  563. Returns the short version of the type name of the X509Extension
  564. :return: The short type name.
  565. """
  566. obj = _lib.X509_EXTENSION_get_object(self._extension)
  567. nid = _lib.OBJ_obj2nid(obj)
  568. return _ffi.string(_lib.OBJ_nid2sn(nid))
  569. def get_data(self):
  570. """
  571. Returns the data of the X509Extension
  572. :return: A :py:data:`str` giving the X509Extension's ASN.1 encoded data.
  573. """
  574. octet_result = _lib.X509_EXTENSION_get_data(self._extension)
  575. string_result = _ffi.cast('ASN1_STRING*', octet_result)
  576. char_result = _lib.ASN1_STRING_data(string_result)
  577. result_length = _lib.ASN1_STRING_length(string_result)
  578. return _ffi.buffer(char_result, result_length)[:]
  579. X509ExtensionType = X509Extension
  580. class X509Req(object):
  581. def __init__(self):
  582. req = _lib.X509_REQ_new()
  583. self._req = _ffi.gc(req, _lib.X509_REQ_free)
  584. def set_pubkey(self, pkey):
  585. """
  586. Set the public key of the certificate request
  587. :param pkey: The public key to use
  588. :return: None
  589. """
  590. set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
  591. if not set_result:
  592. # TODO: This is untested.
  593. _raise_current_error()
  594. def get_pubkey(self):
  595. """
  596. Get the public key from the certificate request
  597. :return: The public key
  598. """
  599. pkey = PKey.__new__(PKey)
  600. pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
  601. if pkey._pkey == _ffi.NULL:
  602. # TODO: This is untested.
  603. _raise_current_error()
  604. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  605. pkey._only_public = True
  606. return pkey
  607. def set_version(self, version):
  608. """
  609. Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
  610. request.
  611. :param version: The version number
  612. :return: None
  613. """
  614. set_result = _lib.X509_REQ_set_version(self._req, version)
  615. if not set_result:
  616. _raise_current_error()
  617. def get_version(self):
  618. """
  619. Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
  620. request.
  621. :return: an integer giving the value of the version subfield
  622. """
  623. return _lib.X509_REQ_get_version(self._req)
  624. def get_subject(self):
  625. """
  626. Create an X509Name object for the subject of the certificate request
  627. :return: An X509Name object
  628. """
  629. name = X509Name.__new__(X509Name)
  630. name._name = _lib.X509_REQ_get_subject_name(self._req)
  631. if name._name == _ffi.NULL:
  632. # TODO: This is untested.
  633. _raise_current_error()
  634. # The name is owned by the X509Req structure. As long as the X509Name
  635. # Python object is alive, keep the X509Req Python object alive.
  636. name._owner = self
  637. return name
  638. def add_extensions(self, extensions):
  639. """
  640. Add extensions to the request.
  641. :param extensions: a sequence of X509Extension objects
  642. :return: None
  643. """
  644. stack = _lib.sk_X509_EXTENSION_new_null()
  645. if stack == _ffi.NULL:
  646. # TODO: This is untested.
  647. _raise_current_error()
  648. stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
  649. for ext in extensions:
  650. if not isinstance(ext, X509Extension):
  651. raise ValueError("One of the elements is not an X509Extension")
  652. # TODO push can fail (here and elsewhere)
  653. _lib.sk_X509_EXTENSION_push(stack, ext._extension)
  654. add_result = _lib.X509_REQ_add_extensions(self._req, stack)
  655. if not add_result:
  656. # TODO: This is untested.
  657. _raise_current_error()
  658. def get_extensions(self):
  659. """
  660. Get extensions to the request.
  661. :return: A :py:class:`list` of :py:class:`X509Extension` objects.
  662. """
  663. exts = []
  664. native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
  665. for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
  666. ext = X509Extension.__new__(X509Extension)
  667. ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
  668. exts.append(ext)
  669. return exts
  670. def sign(self, pkey, digest):
  671. """
  672. Sign the certificate request using the supplied key and digest
  673. :param pkey: The key to sign with
  674. :param digest: The message digest to use
  675. :return: None
  676. """
  677. if pkey._only_public:
  678. raise ValueError("Key has only public part")
  679. if not pkey._initialized:
  680. raise ValueError("Key is uninitialized")
  681. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  682. if digest_obj == _ffi.NULL:
  683. raise ValueError("No such digest method")
  684. sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
  685. if not sign_result:
  686. # TODO: This is untested.
  687. _raise_current_error()
  688. def verify(self, pkey):
  689. """
  690. Verifies a certificate request using the supplied public key
  691. :param key: a public key
  692. :return: True if the signature is correct.
  693. :raise OpenSSL.crypto.Error: If the signature is invalid or there is a
  694. problem verifying the signature.
  695. """
  696. if not isinstance(pkey, PKey):
  697. raise TypeError("pkey must be a PKey instance")
  698. result = _lib.X509_REQ_verify(self._req, pkey._pkey)
  699. if result <= 0:
  700. _raise_current_error()
  701. return result
  702. X509ReqType = X509Req
  703. class X509(object):
  704. def __init__(self):
  705. # TODO Allocation failure? And why not __new__ instead of __init__?
  706. x509 = _lib.X509_new()
  707. self._x509 = _ffi.gc(x509, _lib.X509_free)
  708. def set_version(self, version):
  709. """
  710. Set version number of the certificate
  711. :param version: The version number
  712. :type version: :py:class:`int`
  713. :return: None
  714. """
  715. if not isinstance(version, int):
  716. raise TypeError("version must be an integer")
  717. _lib.X509_set_version(self._x509, version)
  718. def get_version(self):
  719. """
  720. Return version number of the certificate
  721. :return: Version number as a Python integer
  722. """
  723. return _lib.X509_get_version(self._x509)
  724. def get_pubkey(self):
  725. """
  726. Get the public key of the certificate
  727. :return: The public key
  728. """
  729. pkey = PKey.__new__(PKey)
  730. pkey._pkey = _lib.X509_get_pubkey(self._x509)
  731. if pkey._pkey == _ffi.NULL:
  732. _raise_current_error()
  733. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  734. pkey._only_public = True
  735. return pkey
  736. def set_pubkey(self, pkey):
  737. """
  738. Set the public key of the certificate
  739. :param pkey: The public key
  740. :return: None
  741. """
  742. if not isinstance(pkey, PKey):
  743. raise TypeError("pkey must be a PKey instance")
  744. set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
  745. if not set_result:
  746. _raise_current_error()
  747. def sign(self, pkey, digest):
  748. """
  749. Sign the certificate using the supplied key and digest
  750. :param pkey: The key to sign with
  751. :param digest: The message digest to use
  752. :return: None
  753. """
  754. if not isinstance(pkey, PKey):
  755. raise TypeError("pkey must be a PKey instance")
  756. if pkey._only_public:
  757. raise ValueError("Key only has public part")
  758. if not pkey._initialized:
  759. raise ValueError("Key is uninitialized")
  760. evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
  761. if evp_md == _ffi.NULL:
  762. raise ValueError("No such digest method")
  763. sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
  764. if not sign_result:
  765. _raise_current_error()
  766. def get_signature_algorithm(self):
  767. """
  768. Retrieve the signature algorithm used in the certificate
  769. :return: A byte string giving the name of the signature algorithm used in
  770. the certificate.
  771. :raise ValueError: If the signature algorithm is undefined.
  772. """
  773. alg = self._x509.cert_info.signature.algorithm
  774. nid = _lib.OBJ_obj2nid(alg)
  775. if nid == _lib.NID_undef:
  776. raise ValueError("Undefined signature algorithm")
  777. return _ffi.string(_lib.OBJ_nid2ln(nid))
  778. def digest(self, digest_name):
  779. """
  780. Return the digest of the X509 object.
  781. :param digest_name: The name of the digest algorithm to use.
  782. :type digest_name: :py:class:`bytes`
  783. :return: The digest of the object
  784. """
  785. digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
  786. if digest == _ffi.NULL:
  787. raise ValueError("No such digest method")
  788. result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
  789. result_length = _ffi.new("unsigned int[]", 1)
  790. result_length[0] = len(result_buffer)
  791. digest_result = _lib.X509_digest(
  792. self._x509, digest, result_buffer, result_length)
  793. if not digest_result:
  794. # TODO: This is untested.
  795. _raise_current_error()
  796. return b":".join([
  797. b16encode(ch).upper() for ch
  798. in _ffi.buffer(result_buffer, result_length[0])])
  799. def subject_name_hash(self):
  800. """
  801. Return the hash of the X509 subject.
  802. :return: The hash of the subject.
  803. """
  804. return _lib.X509_subject_name_hash(self._x509)
  805. def set_serial_number(self, serial):
  806. """
  807. Set serial number of the certificate
  808. :param serial: The serial number
  809. :type serial: :py:class:`int`
  810. :return: None
  811. """
  812. if not isinstance(serial, _integer_types):
  813. raise TypeError("serial must be an integer")
  814. hex_serial = hex(serial)[2:]
  815. if not isinstance(hex_serial, bytes):
  816. hex_serial = hex_serial.encode('ascii')
  817. bignum_serial = _ffi.new("BIGNUM**")
  818. # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
  819. # it. If bignum is still NULL after this call, then the return value is
  820. # actually the result. I hope. -exarkun
  821. small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
  822. if bignum_serial[0] == _ffi.NULL:
  823. set_result = _lib.ASN1_INTEGER_set(
  824. _lib.X509_get_serialNumber(self._x509), small_serial)
  825. if set_result:
  826. # TODO Not tested
  827. _raise_current_error()
  828. else:
  829. asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
  830. _lib.BN_free(bignum_serial[0])
  831. if asn1_serial == _ffi.NULL:
  832. # TODO Not tested
  833. _raise_current_error()
  834. asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
  835. set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
  836. if not set_result:
  837. # TODO Not tested
  838. _raise_current_error()
  839. def get_serial_number(self):
  840. """
  841. Return serial number of the certificate
  842. :return: Serial number as a Python integer
  843. """
  844. asn1_serial = _lib.X509_get_serialNumber(self._x509)
  845. bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
  846. try:
  847. hex_serial = _lib.BN_bn2hex(bignum_serial)
  848. try:
  849. hexstring_serial = _ffi.string(hex_serial)
  850. serial = int(hexstring_serial, 16)
  851. return serial
  852. finally:
  853. _lib.OPENSSL_free(hex_serial)
  854. finally:
  855. _lib.BN_free(bignum_serial)
  856. def gmtime_adj_notAfter(self, amount):
  857. """
  858. Adjust the time stamp for when the certificate stops being valid
  859. :param amount: The number of seconds by which to adjust the ending
  860. validity time.
  861. :type amount: :py:class:`int`
  862. :return: None
  863. """
  864. if not isinstance(amount, int):
  865. raise TypeError("amount must be an integer")
  866. notAfter = _lib.X509_get_notAfter(self._x509)
  867. _lib.X509_gmtime_adj(notAfter, amount)
  868. def gmtime_adj_notBefore(self, amount):
  869. """
  870. Change the timestamp for when the certificate starts being valid to the current
  871. time plus an offset.
  872. :param amount: The number of seconds by which to adjust the starting validity
  873. time.
  874. :return: None
  875. """
  876. if not isinstance(amount, int):
  877. raise TypeError("amount must be an integer")
  878. notBefore = _lib.X509_get_notBefore(self._x509)
  879. _lib.X509_gmtime_adj(notBefore, amount)
  880. def has_expired(self):
  881. """
  882. Check whether the certificate has expired.
  883. :return: True if the certificate has expired, false otherwise
  884. """
  885. now = int(time())
  886. notAfter = _lib.X509_get_notAfter(self._x509)
  887. return _lib.ASN1_UTCTIME_cmp_time_t(
  888. _ffi.cast('ASN1_UTCTIME*', notAfter), now) < 0
  889. def _get_boundary_time(self, which):
  890. return _get_asn1_time(which(self._x509))
  891. def get_notBefore(self):
  892. """
  893. Retrieve the time stamp for when the certificate starts being valid
  894. :return: A string giving the timestamp, in the format::
  895. YYYYMMDDhhmmssZ
  896. YYYYMMDDhhmmss+hhmm
  897. YYYYMMDDhhmmss-hhmm
  898. or None if there is no value set.
  899. """
  900. return self._get_boundary_time(_lib.X509_get_notBefore)
  901. def _set_boundary_time(self, which, when):
  902. return _set_asn1_time(which(self._x509), when)
  903. def set_notBefore(self, when):
  904. """
  905. Set the time stamp for when the certificate starts being valid
  906. :param when: A string giving the timestamp, in the format:
  907. YYYYMMDDhhmmssZ
  908. YYYYMMDDhhmmss+hhmm
  909. YYYYMMDDhhmmss-hhmm
  910. :type when: :py:class:`bytes`
  911. :return: None
  912. """
  913. return self._set_boundary_time(_lib.X509_get_notBefore, when)
  914. def get_notAfter(self):
  915. """
  916. Retrieve the time stamp for when the certificate stops being valid
  917. :return: A string giving the timestamp, in the format::
  918. YYYYMMDDhhmmssZ
  919. YYYYMMDDhhmmss+hhmm
  920. YYYYMMDDhhmmss-hhmm
  921. or None if there is no value set.
  922. """
  923. return self._get_boundary_time(_lib.X509_get_notAfter)
  924. def set_notAfter(self, when):
  925. """
  926. Set the time stamp for when the certificate stops being valid
  927. :param when: A string giving the timestamp, in the format:
  928. YYYYMMDDhhmmssZ
  929. YYYYMMDDhhmmss+hhmm
  930. YYYYMMDDhhmmss-hhmm
  931. :type when: :py:class:`bytes`
  932. :return: None
  933. """
  934. return self._set_boundary_time(_lib.X509_get_notAfter, when)
  935. def _get_name(self, which):
  936. name = X509Name.__new__(X509Name)
  937. name._name = which(self._x509)
  938. if name._name == _ffi.NULL:
  939. # TODO: This is untested.
  940. _raise_current_error()
  941. # The name is owned by the X509 structure. As long as the X509Name
  942. # Python object is alive, keep the X509 Python object alive.
  943. name._owner = self
  944. return name
  945. def _set_name(self, which, name):
  946. if not isinstance(name, X509Name):
  947. raise TypeError("name must be an X509Name")
  948. set_result = which(self._x509, name._name)
  949. if not set_result:
  950. # TODO: This is untested.
  951. _raise_current_error()
  952. def get_issuer(self):
  953. """
  954. Create an X509Name object for the issuer of the certificate
  955. :return: An X509Name object
  956. """
  957. return self._get_name(_lib.X509_get_issuer_name)
  958. def set_issuer(self, issuer):
  959. """
  960. Set the issuer of the certificate
  961. :param issuer: The issuer name
  962. :type issuer: :py:class:`X509Name`
  963. :return: None
  964. """
  965. return self._set_name(_lib.X509_set_issuer_name, issuer)
  966. def get_subject(self):
  967. """
  968. Create an X509Name object for the subject of the certificate
  969. :return: An X509Name object
  970. """
  971. return self._get_name(_lib.X509_get_subject_name)
  972. def set_subject(self, subject):
  973. """
  974. Set the subject of the certificate
  975. :param subject: The subject name
  976. :type subject: :py:class:`X509Name`
  977. :return: None
  978. """
  979. return self._set_name(_lib.X509_set_subject_name, subject)
  980. def get_extension_count(self):
  981. """
  982. Get the number of extensions on the certificate.
  983. :return: The number of extensions as an integer.
  984. """
  985. return _lib.X509_get_ext_count(self._x509)
  986. def add_extensions(self, extensions):
  987. """
  988. Add extensions to the certificate.
  989. :param extensions: a sequence of X509Extension objects
  990. :return: None
  991. """
  992. for ext in extensions:
  993. if not isinstance(ext, X509Extension):
  994. raise ValueError("One of the elements is not an X509Extension")
  995. add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
  996. if not add_result:
  997. _raise_current_error()
  998. def get_extension(self, index):
  999. """
  1000. Get a specific extension of the certificate by index.
  1001. :param index: The index of the extension to retrieve.
  1002. :return: The X509Extension object at the specified index.
  1003. """
  1004. ext = X509Extension.__new__(X509Extension)
  1005. ext._extension = _lib.X509_get_ext(self._x509, index)
  1006. if ext._extension == _ffi.NULL:
  1007. raise IndexError("extension index out of bounds")
  1008. extension = _lib.X509_EXTENSION_dup(ext._extension)
  1009. ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
  1010. return ext
  1011. X509Type = X509
  1012. class X509Store(object):
  1013. def __init__(self):
  1014. store = _lib.X509_STORE_new()
  1015. self._store = _ffi.gc(store, _lib.X509_STORE_free)
  1016. def add_cert(self, cert):
  1017. if not isinstance(cert, X509):
  1018. raise TypeError()
  1019. result = _lib.X509_STORE_add_cert(self._store, cert._x509)
  1020. if not result:
  1021. _raise_current_error()
  1022. X509StoreType = X509Store
  1023. class X509StoreContextError(Exception):
  1024. """
  1025. An error occurred while verifying a certificate using
  1026. `OpenSSL.X509StoreContext.verify_certificate`.
  1027. :ivar certificate: The certificate which caused verificate failure.
  1028. :type cert: :class:`X509`
  1029. """
  1030. def __init__(self, message, certificate):
  1031. super(X509StoreContextError, self).__init__(message)
  1032. self.certificate = certificate
  1033. class X509StoreContext(object):
  1034. """
  1035. An X.509 store context.
  1036. An :py:class:`X509StoreContext` is used to define some of the criteria for
  1037. certificate verification. The information encapsulated in this object
  1038. includes, but is not limited to, a set of trusted certificates,
  1039. verification parameters, and revoked certificates.
  1040. Of these, only the set of trusted certificates is currently exposed.
  1041. :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
  1042. instance. It is dynamically allocated and automatically garbage
  1043. collected.
  1044. :ivar _store: See the ``store`` ``__init__`` parameter.
  1045. :ivar _cert: See the ``certificate`` ``__init__`` parameter.
  1046. """
  1047. def __init__(self, store, certificate):
  1048. """
  1049. :param X509Store store: The certificates which will be trusted for the
  1050. purposes of any verifications.
  1051. :param X509 certificate: The certificate to be verified.
  1052. """
  1053. store_ctx = _lib.X509_STORE_CTX_new()
  1054. self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
  1055. self._store = store
  1056. self._cert = certificate
  1057. # Make the store context available for use after instantiating this
  1058. # class by initializing it now. Per testing, subsequent calls to
  1059. # :py:meth:`_init` have no adverse affect.
  1060. self._init()
  1061. def _init(self):
  1062. """
  1063. Set up the store context for a subsequent verification operation.
  1064. """
  1065. ret = _lib.X509_STORE_CTX_init(self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL)
  1066. if ret <= 0:
  1067. _raise_current_error()
  1068. def _cleanup(self):
  1069. """
  1070. Internally cleans up the store context.
  1071. The store context can then be reused with a new call to
  1072. :py:meth:`_init`.
  1073. """
  1074. _lib.X509_STORE_CTX_cleanup(self._store_ctx)
  1075. def _exception_from_context(self):
  1076. """
  1077. Convert an OpenSSL native context error failure into a Python
  1078. exception.
  1079. When a call to native OpenSSL X509_verify_cert fails, additonal information
  1080. about the failure can be obtained from the store context.
  1081. """
  1082. errors = [
  1083. _lib.X509_STORE_CTX_get_error(self._store_ctx),
  1084. _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
  1085. _native(_ffi.string(_lib.X509_verify_cert_error_string(
  1086. _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
  1087. ]
  1088. # A context error should always be associated with a certificate, so we
  1089. # expect this call to never return :class:`None`.
  1090. _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
  1091. _cert = _lib.X509_dup(_x509)
  1092. pycert = X509.__new__(X509)
  1093. pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
  1094. return X509StoreContextError(errors, pycert)
  1095. def set_store(self, store):
  1096. """
  1097. Set the context's trust store.
  1098. :param X509Store store: The certificates which will be trusted for the
  1099. purposes of any *future* verifications.
  1100. """
  1101. self._store = store
  1102. def verify_certificate(self):
  1103. """
  1104. Verify a certificate in a context.
  1105. :param store_ctx: The :py:class:`X509StoreContext` to verify.
  1106. :raises: Error
  1107. """
  1108. # Always re-initialize the store context in case
  1109. # :py:meth:`verify_certificate` is called multiple times.
  1110. self._init()
  1111. ret = _lib.X509_verify_cert(self._store_ctx)
  1112. self._cleanup()
  1113. if ret <= 0:
  1114. raise self._exception_from_context()
  1115. def load_certificate(type, buffer):
  1116. """
  1117. Load a certificate from a buffer
  1118. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1119. :param buffer: The buffer the certificate is stored in
  1120. :type buffer: :py:class:`bytes`
  1121. :return: The X509 object
  1122. """
  1123. if isinstance(buffer, _text_type):
  1124. buffer = buffer.encode("ascii")
  1125. bio = _new_mem_buf(buffer)
  1126. if type == FILETYPE_PEM:
  1127. x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  1128. elif type == FILETYPE_ASN1:
  1129. x509 = _lib.d2i_X509_bio(bio, _ffi.NULL);
  1130. else:
  1131. raise ValueError(
  1132. "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1133. if x509 == _ffi.NULL:
  1134. _raise_current_error()
  1135. cert = X509.__new__(X509)
  1136. cert._x509 = _ffi.gc(x509, _lib.X509_free)
  1137. return cert
  1138. def dump_certificate(type, cert):
  1139. """
  1140. Dump a certificate to a buffer
  1141. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
  1142. FILETYPE_TEXT)
  1143. :param cert: The certificate to dump
  1144. :return: The buffer with the dumped certificate in
  1145. """
  1146. bio = _new_mem_buf()
  1147. if type == FILETYPE_PEM:
  1148. result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
  1149. elif type == FILETYPE_ASN1:
  1150. result_code = _lib.i2d_X509_bio(bio, cert._x509)
  1151. elif type == FILETYPE_TEXT:
  1152. result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
  1153. else:
  1154. raise ValueError(
  1155. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  1156. "FILETYPE_TEXT")
  1157. return _bio_to_string(bio)
  1158. def dump_privatekey(type, pkey, cipher=None, passphrase=None):
  1159. """
  1160. Dump a private key to a buffer
  1161. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
  1162. FILETYPE_TEXT)
  1163. :param pkey: The PKey to dump
  1164. :param cipher: (optional) if encrypted PEM format, the cipher to
  1165. use
  1166. :param passphrase: (optional) if encrypted PEM format, this can be either
  1167. the passphrase to use, or a callback for providing the
  1168. passphrase.
  1169. :return: The buffer with the dumped key in
  1170. :rtype: :py:data:`str`
  1171. """
  1172. bio = _new_mem_buf()
  1173. if cipher is not None:
  1174. if passphrase is None:
  1175. raise TypeError(
  1176. "if a value is given for cipher "
  1177. "one must also be given for passphrase")
  1178. cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
  1179. if cipher_obj == _ffi.NULL:
  1180. raise ValueError("Invalid cipher name")
  1181. else:
  1182. cipher_obj = _ffi.NULL
  1183. helper = _PassphraseHelper(type, passphrase)
  1184. if type == FILETYPE_PEM:
  1185. result_code = _lib.PEM_write_bio_PrivateKey(
  1186. bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
  1187. helper.callback, helper.callback_args)
  1188. helper.raise_if_problem()
  1189. elif type == FILETYPE_ASN1:
  1190. result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
  1191. elif type == FILETYPE_TEXT:
  1192. rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)
  1193. result_code = _lib.RSA_print(bio, rsa, 0)
  1194. # TODO RSA_free(rsa)?
  1195. else:
  1196. raise ValueError(
  1197. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
  1198. "FILETYPE_TEXT")
  1199. if result_code == 0:
  1200. _raise_current_error()
  1201. return _bio_to_string(bio)
  1202. def _X509_REVOKED_dup(original):
  1203. copy = _lib.X509_REVOKED_new()
  1204. if copy == _ffi.NULL:
  1205. # TODO: This is untested.
  1206. _raise_current_error()
  1207. if original.serialNumber != _ffi.NULL:
  1208. _lib.ASN1_INTEGER_free(copy.serialNumber)
  1209. copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)
  1210. if original.revocationDate != _ffi.NULL:
  1211. _lib.ASN1_TIME_free(copy.revocationDate)
  1212. copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)
  1213. if original.extensions != _ffi.NULL:
  1214. extension_stack = _lib.sk_X509_EXTENSION_new_null()
  1215. for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):
  1216. original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)
  1217. copy_ext = _lib.X509_EXTENSION_dup(original_ext)
  1218. _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)
  1219. copy.extensions = extension_stack
  1220. copy.sequence = original.sequence
  1221. return copy
  1222. class Revoked(object):
  1223. # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
  1224. # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
  1225. # OCSP_crl_reason_str. We use the latter, just like the command line
  1226. # program.
  1227. _crl_reasons = [
  1228. b"unspecified",
  1229. b"keyCompromise",
  1230. b"CACompromise",
  1231. b"affiliationChanged",
  1232. b"superseded",
  1233. b"cessationOfOperation",
  1234. b"certificateHold",
  1235. # b"removeFromCRL",
  1236. ]
  1237. def __init__(self):
  1238. revoked = _lib.X509_REVOKED_new()
  1239. self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
  1240. def set_serial(self, hex_str):
  1241. """
  1242. Set the serial number of a revoked Revoked structure
  1243. :param hex_str: The new serial number.
  1244. :type hex_str: :py:data:`str`
  1245. :return: None
  1246. """
  1247. bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
  1248. bignum_ptr = _ffi.new("BIGNUM**")
  1249. bignum_ptr[0] = bignum_serial
  1250. bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
  1251. if not bn_result:
  1252. raise ValueError("bad hex string")
  1253. asn1_serial = _ffi.gc(
  1254. _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
  1255. _lib.ASN1_INTEGER_free)
  1256. _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
  1257. def get_serial(self):
  1258. """
  1259. Return the serial number of a Revoked structure
  1260. :return: The serial number as a string
  1261. """
  1262. bio = _new_mem_buf()
  1263. result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)
  1264. if result < 0:
  1265. # TODO: This is untested.
  1266. _raise_current_error()
  1267. return _bio_to_string(bio)
  1268. def _delete_reason(self):
  1269. stack = self._revoked.extensions
  1270. for i in range(_lib.sk_X509_EXTENSION_num(stack)):
  1271. ext = _lib.sk_X509_EXTENSION_value(stack, i)
  1272. if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
  1273. _lib.X509_EXTENSION_free(ext)
  1274. _lib.sk_X509_EXTENSION_delete(stack, i)
  1275. break
  1276. def set_reason(self, reason):
  1277. """
  1278. Set the reason of a Revoked object.
  1279. If :py:data:`reason` is :py:data:`None`, delete the reason instead.
  1280. :param reason: The reason string.
  1281. :type reason: :py:class:`str` or :py:class:`NoneType`
  1282. :return: None
  1283. """
  1284. if reason is None:
  1285. self._delete_reason()
  1286. elif not isinstance(reason, bytes):
  1287. raise TypeError("reason must be None or a byte string")
  1288. else:
  1289. reason = reason.lower().replace(b' ', b'')
  1290. reason_code = [r.lower() for r in self._crl_reasons].index(reason)
  1291. new_reason_ext = _lib.ASN1_ENUMERATED_new()
  1292. if new_reason_ext == _ffi.NULL:
  1293. # TODO: This is untested.
  1294. _raise_current_error()
  1295. new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
  1296. set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
  1297. if set_result == _ffi.NULL:
  1298. # TODO: This is untested.
  1299. _raise_current_error()
  1300. self._delete_reason()
  1301. add_result = _lib.X509_REVOKED_add1_ext_i2d(
  1302. self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
  1303. if not add_result:
  1304. # TODO: This is untested.
  1305. _raise_current_error()
  1306. def get_reason(self):
  1307. """
  1308. Return the reason of a Revoked object.
  1309. :return: The reason as a string
  1310. """
  1311. extensions = self._revoked.extensions
  1312. for i in range(_lib.sk_X509_EXTENSION_num(extensions)):
  1313. ext = _lib.sk_X509_EXTENSION_value(extensions, i)
  1314. if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
  1315. bio = _new_mem_buf()
  1316. print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
  1317. if not print_result:
  1318. print_result = _lib.M_ASN1_OCTET_STRING_print(bio, ext.value)
  1319. if print_result == 0:
  1320. # TODO: This is untested.
  1321. _raise_current_error()
  1322. return _bio_to_string(bio)
  1323. def all_reasons(self):
  1324. """
  1325. Return a list of all the supported reason strings.
  1326. :return: A list of reason strings.
  1327. """
  1328. return self._crl_reasons[:]
  1329. def set_rev_date(self, when):
  1330. """
  1331. Set the revocation timestamp
  1332. :param when: A string giving the timestamp, in the format:
  1333. YYYYMMDDhhmmssZ
  1334. YYYYMMDDhhmmss+hhmm
  1335. YYYYMMDDhhmmss-hhmm
  1336. :return: None
  1337. """
  1338. return _set_asn1_time(self._revoked.revocationDate, when)
  1339. def get_rev_date(self):
  1340. """
  1341. Retrieve the revocation date
  1342. :return: A string giving the timestamp, in the format:
  1343. YYYYMMDDhhmmssZ
  1344. YYYYMMDDhhmmss+hhmm
  1345. YYYYMMDDhhmmss-hhmm
  1346. """
  1347. return _get_asn1_time(self._revoked.revocationDate)
  1348. class CRL(object):
  1349. def __init__(self):
  1350. """
  1351. Create a new empty CRL object.
  1352. """
  1353. crl = _lib.X509_CRL_new()
  1354. self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
  1355. def get_revoked(self):
  1356. """
  1357. Return revoked portion of the CRL structure (by value not reference).
  1358. :return: A tuple of Revoked objects.
  1359. """
  1360. results = []
  1361. revoked_stack = self._crl.crl.revoked
  1362. for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
  1363. revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
  1364. revoked_copy = _X509_REVOKED_dup(revoked)
  1365. pyrev = Revoked.__new__(Revoked)
  1366. pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
  1367. results.append(pyrev)
  1368. if results:
  1369. return tuple(results)
  1370. def add_revoked(self, revoked):
  1371. """
  1372. Add a revoked (by value not reference) to the CRL structure
  1373. :param revoked: The new revoked.
  1374. :type revoked: :class:`X509`
  1375. :return: None
  1376. """
  1377. copy = _X509_REVOKED_dup(revoked._revoked)
  1378. if copy == _ffi.NULL:
  1379. # TODO: This is untested.
  1380. _raise_current_error()
  1381. add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
  1382. if add_result == 0:
  1383. # TODO: This is untested.
  1384. _raise_current_error()
  1385. def export(self, cert, key, type=FILETYPE_PEM, days=100,
  1386. digest=_UNSPECIFIED):
  1387. """
  1388. export a CRL as a string
  1389. :param cert: Used to sign CRL.
  1390. :type cert: :class:`X509`
  1391. :param key: Used to sign CRL.
  1392. :type key: :class:`PKey`
  1393. :param type: The export format, either :py:data:`FILETYPE_PEM`,
  1394. :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.
  1395. :param int days: The number of days until the next update of this CRL.
  1396. :param bytes digest: The name of the message digest to use (eg
  1397. ``b"sha1"``).
  1398. :return: :py:data:`bytes`
  1399. """
  1400. if not isinstance(cert, X509):
  1401. raise TypeError("cert must be an X509 instance")
  1402. if not isinstance(key, PKey):
  1403. raise TypeError("key must be a PKey instance")
  1404. if not isinstance(type, int):
  1405. raise TypeError("type must be an integer")
  1406. if digest is _UNSPECIFIED:
  1407. _warn(
  1408. "The default message digest (md5) is deprecated. "
  1409. "Pass the name of a message digest explicitly.",
  1410. category=DeprecationWarning,
  1411. stacklevel=2,
  1412. )
  1413. digest = b"md5"
  1414. digest_obj = _lib.EVP_get_digestbyname(digest)
  1415. if digest_obj == _ffi.NULL:
  1416. raise ValueError("No such digest method")
  1417. bio = _lib.BIO_new(_lib.BIO_s_mem())
  1418. if bio == _ffi.NULL:
  1419. # TODO: This is untested.
  1420. _raise_current_error()
  1421. # A scratch time object to give different values to different CRL fields
  1422. sometime = _lib.ASN1_TIME_new()
  1423. if sometime == _ffi.NULL:
  1424. # TODO: This is untested.
  1425. _raise_current_error()
  1426. _lib.X509_gmtime_adj(sometime, 0)
  1427. _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
  1428. _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
  1429. _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
  1430. _lib.X509_CRL_set_issuer_name(self._crl, _lib.X509_get_subject_name(cert._x509))
  1431. sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
  1432. if not sign_result:
  1433. _raise_current_error()
  1434. if type == FILETYPE_PEM:
  1435. ret = _lib.PEM_write_bio_X509_CRL(bio, self._crl)
  1436. elif type == FILETYPE_ASN1:
  1437. ret = _lib.i2d_X509_CRL_bio(bio, self._crl)
  1438. elif type == FILETYPE_TEXT:
  1439. ret = _lib.X509_CRL_print(bio, self._crl)
  1440. else:
  1441. raise ValueError(
  1442. "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")
  1443. if not ret:
  1444. # TODO: This is untested.
  1445. _raise_current_error()
  1446. return _bio_to_string(bio)
  1447. CRLType = CRL
  1448. class PKCS7(object):
  1449. def type_is_signed(self):
  1450. """
  1451. Check if this NID_pkcs7_signed object
  1452. :return: True if the PKCS7 is of type signed
  1453. """
  1454. if _lib.PKCS7_type_is_signed(self._pkcs7):
  1455. return True
  1456. return False
  1457. def type_is_enveloped(self):
  1458. """
  1459. Check if this NID_pkcs7_enveloped object
  1460. :returns: True if the PKCS7 is of type enveloped
  1461. """
  1462. if _lib.PKCS7_type_is_enveloped(self._pkcs7):
  1463. return True
  1464. return False
  1465. def type_is_signedAndEnveloped(self):
  1466. """
  1467. Check if this NID_pkcs7_signedAndEnveloped object
  1468. :returns: True if the PKCS7 is of type signedAndEnveloped
  1469. """
  1470. if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
  1471. return True
  1472. return False
  1473. def type_is_data(self):
  1474. """
  1475. Check if this NID_pkcs7_data object
  1476. :return: True if the PKCS7 is of type data
  1477. """
  1478. if _lib.PKCS7_type_is_data(self._pkcs7):
  1479. return True
  1480. return False
  1481. def get_type_name(self):
  1482. """
  1483. Returns the type name of the PKCS7 structure
  1484. :return: A string with the typename
  1485. """
  1486. nid = _lib.OBJ_obj2nid(self._pkcs7.type)
  1487. string_type = _lib.OBJ_nid2sn(nid)
  1488. return _ffi.string(string_type)
  1489. PKCS7Type = PKCS7
  1490. class PKCS12(object):
  1491. def __init__(self):
  1492. self._pkey = None
  1493. self._cert = None
  1494. self._cacerts = None
  1495. self._friendlyname = None
  1496. def get_certificate(self):
  1497. """
  1498. Return certificate portion of the PKCS12 structure
  1499. :return: X509 object containing the certificate
  1500. """
  1501. return self._cert
  1502. def set_certificate(self, cert):
  1503. """
  1504. Replace the certificate portion of the PKCS12 structure
  1505. :param cert: The new certificate.
  1506. :type cert: :py:class:`X509` or :py:data:`None`
  1507. :return: None
  1508. """
  1509. if not isinstance(cert, X509):
  1510. raise TypeError("cert must be an X509 instance")
  1511. self._cert = cert
  1512. def get_privatekey(self):
  1513. """
  1514. Return private key portion of the PKCS12 structure
  1515. :returns: PKey object containing the private key
  1516. """
  1517. return self._pkey
  1518. def set_privatekey(self, pkey):
  1519. """
  1520. Replace or set the certificate portion of the PKCS12 structure
  1521. :param pkey: The new private key.
  1522. :type pkey: :py:class:`PKey`
  1523. :return: None
  1524. """
  1525. if not isinstance(pkey, PKey):
  1526. raise TypeError("pkey must be a PKey instance")
  1527. self._pkey = pkey
  1528. def get_ca_certificates(self):
  1529. """
  1530. Return CA certificates within of the PKCS12 object
  1531. :return: A newly created tuple containing the CA certificates in the chain,
  1532. if any are present, or None if no CA certificates are present.
  1533. """
  1534. if self._cacerts is not None:
  1535. return tuple(self._cacerts)
  1536. def set_ca_certificates(self, cacerts):
  1537. """
  1538. Replace or set the CA certificates within the PKCS12 object.
  1539. :param cacerts: The new CA certificates.
  1540. :type cacerts: :py:data:`None` or an iterable of :py:class:`X509`
  1541. :return: None
  1542. """
  1543. if cacerts is None:
  1544. self._cacerts = None
  1545. else:
  1546. cacerts = list(cacerts)
  1547. for cert in cacerts:
  1548. if not isinstance(cert, X509):
  1549. raise TypeError("iterable must only contain X509 instances")
  1550. self._cacerts = cacerts
  1551. def set_friendlyname(self, name):
  1552. """
  1553. Replace or set the certificate portion of the PKCS12 structure
  1554. :param name: The new friendly name.
  1555. :type name: :py:class:`bytes`
  1556. :return: None
  1557. """
  1558. if name is None:
  1559. self._friendlyname = None
  1560. elif not isinstance(name, bytes):
  1561. raise TypeError("name must be a byte string or None (not %r)" % (name,))
  1562. self._friendlyname = name
  1563. def get_friendlyname(self):
  1564. """
  1565. Return friendly name portion of the PKCS12 structure
  1566. :returns: String containing the friendlyname
  1567. """
  1568. return self._friendlyname
  1569. def export(self, passphrase=None, iter=2048, maciter=1):
  1570. """
  1571. Dump a PKCS12 object as a string. See also "man PKCS12_create".
  1572. :param passphrase: used to encrypt the PKCS12
  1573. :type passphrase: :py:data:`bytes`
  1574. :param iter: How many times to repeat the encryption
  1575. :type iter: :py:data:`int`
  1576. :param maciter: How many times to repeat the MAC
  1577. :type maciter: :py:data:`int`
  1578. :return: The string containing the PKCS12
  1579. """
  1580. passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
  1581. if self._cacerts is None:
  1582. cacerts = _ffi.NULL
  1583. else:
  1584. cacerts = _lib.sk_X509_new_null()
  1585. cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
  1586. for cert in self._cacerts:
  1587. _lib.sk_X509_push(cacerts, cert._x509)
  1588. if passphrase is None:
  1589. passphrase = _ffi.NULL
  1590. friendlyname = self._friendlyname
  1591. if friendlyname is None:
  1592. friendlyname = _ffi.NULL
  1593. if self._pkey is None:
  1594. pkey = _ffi.NULL
  1595. else:
  1596. pkey = self._pkey._pkey
  1597. if self._cert is None:
  1598. cert = _ffi.NULL
  1599. else:
  1600. cert = self._cert._x509
  1601. pkcs12 = _lib.PKCS12_create(
  1602. passphrase, friendlyname, pkey, cert, cacerts,
  1603. _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  1604. _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
  1605. iter, maciter, 0)
  1606. if pkcs12 == _ffi.NULL:
  1607. _raise_current_error()
  1608. pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
  1609. bio = _new_mem_buf()
  1610. _lib.i2d_PKCS12_bio(bio, pkcs12)
  1611. return _bio_to_string(bio)
  1612. PKCS12Type = PKCS12
  1613. class NetscapeSPKI(object):
  1614. def __init__(self):
  1615. spki = _lib.NETSCAPE_SPKI_new()
  1616. self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
  1617. def sign(self, pkey, digest):
  1618. """
  1619. Sign the certificate request using the supplied key and digest
  1620. :param pkey: The key to sign with
  1621. :param digest: The message digest to use
  1622. :return: None
  1623. """
  1624. if pkey._only_public:
  1625. raise ValueError("Key has only public part")
  1626. if not pkey._initialized:
  1627. raise ValueError("Key is uninitialized")
  1628. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  1629. if digest_obj == _ffi.NULL:
  1630. raise ValueError("No such digest method")
  1631. sign_result = _lib.NETSCAPE_SPKI_sign(self._spki, pkey._pkey, digest_obj)
  1632. if not sign_result:
  1633. # TODO: This is untested.
  1634. _raise_current_error()
  1635. def verify(self, key):
  1636. """
  1637. Verifies a certificate request using the supplied public key
  1638. :param key: a public key
  1639. :return: True if the signature is correct.
  1640. :raise OpenSSL.crypto.Error: If the signature is invalid or there is a
  1641. problem verifying the signature.
  1642. """
  1643. answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
  1644. if answer <= 0:
  1645. _raise_current_error()
  1646. return True
  1647. def b64_encode(self):
  1648. """
  1649. Generate a base64 encoded string from an SPKI
  1650. :return: The base64 encoded string
  1651. """
  1652. encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
  1653. result = _ffi.string(encoded)
  1654. _lib.CRYPTO_free(encoded)
  1655. return result
  1656. def get_pubkey(self):
  1657. """
  1658. Get the public key of the certificate
  1659. :return: The public key
  1660. """
  1661. pkey = PKey.__new__(PKey)
  1662. pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
  1663. if pkey._pkey == _ffi.NULL:
  1664. # TODO: This is untested.
  1665. _raise_current_error()
  1666. pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
  1667. pkey._only_public = True
  1668. return pkey
  1669. def set_pubkey(self, pkey):
  1670. """
  1671. Set the public key of the certificate
  1672. :param pkey: The public key
  1673. :return: None
  1674. """
  1675. set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
  1676. if not set_result:
  1677. # TODO: This is untested.
  1678. _raise_current_error()
  1679. NetscapeSPKIType = NetscapeSPKI
  1680. class _PassphraseHelper(object):
  1681. def __init__(self, type, passphrase, more_args=False, truncate=False):
  1682. if type != FILETYPE_PEM and passphrase is not None:
  1683. raise ValueError("only FILETYPE_PEM key format supports encryption")
  1684. self._passphrase = passphrase
  1685. self._more_args = more_args
  1686. self._truncate = truncate
  1687. self._problems = []
  1688. @property
  1689. def callback(self):
  1690. if self._passphrase is None:
  1691. return _ffi.NULL
  1692. elif isinstance(self._passphrase, bytes):
  1693. return _ffi.NULL
  1694. elif callable(self._passphrase):
  1695. return _ffi.callback("pem_password_cb", self._read_passphrase)
  1696. else:
  1697. raise TypeError("Last argument must be string or callable")
  1698. @property
  1699. def callback_args(self):
  1700. if self._passphrase is None:
  1701. return _ffi.NULL
  1702. elif isinstance(self._passphrase, bytes):
  1703. return self._passphrase
  1704. elif callable(self._passphrase):
  1705. return _ffi.NULL
  1706. else:
  1707. raise TypeError("Last argument must be string or callable")
  1708. def raise_if_problem(self, exceptionType=Error):
  1709. try:
  1710. _exception_from_error_queue(exceptionType)
  1711. except exceptionType as e:
  1712. from_queue = e
  1713. if self._problems:
  1714. raise self._problems[0]
  1715. return from_queue
  1716. def _read_passphrase(self, buf, size, rwflag, userdata):
  1717. try:
  1718. if self._more_args:
  1719. result = self._passphrase(size, rwflag, userdata)
  1720. else:
  1721. result = self._passphrase(rwflag)
  1722. if not isinstance(result, bytes):
  1723. raise ValueError("String expected")
  1724. if len(result) > size:
  1725. if self._truncate:
  1726. result = result[:size]
  1727. else:
  1728. raise ValueError("passphrase returned by callback is too long")
  1729. for i in range(len(result)):
  1730. buf[i] = result[i:i + 1]
  1731. return len(result)
  1732. except Exception as e:
  1733. self._problems.append(e)
  1734. return 0
  1735. def load_privatekey(type, buffer, passphrase=None):
  1736. """
  1737. Load a private key from a buffer
  1738. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1739. :param buffer: The buffer the key is stored in
  1740. :param passphrase: (optional) if encrypted PEM format, this can be
  1741. either the passphrase to use, or a callback for
  1742. providing the passphrase.
  1743. :return: The PKey object
  1744. """
  1745. if isinstance(buffer, _text_type):
  1746. buffer = buffer.encode("ascii")
  1747. bio = _new_mem_buf(buffer)
  1748. helper = _PassphraseHelper(type, passphrase)
  1749. if type == FILETYPE_PEM:
  1750. evp_pkey = _lib.PEM_read_bio_PrivateKey(
  1751. bio, _ffi.NULL, helper.callback, helper.callback_args)
  1752. helper.raise_if_problem()
  1753. elif type == FILETYPE_ASN1:
  1754. evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
  1755. else:
  1756. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1757. if evp_pkey == _ffi.NULL:
  1758. _raise_current_error()
  1759. pkey = PKey.__new__(PKey)
  1760. pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
  1761. return pkey
  1762. def dump_certificate_request(type, req):
  1763. """
  1764. Dump a certificate request to a buffer
  1765. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1766. :param req: The certificate request to dump
  1767. :return: The buffer with the dumped certificate request in
  1768. """
  1769. bio = _new_mem_buf()
  1770. if type == FILETYPE_PEM:
  1771. result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
  1772. elif type == FILETYPE_ASN1:
  1773. result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
  1774. elif type == FILETYPE_TEXT:
  1775. result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
  1776. else:
  1777. raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")
  1778. if result_code == 0:
  1779. # TODO: This is untested.
  1780. _raise_current_error()
  1781. return _bio_to_string(bio)
  1782. def load_certificate_request(type, buffer):
  1783. """
  1784. Load a certificate request from a buffer
  1785. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1786. :param buffer: The buffer the certificate request is stored in
  1787. :return: The X509Req object
  1788. """
  1789. if isinstance(buffer, _text_type):
  1790. buffer = buffer.encode("ascii")
  1791. bio = _new_mem_buf(buffer)
  1792. if type == FILETYPE_PEM:
  1793. req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  1794. elif type == FILETYPE_ASN1:
  1795. req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
  1796. else:
  1797. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1798. if req == _ffi.NULL:
  1799. # TODO: This is untested.
  1800. _raise_current_error()
  1801. x509req = X509Req.__new__(X509Req)
  1802. x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
  1803. return x509req
  1804. def sign(pkey, data, digest):
  1805. """
  1806. Sign data with a digest
  1807. :param pkey: Pkey to sign with
  1808. :param data: data to be signed
  1809. :param digest: message digest to use
  1810. :return: signature
  1811. """
  1812. data = _text_to_bytes_and_warn("data", data)
  1813. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  1814. if digest_obj == _ffi.NULL:
  1815. raise ValueError("No such digest method")
  1816. md_ctx = _ffi.new("EVP_MD_CTX*")
  1817. md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
  1818. _lib.EVP_SignInit(md_ctx, digest_obj)
  1819. _lib.EVP_SignUpdate(md_ctx, data, len(data))
  1820. signature_buffer = _ffi.new("unsigned char[]", 512)
  1821. signature_length = _ffi.new("unsigned int*")
  1822. signature_length[0] = len(signature_buffer)
  1823. final_result = _lib.EVP_SignFinal(
  1824. md_ctx, signature_buffer, signature_length, pkey._pkey)
  1825. if final_result != 1:
  1826. # TODO: This is untested.
  1827. _raise_current_error()
  1828. return _ffi.buffer(signature_buffer, signature_length[0])[:]
  1829. def verify(cert, signature, data, digest):
  1830. """
  1831. Verify a signature
  1832. :param cert: signing certificate (X509 object)
  1833. :param signature: signature returned by sign function
  1834. :param data: data to be verified
  1835. :param digest: message digest to use
  1836. :return: None if the signature is correct, raise exception otherwise
  1837. """
  1838. data = _text_to_bytes_and_warn("data", data)
  1839. digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
  1840. if digest_obj == _ffi.NULL:
  1841. raise ValueError("No such digest method")
  1842. pkey = _lib.X509_get_pubkey(cert._x509)
  1843. if pkey == _ffi.NULL:
  1844. # TODO: This is untested.
  1845. _raise_current_error()
  1846. pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
  1847. md_ctx = _ffi.new("EVP_MD_CTX*")
  1848. md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
  1849. _lib.EVP_VerifyInit(md_ctx, digest_obj)
  1850. _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
  1851. verify_result = _lib.EVP_VerifyFinal(md_ctx, signature, len(signature), pkey)
  1852. if verify_result != 1:
  1853. _raise_current_error()
  1854. def load_crl(type, buffer):
  1855. """
  1856. Load a certificate revocation list from a buffer
  1857. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
  1858. :param buffer: The buffer the CRL is stored in
  1859. :return: The PKey object
  1860. """
  1861. if isinstance(buffer, _text_type):
  1862. buffer = buffer.encode("ascii")
  1863. bio = _new_mem_buf(buffer)
  1864. if type == FILETYPE_PEM:
  1865. crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  1866. elif type == FILETYPE_ASN1:
  1867. crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
  1868. else:
  1869. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1870. if crl == _ffi.NULL:
  1871. _raise_current_error()
  1872. result = CRL.__new__(CRL)
  1873. result._crl = crl
  1874. return result
  1875. def load_pkcs7_data(type, buffer):
  1876. """
  1877. Load pkcs7 data from a buffer
  1878. :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
  1879. :param buffer: The buffer with the pkcs7 data.
  1880. :return: The PKCS7 object
  1881. """
  1882. if isinstance(buffer, _text_type):
  1883. buffer = buffer.encode("ascii")
  1884. bio = _new_mem_buf(buffer)
  1885. if type == FILETYPE_PEM:
  1886. pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
  1887. elif type == FILETYPE_ASN1:
  1888. pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
  1889. else:
  1890. # TODO: This is untested.
  1891. _raise_current_error()
  1892. raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
  1893. if pkcs7 == _ffi.NULL:
  1894. _raise_current_error()
  1895. pypkcs7 = PKCS7.__new__(PKCS7)
  1896. pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
  1897. return pypkcs7
  1898. def load_pkcs12(buffer, passphrase=None):
  1899. """
  1900. Load a PKCS12 object from a buffer
  1901. :param buffer: The buffer the certificate is stored in
  1902. :param passphrase: (Optional) The password to decrypt the PKCS12 lump
  1903. :returns: The PKCS12 object
  1904. """
  1905. passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
  1906. if isinstance(buffer, _text_type):
  1907. buffer = buffer.encode("ascii")
  1908. bio = _new_mem_buf(buffer)
  1909. # Use null passphrase if passphrase is None or empty string. With PKCS#12
  1910. # password based encryption no password and a zero length password are two
  1911. # different things, but OpenSSL implementation will try both to figure out
  1912. # which one works.
  1913. if not passphrase:
  1914. passphrase = _ffi.NULL
  1915. p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
  1916. if p12 == _ffi.NULL:
  1917. _raise_current_error()
  1918. p12 = _ffi.gc(p12, _lib.PKCS12_free)
  1919. pkey = _ffi.new("EVP_PKEY**")
  1920. cert = _ffi.new("X509**")
  1921. cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
  1922. parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
  1923. if not parse_result:
  1924. _raise_current_error()
  1925. cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
  1926. # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
  1927. # queue for no particular reason. This error isn't interesting to anyone
  1928. # outside this function. It's not even interesting to us. Get rid of it.
  1929. try:
  1930. _raise_current_error()
  1931. except Error:
  1932. pass
  1933. if pkey[0] == _ffi.NULL:
  1934. pykey = None
  1935. else:
  1936. pykey = PKey.__new__(PKey)
  1937. pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
  1938. if cert[0] == _ffi.NULL:
  1939. pycert = None
  1940. friendlyname = None
  1941. else:
  1942. pycert = X509.__new__(X509)
  1943. pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
  1944. friendlyname_length = _ffi.new("int*")
  1945. friendlyname_buffer = _lib.X509_alias_get0(cert[0], friendlyname_length)
  1946. friendlyname = _ffi.buffer(friendlyname_buffer, friendlyname_length[0])[:]
  1947. if friendlyname_buffer == _ffi.NULL:
  1948. friendlyname = None
  1949. pycacerts = []
  1950. for i in range(_lib.sk_X509_num(cacerts)):
  1951. pycacert = X509.__new__(X509)
  1952. pycacert._x509 = _lib.sk_X509_value(cacerts, i)
  1953. pycacerts.append(pycacert)
  1954. if not pycacerts:
  1955. pycacerts = None
  1956. pkcs12 = PKCS12.__new__(PKCS12)
  1957. pkcs12._pkey = pykey
  1958. pkcs12._cert = pycert
  1959. pkcs12._cacerts = pycacerts
  1960. pkcs12._friendlyname = friendlyname
  1961. return pkcs12
  1962. def _initialize_openssl_threads(get_ident, Lock):
  1963. import _ssl
  1964. return
  1965. locks = list(Lock() for n in range(_lib.CRYPTO_num_locks()))
  1966. def locking_function(mode, index, filename, line):
  1967. if mode & _lib.CRYPTO_LOCK:
  1968. locks[index].acquire()
  1969. else:
  1970. locks[index].release()
  1971. _lib.CRYPTO_set_id_callback(
  1972. _ffi.callback("unsigned long (*)(void)", get_ident))
  1973. _lib.CRYPTO_set_locking_callback(
  1974. _ffi.callback(
  1975. "void (*)(int, int, const char*, int)", locking_function))
  1976. try:
  1977. from thread import get_ident
  1978. from threading import Lock
  1979. except ImportError:
  1980. pass
  1981. else:
  1982. _initialize_openssl_threads(get_ident, Lock)
  1983. del get_ident, Lock
  1984. # There are no direct unit tests for this initialization. It is tested
  1985. # indirectly since it is necessary for functions like dump_privatekey when
  1986. # using encryption.
  1987. #
  1988. # Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
  1989. # and some other similar tests may fail without this (though they may not if
  1990. # the Python runtime has already done some initialization of the underlying
  1991. # OpenSSL library (and is linked against the same one that cryptography is
  1992. # using)).
  1993. _lib.OpenSSL_add_all_algorithms()
  1994. # This is similar but exercised mainly by exception_from_error_queue. It calls
  1995. # both ERR_load_crypto_strings() and ERR_load_SSL_strings().
  1996. _lib.SSL_load_error_strings()