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.

3123 lines
97 KiB

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