blob: 84f92b1ca97501844361f70e0e9e4f33fdde3bde [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
Alex Gaynor124a0132020-10-27 00:15:17 -04001606 res = _lib.X509_STORE_add_cert(self._store, cert._x509)
1607 _openssl_assert(res == 1)
Dan Sully44e767a2016-06-04 18:05:27 -07001608
1609 def add_crl(self, crl):
1610 """
1611 Add a certificate revocation list to this store.
1612
1613 The certificate revocation lists added to a store will only be used if
1614 the associated flags are configured to check certificate revocation
1615 lists.
1616
1617 .. versionadded:: 16.1.0
1618
1619 :param CRL crl: The certificate revocation list to add to this store.
1620 :return: ``None`` if the certificate revocation list was added
1621 successfully.
1622 """
1623 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1624
1625 def set_flags(self, flags):
1626 """
1627 Set verification flags to this store.
1628
1629 Verification flags can be combined by oring them together.
1630
1631 .. note::
1632
1633 Setting a verification flag sometimes requires clients to add
1634 additional information to the store, otherwise a suitable error will
1635 be raised.
1636
1637 For example, in setting flags to enable CRL checking a
1638 suitable CRL must be added to the store otherwise an error will be
1639 raised.
1640
1641 .. versionadded:: 16.1.0
1642
1643 :param int flags: The verification flags to set on this store.
1644 See :class:`X509StoreFlags` for available constants.
1645 :return: ``None`` if the verification flags were successfully set.
1646 """
1647 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001648
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001649 def set_time(self, vfy_time):
1650 """
1651 Set the time against which the certificates are verified.
1652
1653 Normally the current time is used.
1654
1655 .. note::
1656
1657 For example, you can determine if a certificate was valid at a given
1658 time.
1659
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001660 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001661
1662 :param datetime vfy_time: The verification time to set on this store.
1663 :return: ``None`` if the verification time was successfully set.
1664 """
1665 param = _lib.X509_VERIFY_PARAM_new()
1666 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1667
jalberdi004669dcc32020-10-18 17:55:40 +02001668 _lib.X509_VERIFY_PARAM_set_time(
1669 param, calendar.timegm(vfy_time.timetuple())
1670 )
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001671 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1672
Sándor Oroszi43c97762020-09-11 17:17:31 +02001673 def load_locations(self, cafile, capath=None):
1674 """
1675 Let X509Store know where we can find trusted certificates for the
1676 certificate chain. Note that the certificates have to be in PEM
1677 format.
1678
1679 If *capath* is passed, it must be a directory prepared using the
1680 ``c_rehash`` tool included with OpenSSL. Either, but not both, of
1681 *cafile* or *capath* may be ``None``.
1682
1683 .. note::
1684
1685 Both *cafile* and *capath* may be set simultaneously.
1686
1687 Call this method multiple times to add more than one location.
1688 For example, CA certificates, and certificate revocation list bundles
1689 may be passed in *cafile* in subsequent calls to this method.
1690
1691 .. versionadded:: 20.0
1692
1693 :param cafile: In which file we can find the certificates (``bytes`` or
1694 ``unicode``).
1695 :param capath: In which directory we can find the certificates
1696 (``bytes`` or ``unicode``).
1697
1698 :return: ``None`` if the locations were set successfully.
1699
1700 :raises OpenSSL.crypto.Error: If both *cafile* and *capath* is ``None``
1701 or the locations could not be set for any reason.
1702
1703 """
1704 if cafile is None:
1705 cafile = _ffi.NULL
1706 else:
1707 cafile = _path_string(cafile)
1708
1709 if capath is None:
1710 capath = _ffi.NULL
1711 else:
1712 capath = _path_string(capath)
1713
1714 load_result = _lib.X509_STORE_load_locations(
1715 self._store, cafile, capath
1716 )
1717 if not load_result:
1718 _raise_current_error()
1719
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001720
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001721class X509StoreContextError(Exception):
1722 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001723 An exception raised when an error occurred while verifying a certificate
1724 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001725
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001726 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001727 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001728 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001729
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001730 def __init__(self, message, certificate):
1731 super(X509StoreContextError, self).__init__(message)
1732 self.certificate = certificate
1733
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001734
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001735class X509StoreContext(object):
1736 """
1737 An X.509 store context.
1738
Dan Sully44e767a2016-06-04 18:05:27 -07001739 An X.509 store context is used to carry out the actual verification process
1740 of a certificate in a described context. For describing such a context, see
1741 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001742
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001743 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1744 instance. It is dynamically allocated and automatically garbage
1745 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001746 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001747 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001748 :ivar _chain: See the ``chain`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001749 :param X509Store store: The certificates which will be trusted for the
1750 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001751 :param X509 certificate: The certificate to be verified.
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001752 :param chain: List of untrusted certificates that may be used for building
1753 the certificate chain. May be ``None``.
1754 :type chain: :class:`list` of :class:`X509`
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001755 """
1756
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001757 def __init__(self, store, certificate, chain=None):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001758 store_ctx = _lib.X509_STORE_CTX_new()
1759 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1760 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001761 self._cert = certificate
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001762 self._chain = self._build_certificate_stack(chain)
Stephen Holsapple46a09252015-02-12 14:45:43 -08001763 # Make the store context available for use after instantiating this
1764 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001765 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001766 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001767
Sándor Oroszi83ef2302020-10-12 15:42:23 +02001768 @staticmethod
1769 def _build_certificate_stack(certificates):
1770 def cleanup(s):
1771 # Equivalent to sk_X509_pop_free, but we don't
1772 # currently have a CFFI binding for that available
1773 for i in range(_lib.sk_X509_num(s)):
1774 x = _lib.sk_X509_value(s, i)
1775 _lib.X509_free(x)
1776 _lib.sk_X509_free(s)
1777
1778 if certificates is None or len(certificates) == 0:
1779 return _ffi.NULL
1780
1781 stack = _lib.sk_X509_new_null()
1782 _openssl_assert(stack != _ffi.NULL)
1783 stack = _ffi.gc(stack, cleanup)
1784
1785 for cert in certificates:
1786 if not isinstance(cert, X509):
1787 raise TypeError("One of the elements is not an X509 instance")
1788
1789 _openssl_assert(_lib.X509_up_ref(cert._x509) > 0)
1790 if _lib.sk_X509_push(stack, cert._x509) <= 0:
1791 _lib.X509_free(cert._x509)
1792 _raise_current_error()
1793
1794 return stack
1795
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001796 def _init(self):
1797 """
1798 Set up the store context for a subsequent verification operation.
Jeremy Cline58193f12017-09-13 21:14:53 -04001799
1800 Calling this method more than once without first calling
1801 :meth:`_cleanup` will leak memory.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001802 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001803 ret = _lib.X509_STORE_CTX_init(
Shane Harvey33c54992020-08-05 16:48:51 -07001804 self._store_ctx, self._store._store, self._cert._x509, self._chain
Alex Gaynor5945ea82015-09-05 14:59:06 -04001805 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001806 if ret <= 0:
1807 _raise_current_error()
1808
1809 def _cleanup(self):
1810 """
1811 Internally cleans up the store context.
1812
Dan Sully44e767a2016-06-04 18:05:27 -07001813 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001814 """
1815 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1816
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001817 def _exception_from_context(self):
1818 """
1819 Convert an OpenSSL native context error failure into a Python
1820 exception.
1821
Alex Gaynor5945ea82015-09-05 14:59:06 -04001822 When a call to native OpenSSL X509_verify_cert fails, additional
1823 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001824 """
1825 errors = [
1826 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1827 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
Alex Gaynor03737182020-07-23 20:40:46 -04001828 _native(
1829 _ffi.string(
1830 _lib.X509_verify_cert_error_string(
1831 _lib.X509_STORE_CTX_get_error(self._store_ctx)
1832 )
1833 )
1834 ),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001835 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001836 # A context error should always be associated with a certificate, so we
1837 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001838 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001839 _cert = _lib.X509_dup(_x509)
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001840 pycert = X509._from_raw_x509_ptr(_cert)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001841 return X509StoreContextError(errors, pycert)
1842
Stephen Holsapple46a09252015-02-12 14:45:43 -08001843 def set_store(self, store):
1844 """
Dan Sully44e767a2016-06-04 18:05:27 -07001845 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001846
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001847 .. versionadded:: 0.15
1848
Dan Sully44e767a2016-06-04 18:05:27 -07001849 :param X509Store store: The store description which will be used for
1850 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001851 """
1852 self._store = store
1853
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001854 def verify_certificate(self):
1855 """
1856 Verify a certificate in a context.
1857
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001858 .. versionadded:: 0.15
1859
Alex Gaynorca87ff62015-09-04 23:31:03 -04001860 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001861 certificate in the context. Sets ``certificate`` attribute to
1862 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001863 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001864 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001865 # :meth:`verify_certificate` is called multiple times.
Jeremy Cline58193f12017-09-13 21:14:53 -04001866 #
1867 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1868 # before _init to ensure memory is not leaked.
1869 self._cleanup()
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001870 self._init()
1871 ret = _lib.X509_verify_cert(self._store_ctx)
1872 self._cleanup()
1873 if ret <= 0:
1874 raise self._exception_from_context()
1875
Shane Harvey33c54992020-08-05 16:48:51 -07001876 def get_verified_chain(self):
1877 """
1878 Verify a certificate in a context and return the complete validated
1879 chain.
1880
1881 :raises X509StoreContextError: If an error occurred when validating a
1882 certificate in the context. Sets ``certificate`` attribute to
1883 indicate which certificate caused the error.
1884
1885 .. versionadded:: 20.0
1886 """
1887 # Always re-initialize the store context in case
1888 # :meth:`verify_certificate` is called multiple times.
1889 #
1890 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1891 # before _init to ensure memory is not leaked.
1892 self._cleanup()
1893 self._init()
1894 ret = _lib.X509_verify_cert(self._store_ctx)
1895 if ret <= 0:
1896 self._cleanup()
1897 raise self._exception_from_context()
1898
1899 # Note: X509_STORE_CTX_get1_chain returns a deep copy of the chain.
1900 cert_stack = _lib.X509_STORE_CTX_get1_chain(self._store_ctx)
1901 _openssl_assert(cert_stack != _ffi.NULL)
1902
1903 result = []
1904 for i in range(_lib.sk_X509_num(cert_stack)):
1905 cert = _lib.sk_X509_value(cert_stack, i)
1906 _openssl_assert(cert != _ffi.NULL)
1907 pycert = X509._from_raw_x509_ptr(cert)
1908 result.append(pycert)
1909
1910 # Free the stack but not the members which are freed by the X509 class.
1911 _lib.sk_X509_free(cert_stack)
1912 self._cleanup()
1913 return result
1914
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001915
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001916def load_certificate(type, buffer):
1917 """
Alex Chand072cae2018-02-15 09:57:59 +00001918 Load a certificate (X509) from the string *buffer* encoded with the
1919 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001920
1921 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1922
Dan Sully44e767a2016-06-04 18:05:27 -07001923 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001924
1925 :return: The X509 object
1926 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001927 if isinstance(buffer, _text_type):
1928 buffer = buffer.encode("ascii")
1929
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001930 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001931
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001932 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001933 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001934 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001935 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001936 else:
Alex Gaynor03737182020-07-23 20:40:46 -04001937 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001938
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001939 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001940 _raise_current_error()
1941
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001942 return X509._from_raw_x509_ptr(x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001943
1944
1945def dump_certificate(type, cert):
1946 """
Alex Chand072cae2018-02-15 09:57:59 +00001947 Dump the certificate *cert* into a buffer string encoded with the type
1948 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001949
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001950 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1951 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001952 :param cert: The certificate to dump
1953 :return: The buffer with the dumped certificate in
1954 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001955 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001956
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001957 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001958 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001959 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001961 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001962 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001963 else:
1964 raise ValueError(
1965 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04001966 "FILETYPE_TEXT"
1967 )
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001968
Adrián Chaves98c57be2020-03-31 16:14:50 +02001969 _openssl_assert(result_code == 1)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001970 return _bio_to_string(bio)
1971
1972
Cory Benfield6492f7c2015-10-27 16:57:58 +09001973def dump_publickey(type, pkey):
1974 """
Cory Benfield11c10192015-10-27 17:23:03 +09001975 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001976
Cory Benfield9c590b92015-10-28 14:55:05 +09001977 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001978 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001979 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001980 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001981 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001982 """
1983 bio = _new_mem_buf()
1984 if type == FILETYPE_PEM:
1985 write_bio = _lib.PEM_write_bio_PUBKEY
1986 elif type == FILETYPE_ASN1:
1987 write_bio = _lib.i2d_PUBKEY_bio
1988 else:
1989 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1990
1991 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001992 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001993 _raise_current_error()
1994
1995 return _bio_to_string(bio)
1996
1997
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001998def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1999 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002000 Dump the private key *pkey* into a buffer string encoded with the type
2001 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
2002 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002003
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002004 :param type: The file type (one of :const:`FILETYPE_PEM`,
2005 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
2006 :param PKey pkey: The PKey to dump
2007 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002008 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002009 the passphrase to use, or a callback for providing the passphrase.
2010
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002011 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07002012 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002013 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002014 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002015
Paul Kehrercded9932017-06-29 18:43:42 -05002016 if not isinstance(pkey, PKey):
2017 raise TypeError("pkey must be a PKey")
2018
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002019 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002020 if passphrase is None:
2021 raise TypeError(
2022 "if a value is given for cipher "
Alex Gaynor03737182020-07-23 20:40:46 -04002023 "one must also be given for passphrase"
2024 )
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002025 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002026 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002027 raise ValueError("Invalid cipher name")
2028 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002029 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002030
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002031 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002032 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002033 result_code = _lib.PEM_write_bio_PrivateKey(
Alex Gaynor03737182020-07-23 20:40:46 -04002034 bio,
2035 pkey._pkey,
2036 cipher_obj,
2037 _ffi.NULL,
2038 0,
2039 helper.callback,
2040 helper.callback_args,
2041 )
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002042 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002043 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002044 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002045 elif type == FILETYPE_TEXT:
Paul Kehrercded9932017-06-29 18:43:42 -05002046 if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:
2047 raise TypeError("Only RSA keys are supported for FILETYPE_TEXT")
2048
Alex Gaynor03737182020-07-23 20:40:46 -04002049 rsa = _ffi.gc(_lib.EVP_PKEY_get1_RSA(pkey._pkey), _lib.RSA_free)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002050 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002051 else:
2052 raise ValueError(
2053 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04002054 "FILETYPE_TEXT"
2055 )
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002056
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02002057 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002058
2059 return _bio_to_string(bio)
2060
2061
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002062class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002063 """
2064 A certificate revocation.
2065 """
Alex Gaynor03737182020-07-23 20:40:46 -04002066
Cyril Stoller37e60222018-08-27 13:38:10 +02002067 # https://www.openssl.org/docs/manmaster/man5/x509v3_config.html#CRL-distribution-points
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002068 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
2069 # OCSP_crl_reason_str. We use the latter, just like the command line
2070 # program.
2071 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002072 b"unspecified",
2073 b"keyCompromise",
2074 b"CACompromise",
2075 b"affiliationChanged",
2076 b"superseded",
2077 b"cessationOfOperation",
2078 b"certificateHold",
2079 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04002080 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002081
2082 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002083 revoked = _lib.X509_REVOKED_new()
2084 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002085
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002086 def set_serial(self, hex_str):
2087 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002088 Set the serial number.
2089
2090 The serial number is formatted as a hexadecimal number encoded in
2091 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002092
Dan Sully44e767a2016-06-04 18:05:27 -07002093 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002094
Dan Sully44e767a2016-06-04 18:05:27 -07002095 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002096 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002097 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
2098 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002099 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002100 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002101 if not bn_result:
2102 raise ValueError("bad hex string")
2103
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002104 asn1_serial = _ffi.gc(
2105 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
Alex Gaynor03737182020-07-23 20:40:46 -04002106 _lib.ASN1_INTEGER_free,
2107 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002108 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002109
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002110 def get_serial(self):
2111 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002112 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002113
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002114 The serial number is formatted as a hexadecimal number encoded in
2115 ASCII.
2116
2117 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07002118 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002119 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002120 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002121
Alex Gaynor67903a62016-06-02 10:37:13 -07002122 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
2123 _openssl_assert(asn1_int != _ffi.NULL)
2124 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
2125 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002126 return _bio_to_string(bio)
2127
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002128 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07002129 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2130 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002131 obj = _lib.X509_EXTENSION_get_object(ext)
2132 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002133 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07002134 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002135 break
2136
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002137 def set_reason(self, reason):
2138 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002139 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002140
Dan Sully44e767a2016-06-04 18:05:27 -07002141 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002142
2143 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07002144 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002145
Dan Sully44e767a2016-06-04 18:05:27 -07002146 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002147
2148 .. seealso::
2149
Dan Sully44e767a2016-06-04 18:05:27 -07002150 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002151 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002152 """
2153 if reason is None:
2154 self._delete_reason()
2155 elif not isinstance(reason, bytes):
2156 raise TypeError("reason must be None or a byte string")
2157 else:
Alex Gaynor03737182020-07-23 20:40:46 -04002158 reason = reason.lower().replace(b" ", b"")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002159 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
2160
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002161 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002162 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002163 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002164
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002165 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002166 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002167
2168 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002169 add_result = _lib.X509_REVOKED_add1_ext_i2d(
Alex Gaynor03737182020-07-23 20:40:46 -04002170 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0
2171 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002172 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002173
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002174 def get_reason(self):
2175 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04002176 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002177
Dan Sully44e767a2016-06-04 18:05:27 -07002178 :return: The reason, or ``None`` if there is none.
2179 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002180
2181 .. seealso::
2182
Dan Sully44e767a2016-06-04 18:05:27 -07002183 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002184 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002185 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002186 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2187 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002188 obj = _lib.X509_EXTENSION_get_object(ext)
2189 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002190 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002191
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002192 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002193 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002194 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002195 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04002196 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002197 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002198
2199 return _bio_to_string(bio)
2200
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002201 def all_reasons(self):
2202 """
2203 Return a list of all the supported reason strings.
2204
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002205 This list is a copy; modifying it does not change the supported reason
2206 strings.
2207
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002208 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07002209 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002210 """
2211 return self._crl_reasons[:]
2212
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002213 def set_rev_date(self, when):
2214 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002215 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002216
Dan Sully44e767a2016-06-04 18:05:27 -07002217 :param bytes when: The timestamp of the revocation,
Paul Kehrerce98ee62017-06-21 06:59:58 -10002218 as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002219 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002220 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002221 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2222 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002223
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002224 def get_rev_date(self):
2225 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002226 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002227
Paul Kehrerce98ee62017-06-21 06:59:58 -10002228 :return: The timestamp of the revocation, as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002229 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002230 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002231 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2232 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002233
2234
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002235class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002236 """
2237 A certificate revocation list.
2238 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002239
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002240 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002241 crl = _lib.X509_CRL_new()
2242 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002243
Paul Kehrer41c10242017-06-29 18:24:17 -05002244 def to_cryptography(self):
2245 """
2246 Export as a ``cryptography`` CRL.
2247
2248 :rtype: ``cryptography.x509.CertificateRevocationList``
2249
2250 .. versionadded:: 17.1.0
2251 """
2252 from cryptography.hazmat.backends.openssl.x509 import (
Alex Gaynor03737182020-07-23 20:40:46 -04002253 _CertificateRevocationList,
Paul Kehrer41c10242017-06-29 18:24:17 -05002254 )
Alex Gaynor03737182020-07-23 20:40:46 -04002255
Paul Kehrer41c10242017-06-29 18:24:17 -05002256 backend = _get_backend()
2257 return _CertificateRevocationList(backend, self._crl)
2258
2259 @classmethod
2260 def from_cryptography(cls, crypto_crl):
2261 """
2262 Construct based on a ``cryptography`` *crypto_crl*.
2263
2264 :param crypto_crl: A ``cryptography`` certificate revocation list
2265 :type crypto_crl: ``cryptography.x509.CertificateRevocationList``
2266
2267 :rtype: CRL
2268
2269 .. versionadded:: 17.1.0
2270 """
2271 if not isinstance(crypto_crl, x509.CertificateRevocationList):
2272 raise TypeError("Must be a certificate revocation list")
2273
2274 crl = cls()
2275 crl._crl = crypto_crl._x509_crl
2276 return crl
2277
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002278 def get_revoked(self):
2279 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002280 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002281
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002282 These revocations will be provided by value, not by reference.
2283 That means it's okay to mutate them: it won't affect this CRL.
2284
2285 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002286 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002287 """
2288 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07002289 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002290 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
2291 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04002292 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002293 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002294 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002295 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002296 if results:
2297 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002298
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002299 def add_revoked(self, revoked):
2300 """
2301 Add a revoked (by value not reference) to the CRL structure
2302
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002303 This revocation will be added by value, not by reference. That
2304 means it's okay to mutate it after adding: it won't affect
2305 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002306
Dan Sully44e767a2016-06-04 18:05:27 -07002307 :param Revoked revoked: The new revocation.
2308 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002309 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04002310 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002311 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002312
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002313 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002314 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002315
Dan Sully44e767a2016-06-04 18:05:27 -07002316 def get_issuer(self):
2317 """
2318 Get the CRL's issuer.
2319
2320 .. versionadded:: 16.1.0
2321
2322 :rtype: X509Name
2323 """
2324 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2325 _openssl_assert(_issuer != _ffi.NULL)
2326 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2327 issuer = X509Name.__new__(X509Name)
2328 issuer._name = _issuer
2329 return issuer
2330
2331 def set_version(self, version):
2332 """
2333 Set the CRL version.
2334
2335 .. versionadded:: 16.1.0
2336
2337 :param int version: The version of the CRL.
2338 :return: ``None``
2339 """
2340 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2341
2342 def _set_boundary_time(self, which, when):
2343 return _set_asn1_time(which(self._crl), when)
2344
2345 def set_lastUpdate(self, when):
2346 """
2347 Set when the CRL was last updated.
2348
Paul Kehrerce98ee62017-06-21 06:59:58 -10002349 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002350
2351 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002352
2353 .. versionadded:: 16.1.0
2354
2355 :param bytes when: A timestamp string.
2356 :return: ``None``
2357 """
2358 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2359
2360 def set_nextUpdate(self, when):
2361 """
Felix Yan3db93f12020-10-15 03:41:20 +08002362 Set when the CRL will next be updated.
Dan Sully44e767a2016-06-04 18:05:27 -07002363
Paul Kehrerce98ee62017-06-21 06:59:58 -10002364 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002365
2366 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002367
2368 .. versionadded:: 16.1.0
2369
2370 :param bytes when: A timestamp string.
2371 :return: ``None``
2372 """
2373 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2374
2375 def sign(self, issuer_cert, issuer_key, digest):
2376 """
2377 Sign the CRL.
2378
2379 Signing a CRL enables clients to associate the CRL itself with an
2380 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2381 be signed by an issuer.
2382
2383 This method implicitly sets the issuer's name based on the issuer
2384 certificate and private key used to sign the CRL.
2385
2386 .. versionadded:: 16.1.0
2387
2388 :param X509 issuer_cert: The issuer's certificate.
2389 :param PKey issuer_key: The issuer's private key.
2390 :param bytes digest: The digest method to sign the CRL with.
2391 """
2392 digest_obj = _lib.EVP_get_digestbyname(digest)
2393 _openssl_assert(digest_obj != _ffi.NULL)
2394 _lib.X509_CRL_set_issuer_name(
Alex Gaynor03737182020-07-23 20:40:46 -04002395 self._crl, _lib.X509_get_subject_name(issuer_cert._x509)
2396 )
Dan Sully44e767a2016-06-04 18:05:27 -07002397 _lib.X509_CRL_sort(self._crl)
2398 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2399 _openssl_assert(result != 0)
2400
Alex Gaynor03737182020-07-23 20:40:46 -04002401 def export(
2402 self, cert, key, type=FILETYPE_PEM, days=100, digest=_UNSPECIFIED
2403 ):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002404 """
Dan Sully44e767a2016-06-04 18:05:27 -07002405 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002406
Dan Sully44e767a2016-06-04 18:05:27 -07002407 :param X509 cert: The certificate used to sign the CRL.
2408 :param PKey key: The key used to sign the CRL.
2409 :param int type: The export format, either :data:`FILETYPE_PEM`,
2410 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002411 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002412 :param bytes digest: The name of the message digest to use (eg
Wayne Werner80dcf382019-01-30 15:03:16 -06002413 ``b"sha256"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002414 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002415 """
Dan Sully44e767a2016-06-04 18:05:27 -07002416
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002417 if not isinstance(cert, X509):
2418 raise TypeError("cert must be an X509 instance")
2419 if not isinstance(key, PKey):
2420 raise TypeError("key must be a PKey instance")
2421 if not isinstance(type, int):
2422 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002423
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002424 if digest is _UNSPECIFIED:
Alex Gaynor173e4ba2017-06-30 08:01:12 -07002425 raise TypeError("digest must be provided")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002426
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002427 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002428 if digest_obj == _ffi.NULL:
2429 raise ValueError("No such digest method")
2430
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002431 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002432 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002433
Alex Gaynora738ed52015-09-05 11:17:10 -04002434 # A scratch time object to give different values to different CRL
2435 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002436 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002437 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002438
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002439 _lib.X509_gmtime_adj(sometime, 0)
2440 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002441
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002442 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2443 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002444
Alex Gaynor5945ea82015-09-05 14:59:06 -04002445 _lib.X509_CRL_set_issuer_name(
2446 self._crl, _lib.X509_get_subject_name(cert._x509)
2447 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002448
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002449 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002450 if not sign_result:
2451 _raise_current_error()
2452
Dominic Chenf05b2122015-10-13 16:32:35 +00002453 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002454
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002455
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002456class PKCS7(object):
2457 def type_is_signed(self):
2458 """
2459 Check if this NID_pkcs7_signed object
2460
2461 :return: True if the PKCS7 is of type signed
2462 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002463 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002464
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002465 def type_is_enveloped(self):
2466 """
2467 Check if this NID_pkcs7_enveloped object
2468
2469 :returns: True if the PKCS7 is of type enveloped
2470 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002471 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002472
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002473 def type_is_signedAndEnveloped(self):
2474 """
2475 Check if this NID_pkcs7_signedAndEnveloped object
2476
2477 :returns: True if the PKCS7 is of type signedAndEnveloped
2478 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002479 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002480
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002481 def type_is_data(self):
2482 """
2483 Check if this NID_pkcs7_data object
2484
2485 :return: True if the PKCS7 is of type data
2486 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002487 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002488
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002489 def get_type_name(self):
2490 """
2491 Returns the type name of the PKCS7 structure
2492
2493 :return: A string with the typename
2494 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002495 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2496 string_type = _lib.OBJ_nid2sn(nid)
2497 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002498
Alex Chanc6077062016-11-18 13:53:39 +00002499
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002500class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002501 """
2502 A PKCS #12 archive.
2503 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002504
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002505 def __init__(self):
2506 self._pkey = None
2507 self._cert = None
2508 self._cacerts = None
2509 self._friendlyname = None
2510
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002511 def get_certificate(self):
2512 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002513 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002514
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002515 :return: The certificate, or :py:const:`None` if there is none.
2516 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002517 """
2518 return self._cert
2519
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002520 def set_certificate(self, cert):
2521 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002522 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002523
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002524 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002525 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002526
Dan Sully44e767a2016-06-04 18:05:27 -07002527 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002528 """
2529 if not isinstance(cert, X509):
2530 raise TypeError("cert must be an X509 instance")
2531 self._cert = cert
2532
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002533 def get_privatekey(self):
2534 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002535 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002536
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002537 :return: The private key, or :py:const:`None` if there is none.
2538 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002539 """
2540 return self._pkey
2541
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002542 def set_privatekey(self, pkey):
2543 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002544 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002545
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002546 :param pkey: The new private key, or :py:const:`None` to unset it.
2547 :type pkey: :py:class:`PKey` or :py:const:`None`
2548
Dan Sully44e767a2016-06-04 18:05:27 -07002549 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002550 """
2551 if not isinstance(pkey, PKey):
2552 raise TypeError("pkey must be a PKey instance")
2553 self._pkey = pkey
2554
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002555 def get_ca_certificates(self):
2556 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002557 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002558
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002559 :return: A tuple with the CA certificates in the chain, or
2560 :py:const:`None` if there are none.
2561 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002562 """
2563 if self._cacerts is not None:
2564 return tuple(self._cacerts)
2565
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002566 def set_ca_certificates(self, cacerts):
2567 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002568 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002569
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002570 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2571 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002572 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002573
Dan Sully44e767a2016-06-04 18:05:27 -07002574 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002575 """
2576 if cacerts is None:
2577 self._cacerts = None
2578 else:
2579 cacerts = list(cacerts)
2580 for cert in cacerts:
2581 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002582 raise TypeError(
2583 "iterable must only contain X509 instances"
2584 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002585 self._cacerts = cacerts
2586
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002587 def set_friendlyname(self, name):
2588 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002589 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002590
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002591 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002592 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002593
Dan Sully44e767a2016-06-04 18:05:27 -07002594 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002595 """
2596 if name is None:
2597 self._friendlyname = None
2598 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002599 raise TypeError(
2600 "name must be a byte string or None (not %r)" % (name,)
2601 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002602 self._friendlyname = name
2603
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002604 def get_friendlyname(self):
2605 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002606 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002607
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002608 :returns: The friendly name, or :py:const:`None` if there is none.
2609 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002610 """
2611 return self._friendlyname
2612
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002613 def export(self, passphrase=None, iter=2048, maciter=1):
2614 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002615 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002616
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002617 For more information, see the :c:func:`PKCS12_create` man page.
2618
2619 :param passphrase: The passphrase used to encrypt the structure. Unlike
2620 some other passphrase arguments, this *must* be a string, not a
2621 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002622 :type passphrase: :py:data:`bytes`
2623
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002624 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002625 :type iter: :py:data:`int`
2626
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002627 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002628 :type maciter: :py:data:`int`
2629
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002630 :return: The string representation of the PKCS #12 structure.
2631 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002632 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002633 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002634
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002635 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002636 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002637 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002638 cacerts = _lib.sk_X509_new_null()
2639 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002640 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002641 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002642
2643 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002644 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002645
2646 friendlyname = self._friendlyname
2647 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002648 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002649
2650 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002651 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002652 else:
2653 pkey = self._pkey._pkey
2654
2655 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002656 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002657 else:
2658 cert = self._cert._x509
2659
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002660 pkcs12 = _lib.PKCS12_create(
Alex Gaynor03737182020-07-23 20:40:46 -04002661 passphrase,
2662 friendlyname,
2663 pkey,
2664 cert,
2665 cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002666 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2667 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Alex Gaynor03737182020-07-23 20:40:46 -04002668 iter,
2669 maciter,
2670 0,
2671 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002672 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002673 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002674 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002675
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002676 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002677 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002678 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002679
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002680
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002681class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002682 """
2683 A Netscape SPKI object.
2684 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002685
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002686 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002687 spki = _lib.NETSCAPE_SPKI_new()
2688 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002689
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002690 def sign(self, pkey, digest):
2691 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002692 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002693
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002694 :param pkey: The private key to sign with.
2695 :type pkey: :py:class:`PKey`
2696
2697 :param digest: The message digest to use.
2698 :type digest: :py:class:`bytes`
2699
Dan Sully44e767a2016-06-04 18:05:27 -07002700 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002701 """
2702 if pkey._only_public:
2703 raise ValueError("Key has only public part")
2704
2705 if not pkey._initialized:
2706 raise ValueError("Key is uninitialized")
2707
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002708 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002709 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002710 raise ValueError("No such digest method")
2711
Alex Gaynor5945ea82015-09-05 14:59:06 -04002712 sign_result = _lib.NETSCAPE_SPKI_sign(
2713 self._spki, pkey._pkey, digest_obj
2714 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002715 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002716
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002717 def verify(self, key):
2718 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002719 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002720
Hynek Schlawack01c31672016-12-11 15:14:09 +01002721 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002722
Hynek Schlawack01c31672016-12-11 15:14:09 +01002723 :return: ``True`` if the signature is correct.
2724 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002725
Hynek Schlawack01c31672016-12-11 15:14:09 +01002726 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2727 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002728 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002729 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002730 if answer <= 0:
2731 _raise_current_error()
2732 return True
2733
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002734 def b64_encode(self):
2735 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002736 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002737
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002738 :return: The base64 encoded string.
2739 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002740 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002741 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2742 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002743 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002744 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002745
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002746 def get_pubkey(self):
2747 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002748 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002749
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002750 :return: The public key.
2751 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002752 """
2753 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002754 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002755 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002756 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002757 pkey._only_public = True
2758 return pkey
2759
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002760 def set_pubkey(self, pkey):
2761 """
2762 Set the public key of the certificate
2763
2764 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002765 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002766 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002767 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002768 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002769
2770
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002771class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002772 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002773 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002774 raise ValueError(
2775 "only FILETYPE_PEM key format supports encryption"
2776 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002777 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002778 self._more_args = more_args
2779 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002780 self._problems = []
2781
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002782 @property
2783 def callback(self):
2784 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002785 return _ffi.NULL
Huw Jonescdd66962020-10-13 05:14:19 +01002786 elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002787 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002788 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002789 raise TypeError(
2790 "Last argument must be a byte string or a callable."
2791 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002792
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002793 @property
2794 def callback_args(self):
2795 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002796 return _ffi.NULL
Huw Jonescdd66962020-10-13 05:14:19 +01002797 elif isinstance(self._passphrase, bytes) or callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002798 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002799 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002800 raise TypeError(
2801 "Last argument must be a byte string or a callable."
2802 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002803
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002804 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002805 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002806
2807 # Flush the OpenSSL error queue
2808 try:
2809 _exception_from_error_queue(exceptionType)
2810 except exceptionType:
2811 pass
2812
2813 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002814
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002815 def _read_passphrase(self, buf, size, rwflag, userdata):
2816 try:
Huw Jonescdd66962020-10-13 05:14:19 +01002817 if callable(self._passphrase):
2818 if self._more_args:
2819 result = self._passphrase(size, rwflag, userdata)
2820 else:
2821 result = self._passphrase(rwflag)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002822 else:
Huw Jonescdd66962020-10-13 05:14:19 +01002823 result = self._passphrase
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002824 if not isinstance(result, bytes):
Huw Jonescdd66962020-10-13 05:14:19 +01002825 raise ValueError("Bytes expected")
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002826 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002827 if self._truncate:
2828 result = result[:size]
2829 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002830 raise ValueError(
2831 "passphrase returned by callback is too long"
2832 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002833 for i in range(len(result)):
Alex Gaynor03737182020-07-23 20:40:46 -04002834 buf[i] = result[i : i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002835 return len(result)
2836 except Exception as e:
2837 self._problems.append(e)
2838 return 0
2839
2840
Cory Benfield6492f7c2015-10-27 16:57:58 +09002841def load_publickey(type, buffer):
2842 """
Cory Benfield11c10192015-10-27 17:23:03 +09002843 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002844
Cory Benfield9c590b92015-10-28 14:55:05 +09002845 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002846 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002847 :param buffer: The buffer the key is stored in.
2848 :type buffer: A Python string object, either unicode or bytestring.
2849 :return: The PKey object.
2850 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002851 """
2852 if isinstance(buffer, _text_type):
2853 buffer = buffer.encode("ascii")
2854
2855 bio = _new_mem_buf(buffer)
2856
2857 if type == FILETYPE_PEM:
2858 evp_pkey = _lib.PEM_read_bio_PUBKEY(
Alex Gaynor03737182020-07-23 20:40:46 -04002859 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL
2860 )
Cory Benfield6492f7c2015-10-27 16:57:58 +09002861 elif type == FILETYPE_ASN1:
2862 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2863 else:
2864 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2865
2866 if evp_pkey == _ffi.NULL:
2867 _raise_current_error()
2868
2869 pkey = PKey.__new__(PKey)
2870 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002871 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002872 return pkey
2873
2874
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002875def load_privatekey(type, buffer, passphrase=None):
2876 """
Alex Chand072cae2018-02-15 09:57:59 +00002877 Load a private key (PKey) from the string *buffer* encoded with the type
2878 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002879
2880 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2881 :param buffer: The buffer the key is stored in
2882 :param passphrase: (optional) if encrypted PEM format, this can be
2883 either the passphrase to use, or a callback for
2884 providing the passphrase.
2885
2886 :return: The PKey object
2887 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002888 if isinstance(buffer, _text_type):
2889 buffer = buffer.encode("ascii")
2890
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002891 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002892
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002893 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002894 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002895 evp_pkey = _lib.PEM_read_bio_PrivateKey(
Alex Gaynor03737182020-07-23 20:40:46 -04002896 bio, _ffi.NULL, helper.callback, helper.callback_args
2897 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002898 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002899 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002900 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002901 else:
2902 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2903
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002904 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002905 _raise_current_error()
2906
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002907 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002908 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002909 return pkey
2910
2911
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002912def dump_certificate_request(type, req):
2913 """
Alex Chand072cae2018-02-15 09:57:59 +00002914 Dump the certificate request *req* into a buffer string encoded with the
2915 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002916
2917 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2918 :param req: The certificate request to dump
2919 :return: The buffer with the dumped certificate request in
2920 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002921 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002922
2923 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002924 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002925 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002926 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002927 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002928 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002929 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002930 raise ValueError(
2931 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2932 "FILETYPE_TEXT"
2933 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002934
Alex Gaynor09a386e2016-07-03 09:32:44 -04002935 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002936
2937 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002938
2939
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002940def load_certificate_request(type, buffer):
2941 """
Alex Chand072cae2018-02-15 09:57:59 +00002942 Load a certificate request (X509Req) from the string *buffer* encoded with
2943 the type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002944
2945 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2946 :param buffer: The buffer the certificate request is stored in
2947 :return: The X509Req object
2948 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002949 if isinstance(buffer, _text_type):
2950 buffer = buffer.encode("ascii")
2951
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002952 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002953
2954 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002955 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002956 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002957 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002958 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002959 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002960
Alex Gaynoradd5b072016-06-04 21:04:00 -07002961 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002962
2963 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002964 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002965 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002966
2967
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002968def sign(pkey, data, digest):
2969 """
Alex Chand072cae2018-02-15 09:57:59 +00002970 Sign a data string using the given key and message digest.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002971
Alex Chand072cae2018-02-15 09:57:59 +00002972 :param pkey: PKey to sign with
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002973 :param data: data to be signed
2974 :param digest: message digest to use
2975 :return: signature
Alex Chand072cae2018-02-15 09:57:59 +00002976
2977 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002978 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002979 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002980
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002981 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002982 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002983 raise ValueError("No such digest method")
2984
Alex Gaynor67903a62016-06-02 10:37:13 -07002985 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002986 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002987
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002988 _lib.EVP_SignInit(md_ctx, digest_obj)
2989 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002990
Paul Kehrer59d26252017-07-20 10:45:54 +02002991 length = _lib.EVP_PKEY_size(pkey._pkey)
2992 _openssl_assert(length > 0)
2993 signature_buffer = _ffi.new("unsigned char[]", length)
2994 signature_length = _ffi.new("unsigned int *")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002995 final_result = _lib.EVP_SignFinal(
Alex Gaynor03737182020-07-23 20:40:46 -04002996 md_ctx, signature_buffer, signature_length, pkey._pkey
2997 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002998 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002999
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003000 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003001
3002
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003003def verify(cert, signature, data, digest):
3004 """
Alex Chand072cae2018-02-15 09:57:59 +00003005 Verify the signature for a data string.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003006
Alex Chand072cae2018-02-15 09:57:59 +00003007 :param cert: signing certificate (X509 object) corresponding to the
3008 private key which generated the signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003009 :param signature: signature returned by sign function
3010 :param data: data to be verified
3011 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07003012 :return: ``None`` if the signature is correct, raise exception otherwise.
Alex Chand072cae2018-02-15 09:57:59 +00003013
3014 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003015 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003016 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00003017
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003018 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003019 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003020 raise ValueError("No such digest method")
3021
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003022 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07003023 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003024 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003025
Alex Gaynor67903a62016-06-02 10:37:13 -07003026 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07003027 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003028
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003029 _lib.EVP_VerifyInit(md_ctx, digest_obj)
3030 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04003031 verify_result = _lib.EVP_VerifyFinal(
3032 md_ctx, signature, len(signature), pkey
3033 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08003034
3035 if verify_result != 1:
3036 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003037
3038
Dominic Chenf05b2122015-10-13 16:32:35 +00003039def dump_crl(type, crl):
3040 """
3041 Dump a certificate revocation list to a buffer.
3042
3043 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
3044 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02003045 :param CRL crl: The CRL to dump.
3046
Dominic Chenf05b2122015-10-13 16:32:35 +00003047 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07003048 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00003049 """
3050 bio = _new_mem_buf()
3051
3052 if type == FILETYPE_PEM:
3053 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
3054 elif type == FILETYPE_ASN1:
3055 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
3056 elif type == FILETYPE_TEXT:
3057 ret = _lib.X509_CRL_print(bio, crl._crl)
3058 else:
3059 raise ValueError(
3060 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
Alex Gaynor03737182020-07-23 20:40:46 -04003061 "FILETYPE_TEXT"
3062 )
Dominic Chenf05b2122015-10-13 16:32:35 +00003063
Adrián Chaves98c57be2020-03-31 16:14:50 +02003064 _openssl_assert(ret == 1)
Dominic Chenf05b2122015-10-13 16:32:35 +00003065 return _bio_to_string(bio)
3066
3067
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003068def load_crl(type, buffer):
3069 """
Alex Chand072cae2018-02-15 09:57:59 +00003070 Load Certificate Revocation List (CRL) data from a string *buffer*.
3071 *buffer* encoded with the type *type*.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003072
3073 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
3074 :param buffer: The buffer the CRL is stored in
3075
3076 :return: The PKey object
3077 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003078 if isinstance(buffer, _text_type):
3079 buffer = buffer.encode("ascii")
3080
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003081 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003082
3083 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003084 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003085 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003086 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003087 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003088 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
3089
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003090 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003091 _raise_current_error()
3092
3093 result = CRL.__new__(CRL)
Jeremy Cline9e15eca2017-09-07 20:11:08 -04003094 result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08003095 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003096
3097
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003098def load_pkcs7_data(type, buffer):
3099 """
Alex Chand072cae2018-02-15 09:57:59 +00003100 Load pkcs7 data from the string *buffer* encoded with the type
3101 *type*.
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003102
3103 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
3104 :param buffer: The buffer with the pkcs7 data.
3105 :return: The PKCS7 object
3106 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003107 if isinstance(buffer, _text_type):
3108 buffer = buffer.encode("ascii")
3109
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003110 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003111
3112 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003113 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003114 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07003115 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003116 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003117 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
3118
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003119 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08003120 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003121
3122 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003123 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003124 return pypkcs7
3125
3126
Alex Gaynorbb971ae2020-08-05 01:14:16 -04003127load_pkcs7_data = utils.deprecated(
3128 load_pkcs7_data,
3129 __name__,
3130 (
3131 "PKCS#7 support in pyOpenSSL is deprecated. You should use the APIs "
3132 "in cryptography."
3133 ),
3134 DeprecationWarning,
3135)
3136
3137
Stephen Holsapple38482622014-04-05 20:29:34 -07003138def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003139 """
Alex Chand072cae2018-02-15 09:57:59 +00003140 Load pkcs12 data from the string *buffer*. If the pkcs12 structure is
3141 encrypted, a *passphrase* must be included. The MAC is always
3142 checked and thus required.
3143
3144 See also the man page for the C function :py:func:`PKCS12_parse`.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003145
3146 :param buffer: The buffer the certificate is stored in
3147 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
3148 :returns: The PKCS12 object
3149 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003150 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00003151
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003152 if isinstance(buffer, _text_type):
3153 buffer = buffer.encode("ascii")
3154
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003155 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003156
Stephen Holsapple38482622014-04-05 20:29:34 -07003157 # Use null passphrase if passphrase is None or empty string. With PKCS#12
3158 # password based encryption no password and a zero length password are two
3159 # different things, but OpenSSL implementation will try both to figure out
3160 # which one works.
3161 if not passphrase:
3162 passphrase = _ffi.NULL
3163
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003164 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
3165 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003166 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003167 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003168
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003169 pkey = _ffi.new("EVP_PKEY**")
3170 cert = _ffi.new("X509**")
3171 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003172
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003173 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003174 if not parse_result:
3175 _raise_current_error()
3176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003177 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08003178
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003179 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
3180 # queue for no particular reason. This error isn't interesting to anyone
3181 # outside this function. It's not even interesting to us. Get rid of it.
3182 try:
3183 _raise_current_error()
3184 except Error:
3185 pass
3186
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003187 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003188 pykey = None
3189 else:
3190 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003191 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003192
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003193 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003194 pycert = None
3195 friendlyname = None
3196 else:
Paul Kehrere7381862017-11-30 20:55:25 +08003197 pycert = X509._from_raw_x509_ptr(cert[0])
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003198
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003199 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04003200 friendlyname_buffer = _lib.X509_alias_get0(
3201 cert[0], friendlyname_length
3202 )
3203 friendlyname = _ffi.buffer(
3204 friendlyname_buffer, friendlyname_length[0]
3205 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003206 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003207 friendlyname = None
3208
3209 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003210 for i in range(_lib.sk_X509_num(cacerts)):
Paul Kehrere7381862017-11-30 20:55:25 +08003211 x509 = _lib.sk_X509_value(cacerts, i)
3212 pycacert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003213 pycacerts.append(pycacert)
3214 if not pycacerts:
3215 pycacerts = None
3216
3217 pkcs12 = PKCS12.__new__(PKCS12)
3218 pkcs12._pkey = pykey
3219 pkcs12._cert = pycert
3220 pkcs12._cacerts = pycacerts
3221 pkcs12._friendlyname = friendlyname
3222 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05003223
3224
Alex Gaynorbb971ae2020-08-05 01:14:16 -04003225load_pkcs12 = utils.deprecated(
3226 load_pkcs12,
3227 __name__,
3228 (
3229 "PKCS#12 support in pyOpenSSL is deprecated. You should use the APIs "
3230 "in cryptography."
3231 ),
3232 DeprecationWarning,
3233)
3234
3235
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05003236# There are no direct unit tests for this initialization. It is tested
3237# indirectly since it is necessary for functions like dump_privatekey when
3238# using encryption.
3239#
3240# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
3241# and some other similar tests may fail without this (though they may not if
3242# the Python runtime has already done some initialization of the underlying
3243# OpenSSL library (and is linked against the same one that cryptography is
3244# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05003245_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05003246
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05003247# This is similar but exercised mainly by exception_from_error_queue. It calls
3248# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
3249_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003250
3251
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003252# Set the default string mask to match OpenSSL upstream (since 2005) and
3253# RFC5280 recommendations.
Alex Gaynor03737182020-07-23 20:40:46 -04003254_lib.ASN1_STRING_set_default_mask_asc(b"utf8only")