blob: 11be813ca4d564c2e32b8026fdd2d960eccdeacd [file] [log] [blame]
jalberdi004669dcc32020-10-18 17:55:40 +02001import calendar
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05002import datetime
Paul Kehrer8d887e12015-10-24 09:09:55 -05003
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05004from base64 import b16encode
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05005from functools import partial
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05006from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
7
8from six import (
9 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -040010 text_type as _text_type,
Alex Gaynor03737182020-07-23 20:40:46 -040011 PY2 as _PY2,
12)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080013
Alex Gaynorbb971ae2020-08-05 01:14:16 -040014from cryptography import utils, x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080015from cryptography.hazmat.primitives.asymmetric import dsa, rsa
16
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050017from OpenSSL._util import (
18 ffi as _ffi,
19 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050020 exception_from_error_queue as _exception_from_error_queue,
21 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040022 native as _native,
Sándor Oroszi43c97762020-09-11 17:17:31 +020023 path_string as _path_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040024 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040025 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070026 make_assert as _make_assert,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040027)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080028
Nicolas Karolak736c6212017-11-26 14:40:28 +010029__all__ = [
Alex Gaynor03737182020-07-23 20:40:46 -040030 "FILETYPE_PEM",
31 "FILETYPE_ASN1",
32 "FILETYPE_TEXT",
33 "TYPE_RSA",
34 "TYPE_DSA",
35 "Error",
36 "PKey",
37 "get_elliptic_curves",
38 "get_elliptic_curve",
39 "X509Name",
40 "X509Extension",
41 "X509Req",
42 "X509",
43 "X509StoreFlags",
44 "X509Store",
45 "X509StoreContextError",
46 "X509StoreContext",
47 "load_certificate",
48 "dump_certificate",
49 "dump_publickey",
50 "dump_privatekey",
51 "Revoked",
52 "CRL",
53 "PKCS7",
54 "PKCS12",
55 "NetscapeSPKI",
56 "load_publickey",
57 "load_privatekey",
58 "dump_certificate_request",
59 "load_certificate_request",
60 "sign",
61 "verify",
62 "dump_crl",
63 "load_crl",
64 "load_pkcs7_data",
65 "load_pkcs12",
Nicolas Karolak736c6212017-11-26 14:40:28 +010066]
67
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050068FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
69FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080070
71# TODO This was an API mistake. OpenSSL has no such constant.
72FILETYPE_TEXT = 2 ** 16 - 1
73
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050074TYPE_RSA = _lib.EVP_PKEY_RSA
75TYPE_DSA = _lib.EVP_PKEY_DSA
Igr2f874f22019-01-21 21:39:37 +030076TYPE_DH = _lib.EVP_PKEY_DH
77TYPE_EC = _lib.EVP_PKEY_EC
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080078
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080079
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050080class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050081 """
82 An error occurred in an `OpenSSL.crypto` API.
83 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050084
85
86_raise_current_error = partial(_exception_from_error_queue, Error)
Alex Gaynor67903a62016-06-02 10:37:13 -070087_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050088
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070089
Paul Kehrereb633842016-10-06 11:22:01 +020090def _get_backend():
91 """
92 Importing the backend from cryptography has the side effect of activating
93 the osrandom engine. This mutates the global state of OpenSSL in the
94 process and causes issues for various programs that use subinterpreters or
95 embed Python. By putting the import in this function we can avoid
96 triggering this side effect unless _get_backend is called.
97 """
98 from cryptography.hazmat.backends.openssl.backend import backend
Alex Gaynor03737182020-07-23 20:40:46 -040099
Paul Kehrereb633842016-10-06 11:22:01 +0200100 return backend
101
102
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500103def _untested_error(where):
104 """
105 An OpenSSL API failed somehow. Additionally, the failure which was
106 encountered isn't one that's exercised by the test suite so future behavior
107 of pyOpenSSL is now somewhat less predictable.
108 """
109 raise RuntimeError("Unknown %s failure" % (where,))
110
111
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500112def _new_mem_buf(buffer=None):
113 """
114 Allocate a new OpenSSL memory BIO.
115
116 Arrange for the garbage collector to clean it up automatically.
117
118 :param buffer: None or some bytes to use to put into the BIO so that they
119 can be read out.
120 """
121 if buffer is None:
122 bio = _lib.BIO_new(_lib.BIO_s_mem())
123 free = _lib.BIO_free
124 else:
125 data = _ffi.new("char[]", buffer)
126 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -0400127
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500128 # Keep the memory alive as long as the bio is alive!
129 def free(bio, ref=data):
130 return _lib.BIO_free(bio)
131
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700132 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500133
134 bio = _ffi.gc(bio, free)
135 return bio
136
137
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800138def _bio_to_string(bio):
139 """
140 Copy the contents of an OpenSSL BIO object into a Python byte string.
141 """
Alex Gaynor03737182020-07-23 20:40:46 -0400142 result_buffer = _ffi.new("char**")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500143 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
144 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800145
146
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800147def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500148 """
149 The the time value of an ASN1 time object.
150
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900151 @param boundary: An ASN1_TIME pointer (or an object safely
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500152 castable to that type) which will have its value set.
153 @param when: A string representation of the desired time value.
154
155 @raise TypeError: If C{when} is not a L{bytes} string.
156 @raise ValueError: If C{when} does not represent a time in the required
157 format.
158 @raise RuntimeError: If the time value cannot be set for some other
159 (unspecified) reason.
160 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800161 if not isinstance(when, bytes):
162 raise TypeError("when must be a byte string")
163
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900164 set_result = _lib.ASN1_TIME_set_string(boundary, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800165 if set_result == 0:
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900166 raise ValueError("Invalid string")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800167
Alex Gaynor510293e2016-06-02 12:07:59 -0700168
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800169def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500170 """
171 Retrieve the time value of an ASN1 time object.
172
173 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
174 that type) from which the time value will be retrieved.
175
176 @return: The time value from C{timestamp} as a L{bytes} string in a certain
177 format. Or C{None} if the object contains no time value.
178 """
Alex Gaynor03737182020-07-23 20:40:46 -0400179 string_timestamp = _ffi.cast("ASN1_STRING*", timestamp)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800181 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400182 elif (
183 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
184 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500185 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800186 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500187 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
188 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
189 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500190 # This may happen:
191 # - if timestamp was not an ASN1_TIME
192 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
193 # - if a copy of the time data from timestamp cannot be made for
194 # the newly allocated ASN1_GENERALIZEDTIME
195 #
196 # These are difficult to test. cffi enforces the ASN1_TIME type.
197 # Memory allocation failures are a pain to trigger
198 # deterministically.
199 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800200 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201 string_timestamp = _ffi.cast(
Alex Gaynor03737182020-07-23 20:40:46 -0400202 "ASN1_STRING*", generalized_timestamp[0]
203 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500204 string_data = _lib.ASN1_STRING_data(string_timestamp)
205 string_result = _ffi.string(string_data)
206 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800207 return string_result
208
209
Alex Gaynor4aa52c32017-11-20 09:04:08 -0500210class _X509NameInvalidator(object):
211 def __init__(self):
212 self._names = []
213
214 def add(self, name):
215 self._names.append(name)
216
217 def clear(self):
218 for name in self._names:
219 # Breaks the object, but also prevents UAF!
220 del name._name
221
222
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800223class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200224 """
225 A class representing an DSA or RSA public key or key pair.
226 """
Alex Gaynor03737182020-07-23 20:40:46 -0400227
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800228 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800229 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800230
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800231 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500232 pkey = _lib.EVP_PKEY_new()
233 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800234 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800235
Paul Kehrer72d968b2016-07-29 15:31:04 +0800236 def to_cryptography_key(self):
237 """
238 Export as a ``cryptography`` key.
239
240 :rtype: One of ``cryptography``'s `key interfaces`_.
241
242 .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
243 primitives/asymmetric/rsa/#key-interfaces
244
245 .. versionadded:: 16.1.0
246 """
Paul Kehrereb633842016-10-06 11:22:01 +0200247 backend = _get_backend()
Paul Kehrer72d968b2016-07-29 15:31:04 +0800248 if self._only_public:
249 return backend._evp_pkey_to_public_key(self._pkey)
250 else:
251 return backend._evp_pkey_to_private_key(self._pkey)
252
253 @classmethod
254 def from_cryptography_key(cls, crypto_key):
255 """
256 Construct based on a ``cryptography`` *crypto_key*.
257
258 :param crypto_key: A ``cryptography`` key.
259 :type crypto_key: One of ``cryptography``'s `key interfaces`_.
260
261 :rtype: PKey
262
263 .. versionadded:: 16.1.0
264 """
265 pkey = cls()
Alex Gaynor03737182020-07-23 20:40:46 -0400266 if not isinstance(
267 crypto_key,
268 (
269 rsa.RSAPublicKey,
270 rsa.RSAPrivateKey,
271 dsa.DSAPublicKey,
272 dsa.DSAPrivateKey,
273 ),
274 ):
Paul Kehrer72d968b2016-07-29 15:31:04 +0800275 raise TypeError("Unsupported key type")
276
277 pkey._pkey = crypto_key._evp_pkey
278 if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
279 pkey._only_public = True
280 pkey._initialized = True
281 return pkey
282
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800283 def generate_key(self, type, bits):
284 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700285 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800286
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200287 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800288
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200289 :param type: The key type.
290 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
291 :param bits: The number of bits.
292 :type bits: :py:data:`int` ``>= 0``
293 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
294 of the appropriate type.
295 :raises ValueError: If the number of bits isn't an integer of
296 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700297 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800298 """
299 if not isinstance(type, int):
300 raise TypeError("type must be an integer")
301
302 if not isinstance(bits, int):
303 raise TypeError("bits must be an integer")
304
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800305 if type == TYPE_RSA:
306 if bits <= 0:
307 raise ValueError("Invalid number of bits")
308
David Benjamin179eb1d2018-06-05 17:56:07 -0400309 # TODO Check error return
310 exponent = _lib.BN_new()
311 exponent = _ffi.gc(exponent, _lib.BN_free)
312 _lib.BN_set_word(exponent, _lib.RSA_F4)
313
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500314 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800315
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500316 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400317 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800318
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500319 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400320 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800321
322 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400323 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700324 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400325
326 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400327 res = _lib.DSA_generate_parameters_ex(
328 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
329 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700330 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400331
332 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
333 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800334 else:
335 raise Error("No such key type")
336
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800337 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800338
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800339 def check(self):
340 """
341 Check the consistency of an RSA private key.
342
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200343 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
344
Hynek Schlawack01c31672016-12-11 15:14:09 +0100345 :return: ``True`` if key is consistent.
346
347 :raise OpenSSL.crypto.Error: if the key is inconsistent.
348
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800349 :raise TypeError: if the key is of a type which cannot be checked.
350 Only RSA keys can currently be checked.
351 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800352 if self._only_public:
353 raise TypeError("public key only")
354
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100355 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800356 raise TypeError("key type unsupported")
357
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500358 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
359 rsa = _ffi.gc(rsa, _lib.RSA_free)
360 result = _lib.RSA_check_key(rsa)
Mrmaxmeier8cd3b172020-03-11 22:03:59 +0100361 if result == 1:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800362 return True
363 _raise_current_error()
364
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800365 def type(self):
366 """
367 Returns the type of the key
368
369 :return: The type of the key.
370 """
Alex Gaynor0d2aec52017-05-31 04:26:27 -0400371 return _lib.EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800372
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800373 def bits(self):
374 """
375 Returns the number of bits of the key
376
377 :return: The number of bits of the key.
378 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500379 return _lib.EVP_PKEY_bits(self._pkey)
Alex Chanc6077062016-11-18 13:53:39 +0000380
381
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400382class _EllipticCurve(object):
383 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400384 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400385
386 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
387 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
388 instances each of which represents one curve supported by the system.
389 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400390 """
Alex Gaynor03737182020-07-23 20:40:46 -0400391
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400392 _curves = None
393
Alex Gaynor26f1a922019-11-18 00:37:39 -0500394 if not _PY2:
Felix Yan3db93f12020-10-15 03:41:20 +0800395 # This only necessary on Python 3. Moreover, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400396 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400397 """
398 Implement cooperation with the right-hand side argument of ``!=``.
399
400 Python 3 seems to have dropped this cooperation in this very narrow
401 circumstance.
402 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400403 if isinstance(other, _EllipticCurve):
404 return super(_EllipticCurve, self).__ne__(other)
405 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400406
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400407 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400408 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400409 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400410 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400411
412 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400413
414 :return: A :py:type:`set` of ``cls`` instances giving the names of the
415 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400416 """
Alex Chan84902a22017-04-20 11:50:47 +0100417 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400418 builtin_curves = _ffi.new("EC_builtin_curve[]", num_curves)
Alex Chan84902a22017-04-20 11:50:47 +0100419 # The return value on this call should be num_curves again. We
420 # could check it to make sure but if it *isn't* then.. what could
421 # we do? Abort the whole process, I suppose...? -exarkun
422 lib.EC_get_builtin_curves(builtin_curves, num_curves)
Alex Gaynor03737182020-07-23 20:40:46 -0400423 return set(cls.from_nid(lib, c.nid) for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400424
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400425 @classmethod
426 def _get_elliptic_curves(cls, lib):
427 """
428 Get, cache, and return the curves supported by OpenSSL.
429
430 :param lib: The OpenSSL library binding object.
431
432 :return: A :py:type:`set` of ``cls`` instances giving the names of the
433 elliptic curves the underlying library supports.
434 """
435 if cls._curves is None:
436 cls._curves = cls._load_elliptic_curves(lib)
437 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400438
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400439 @classmethod
440 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400441 """
442 Instantiate a new :py:class:`_EllipticCurve` associated with the given
443 OpenSSL NID.
444
445 :param lib: The OpenSSL library binding object.
446
447 :param nid: The OpenSSL NID the resulting curve object will represent.
448 This must be a curve NID (and not, for example, a hash NID) or
449 subsequent operations will fail in unpredictable ways.
450 :type nid: :py:class:`int`
451
452 :return: The curve object.
453 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400454 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
455
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400456 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400457 """
458 :param _lib: The :py:mod:`cryptography` binding instance used to
459 interface with OpenSSL.
460
461 :param _nid: The OpenSSL NID identifying the curve this object
462 represents.
463 :type _nid: :py:class:`int`
464
465 :param name: The OpenSSL short name identifying the curve this object
466 represents.
467 :type name: :py:class:`unicode`
468 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400469 self._lib = lib
470 self._nid = nid
471 self.name = name
472
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400473 def __repr__(self):
474 return "<Curve %r>" % (self.name,)
475
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400476 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400477 """
478 Create a new OpenSSL EC_KEY structure initialized to use this curve.
479
480 The structure is automatically garbage collected when the Python object
481 is garbage collected.
482 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400483 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
484 return _ffi.gc(key, _lib.EC_KEY_free)
485
486
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400487def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400488 """
489 Return a set of objects representing the elliptic curves supported in the
490 OpenSSL build in use.
491
492 The curve objects have a :py:class:`unicode` ``name`` attribute by which
493 they identify themselves.
494
495 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400496 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
497 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400498 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400499 return _EllipticCurve._get_elliptic_curves(_lib)
500
501
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400502def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400503 """
504 Return a single curve object selected by name.
505
506 See :py:func:`get_elliptic_curves` for information about curve objects.
507
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400508 :param name: The OpenSSL short name identifying the curve object to
509 retrieve.
510 :type name: :py:class:`unicode`
511
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400512 If the named curve is not supported then :py:class:`ValueError` is raised.
513 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400514 for curve in get_elliptic_curves():
515 if curve.name == name:
516 return curve
517 raise ValueError("unknown curve name", name)
518
519
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800520class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200521 """
522 An X.509 Distinguished Name.
523
524 :ivar countryName: The country of the entity.
525 :ivar C: Alias for :py:attr:`countryName`.
526
527 :ivar stateOrProvinceName: The state or province of the entity.
528 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
529
530 :ivar localityName: The locality of the entity.
531 :ivar L: Alias for :py:attr:`localityName`.
532
533 :ivar organizationName: The organization name of the entity.
534 :ivar O: Alias for :py:attr:`organizationName`.
535
536 :ivar organizationalUnitName: The organizational unit of the entity.
537 :ivar OU: Alias for :py:attr:`organizationalUnitName`
538
539 :ivar commonName: The common name of the entity.
540 :ivar CN: Alias for :py:attr:`commonName`.
541
542 :ivar emailAddress: The e-mail address of the entity.
543 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400544
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800545 def __init__(self, name):
546 """
547 Create a new X509Name, copying the given X509Name instance.
548
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200549 :param name: The name to copy.
550 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800551 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500552 name = _lib.X509_NAME_dup(name._name)
553 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800554
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800555 def __setattr__(self, name, value):
Alex Gaynor03737182020-07-23 20:40:46 -0400556 if name.startswith("_"):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800557 return super(X509Name, self).__setattr__(name, value)
558
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800559 # Note: we really do not want str subclasses here, so we do not use
560 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800561 if type(name) is not str:
Alex Gaynor03737182020-07-23 20:40:46 -0400562 raise TypeError(
563 "attribute name must be string, not '%.200s'"
564 % (type(value).__name__,)
565 )
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800566
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500567 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500568 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800569 try:
570 _raise_current_error()
571 except Error:
572 pass
573 raise AttributeError("No such attribute")
574
575 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500576 for i in range(_lib.X509_NAME_entry_count(self._name)):
577 ent = _lib.X509_NAME_get_entry(self._name, i)
578 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
579 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800580 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500581 ent = _lib.X509_NAME_delete_entry(self._name, i)
582 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800583 break
584
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500585 if isinstance(value, _text_type):
Alex Gaynor03737182020-07-23 20:40:46 -0400586 value = value.encode("utf-8")
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800587
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500588 add_result = _lib.X509_NAME_add_entry_by_NID(
Alex Gaynor03737182020-07-23 20:40:46 -0400589 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0
590 )
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500592 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800593
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800594 def __getattr__(self, name):
595 """
596 Find attribute. An X509Name object has the following attributes:
597 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400598 organization (alias O), organizationalUnit (alias OU), commonName
599 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800600 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500601 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500602 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800603 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
604 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
605 # push something onto the error queue. If we don't clean that up
606 # now, someone else will bump into it later and be quite confused.
607 # See lp#314814.
608 try:
609 _raise_current_error()
610 except Error:
611 pass
612 return super(X509Name, self).__getattr__(name)
613
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500614 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800615 if entry_index == -1:
616 return None
617
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500618 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
619 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800620
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500621 result_buffer = _ffi.new("unsigned char**")
622 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400623 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800624
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700625 try:
Alex Gaynor03737182020-07-23 20:40:46 -0400626 result = _ffi.buffer(result_buffer[0], data_length)[:].decode(
627 "utf-8"
628 )
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700629 finally:
630 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500631 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800632 return result
633
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500634 def _cmp(op):
635 def f(self, other):
636 if not isinstance(other, X509Name):
637 return NotImplemented
638 result = _lib.X509_NAME_cmp(self._name, other._name)
639 return op(result, 0)
Alex Gaynor03737182020-07-23 20:40:46 -0400640
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500641 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800642
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500643 __eq__ = _cmp(__eq__)
644 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800645
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500646 __lt__ = _cmp(__lt__)
647 __le__ = _cmp(__le__)
648
649 __gt__ = _cmp(__gt__)
650 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800651
652 def __repr__(self):
653 """
654 String representation of an X509Name
655 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400656 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500657 format_result = _lib.X509_NAME_oneline(
Alex Gaynor03737182020-07-23 20:40:46 -0400658 self._name, result_buffer, len(result_buffer)
659 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700660 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800661
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500662 return "<X509Name object '%s'>" % (
Alex Gaynor03737182020-07-23 20:40:46 -0400663 _native(_ffi.string(result_buffer)),
664 )
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800665
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800666 def hash(self):
667 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200668 Return an integer representation of the first four bytes of the
669 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800670
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200671 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
672
673 :return: The (integer) hash of this name.
674 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800675 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500676 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800677
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800678 def der(self):
679 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200680 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800681
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200682 :return: The DER encoded form of this name.
683 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800684 """
Alex Gaynor03737182020-07-23 20:40:46 -0400685 result_buffer = _ffi.new("unsigned char**")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500686 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400687 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800688
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
690 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800691 return string_result
692
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800693 def get_components(self):
694 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200695 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800696
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200697 :return: The components of this name.
698 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800699 """
700 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500701 for i in range(_lib.X509_NAME_entry_count(self._name)):
702 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800703
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500704 fname = _lib.X509_NAME_ENTRY_get_object(ent)
705 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800706
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500707 nid = _lib.OBJ_obj2nid(fname)
708 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800709
Romuald Brunet4183beb2019-01-21 19:38:33 +0100710 # ffi.string does not handle strings containing NULL bytes
711 # (which may have been generated by old, broken software)
Alex Gaynor03737182020-07-23 20:40:46 -0400712 value = _ffi.buffer(
713 _lib.ASN1_STRING_data(fval), _lib.ASN1_STRING_length(fval)
714 )[:]
Romuald Brunet4183beb2019-01-21 19:38:33 +0100715 result.append((_ffi.string(name), value))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800716
717 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200718
719
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800720class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200721 """
722 An X.509 v3 certificate extension.
723 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400724
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800725 def __init__(self, type_name, critical, value, subject=None, issuer=None):
726 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200727 Initializes an X509 extension.
728
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100729 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400730 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800731
Alex Gaynor5945ea82015-09-05 14:59:06 -0400732 :param bool critical: A flag indicating whether this is a critical
733 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800734
735 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200736 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800737
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200738 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800739 :type subject: :py:class:`X509`
740
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200741 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800742 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100743
Alex Chan54005ce2017-03-21 08:08:17 +0000744 .. _extension: https://www.openssl.org/docs/manmaster/man5/
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100745 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800746 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500747 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800748
Alex Gaynor5945ea82015-09-05 14:59:06 -0400749 # A context is necessary for any extension which uses the r2i
750 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
751 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500752 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800753
754 # We have no configuration database - but perhaps we should (some
755 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500756 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800757
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800758 # Initialize the subject and issuer, if appropriate. ctx is a local,
759 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400760 # any references, so no need to mess with reference counts or
761 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800762 if issuer is not None:
763 if not isinstance(issuer, X509):
764 raise TypeError("issuer must be an X509 instance")
765 ctx.issuer_cert = issuer._x509
766 if subject is not None:
767 if not isinstance(subject, X509):
768 raise TypeError("subject must be an X509 instance")
769 ctx.subject_cert = subject._x509
770
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800771 if critical:
772 # There are other OpenSSL APIs which would let us pass in critical
773 # separately, but they're harder to use, and since value is already
774 # a pile of crappy junk smuggling a ton of utterly important
775 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400776 # with strings? (However, X509V3_EXT_i2d in particular seems like
777 # it would be a better API to invoke. I do not know where to get
778 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500779 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800780
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500781 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
782 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800783 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500784 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800785
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400786 @property
787 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400788 return _lib.OBJ_obj2nid(
789 _lib.X509_EXTENSION_get_object(self._extension)
790 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400791
792 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500793 _lib.GEN_EMAIL: "email",
794 _lib.GEN_DNS: "DNS",
795 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400796 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400797
798 def _subjectAltNameString(self):
Alex Gaynord61c46a2017-06-29 22:51:33 -0700799 names = _ffi.cast(
800 "GENERAL_NAMES*", _lib.X509V3_EXT_d2i(self._extension)
801 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400802
Paul Kehrerb7d79502015-05-04 07:43:51 -0500803 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400804 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500805 for i in range(_lib.sk_GENERAL_NAME_num(names)):
806 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400807 try:
808 label = self._prefixes[name.type]
809 except KeyError:
810 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500812 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400813 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500814 value = _native(
Alex Gaynor03737182020-07-23 20:40:46 -0400815 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:]
816 )
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500817 parts.append(label + ":" + value)
818 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400819
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800820 def __str__(self):
821 """
822 :return: a nice text representation of the extension
823 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500824 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400825 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800826
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400827 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500828 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400829 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800830
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500831 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800832
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800833 def get_critical(self):
834 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200835 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800836
837 :return: The critical field.
838 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500839 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800840
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800841 def get_short_name(self):
842 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200843 Returns the short type name of this X.509 extension.
844
845 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800846
847 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200848 :rtype: :py:data:`bytes`
849
850 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800851 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500852 obj = _lib.X509_EXTENSION_get_object(self._extension)
853 nid = _lib.OBJ_obj2nid(obj)
854 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800855
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800856 def get_data(self):
857 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200858 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800859
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200860 :return: The ASN.1 encoded data of this X509 extension.
861 :rtype: :py:data:`bytes`
862
863 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800864 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500865 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
Alex Gaynor03737182020-07-23 20:40:46 -0400866 string_result = _ffi.cast("ASN1_STRING*", octet_result)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500867 char_result = _lib.ASN1_STRING_data(string_result)
868 result_length = _lib.ASN1_STRING_length(string_result)
869 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800870
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200871
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800872class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200873 """
874 An X.509 certificate signing requests.
875 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400876
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800877 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500878 req = _lib.X509_REQ_new()
879 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Alex Gaynor5af32d02016-09-24 01:52:21 -0400880 # Default to version 0.
881 self.set_version(0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800882
Paul Kehrer41c10242017-06-29 18:24:17 -0500883 def to_cryptography(self):
884 """
885 Export as a ``cryptography`` certificate signing request.
886
887 :rtype: ``cryptography.x509.CertificateSigningRequest``
888
889 .. versionadded:: 17.1.0
890 """
891 from cryptography.hazmat.backends.openssl.x509 import (
Alex Gaynor03737182020-07-23 20:40:46 -0400892 _CertificateSigningRequest,
Paul Kehrer41c10242017-06-29 18:24:17 -0500893 )
Alex Gaynor03737182020-07-23 20:40:46 -0400894
Paul Kehrer41c10242017-06-29 18:24:17 -0500895 backend = _get_backend()
896 return _CertificateSigningRequest(backend, self._req)
897
898 @classmethod
899 def from_cryptography(cls, crypto_req):
900 """
901 Construct based on a ``cryptography`` *crypto_req*.
902
903 :param crypto_req: A ``cryptography`` X.509 certificate signing request
904 :type crypto_req: ``cryptography.x509.CertificateSigningRequest``
905
Gaurav Malhotra4121e252019-01-22 00:09:19 +0530906 :rtype: X509Req
Paul Kehrer41c10242017-06-29 18:24:17 -0500907
908 .. versionadded:: 17.1.0
909 """
910 if not isinstance(crypto_req, x509.CertificateSigningRequest):
911 raise TypeError("Must be a certificate signing request")
912
913 req = cls()
914 req._req = crypto_req._x509_req
915 return req
916
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800917 def set_pubkey(self, pkey):
918 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200919 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800920
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200921 :param pkey: The public key to use.
922 :type pkey: :py:class:`PKey`
923
Dan Sully44e767a2016-06-04 18:05:27 -0700924 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800925 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500926 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400927 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800928
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800929 def get_pubkey(self):
930 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200931 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800932
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200933 :return: The public key.
934 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800935 """
936 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500937 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700938 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500939 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800940 pkey._only_public = True
941 return pkey
942
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800943 def set_version(self, version):
944 """
945 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
946 request.
947
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200948 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700949 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800950 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500951 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400952 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800953
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800954 def get_version(self):
955 """
956 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
957 request.
958
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200959 :return: The value of the version subfield.
960 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800961 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500962 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800963
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800964 def get_subject(self):
965 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200966 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800967
Cory Benfield881dc8d2015-12-09 08:25:14 +0000968 This creates a new :class:`X509Name` that wraps the underlying subject
969 name field on the certificate signing request. Modifying it will modify
970 the underlying signing request, and will have the effect of modifying
971 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200972
973 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000974 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800975 """
976 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500977 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700978 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800979
980 # The name is owned by the X509Req structure. As long as the X509Name
981 # Python object is alive, keep the X509Req Python object alive.
982 name._owner = self
983
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800984 return name
985
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800986 def add_extensions(self, extensions):
987 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200988 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800989
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200990 :param extensions: The X.509 extensions to add.
991 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700992 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800993 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500994 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700995 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800996
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500997 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800998
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800999 for ext in extensions:
1000 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -08001001 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001002
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001003 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001005
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001006 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001007 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001008
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001009 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001010 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001011 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001012
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001013 :return: The X.509 extensions in this request.
1014 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
1015
1016 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001017 """
1018 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -05001019 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -05001020 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001021 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -05001022 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001023 exts.append(ext)
1024 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001025
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001026 def sign(self, pkey, digest):
1027 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001028 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001029
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001030 :param pkey: The key pair to sign with.
1031 :type pkey: :py:class:`PKey`
1032 :param digest: The name of the message digest to use for the signature,
Alex Gaynor239e2d32016-09-11 12:36:35 -04001033 e.g. :py:data:`b"sha256"`.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001034 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -07001035 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001036 """
1037 if pkey._only_public:
1038 raise ValueError("Key has only public part")
1039
1040 if not pkey._initialized:
1041 raise ValueError("Key is uninitialized")
1042
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001043 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001044 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001045 raise ValueError("No such digest method")
1046
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001047 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001048 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001049
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001050 def verify(self, pkey):
1051 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001052 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001053
Hynek Schlawack01c31672016-12-11 15:14:09 +01001054 :param PKey key: A public key.
1055
1056 :return: ``True`` if the signature is correct.
1057 :rtype: bool
1058
1059 :raises OpenSSL.crypto.Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001060 problem verifying the signature.
1061 """
1062 if not isinstance(pkey, PKey):
1063 raise TypeError("pkey must be a PKey instance")
1064
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001065 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001066 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001067 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001068
1069 return result
1070
1071
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001072class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001073 """
1074 An X.509 certificate.
1075 """
Alex Gaynor03737182020-07-23 20:40:46 -04001076
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001077 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001078 x509 = _lib.X509_new()
Hynek Schlawack8a2dd772016-07-31 13:46:20 +02001079 _openssl_assert(x509 != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001080 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001081
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001082 self._issuer_invalidator = _X509NameInvalidator()
1083 self._subject_invalidator = _X509NameInvalidator()
1084
1085 @classmethod
1086 def _from_raw_x509_ptr(cls, x509):
1087 cert = cls.__new__(cls)
1088 cert._x509 = _ffi.gc(x509, _lib.X509_free)
1089 cert._issuer_invalidator = _X509NameInvalidator()
1090 cert._subject_invalidator = _X509NameInvalidator()
1091 return cert
1092
Alex Gaynor9939ba12017-06-25 16:28:24 -04001093 def to_cryptography(self):
1094 """
1095 Export as a ``cryptography`` certificate.
1096
1097 :rtype: ``cryptography.x509.Certificate``
1098
1099 .. versionadded:: 17.1.0
1100 """
1101 from cryptography.hazmat.backends.openssl.x509 import _Certificate
Alex Gaynor03737182020-07-23 20:40:46 -04001102
Alex Gaynor9939ba12017-06-25 16:28:24 -04001103 backend = _get_backend()
1104 return _Certificate(backend, self._x509)
1105
1106 @classmethod
1107 def from_cryptography(cls, crypto_cert):
1108 """
1109 Construct based on a ``cryptography`` *crypto_cert*.
1110
1111 :param crypto_key: A ``cryptography`` X.509 certificate.
1112 :type crypto_key: ``cryptography.x509.Certificate``
1113
Gaurav Malhotra4121e252019-01-22 00:09:19 +05301114 :rtype: X509
Alex Gaynor9939ba12017-06-25 16:28:24 -04001115
1116 .. versionadded:: 17.1.0
1117 """
1118 if not isinstance(crypto_cert, x509.Certificate):
1119 raise TypeError("Must be a certificate")
1120
1121 cert = cls()
1122 cert._x509 = crypto_cert._x509
1123 return cert
1124
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001125 def set_version(self, version):
1126 """
Cyril Stoller6f25ced2018-08-27 13:37:51 +02001127 Set the version number of the certificate. Note that the
1128 version value is zero-based, eg. a value of 0 is V1.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001129
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001130 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001131 :type version: :py:class:`int`
1132
Dan Sully44e767a2016-06-04 18:05:27 -07001133 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001134 """
1135 if not isinstance(version, int):
1136 raise TypeError("version must be an integer")
1137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001138 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001139
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001140 def get_version(self):
1141 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001142 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001143
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001144 :return: The version number of the certificate.
1145 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001146 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001147 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001148
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001149 def get_pubkey(self):
1150 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001151 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001152
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001153 :return: The public key.
1154 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001155 """
1156 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1158 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001159 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001161 pkey._only_public = True
1162 return pkey
1163
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001164 def set_pubkey(self, pkey):
1165 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001166 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001167
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001168 :param pkey: The public key.
1169 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001170
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001171 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001172 """
1173 if not isinstance(pkey, PKey):
1174 raise TypeError("pkey must be a PKey instance")
1175
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001176 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001177 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001178
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001179 def sign(self, pkey, digest):
1180 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001181 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001182
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001183 :param pkey: The key to sign with.
1184 :type pkey: :py:class:`PKey`
1185
1186 :param digest: The name of the message digest to use.
1187 :type digest: :py:class:`bytes`
1188
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001189 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001190 """
1191 if not isinstance(pkey, PKey):
1192 raise TypeError("pkey must be a PKey instance")
1193
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001194 if pkey._only_public:
1195 raise ValueError("Key only has public part")
1196
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001197 if not pkey._initialized:
1198 raise ValueError("Key is uninitialized")
1199
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001200 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001201 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001202 raise ValueError("No such digest method")
1203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001205 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001206
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001207 def get_signature_algorithm(self):
1208 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001209 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001210
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001211 :return: The name of the algorithm.
1212 :rtype: :py:class:`bytes`
1213
1214 :raises ValueError: If the signature algorithm is undefined.
1215
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001216 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001217 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001218 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1219 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001220 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001221 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001222 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001223
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001224 def digest(self, digest_name):
1225 """
1226 Return the digest of the X509 object.
1227
1228 :param digest_name: The name of the digest algorithm to use.
1229 :type digest_name: :py:class:`bytes`
1230
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001231 :return: The digest of the object, formatted as
1232 :py:const:`b":"`-delimited hex pairs.
1233 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001234 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001235 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001236 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001237 raise ValueError("No such digest method")
1238
Paul Kehrer9f9113a2016-09-20 20:10:25 -05001239 result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001241 result_length[0] = len(result_buffer)
1242
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 digest_result = _lib.X509_digest(
Alex Gaynor03737182020-07-23 20:40:46 -04001244 self._x509, digest, result_buffer, result_length
1245 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001246 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001247
Alex Gaynor03737182020-07-23 20:40:46 -04001248 return b":".join(
1249 [
1250 b16encode(ch).upper()
1251 for ch in _ffi.buffer(result_buffer, result_length[0])
1252 ]
1253 )
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001254
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001255 def subject_name_hash(self):
1256 """
1257 Return the hash of the X509 subject.
1258
1259 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001260 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001261 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001262 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001263
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001264 def set_serial_number(self, serial):
1265 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001266 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001267
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001268 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001269 :type serial: :py:class:`int`
1270
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001271 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001272 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001273 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001274 raise TypeError("serial must be an integer")
1275
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001276 hex_serial = hex(serial)[2:]
1277 if not isinstance(hex_serial, bytes):
Alex Gaynor03737182020-07-23 20:40:46 -04001278 hex_serial = hex_serial.encode("ascii")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001279
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001280 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001281
1282 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001283 # it. If bignum is still NULL after this call, then the return value
1284 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001285 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001286
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 if bignum_serial[0] == _ffi.NULL:
1288 set_result = _lib.ASN1_INTEGER_set(
Alex Gaynor03737182020-07-23 20:40:46 -04001289 _lib.X509_get_serialNumber(self._x509), small_serial
1290 )
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001291 if set_result:
1292 # TODO Not tested
1293 _raise_current_error()
1294 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001295 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1296 _lib.BN_free(bignum_serial[0])
1297 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001298 # TODO Not tested
1299 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001300 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1301 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001302 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001303
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001304 def get_serial_number(self):
1305 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001306 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001307
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001308 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001309 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001310 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001311 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1312 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001313 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001314 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001315 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001316 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001317 serial = int(hexstring_serial, 16)
1318 return serial
1319 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001321 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001322 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001323
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001324 def gmtime_adj_notAfter(self, amount):
1325 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001326 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001327
Dan Sully44e767a2016-06-04 18:05:27 -07001328 :param int amount: The number of seconds by which to adjust the
1329 timestamp.
1330 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001331 """
1332 if not isinstance(amount, int):
1333 raise TypeError("amount must be an integer")
1334
Rosen Penev43a23a32020-08-13 12:07:12 -07001335 notAfter = _lib.X509_getm_notAfter(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001336 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001337
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001338 def gmtime_adj_notBefore(self, amount):
1339 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001340 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001341
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001342 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001343 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001344 """
1345 if not isinstance(amount, int):
1346 raise TypeError("amount must be an integer")
1347
Rosen Penev43a23a32020-08-13 12:07:12 -07001348 notBefore = _lib.X509_getm_notBefore(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001349 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001350
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001351 def has_expired(self):
1352 """
1353 Check whether the certificate has expired.
1354
Dan Sully44e767a2016-06-04 18:05:27 -07001355 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1356 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001357 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001358 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001359 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001360
Paul Kehrerfde45c92016-01-21 12:57:37 -06001361 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001362
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001363 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001364 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001365
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001366 def get_notBefore(self):
1367 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001368 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001369
Paul Kehrerce98ee62017-06-21 06:59:58 -10001370 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001371
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001372 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001373
Dan Sully44e767a2016-06-04 18:05:27 -07001374 :return: A timestamp string, or ``None`` if there is none.
1375 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001376 """
Rosen Penev43a23a32020-08-13 12:07:12 -07001377 return self._get_boundary_time(_lib.X509_getm_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001378
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001379 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001380 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001381
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001382 def set_notBefore(self, when):
1383 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001384 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001385
Paul Kehrerce98ee62017-06-21 06:59:58 -10001386 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001387
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001388 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001389
Dan Sully44e767a2016-06-04 18:05:27 -07001390 :param bytes when: A timestamp string.
1391 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001392 """
Rosen Penev43a23a32020-08-13 12:07:12 -07001393 return self._set_boundary_time(_lib.X509_getm_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001394
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001395 def get_notAfter(self):
1396 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001397 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001398
Paul Kehrerce98ee62017-06-21 06:59:58 -10001399 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001400
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001401 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001402
Dan Sully44e767a2016-06-04 18:05:27 -07001403 :return: A timestamp string, or ``None`` if there is none.
1404 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001405 """
Rosen Penev43a23a32020-08-13 12:07:12 -07001406 return self._get_boundary_time(_lib.X509_getm_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001407
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001408 def set_notAfter(self, when):
1409 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001410 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001411
Paul Kehrerce98ee62017-06-21 06:59:58 -10001412 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001413
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001414 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001415
Dan Sully44e767a2016-06-04 18:05:27 -07001416 :param bytes when: A timestamp string.
1417 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001418 """
Rosen Penev43a23a32020-08-13 12:07:12 -07001419 return self._set_boundary_time(_lib.X509_getm_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001420
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001421 def _get_name(self, which):
1422 name = X509Name.__new__(X509Name)
1423 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001424 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001425
1426 # The name is owned by the X509 structure. As long as the X509Name
1427 # Python object is alive, keep the X509 Python object alive.
1428 name._owner = self
1429
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001430 return name
1431
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001432 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001433 if not isinstance(name, X509Name):
1434 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001435 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001436 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001437
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001438 def get_issuer(self):
1439 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001440 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001441
Cory Benfielde6bcce82015-12-09 08:40:03 +00001442 This creates a new :class:`X509Name` that wraps the underlying issuer
1443 name field on the certificate. Modifying it will modify the underlying
1444 certificate, and will have the effect of modifying any other
1445 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001446
1447 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001448 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001449 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001450 name = self._get_name(_lib.X509_get_issuer_name)
1451 self._issuer_invalidator.add(name)
1452 return name
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001453
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001454 def set_issuer(self, issuer):
1455 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001456 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001457
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001458 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001459 :type issuer: :py:class:`X509Name`
1460
Dan Sully44e767a2016-06-04 18:05:27 -07001461 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001462 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001463 self._set_name(_lib.X509_set_issuer_name, issuer)
1464 self._issuer_invalidator.clear()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001465
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001466 def get_subject(self):
1467 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001468 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001469
Cory Benfielde6bcce82015-12-09 08:40:03 +00001470 This creates a new :class:`X509Name` that wraps the underlying subject
1471 name field on the certificate. Modifying it will modify the underlying
1472 certificate, and will have the effect of modifying any other
1473 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001474
1475 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001476 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001477 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001478 name = self._get_name(_lib.X509_get_subject_name)
1479 self._subject_invalidator.add(name)
1480 return name
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001481
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001482 def set_subject(self, subject):
1483 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001484 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001485
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001486 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001487 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001488
Dan Sully44e767a2016-06-04 18:05:27 -07001489 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001490 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001491 self._set_name(_lib.X509_set_subject_name, subject)
1492 self._subject_invalidator.clear()
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001493
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001494 def get_extension_count(self):
1495 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001496 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001497
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001498 :return: The number of extensions.
1499 :rtype: :py:class:`int`
1500
1501 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001502 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001503 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001504
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001505 def add_extensions(self, extensions):
1506 """
1507 Add extensions to the certificate.
1508
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001509 :param extensions: The extensions to add.
1510 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001511 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001512 """
1513 for ext in extensions:
1514 if not isinstance(ext, X509Extension):
1515 raise ValueError("One of the elements is not an X509Extension")
1516
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001517 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001518 if not add_result:
1519 _raise_current_error()
1520
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001521 def get_extension(self, index):
1522 """
1523 Get a specific extension of the certificate by index.
1524
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001525 Extensions on a certificate are kept in order. The index
1526 parameter selects which extension will be returned.
1527
1528 :param int index: The index of the extension to retrieve.
1529 :return: The extension at the specified index.
1530 :rtype: :py:class:`X509Extension`
1531 :raises IndexError: If the extension index was out of bounds.
1532
1533 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001534 """
1535 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001536 ext._extension = _lib.X509_get_ext(self._x509, index)
1537 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001538 raise IndexError("extension index out of bounds")
1539
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001540 extension = _lib.X509_EXTENSION_dup(ext._extension)
1541 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001542 return ext
1543
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001544
Dan Sully44e767a2016-06-04 18:05:27 -07001545class X509StoreFlags(object):
1546 """
1547 Flags for X509 verification, used to change the behavior of
1548 :class:`X509Store`.
1549
1550 See `OpenSSL Verification Flags`_ for details.
1551
1552 .. _OpenSSL Verification Flags:
Alex Chan54005ce2017-03-21 08:08:17 +00001553 https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html
Dan Sully44e767a2016-06-04 18:05:27 -07001554 """
Alex Gaynor03737182020-07-23 20:40:46 -04001555
Dan Sully44e767a2016-06-04 18:05:27 -07001556 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1557 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1558 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1559 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1560 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1561 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1562 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1563 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1564 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1565 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1566 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1567
1568
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001569class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001570 """
Dan Sully44e767a2016-06-04 18:05:27 -07001571 An X.509 store.
1572
1573 An X.509 store is used to describe a context in which to verify a
1574 certificate. A description of a context may include a set of certificates
1575 to trust, a set of certificate revocation lists, verification flags and
1576 more.
1577
1578 An X.509 store, being only a description, cannot be used by itself to
1579 verify a certificate. To carry out the actual verification process, see
1580 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001581 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001582
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001583 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001584 store = _lib.X509_STORE_new()
1585 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001586
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001587 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001588 """
Dan Sully44e767a2016-06-04 18:05:27 -07001589 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001590
Dan Sully44e767a2016-06-04 18:05:27 -07001591 Adding a certificate with this method adds this certificate as a
1592 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001593
1594 :param X509 cert: The certificate to add to this store.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001595
Dan Sully44e767a2016-06-04 18:05:27 -07001596 :raises TypeError: If the certificate is not an :class:`X509`.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001597
1598 :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your
1599 certificate.
1600
Dan Sully44e767a2016-06-04 18:05:27 -07001601 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001602 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001603 if not isinstance(cert, X509):
1604 raise TypeError()
1605
Paul Kehrer0e6c5532018-08-23 10:52:15 -05001606 # As of OpenSSL 1.1.0i adding the same cert to the store more than
1607 # once doesn't cause an error. Accordingly, this code now silences
1608 # the error for OpenSSL < 1.1.0i as well.
1609 if _lib.X509_STORE_add_cert(self._store, cert._x509) == 0:
1610 code = _lib.ERR_peek_error()
1611 err_reason = _lib.ERR_GET_REASON(code)
1612 _openssl_assert(
1613 err_reason == _lib.X509_R_CERT_ALREADY_IN_HASH_TABLE
1614 )
1615 _lib.ERR_clear_error()
Dan Sully44e767a2016-06-04 18:05:27 -07001616
1617 def add_crl(self, crl):
1618 """
1619 Add a certificate revocation list to this store.
1620
1621 The certificate revocation lists added to a store will only be used if
1622 the associated flags are configured to check certificate revocation
1623 lists.
1624
1625 .. versionadded:: 16.1.0
1626
1627 :param CRL crl: The certificate revocation list to add to this store.
1628 :return: ``None`` if the certificate revocation list was added
1629 successfully.
1630 """
1631 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1632
1633 def set_flags(self, flags):
1634 """
1635 Set verification flags to this store.
1636
1637 Verification flags can be combined by oring them together.
1638
1639 .. note::
1640
1641 Setting a verification flag sometimes requires clients to add
1642 additional information to the store, otherwise a suitable error will
1643 be raised.
1644
1645 For example, in setting flags to enable CRL checking a
1646 suitable CRL must be added to the store otherwise an error will be
1647 raised.
1648
1649 .. versionadded:: 16.1.0
1650
1651 :param int flags: The verification flags to set on this store.
1652 See :class:`X509StoreFlags` for available constants.
1653 :return: ``None`` if the verification flags were successfully set.
1654 """
1655 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001656
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001657 def set_time(self, vfy_time):
1658 """
1659 Set the time against which the certificates are verified.
1660
1661 Normally the current time is used.
1662
1663 .. note::
1664
1665 For example, you can determine if a certificate was valid at a given
1666 time.
1667
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001668 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001669
1670 :param datetime vfy_time: The verification time to set on this store.
1671 :return: ``None`` if the verification time was successfully set.
1672 """
1673 param = _lib.X509_VERIFY_PARAM_new()
1674 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1675
jalberdi004669dcc32020-10-18 17:55:40 +02001676 _lib.X509_VERIFY_PARAM_set_time(
1677 param, calendar.timegm(vfy_time.timetuple())
1678 )
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001679 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1680
Sándor Oroszi43c97762020-09-11 17:17:31 +02001681 def load_locations(self, cafile, capath=None):
1682 """
1683 Let X509Store know where we can find trusted certificates for the
1684 certificate chain. Note that the certificates have to be in PEM
1685 format.
1686
1687 If *capath* is passed, it must be a directory prepared using the
1688 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
1689 *cafile* or *capath* may be ``None``.
1690
1691 .. note::
1692
1693 Both *cafile* and *capath* may be set simultaneously.
1694
1695 Call this method multiple times to add more than one location.
1696 For example, CA certificates, and certificate revocation list bundles
1697 may be passed in *cafile* in subsequent calls to this method.
1698
1699 .. versionadded:: 20.0
1700
1701 :param cafile: In which file we can find the certificates (``bytes`` or
1702 ``unicode``).
1703 :param capath: In which directory we can find the certificates
1704 (``bytes`` or ``unicode``).
1705
1706 :return: ``None`` if the locations were set successfully.
1707
1708 :raises OpenSSL.crypto.Error: If both *cafile* and *capath* is ``None``
1709 or the locations could not be set for any reason.
1710
1711 """
1712 if cafile is None:
1713 cafile = _ffi.NULL
1714 else:
1715 cafile = _path_string(cafile)
1716
1717 if capath is None:
1718 capath = _ffi.NULL
1719 else:
1720 capath = _path_string(capath)
1721
1722 load_result = _lib.X509_STORE_load_locations(
1723 self._store, cafile, capath
1724 )
1725 if not load_result:
1726 _raise_current_error()
1727
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001728
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001729class X509StoreContextError(Exception):
1730 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001731 An exception raised when an error occurred while verifying a certificate
1732 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001733
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001734 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001735 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001736 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001737
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001738 def __init__(self, message, certificate):
1739 super(X509StoreContextError, self).__init__(message)
1740 self.certificate = certificate
1741
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001742
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001743class X509StoreContext(object):
1744 """
1745 An X.509 store context.
1746
Dan Sully44e767a2016-06-04 18:05:27 -07001747 An X.509 store context is used to carry out the actual verification process
1748 of a certificate in a described context. For describing such a context, see
1749 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001750
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001751 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1752 instance. It is dynamically allocated and automatically garbage
1753 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001754 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001755 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001756 :ivar _chain: See the ``chain`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001757 :param X509Store store: The certificates which will be trusted for the
1758 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001759 :param X509 certificate: The certificate to be verified.
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001760 :param chain: List of untrusted certificates that may be used for building
1761 the certificate chain. May be ``None``.
1762 :type chain: :class:`list` of :class:`X509`
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001763 """
1764
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001765 def __init__(self, store, certificate, chain=None):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001766 store_ctx = _lib.X509_STORE_CTX_new()
1767 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1768 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001769 self._cert = certificate
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001770 self._chain = self._build_certificate_stack(chain)
Stephen Holsapple46a09252015-02-12 14:45:43 -08001771 # Make the store context available for use after instantiating this
1772 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001773 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001774 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001775
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001776 @staticmethod
1777 def _build_certificate_stack(certificates):
1778 def cleanup(s):
1779 # Equivalent to sk_X509_pop_free, but we don't
1780 # currently have a CFFI binding for that available
1781 for i in range(_lib.sk_X509_num(s)):
1782 x = _lib.sk_X509_value(s, i)
1783 _lib.X509_free(x)
1784 _lib.sk_X509_free(s)
1785
1786 if certificates is None or len(certificates) == 0:
1787 return _ffi.NULL
1788
1789 stack = _lib.sk_X509_new_null()
1790 _openssl_assert(stack != _ffi.NULL)
1791 stack = _ffi.gc(stack, cleanup)
1792
1793 for cert in certificates:
1794 if not isinstance(cert, X509):
1795 raise TypeError("One of the elements is not an X509 instance")
1796
1797 _openssl_assert(_lib.X509_up_ref(cert._x509) > 0)
1798 if _lib.sk_X509_push(stack, cert._x509) <= 0:
1799 _lib.X509_free(cert._x509)
1800 _raise_current_error()
1801
1802 return stack
1803
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001804 def _init(self):
1805 """
1806 Set up the store context for a subsequent verification operation.
Jeremy Cline58193f12017-09-13 21:14:53 -04001807
1808 Calling this method more than once without first calling
1809 :meth:`_cleanup` will leak memory.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001810 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001811 ret = _lib.X509_STORE_CTX_init(
Shane Harvey33c54992020-08-05 16:48:51 -07001812 self._store_ctx, self._store._store, self._cert._x509, self._chain
Alex Gaynor5945ea82015-09-05 14:59:06 -04001813 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001814 if ret <= 0:
1815 _raise_current_error()
1816
1817 def _cleanup(self):
1818 """
1819 Internally cleans up the store context.
1820
Dan Sully44e767a2016-06-04 18:05:27 -07001821 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001822 """
1823 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1824
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001825 def _exception_from_context(self):
1826 """
1827 Convert an OpenSSL native context error failure into a Python
1828 exception.
1829
Alex Gaynor5945ea82015-09-05 14:59:06 -04001830 When a call to native OpenSSL X509_verify_cert fails, additional
1831 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001832 """
1833 errors = [
1834 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1835 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
Alex Gaynor03737182020-07-23 20:40:46 -04001836 _native(
1837 _ffi.string(
1838 _lib.X509_verify_cert_error_string(
1839 _lib.X509_STORE_CTX_get_error(self._store_ctx)
1840 )
1841 )
1842 ),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001843 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001844 # A context error should always be associated with a certificate, so we
1845 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001846 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001847 _cert = _lib.X509_dup(_x509)
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001848 pycert = X509._from_raw_x509_ptr(_cert)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001849 return X509StoreContextError(errors, pycert)
1850
Stephen Holsapple46a09252015-02-12 14:45:43 -08001851 def set_store(self, store):
1852 """
Dan Sully44e767a2016-06-04 18:05:27 -07001853 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001854
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001855 .. versionadded:: 0.15
1856
Dan Sully44e767a2016-06-04 18:05:27 -07001857 :param X509Store store: The store description which will be used for
1858 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001859 """
1860 self._store = store
1861
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001862 def verify_certificate(self):
1863 """
1864 Verify a certificate in a context.
1865
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001866 .. versionadded:: 0.15
1867
Alex Gaynorca87ff62015-09-04 23:31:03 -04001868 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001869 certificate in the context. Sets ``certificate`` attribute to
1870 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001871 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001872 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001873 # :meth:`verify_certificate` is called multiple times.
Jeremy Cline58193f12017-09-13 21:14:53 -04001874 #
1875 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1876 # before _init to ensure memory is not leaked.
1877 self._cleanup()
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001878 self._init()
1879 ret = _lib.X509_verify_cert(self._store_ctx)
1880 self._cleanup()
1881 if ret <= 0:
1882 raise self._exception_from_context()
1883
Shane Harvey33c54992020-08-05 16:48:51 -07001884 def get_verified_chain(self):
1885 """
1886 Verify a certificate in a context and return the complete validated
1887 chain.
1888
1889 :raises X509StoreContextError: If an error occurred when validating a
1890 certificate in the context. Sets ``certificate`` attribute to
1891 indicate which certificate caused the error.
1892
1893 .. versionadded:: 20.0
1894 """
1895 # Always re-initialize the store context in case
1896 # :meth:`verify_certificate` is called multiple times.
1897 #
1898 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1899 # before _init to ensure memory is not leaked.
1900 self._cleanup()
1901 self._init()
1902 ret = _lib.X509_verify_cert(self._store_ctx)
1903 if ret <= 0:
1904 self._cleanup()
1905 raise self._exception_from_context()
1906
1907 # Note: X509_STORE_CTX_get1_chain returns a deep copy of the chain.
1908 cert_stack = _lib.X509_STORE_CTX_get1_chain(self._store_ctx)
1909 _openssl_assert(cert_stack != _ffi.NULL)
1910
1911 result = []
1912 for i in range(_lib.sk_X509_num(cert_stack)):
1913 cert = _lib.sk_X509_value(cert_stack, i)
1914 _openssl_assert(cert != _ffi.NULL)
1915 pycert = X509._from_raw_x509_ptr(cert)
1916 result.append(pycert)
1917
1918 # Free the stack but not the members which are freed by the X509 class.
1919 _lib.sk_X509_free(cert_stack)
1920 self._cleanup()
1921 return result
1922
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001923
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001924def load_certificate(type, buffer):
1925 """
Alex Chand072cae2018-02-15 09:57:59 +00001926 Load a certificate (X509) from the string *buffer* encoded with the
1927 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001928
1929 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1930
Dan Sully44e767a2016-06-04 18:05:27 -07001931 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001932
1933 :return: The X509 object
1934 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001935 if isinstance(buffer, _text_type):
1936 buffer = buffer.encode("ascii")
1937
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001938 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001939
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001940 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001941 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001942 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001943 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001944 else:
Alex Gaynor03737182020-07-23 20:40:46 -04001945 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001946
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001947 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001948 _raise_current_error()
1949
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001950 return X509._from_raw_x509_ptr(x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001951
1952
1953def dump_certificate(type, cert):
1954 """
Alex Chand072cae2018-02-15 09:57:59 +00001955 Dump the certificate *cert* into a buffer string encoded with the type
1956 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001957
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001958 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1959 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001960 :param cert: The certificate to dump
1961 :return: The buffer with the dumped certificate in
1962 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001963 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001964
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001965 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001966 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001967 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001968 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001969 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001970 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001971 else:
1972 raise ValueError(
1973 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04001974 "FILETYPE_TEXT"
1975 )
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001976
Adrián Chaves98c57be2020-03-31 16:14:50 +02001977 _openssl_assert(result_code == 1)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001978 return _bio_to_string(bio)
1979
1980
Cory Benfield6492f7c2015-10-27 16:57:58 +09001981def dump_publickey(type, pkey):
1982 """
Cory Benfield11c10192015-10-27 17:23:03 +09001983 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001984
Cory Benfield9c590b92015-10-28 14:55:05 +09001985 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001986 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001987 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001988 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001989 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001990 """
1991 bio = _new_mem_buf()
1992 if type == FILETYPE_PEM:
1993 write_bio = _lib.PEM_write_bio_PUBKEY
1994 elif type == FILETYPE_ASN1:
1995 write_bio = _lib.i2d_PUBKEY_bio
1996 else:
1997 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1998
1999 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09002000 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09002001 _raise_current_error()
2002
2003 return _bio_to_string(bio)
2004
2005
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002006def dump_privatekey(type, pkey, cipher=None, passphrase=None):
2007 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002008 Dump the private key *pkey* into a buffer string encoded with the type
2009 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
2010 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002011
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002012 :param type: The file type (one of :const:`FILETYPE_PEM`,
2013 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
2014 :param PKey pkey: The PKey to dump
2015 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002016 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002017 the passphrase to use, or a callback for providing the passphrase.
2018
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002019 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07002020 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002021 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002022 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002023
Paul Kehrercded9932017-06-29 18:43:42 -05002024 if not isinstance(pkey, PKey):
2025 raise TypeError("pkey must be a PKey")
2026
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002027 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002028 if passphrase is None:
2029 raise TypeError(
2030 "if a value is given for cipher "
Alex Gaynor03737182020-07-23 20:40:46 -04002031 "one must also be given for passphrase"
2032 )
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002033 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002034 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002035 raise ValueError("Invalid cipher name")
2036 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002037 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002038
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002039 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002040 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002041 result_code = _lib.PEM_write_bio_PrivateKey(
Alex Gaynor03737182020-07-23 20:40:46 -04002042 bio,
2043 pkey._pkey,
2044 cipher_obj,
2045 _ffi.NULL,
2046 0,
2047 helper.callback,
2048 helper.callback_args,
2049 )
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002050 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002051 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002052 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002053 elif type == FILETYPE_TEXT:
Paul Kehrercded9932017-06-29 18:43:42 -05002054 if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:
2055 raise TypeError("Only RSA keys are supported for FILETYPE_TEXT")
2056
Alex Gaynor03737182020-07-23 20:40:46 -04002057 rsa = _ffi.gc(_lib.EVP_PKEY_get1_RSA(pkey._pkey), _lib.RSA_free)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002058 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002059 else:
2060 raise ValueError(
2061 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04002062 "FILETYPE_TEXT"
2063 )
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002064
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002065 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002066
2067 return _bio_to_string(bio)
2068
2069
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002070class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002071 """
2072 A certificate revocation.
2073 """
Alex Gaynor03737182020-07-23 20:40:46 -04002074
Cyril Stoller37e60222018-08-27 13:38:10 +02002075 # https://www.openssl.org/docs/manmaster/man5/x509v3_config.html#CRL-distribution-points
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002076 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
2077 # OCSP_crl_reason_str. We use the latter, just like the command line
2078 # program.
2079 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002080 b"unspecified",
2081 b"keyCompromise",
2082 b"CACompromise",
2083 b"affiliationChanged",
2084 b"superseded",
2085 b"cessationOfOperation",
2086 b"certificateHold",
2087 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04002088 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002089
2090 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002091 revoked = _lib.X509_REVOKED_new()
2092 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002093
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002094 def set_serial(self, hex_str):
2095 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002096 Set the serial number.
2097
2098 The serial number is formatted as a hexadecimal number encoded in
2099 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002100
Dan Sully44e767a2016-06-04 18:05:27 -07002101 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002102
Dan Sully44e767a2016-06-04 18:05:27 -07002103 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002104 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002105 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
2106 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002107 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002108 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002109 if not bn_result:
2110 raise ValueError("bad hex string")
2111
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002112 asn1_serial = _ffi.gc(
2113 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
Alex Gaynor03737182020-07-23 20:40:46 -04002114 _lib.ASN1_INTEGER_free,
2115 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002116 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002117
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002118 def get_serial(self):
2119 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002120 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002121
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002122 The serial number is formatted as a hexadecimal number encoded in
2123 ASCII.
2124
2125 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07002126 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002127 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002128 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002129
Alex Gaynor67903a62016-06-02 10:37:13 -07002130 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
2131 _openssl_assert(asn1_int != _ffi.NULL)
2132 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
2133 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002134 return _bio_to_string(bio)
2135
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002136 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07002137 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2138 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002139 obj = _lib.X509_EXTENSION_get_object(ext)
2140 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002141 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07002142 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002143 break
2144
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002145 def set_reason(self, reason):
2146 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002147 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002148
Dan Sully44e767a2016-06-04 18:05:27 -07002149 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002150
2151 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07002152 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002153
Dan Sully44e767a2016-06-04 18:05:27 -07002154 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002155
2156 .. seealso::
2157
Dan Sully44e767a2016-06-04 18:05:27 -07002158 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002159 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002160 """
2161 if reason is None:
2162 self._delete_reason()
2163 elif not isinstance(reason, bytes):
2164 raise TypeError("reason must be None or a byte string")
2165 else:
Alex Gaynor03737182020-07-23 20:40:46 -04002166 reason = reason.lower().replace(b" ", b"")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002167 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
2168
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002169 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002170 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002171 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002172
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002173 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002174 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002175
2176 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002177 add_result = _lib.X509_REVOKED_add1_ext_i2d(
Alex Gaynor03737182020-07-23 20:40:46 -04002178 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0
2179 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002180 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002181
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002182 def get_reason(self):
2183 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04002184 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002185
Dan Sully44e767a2016-06-04 18:05:27 -07002186 :return: The reason, or ``None`` if there is none.
2187 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002188
2189 .. seealso::
2190
Dan Sully44e767a2016-06-04 18:05:27 -07002191 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002192 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002193 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002194 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2195 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002196 obj = _lib.X509_EXTENSION_get_object(ext)
2197 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002198 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002199
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002200 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002201 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002202 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002203 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04002204 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002205 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002206
2207 return _bio_to_string(bio)
2208
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002209 def all_reasons(self):
2210 """
2211 Return a list of all the supported reason strings.
2212
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002213 This list is a copy; modifying it does not change the supported reason
2214 strings.
2215
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002216 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07002217 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002218 """
2219 return self._crl_reasons[:]
2220
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002221 def set_rev_date(self, when):
2222 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002223 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002224
Dan Sully44e767a2016-06-04 18:05:27 -07002225 :param bytes when: The timestamp of the revocation,
Paul Kehrerce98ee62017-06-21 06:59:58 -10002226 as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002227 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002228 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002229 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2230 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002231
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002232 def get_rev_date(self):
2233 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002234 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002235
Paul Kehrerce98ee62017-06-21 06:59:58 -10002236 :return: The timestamp of the revocation, as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002237 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002238 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002239 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2240 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002241
2242
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002243class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002244 """
2245 A certificate revocation list.
2246 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002247
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002248 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002249 crl = _lib.X509_CRL_new()
2250 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002251
Paul Kehrer41c10242017-06-29 18:24:17 -05002252 def to_cryptography(self):
2253 """
2254 Export as a ``cryptography`` CRL.
2255
2256 :rtype: ``cryptography.x509.CertificateRevocationList``
2257
2258 .. versionadded:: 17.1.0
2259 """
2260 from cryptography.hazmat.backends.openssl.x509 import (
Alex Gaynor03737182020-07-23 20:40:46 -04002261 _CertificateRevocationList,
Paul Kehrer41c10242017-06-29 18:24:17 -05002262 )
Alex Gaynor03737182020-07-23 20:40:46 -04002263
Paul Kehrer41c10242017-06-29 18:24:17 -05002264 backend = _get_backend()
2265 return _CertificateRevocationList(backend, self._crl)
2266
2267 @classmethod
2268 def from_cryptography(cls, crypto_crl):
2269 """
2270 Construct based on a ``cryptography`` *crypto_crl*.
2271
2272 :param crypto_crl: A ``cryptography`` certificate revocation list
2273 :type crypto_crl: ``cryptography.x509.CertificateRevocationList``
2274
2275 :rtype: CRL
2276
2277 .. versionadded:: 17.1.0
2278 """
2279 if not isinstance(crypto_crl, x509.CertificateRevocationList):
2280 raise TypeError("Must be a certificate revocation list")
2281
2282 crl = cls()
2283 crl._crl = crypto_crl._x509_crl
2284 return crl
2285
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002286 def get_revoked(self):
2287 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002288 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002289
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002290 These revocations will be provided by value, not by reference.
2291 That means it's okay to mutate them: it won't affect this CRL.
2292
2293 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002294 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002295 """
2296 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07002297 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002298 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
2299 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04002300 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002301 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002302 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002303 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002304 if results:
2305 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002306
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002307 def add_revoked(self, revoked):
2308 """
2309 Add a revoked (by value not reference) to the CRL structure
2310
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002311 This revocation will be added by value, not by reference. That
2312 means it's okay to mutate it after adding: it won't affect
2313 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002314
Dan Sully44e767a2016-06-04 18:05:27 -07002315 :param Revoked revoked: The new revocation.
2316 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002317 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04002318 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002319 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002320
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002321 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002322 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002323
Dan Sully44e767a2016-06-04 18:05:27 -07002324 def get_issuer(self):
2325 """
2326 Get the CRL's issuer.
2327
2328 .. versionadded:: 16.1.0
2329
2330 :rtype: X509Name
2331 """
2332 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2333 _openssl_assert(_issuer != _ffi.NULL)
2334 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2335 issuer = X509Name.__new__(X509Name)
2336 issuer._name = _issuer
2337 return issuer
2338
2339 def set_version(self, version):
2340 """
2341 Set the CRL version.
2342
2343 .. versionadded:: 16.1.0
2344
2345 :param int version: The version of the CRL.
2346 :return: ``None``
2347 """
2348 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2349
2350 def _set_boundary_time(self, which, when):
2351 return _set_asn1_time(which(self._crl), when)
2352
2353 def set_lastUpdate(self, when):
2354 """
2355 Set when the CRL was last updated.
2356
Paul Kehrerce98ee62017-06-21 06:59:58 -10002357 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002358
2359 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002360
2361 .. versionadded:: 16.1.0
2362
2363 :param bytes when: A timestamp string.
2364 :return: ``None``
2365 """
2366 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2367
2368 def set_nextUpdate(self, when):
2369 """
Felix Yan3db93f12020-10-15 03:41:20 +08002370 Set when the CRL will next be updated.
Dan Sully44e767a2016-06-04 18:05:27 -07002371
Paul Kehrerce98ee62017-06-21 06:59:58 -10002372 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002373
2374 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002375
2376 .. versionadded:: 16.1.0
2377
2378 :param bytes when: A timestamp string.
2379 :return: ``None``
2380 """
2381 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2382
2383 def sign(self, issuer_cert, issuer_key, digest):
2384 """
2385 Sign the CRL.
2386
2387 Signing a CRL enables clients to associate the CRL itself with an
2388 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2389 be signed by an issuer.
2390
2391 This method implicitly sets the issuer's name based on the issuer
2392 certificate and private key used to sign the CRL.
2393
2394 .. versionadded:: 16.1.0
2395
2396 :param X509 issuer_cert: The issuer's certificate.
2397 :param PKey issuer_key: The issuer's private key.
2398 :param bytes digest: The digest method to sign the CRL with.
2399 """
2400 digest_obj = _lib.EVP_get_digestbyname(digest)
2401 _openssl_assert(digest_obj != _ffi.NULL)
2402 _lib.X509_CRL_set_issuer_name(
Alex Gaynor03737182020-07-23 20:40:46 -04002403 self._crl, _lib.X509_get_subject_name(issuer_cert._x509)
2404 )
Dan Sully44e767a2016-06-04 18:05:27 -07002405 _lib.X509_CRL_sort(self._crl)
2406 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2407 _openssl_assert(result != 0)
2408
Alex Gaynor03737182020-07-23 20:40:46 -04002409 def export(
2410 self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED
2411 ):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002412 """
Dan Sully44e767a2016-06-04 18:05:27 -07002413 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002414
Dan Sully44e767a2016-06-04 18:05:27 -07002415 :param X509 cert: The certificate used to sign the CRL.
2416 :param PKey key: The key used to sign the CRL.
2417 :param int type: The export format, either :data:`FILETYPE_PEM`,
2418 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002419 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002420 :param bytes digest: The name of the message digest to use (eg
Wayne Werner80dcf382019-01-30 15:03:16 -06002421 ``b"sha256"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002422 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002423 """
Dan Sully44e767a2016-06-04 18:05:27 -07002424
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002425 if not isinstance(cert, X509):
2426 raise TypeError("cert must be an X509 instance")
2427 if not isinstance(key, PKey):
2428 raise TypeError("key must be a PKey instance")
2429 if not isinstance(type, int):
2430 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002431
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002432 if digest is _UNSPECIFIED:
Alex Gaynor173e4ba2017-06-30 08:01:12 -07002433 raise TypeError("digest must be provided")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002434
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002435 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002436 if digest_obj == _ffi.NULL:
2437 raise ValueError("No such digest method")
2438
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002439 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002440 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002441
Alex Gaynora738ed52015-09-05 11:17:10 -04002442 # A scratch time object to give different values to different CRL
2443 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002444 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002445 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002446
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002447 _lib.X509_gmtime_adj(sometime, 0)
2448 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002449
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002450 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2451 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002452
Alex Gaynor5945ea82015-09-05 14:59:06 -04002453 _lib.X509_CRL_set_issuer_name(
2454 self._crl, _lib.X509_get_subject_name(cert._x509)
2455 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002456
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002457 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002458 if not sign_result:
2459 _raise_current_error()
2460
Dominic Chenf05b2122015-10-13 16:32:35 +00002461 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002462
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002463
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002464class PKCS7(object):
2465 def type_is_signed(self):
2466 """
2467 Check if this NID_pkcs7_signed object
2468
2469 :return: True if the PKCS7 is of type signed
2470 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002471 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002472
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002473 def type_is_enveloped(self):
2474 """
2475 Check if this NID_pkcs7_enveloped object
2476
2477 :returns: True if the PKCS7 is of type enveloped
2478 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002479 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002480
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002481 def type_is_signedAndEnveloped(self):
2482 """
2483 Check if this NID_pkcs7_signedAndEnveloped object
2484
2485 :returns: True if the PKCS7 is of type signedAndEnveloped
2486 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002487 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002488
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002489 def type_is_data(self):
2490 """
2491 Check if this NID_pkcs7_data object
2492
2493 :return: True if the PKCS7 is of type data
2494 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002495 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002496
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002497 def get_type_name(self):
2498 """
2499 Returns the type name of the PKCS7 structure
2500
2501 :return: A string with the typename
2502 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002503 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2504 string_type = _lib.OBJ_nid2sn(nid)
2505 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002506
Alex Chanc6077062016-11-18 13:53:39 +00002507
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002508class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002509 """
2510 A PKCS #12 archive.
2511 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002512
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002513 def __init__(self):
2514 self._pkey = None
2515 self._cert = None
2516 self._cacerts = None
2517 self._friendlyname = None
2518
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002519 def get_certificate(self):
2520 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002521 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002522
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002523 :return: The certificate, or :py:const:`None` if there is none.
2524 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002525 """
2526 return self._cert
2527
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002528 def set_certificate(self, cert):
2529 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002530 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002531
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002532 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002533 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002534
Dan Sully44e767a2016-06-04 18:05:27 -07002535 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002536 """
2537 if not isinstance(cert, X509):
2538 raise TypeError("cert must be an X509 instance")
2539 self._cert = cert
2540
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002541 def get_privatekey(self):
2542 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002543 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002544
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002545 :return: The private key, or :py:const:`None` if there is none.
2546 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002547 """
2548 return self._pkey
2549
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002550 def set_privatekey(self, pkey):
2551 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002552 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002553
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002554 :param pkey: The new private key, or :py:const:`None` to unset it.
2555 :type pkey: :py:class:`PKey` or :py:const:`None`
2556
Dan Sully44e767a2016-06-04 18:05:27 -07002557 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002558 """
2559 if not isinstance(pkey, PKey):
2560 raise TypeError("pkey must be a PKey instance")
2561 self._pkey = pkey
2562
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002563 def get_ca_certificates(self):
2564 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002565 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002566
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002567 :return: A tuple with the CA certificates in the chain, or
2568 :py:const:`None` if there are none.
2569 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002570 """
2571 if self._cacerts is not None:
2572 return tuple(self._cacerts)
2573
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002574 def set_ca_certificates(self, cacerts):
2575 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002576 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002577
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002578 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2579 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002580 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002581
Dan Sully44e767a2016-06-04 18:05:27 -07002582 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002583 """
2584 if cacerts is None:
2585 self._cacerts = None
2586 else:
2587 cacerts = list(cacerts)
2588 for cert in cacerts:
2589 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002590 raise TypeError(
2591 "iterable must only contain X509 instances"
2592 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002593 self._cacerts = cacerts
2594
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002595 def set_friendlyname(self, name):
2596 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002597 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002598
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002599 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002600 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002601
Dan Sully44e767a2016-06-04 18:05:27 -07002602 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002603 """
2604 if name is None:
2605 self._friendlyname = None
2606 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002607 raise TypeError(
2608 "name must be a byte string or None (not %r)" % (name,)
2609 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002610 self._friendlyname = name
2611
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002612 def get_friendlyname(self):
2613 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002614 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002615
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002616 :returns: The friendly name, or :py:const:`None` if there is none.
2617 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002618 """
2619 return self._friendlyname
2620
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002621 def export(self, passphrase=None, iter=2048, maciter=1):
2622 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002623 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002624
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002625 For more information, see the :c:func:`PKCS12_create` man page.
2626
2627 :param passphrase: The passphrase used to encrypt the structure. Unlike
2628 some other passphrase arguments, this *must* be a string, not a
2629 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002630 :type passphrase: :py:data:`bytes`
2631
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002632 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002633 :type iter: :py:data:`int`
2634
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002635 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002636 :type maciter: :py:data:`int`
2637
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002638 :return: The string representation of the PKCS #12 structure.
2639 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002640 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002641 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002642
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002643 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002644 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002645 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002646 cacerts = _lib.sk_X509_new_null()
2647 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002648 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002649 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002650
2651 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002652 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002653
2654 friendlyname = self._friendlyname
2655 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002656 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002657
2658 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002659 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002660 else:
2661 pkey = self._pkey._pkey
2662
2663 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002664 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002665 else:
2666 cert = self._cert._x509
2667
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002668 pkcs12 = _lib.PKCS12_create(
Alex Gaynor03737182020-07-23 20:40:46 -04002669 passphrase,
2670 friendlyname,
2671 pkey,
2672 cert,
2673 cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002674 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2675 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Alex Gaynor03737182020-07-23 20:40:46 -04002676 iter,
2677 maciter,
2678 0,
2679 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002680 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002681 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002682 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002683
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002684 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002685 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002686 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002687
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002688
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002689class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002690 """
2691 A Netscape SPKI object.
2692 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002693
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002694 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002695 spki = _lib.NETSCAPE_SPKI_new()
2696 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002697
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002698 def sign(self, pkey, digest):
2699 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002700 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002701
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002702 :param pkey: The private key to sign with.
2703 :type pkey: :py:class:`PKey`
2704
2705 :param digest: The message digest to use.
2706 :type digest: :py:class:`bytes`
2707
Dan Sully44e767a2016-06-04 18:05:27 -07002708 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002709 """
2710 if pkey._only_public:
2711 raise ValueError("Key has only public part")
2712
2713 if not pkey._initialized:
2714 raise ValueError("Key is uninitialized")
2715
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002716 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002717 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002718 raise ValueError("No such digest method")
2719
Alex Gaynor5945ea82015-09-05 14:59:06 -04002720 sign_result = _lib.NETSCAPE_SPKI_sign(
2721 self._spki, pkey._pkey, digest_obj
2722 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002723 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002724
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002725 def verify(self, key):
2726 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002727 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002728
Hynek Schlawack01c31672016-12-11 15:14:09 +01002729 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002730
Hynek Schlawack01c31672016-12-11 15:14:09 +01002731 :return: ``True`` if the signature is correct.
2732 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002733
Hynek Schlawack01c31672016-12-11 15:14:09 +01002734 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2735 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002736 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002737 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002738 if answer <= 0:
2739 _raise_current_error()
2740 return True
2741
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002742 def b64_encode(self):
2743 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002744 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002745
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002746 :return: The base64 encoded string.
2747 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002748 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002749 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2750 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002751 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002752 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002753
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002754 def get_pubkey(self):
2755 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002756 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002757
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002758 :return: The public key.
2759 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002760 """
2761 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002762 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002763 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002764 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002765 pkey._only_public = True
2766 return pkey
2767
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002768 def set_pubkey(self, pkey):
2769 """
2770 Set the public key of the certificate
2771
2772 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002773 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002774 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002775 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002776 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002777
2778
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002779class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002780 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002781 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002782 raise ValueError(
2783 "only FILETYPE_PEM key format supports encryption"
2784 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002785 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002786 self._more_args = more_args
2787 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002788 self._problems = []
2789
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002790 @property
2791 def callback(self):
2792 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002793 return _ffi.NULL
Huw Jonescdd66962020-10-13 05:14:19 +01002794 elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002795 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002796 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002797 raise TypeError(
2798 "Last argument must be a byte string or a callable."
2799 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002800
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002801 @property
2802 def callback_args(self):
2803 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002804 return _ffi.NULL
Huw Jonescdd66962020-10-13 05:14:19 +01002805 elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002806 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002807 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002808 raise TypeError(
2809 "Last argument must be a byte string or a callable."
2810 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002811
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002812 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002813 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002814
2815 # Flush the OpenSSL error queue
2816 try:
2817 _exception_from_error_queue(exceptionType)
2818 except exceptionType:
2819 pass
2820
2821 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002822
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002823 def _read_passphrase(self, buf, size, rwflag, userdata):
2824 try:
Huw Jonescdd66962020-10-13 05:14:19 +01002825 if callable(self._passphrase):
2826 if self._more_args:
2827 result = self._passphrase(size, rwflag, userdata)
2828 else:
2829 result = self._passphrase(rwflag)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002830 else:
Huw Jonescdd66962020-10-13 05:14:19 +01002831 result = self._passphrase
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002832 if not isinstance(result, bytes):
Huw Jonescdd66962020-10-13 05:14:19 +01002833 raise ValueError("Bytes expected")
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002834 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002835 if self._truncate:
2836 result = result[:size]
2837 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002838 raise ValueError(
2839 "passphrase returned by callback is too long"
2840 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002841 for i in range(len(result)):
Alex Gaynor03737182020-07-23 20:40:46 -04002842 buf[i] = result[i : i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002843 return len(result)
2844 except Exception as e:
2845 self._problems.append(e)
2846 return 0
2847
2848
Cory Benfield6492f7c2015-10-27 16:57:58 +09002849def load_publickey(type, buffer):
2850 """
Cory Benfield11c10192015-10-27 17:23:03 +09002851 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002852
Cory Benfield9c590b92015-10-28 14:55:05 +09002853 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002854 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002855 :param buffer: The buffer the key is stored in.
2856 :type buffer: A Python string object, either unicode or bytestring.
2857 :return: The PKey object.
2858 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002859 """
2860 if isinstance(buffer, _text_type):
2861 buffer = buffer.encode("ascii")
2862
2863 bio = _new_mem_buf(buffer)
2864
2865 if type == FILETYPE_PEM:
2866 evp_pkey = _lib.PEM_read_bio_PUBKEY(
Alex Gaynor03737182020-07-23 20:40:46 -04002867 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL
2868 )
Cory Benfield6492f7c2015-10-27 16:57:58 +09002869 elif type == FILETYPE_ASN1:
2870 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2871 else:
2872 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2873
2874 if evp_pkey == _ffi.NULL:
2875 _raise_current_error()
2876
2877 pkey = PKey.__new__(PKey)
2878 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002879 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002880 return pkey
2881
2882
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002883def load_privatekey(type, buffer, passphrase=None):
2884 """
Alex Chand072cae2018-02-15 09:57:59 +00002885 Load a private key (PKey) from the string *buffer* encoded with the type
2886 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002887
2888 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2889 :param buffer: The buffer the key is stored in
2890 :param passphrase: (optional) if encrypted PEM format, this can be
2891 either the passphrase to use, or a callback for
2892 providing the passphrase.
2893
2894 :return: The PKey object
2895 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002896 if isinstance(buffer, _text_type):
2897 buffer = buffer.encode("ascii")
2898
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002899 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002900
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002901 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002902 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002903 evp_pkey = _lib.PEM_read_bio_PrivateKey(
Alex Gaynor03737182020-07-23 20:40:46 -04002904 bio, _ffi.NULL, helper.callback, helper.callback_args
2905 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002906 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002907 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002908 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002909 else:
2910 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2911
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002912 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002913 _raise_current_error()
2914
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002915 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002916 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002917 return pkey
2918
2919
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002920def dump_certificate_request(type, req):
2921 """
Alex Chand072cae2018-02-15 09:57:59 +00002922 Dump the certificate request *req* into a buffer string encoded with the
2923 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002924
2925 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2926 :param req: The certificate request to dump
2927 :return: The buffer with the dumped certificate request in
2928 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002929 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002930
2931 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002932 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002933 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002934 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002935 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002936 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002937 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002938 raise ValueError(
2939 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2940 "FILETYPE_TEXT"
2941 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002942
Alex Gaynor09a386e2016-07-03 09:32:44 -04002943 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002944
2945 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002946
2947
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002948def load_certificate_request(type, buffer):
2949 """
Alex Chand072cae2018-02-15 09:57:59 +00002950 Load a certificate request (X509Req) from the string *buffer* encoded with
2951 the type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002952
2953 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2954 :param buffer: The buffer the certificate request is stored in
2955 :return: The X509Req object
2956 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002957 if isinstance(buffer, _text_type):
2958 buffer = buffer.encode("ascii")
2959
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002960 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002961
2962 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002963 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002964 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002965 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002966 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002967 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002968
Alex Gaynoradd5b072016-06-04 21:04:00 -07002969 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002970
2971 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002972 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002973 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002974
2975
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002976def sign(pkey, data, digest):
2977 """
Alex Chand072cae2018-02-15 09:57:59 +00002978 Sign a data string using the given key and message digest.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002979
Alex Chand072cae2018-02-15 09:57:59 +00002980 :param pkey: PKey to sign with
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002981 :param data: data to be signed
2982 :param digest: message digest to use
2983 :return: signature
Alex Chand072cae2018-02-15 09:57:59 +00002984
2985 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002986 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002987 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002988
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002989 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002990 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002991 raise ValueError("No such digest method")
2992
Alex Gaynor67903a62016-06-02 10:37:13 -07002993 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002994 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002995
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002996 _lib.EVP_SignInit(md_ctx, digest_obj)
2997 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002998
Paul Kehrer59d26252017-07-20 10:45:54 +02002999 length = _lib.EVP_PKEY_size(pkey._pkey)
3000 _openssl_assert(length > 0)
3001 signature_buffer = _ffi.new("unsigned char[]", length)
3002 signature_length = _ffi.new("unsigned int *")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003003 final_result = _lib.EVP_SignFinal(
Alex Gaynor03737182020-07-23 20:40:46 -04003004 md_ctx, signature_buffer, signature_length, pkey._pkey
3005 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04003006 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003007
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003008 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003009
3010
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003011def verify(cert, signature, data, digest):
3012 """
Alex Chand072cae2018-02-15 09:57:59 +00003013 Verify the signature for a data string.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003014
Alex Chand072cae2018-02-15 09:57:59 +00003015 :param cert: signing certificate (X509 object) corresponding to the
3016 private key which generated the signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003017 :param signature: signature returned by sign function
3018 :param data: data to be verified
3019 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07003020 :return: ``None`` if the signature is correct, raise exception otherwise.
Alex Chand072cae2018-02-15 09:57:59 +00003021
3022 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003023 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003024 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00003025
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003026 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003027 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003028 raise ValueError("No such digest method")
3029
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003030 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07003031 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003032 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003033
Alex Gaynor67903a62016-06-02 10:37:13 -07003034 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07003035 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003036
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003037 _lib.EVP_VerifyInit(md_ctx, digest_obj)
3038 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04003039 verify_result = _lib.EVP_VerifyFinal(
3040 md_ctx, signature, len(signature), pkey
3041 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003042
3043 if verify_result != 1:
3044 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003045
3046
Dominic Chenf05b2122015-10-13 16:32:35 +00003047def dump_crl(type, crl):
3048 """
3049 Dump a certificate revocation list to a buffer.
3050
3051 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
3052 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02003053 :param CRL crl: The CRL to dump.
3054
Dominic Chenf05b2122015-10-13 16:32:35 +00003055 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07003056 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00003057 """
3058 bio = _new_mem_buf()
3059
3060 if type == FILETYPE_PEM:
3061 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
3062 elif type == FILETYPE_ASN1:
3063 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
3064 elif type == FILETYPE_TEXT:
3065 ret = _lib.X509_CRL_print(bio, crl._crl)
3066 else:
3067 raise ValueError(
3068 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04003069 "FILETYPE_TEXT"
3070 )
Dominic Chenf05b2122015-10-13 16:32:35 +00003071
Adrián Chaves98c57be2020-03-31 16:14:50 +02003072 _openssl_assert(ret == 1)
Dominic Chenf05b2122015-10-13 16:32:35 +00003073 return _bio_to_string(bio)
3074
3075
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003076def load_crl(type, buffer):
3077 """
Alex Chand072cae2018-02-15 09:57:59 +00003078 Load Certificate Revocation List (CRL) data from a string *buffer*.
3079 *buffer* encoded with the type *type*.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003080
3081 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
3082 :param buffer: The buffer the CRL is stored in
3083
3084 :return: The PKey object
3085 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003086 if isinstance(buffer, _text_type):
3087 buffer = buffer.encode("ascii")
3088
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003089 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003090
3091 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003092 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003093 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003094 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003095 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003096 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
3097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003098 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003099 _raise_current_error()
3100
3101 result = CRL.__new__(CRL)
Jeremy Cline9e15eca2017-09-07 20:11:08 -04003102 result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003103 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003104
3105
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003106def load_pkcs7_data(type, buffer):
3107 """
Alex Chand072cae2018-02-15 09:57:59 +00003108 Load pkcs7 data from the string *buffer* encoded with the type
3109 *type*.
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003110
3111 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
3112 :param buffer: The buffer with the pkcs7 data.
3113 :return: The PKCS7 object
3114 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003115 if isinstance(buffer, _text_type):
3116 buffer = buffer.encode("ascii")
3117
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003118 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003119
3120 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003121 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003122 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07003123 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003124 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003125 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
3126
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003127 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08003128 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003129
3130 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003131 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003132 return pypkcs7
3133
3134
Alex Gaynorbb971ae2020-08-05 01:14:16 -04003135load_pkcs7_data = utils.deprecated(
3136 load_pkcs7_data,
3137 __name__,
3138 (
3139 "PKCS#7 support in pyOpenSSL is deprecated. You should use the APIs "
3140 "in cryptography."
3141 ),
3142 DeprecationWarning,
3143)
3144
3145
Stephen Holsapple38482622014-04-05 20:29:34 -07003146def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003147 """
Alex Chand072cae2018-02-15 09:57:59 +00003148 Load pkcs12 data from the string *buffer*. If the pkcs12 structure is
3149 encrypted, a *passphrase* must be included. The MAC is always
3150 checked and thus required.
3151
3152 See also the man page for the C function :py:func:`PKCS12_parse`.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003153
3154 :param buffer: The buffer the certificate is stored in
3155 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
3156 :returns: The PKCS12 object
3157 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003158 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00003159
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003160 if isinstance(buffer, _text_type):
3161 buffer = buffer.encode("ascii")
3162
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003163 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003164
Stephen Holsapple38482622014-04-05 20:29:34 -07003165 # Use null passphrase if passphrase is None or empty string. With PKCS#12
3166 # password based encryption no password and a zero length password are two
3167 # different things, but OpenSSL implementation will try both to figure out
3168 # which one works.
3169 if not passphrase:
3170 passphrase = _ffi.NULL
3171
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003172 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
3173 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003174 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003175 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003177 pkey = _ffi.new("EVP_PKEY**")
3178 cert = _ffi.new("X509**")
3179 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003180
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003181 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003182 if not parse_result:
3183 _raise_current_error()
3184
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003185 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08003186
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003187 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
3188 # queue for no particular reason. This error isn't interesting to anyone
3189 # outside this function. It's not even interesting to us. Get rid of it.
3190 try:
3191 _raise_current_error()
3192 except Error:
3193 pass
3194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003195 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003196 pykey = None
3197 else:
3198 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003199 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003201 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003202 pycert = None
3203 friendlyname = None
3204 else:
Paul Kehrere7381862017-11-30 20:55:25 +08003205 pycert = X509._from_raw_x509_ptr(cert[0])
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003206
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003207 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04003208 friendlyname_buffer = _lib.X509_alias_get0(
3209 cert[0], friendlyname_length
3210 )
3211 friendlyname = _ffi.buffer(
3212 friendlyname_buffer, friendlyname_length[0]
3213 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003214 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003215 friendlyname = None
3216
3217 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003218 for i in range(_lib.sk_X509_num(cacerts)):
Paul Kehrere7381862017-11-30 20:55:25 +08003219 x509 = _lib.sk_X509_value(cacerts, i)
3220 pycacert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003221 pycacerts.append(pycacert)
3222 if not pycacerts:
3223 pycacerts = None
3224
3225 pkcs12 = PKCS12.__new__(PKCS12)
3226 pkcs12._pkey = pykey
3227 pkcs12._cert = pycert
3228 pkcs12._cacerts = pycacerts
3229 pkcs12._friendlyname = friendlyname
3230 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05003231
3232
Alex Gaynorbb971ae2020-08-05 01:14:16 -04003233load_pkcs12 = utils.deprecated(
3234 load_pkcs12,
3235 __name__,
3236 (
3237 "PKCS#12 support in pyOpenSSL is deprecated. You should use the APIs "
3238 "in cryptography."
3239 ),
3240 DeprecationWarning,
3241)
3242
3243
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05003244# There are no direct unit tests for this initialization. It is tested
3245# indirectly since it is necessary for functions like dump_privatekey when
3246# using encryption.
3247#
3248# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
3249# and some other similar tests may fail without this (though they may not if
3250# the Python runtime has already done some initialization of the underlying
3251# OpenSSL library (and is linked against the same one that cryptography is
3252# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05003253_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05003254
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05003255# This is similar but exercised mainly by exception_from_error_queue. It calls
3256# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
3257_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003258
3259
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003260# Set the default string mask to match OpenSSL upstream (since 2005) and
3261# RFC5280 recommendations.
Alex Gaynor03737182020-07-23 20:40:46 -04003262_lib.ASN1_STRING_set_default_mask_asc(b"utf8only")