blob: ea7b354b817aa04a45f8baa7e8b374f203598d6f [file] [log] [blame]
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001import datetime
Paul Kehrer8d887e12015-10-24 09:09:55 -05002
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003from base64 import b16encode
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import partial
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05005from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
6
7from six import (
8 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -04009 text_type as _text_type,
10 PY3 as _PY3)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080011
Alex Gaynor9939ba12017-06-25 16:28:24 -040012from cryptography import x509
Paul Kehrer72d968b2016-07-29 15:31:04 +080013from cryptography.hazmat.primitives.asymmetric import dsa, rsa
Alex Gaynor10d30832017-06-29 15:31:39 -070014from cryptography.utils import deprecated
Paul Kehrer72d968b2016-07-29 15:31:04 +080015
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050016from OpenSSL._util import (
17 ffi as _ffi,
18 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050019 exception_from_error_queue as _exception_from_error_queue,
20 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040021 native as _native,
22 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070024 make_assert as _make_assert,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040025)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080026
Nicolas Karolak736c6212017-11-26 14:40:28 +010027__all__ = [
28 'FILETYPE_PEM',
29 'FILETYPE_ASN1',
30 'FILETYPE_TEXT',
31 'TYPE_RSA',
32 'TYPE_DSA',
33 'Error',
34 'PKey',
35 'get_elliptic_curves',
36 'get_elliptic_curve',
37 'X509Name',
38 'X509Extension',
39 'X509Req',
40 'X509',
41 'X509StoreFlags',
42 'X509Store',
43 'X509StoreContextError',
44 'X509StoreContext',
45 'load_certificate',
46 'dump_certificate',
47 'dump_publickey',
48 'dump_privatekey',
49 'Revoked',
50 'CRL',
51 'PKCS7',
52 'PKCS12',
53 'NetscapeSPKI',
54 'load_publickey',
55 'load_privatekey',
56 'dump_certificate_request',
57 'load_certificate_request',
58 'sign',
59 'verify',
60 'dump_crl',
61 'load_crl',
62 'load_pkcs7_data',
63 'load_pkcs12'
64]
65
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050066FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
67FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080068
69# TODO This was an API mistake. OpenSSL has no such constant.
70FILETYPE_TEXT = 2 ** 16 - 1
71
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050072TYPE_RSA = _lib.EVP_PKEY_RSA
73TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080074
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080075
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050076class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050077 """
78 An error occurred in an `OpenSSL.crypto` API.
79 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050080
81
82_raise_current_error = partial(_exception_from_error_queue, Error)
Alex Gaynor67903a62016-06-02 10:37:13 -070083_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050084
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070085
Paul Kehrereb633842016-10-06 11:22:01 +020086def _get_backend():
87 """
88 Importing the backend from cryptography has the side effect of activating
89 the osrandom engine. This mutates the global state of OpenSSL in the
90 process and causes issues for various programs that use subinterpreters or
91 embed Python. By putting the import in this function we can avoid
92 triggering this side effect unless _get_backend is called.
93 """
94 from cryptography.hazmat.backends.openssl.backend import backend
95 return backend
96
97
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050098def _untested_error(where):
99 """
100 An OpenSSL API failed somehow. Additionally, the failure which was
101 encountered isn't one that's exercised by the test suite so future behavior
102 of pyOpenSSL is now somewhat less predictable.
103 """
104 raise RuntimeError("Unknown %s failure" % (where,))
105
106
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500107def _new_mem_buf(buffer=None):
108 """
109 Allocate a new OpenSSL memory BIO.
110
111 Arrange for the garbage collector to clean it up automatically.
112
113 :param buffer: None or some bytes to use to put into the BIO so that they
114 can be read out.
115 """
116 if buffer is None:
117 bio = _lib.BIO_new(_lib.BIO_s_mem())
118 free = _lib.BIO_free
119 else:
120 data = _ffi.new("char[]", buffer)
121 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -0400122
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500123 # Keep the memory alive as long as the bio is alive!
124 def free(bio, ref=data):
125 return _lib.BIO_free(bio)
126
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700127 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500128
129 bio = _ffi.gc(bio, free)
130 return bio
131
132
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800133def _bio_to_string(bio):
134 """
135 Copy the contents of an OpenSSL BIO object into a Python byte string.
136 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500137 result_buffer = _ffi.new('char**')
138 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
139 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800140
141
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800142def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500143 """
144 The the time value of an ASN1 time object.
145
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900146 @param boundary: An ASN1_TIME pointer (or an object safely
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500147 castable to that type) which will have its value set.
148 @param when: A string representation of the desired time value.
149
150 @raise TypeError: If C{when} is not a L{bytes} string.
151 @raise ValueError: If C{when} does not represent a time in the required
152 format.
153 @raise RuntimeError: If the time value cannot be set for some other
154 (unspecified) reason.
155 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800156 if not isinstance(when, bytes):
157 raise TypeError("when must be a byte string")
158
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900159 set_result = _lib.ASN1_TIME_set_string(boundary, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800160 if set_result == 0:
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900161 raise ValueError("Invalid string")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800162
Alex Gaynor510293e2016-06-02 12:07:59 -0700163
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800164def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500165 """
166 Retrieve the time value of an ASN1 time object.
167
168 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
169 that type) from which the time value will be retrieved.
170
171 @return: The time value from C{timestamp} as a L{bytes} string in a certain
172 format. Or C{None} if the object contains no time value.
173 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500174 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
175 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800176 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400177 elif (
178 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
179 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800181 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500182 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
183 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
184 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500185 # This may happen:
186 # - if timestamp was not an ASN1_TIME
187 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
188 # - if a copy of the time data from timestamp cannot be made for
189 # the newly allocated ASN1_GENERALIZEDTIME
190 #
191 # These are difficult to test. cffi enforces the ASN1_TIME type.
192 # Memory allocation failures are a pain to trigger
193 # deterministically.
194 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800195 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500196 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800197 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500198 string_data = _lib.ASN1_STRING_data(string_timestamp)
199 string_result = _ffi.string(string_data)
200 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800201 return string_result
202
203
Alex Gaynor4aa52c32017-11-20 09:04:08 -0500204class _X509NameInvalidator(object):
205 def __init__(self):
206 self._names = []
207
208 def add(self, name):
209 self._names.append(name)
210
211 def clear(self):
212 for name in self._names:
213 # Breaks the object, but also prevents UAF!
214 del name._name
215
216
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800217class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200218 """
219 A class representing an DSA or RSA public key or key pair.
220 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800221 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800222 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800223
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800224 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500225 pkey = _lib.EVP_PKEY_new()
226 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800227 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800228
Paul Kehrer72d968b2016-07-29 15:31:04 +0800229 def to_cryptography_key(self):
230 """
231 Export as a ``cryptography`` key.
232
233 :rtype: One of ``cryptography``'s `key interfaces`_.
234
235 .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
236 primitives/asymmetric/rsa/#key-interfaces
237
238 .. versionadded:: 16.1.0
239 """
Paul Kehrereb633842016-10-06 11:22:01 +0200240 backend = _get_backend()
Paul Kehrer72d968b2016-07-29 15:31:04 +0800241 if self._only_public:
242 return backend._evp_pkey_to_public_key(self._pkey)
243 else:
244 return backend._evp_pkey_to_private_key(self._pkey)
245
246 @classmethod
247 def from_cryptography_key(cls, crypto_key):
248 """
249 Construct based on a ``cryptography`` *crypto_key*.
250
251 :param crypto_key: A ``cryptography`` key.
252 :type crypto_key: One of ``cryptography``'s `key interfaces`_.
253
254 :rtype: PKey
255
256 .. versionadded:: 16.1.0
257 """
258 pkey = cls()
259 if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
260 dsa.DSAPublicKey, dsa.DSAPrivateKey)):
261 raise TypeError("Unsupported key type")
262
263 pkey._pkey = crypto_key._evp_pkey
264 if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
265 pkey._only_public = True
266 pkey._initialized = True
267 return pkey
268
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800269 def generate_key(self, type, bits):
270 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700271 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800272
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200273 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800274
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200275 :param type: The key type.
276 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
277 :param bits: The number of bits.
278 :type bits: :py:data:`int` ``>= 0``
279 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
280 of the appropriate type.
281 :raises ValueError: If the number of bits isn't an integer of
282 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700283 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800284 """
285 if not isinstance(type, int):
286 raise TypeError("type must be an integer")
287
288 if not isinstance(bits, int):
289 raise TypeError("bits must be an integer")
290
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800291 if type == TYPE_RSA:
292 if bits <= 0:
293 raise ValueError("Invalid number of bits")
294
David Benjamin179eb1d2018-06-05 17:56:07 -0400295 # TODO Check error return
296 exponent = _lib.BN_new()
297 exponent = _ffi.gc(exponent, _lib.BN_free)
298 _lib.BN_set_word(exponent, _lib.RSA_F4)
299
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500300 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800301
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500302 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400303 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800304
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500305 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400306 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800307
308 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400309 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700310 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400311
312 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400313 res = _lib.DSA_generate_parameters_ex(
314 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
315 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700316 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400317
318 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
319 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800320 else:
321 raise Error("No such key type")
322
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800323 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800324
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800325 def check(self):
326 """
327 Check the consistency of an RSA private key.
328
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200329 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
330
Hynek Schlawack01c31672016-12-11 15:14:09 +0100331 :return: ``True`` if key is consistent.
332
333 :raise OpenSSL.crypto.Error: if the key is inconsistent.
334
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800335 :raise TypeError: if the key is of a type which cannot be checked.
336 Only RSA keys can currently be checked.
337 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800338 if self._only_public:
339 raise TypeError("public key only")
340
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100341 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800342 raise TypeError("key type unsupported")
343
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500344 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
345 rsa = _ffi.gc(rsa, _lib.RSA_free)
346 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800347 if result:
348 return True
349 _raise_current_error()
350
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800351 def type(self):
352 """
353 Returns the type of the key
354
355 :return: The type of the key.
356 """
Alex Gaynor0d2aec52017-05-31 04:26:27 -0400357 return _lib.EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800358
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800359 def bits(self):
360 """
361 Returns the number of bits of the key
362
363 :return: The number of bits of the key.
364 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500365 return _lib.EVP_PKEY_bits(self._pkey)
Alex Chanc6077062016-11-18 13:53:39 +0000366
367
Alex Gaynor10d30832017-06-29 15:31:39 -0700368PKeyType = deprecated(
369 PKey, __name__,
370 "PKeyType has been deprecated, use PKey instead",
371 DeprecationWarning
372)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800373
374
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400375class _EllipticCurve(object):
376 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400377 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400378
379 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
380 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
381 instances each of which represents one curve supported by the system.
382 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400383 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400384 _curves = None
385
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400386 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400387 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400388 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400389 """
390 Implement cooperation with the right-hand side argument of ``!=``.
391
392 Python 3 seems to have dropped this cooperation in this very narrow
393 circumstance.
394 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400395 if isinstance(other, _EllipticCurve):
396 return super(_EllipticCurve, self).__ne__(other)
397 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400398
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400399 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400400 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400401 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400402 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400403
404 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400405
406 :return: A :py:type:`set` of ``cls`` instances giving the names of the
407 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400408 """
Alex Chan84902a22017-04-20 11:50:47 +0100409 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
410 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
411 # The return value on this call should be num_curves again. We
412 # could check it to make sure but if it *isn't* then.. what could
413 # we do? Abort the whole process, I suppose...? -exarkun
414 lib.EC_get_builtin_curves(builtin_curves, num_curves)
415 return set(
416 cls.from_nid(lib, c.nid)
417 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400418
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400419 @classmethod
420 def _get_elliptic_curves(cls, lib):
421 """
422 Get, cache, and return the curves supported by OpenSSL.
423
424 :param lib: The OpenSSL library binding object.
425
426 :return: A :py:type:`set` of ``cls`` instances giving the names of the
427 elliptic curves the underlying library supports.
428 """
429 if cls._curves is None:
430 cls._curves = cls._load_elliptic_curves(lib)
431 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400432
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400433 @classmethod
434 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400435 """
436 Instantiate a new :py:class:`_EllipticCurve` associated with the given
437 OpenSSL NID.
438
439 :param lib: The OpenSSL library binding object.
440
441 :param nid: The OpenSSL NID the resulting curve object will represent.
442 This must be a curve NID (and not, for example, a hash NID) or
443 subsequent operations will fail in unpredictable ways.
444 :type nid: :py:class:`int`
445
446 :return: The curve object.
447 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400448 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
449
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400450 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400451 """
452 :param _lib: The :py:mod:`cryptography` binding instance used to
453 interface with OpenSSL.
454
455 :param _nid: The OpenSSL NID identifying the curve this object
456 represents.
457 :type _nid: :py:class:`int`
458
459 :param name: The OpenSSL short name identifying the curve this object
460 represents.
461 :type name: :py:class:`unicode`
462 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400463 self._lib = lib
464 self._nid = nid
465 self.name = name
466
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400467 def __repr__(self):
468 return "<Curve %r>" % (self.name,)
469
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400470 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400471 """
472 Create a new OpenSSL EC_KEY structure initialized to use this curve.
473
474 The structure is automatically garbage collected when the Python object
475 is garbage collected.
476 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400477 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
478 return _ffi.gc(key, _lib.EC_KEY_free)
479
480
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400481def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400482 """
483 Return a set of objects representing the elliptic curves supported in the
484 OpenSSL build in use.
485
486 The curve objects have a :py:class:`unicode` ``name`` attribute by which
487 they identify themselves.
488
489 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400490 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
491 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400492 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400493 return _EllipticCurve._get_elliptic_curves(_lib)
494
495
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400496def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400497 """
498 Return a single curve object selected by name.
499
500 See :py:func:`get_elliptic_curves` for information about curve objects.
501
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400502 :param name: The OpenSSL short name identifying the curve object to
503 retrieve.
504 :type name: :py:class:`unicode`
505
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400506 If the named curve is not supported then :py:class:`ValueError` is raised.
507 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400508 for curve in get_elliptic_curves():
509 if curve.name == name:
510 return curve
511 raise ValueError("unknown curve name", name)
512
513
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800514class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200515 """
516 An X.509 Distinguished Name.
517
518 :ivar countryName: The country of the entity.
519 :ivar C: Alias for :py:attr:`countryName`.
520
521 :ivar stateOrProvinceName: The state or province of the entity.
522 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
523
524 :ivar localityName: The locality of the entity.
525 :ivar L: Alias for :py:attr:`localityName`.
526
527 :ivar organizationName: The organization name of the entity.
528 :ivar O: Alias for :py:attr:`organizationName`.
529
530 :ivar organizationalUnitName: The organizational unit of the entity.
531 :ivar OU: Alias for :py:attr:`organizationalUnitName`
532
533 :ivar commonName: The common name of the entity.
534 :ivar CN: Alias for :py:attr:`commonName`.
535
536 :ivar emailAddress: The e-mail address of the entity.
537 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400538
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800539 def __init__(self, name):
540 """
541 Create a new X509Name, copying the given X509Name instance.
542
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200543 :param name: The name to copy.
544 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800545 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500546 name = _lib.X509_NAME_dup(name._name)
547 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800548
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800549 def __setattr__(self, name, value):
550 if name.startswith('_'):
551 return super(X509Name, self).__setattr__(name, value)
552
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800553 # Note: we really do not want str subclasses here, so we do not use
554 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800555 if type(name) is not str:
556 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400557 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800558
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500559 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500560 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800561 try:
562 _raise_current_error()
563 except Error:
564 pass
565 raise AttributeError("No such attribute")
566
567 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500568 for i in range(_lib.X509_NAME_entry_count(self._name)):
569 ent = _lib.X509_NAME_get_entry(self._name, i)
570 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
571 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800572 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500573 ent = _lib.X509_NAME_delete_entry(self._name, i)
574 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800575 break
576
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500577 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800578 value = value.encode('utf-8')
579
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500580 add_result = _lib.X509_NAME_add_entry_by_NID(
581 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800582 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500583 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800584
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800585 def __getattr__(self, name):
586 """
587 Find attribute. An X509Name object has the following attributes:
588 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400589 organization (alias O), organizationalUnit (alias OU), commonName
590 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500592 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500593 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800594 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
595 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
596 # push something onto the error queue. If we don't clean that up
597 # now, someone else will bump into it later and be quite confused.
598 # See lp#314814.
599 try:
600 _raise_current_error()
601 except Error:
602 pass
603 return super(X509Name, self).__getattr__(name)
604
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500605 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800606 if entry_index == -1:
607 return None
608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500609 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
610 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800611
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500612 result_buffer = _ffi.new("unsigned char**")
613 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400614 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800615
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700616 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400617 result = _ffi.buffer(
618 result_buffer[0], data_length
619 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700620 finally:
621 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500622 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800623 return result
624
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500625 def _cmp(op):
626 def f(self, other):
627 if not isinstance(other, X509Name):
628 return NotImplemented
629 result = _lib.X509_NAME_cmp(self._name, other._name)
630 return op(result, 0)
631 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800632
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500633 __eq__ = _cmp(__eq__)
634 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800635
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500636 __lt__ = _cmp(__lt__)
637 __le__ = _cmp(__le__)
638
639 __gt__ = _cmp(__gt__)
640 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800641
642 def __repr__(self):
643 """
644 String representation of an X509Name
645 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400646 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500647 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800648 self._name, result_buffer, len(result_buffer))
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700649 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800650
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500651 return "<X509Name object '%s'>" % (
652 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800653
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800654 def hash(self):
655 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200656 Return an integer representation of the first four bytes of the
657 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800658
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200659 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
660
661 :return: The (integer) hash of this name.
662 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800663 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500664 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800665
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800666 def der(self):
667 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200668 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800669
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200670 :return: The DER encoded form of this name.
671 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800672 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500673 result_buffer = _ffi.new('unsigned char**')
674 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400675 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800676
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500677 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
678 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800679 return string_result
680
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800681 def get_components(self):
682 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200683 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800684
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200685 :return: The components of this name.
686 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800687 """
688 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 for i in range(_lib.X509_NAME_entry_count(self._name)):
690 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800691
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500692 fname = _lib.X509_NAME_ENTRY_get_object(ent)
693 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800694
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500695 nid = _lib.OBJ_obj2nid(fname)
696 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800697
698 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400699 _ffi.string(name),
700 _ffi.string(
701 _lib.ASN1_STRING_data(fval),
702 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800703
704 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200705
706
Alex Gaynor10d30832017-06-29 15:31:39 -0700707X509NameType = deprecated(
708 X509Name, __name__,
709 "X509NameType has been deprecated, use X509Name instead",
710 DeprecationWarning
711)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800712
713
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800714class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200715 """
716 An X.509 v3 certificate extension.
717 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400718
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800719 def __init__(self, type_name, critical, value, subject=None, issuer=None):
720 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200721 Initializes an X509 extension.
722
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100723 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400724 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800725
Alex Gaynor5945ea82015-09-05 14:59:06 -0400726 :param bool critical: A flag indicating whether this is a critical
727 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800728
729 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200730 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800731
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200732 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800733 :type subject: :py:class:`X509`
734
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200735 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800736 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100737
Alex Chan54005ce2017-03-21 08:08:17 +0000738 .. _extension: https://www.openssl.org/docs/manmaster/man5/
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100739 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800740 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500741 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800742
Alex Gaynor5945ea82015-09-05 14:59:06 -0400743 # A context is necessary for any extension which uses the r2i
744 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
745 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800747
748 # We have no configuration database - but perhaps we should (some
749 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500750 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800751
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800752 # Initialize the subject and issuer, if appropriate. ctx is a local,
753 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400754 # any references, so no need to mess with reference counts or
755 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800756 if issuer is not None:
757 if not isinstance(issuer, X509):
758 raise TypeError("issuer must be an X509 instance")
759 ctx.issuer_cert = issuer._x509
760 if subject is not None:
761 if not isinstance(subject, X509):
762 raise TypeError("subject must be an X509 instance")
763 ctx.subject_cert = subject._x509
764
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800765 if critical:
766 # There are other OpenSSL APIs which would let us pass in critical
767 # separately, but they're harder to use, and since value is already
768 # a pile of crappy junk smuggling a ton of utterly important
769 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400770 # with strings? (However, X509V3_EXT_i2d in particular seems like
771 # it would be a better API to invoke. I do not know where to get
772 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500773 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800774
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500775 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
776 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800777 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500778 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800779
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400780 @property
781 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400782 return _lib.OBJ_obj2nid(
783 _lib.X509_EXTENSION_get_object(self._extension)
784 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400785
786 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500787 _lib.GEN_EMAIL: "email",
788 _lib.GEN_DNS: "DNS",
789 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400790 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400791
792 def _subjectAltNameString(self):
Alex Gaynord61c46a2017-06-29 22:51:33 -0700793 names = _ffi.cast(
794 "GENERAL_NAMES*", _lib.X509V3_EXT_d2i(self._extension)
795 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400796
Paul Kehrerb7d79502015-05-04 07:43:51 -0500797 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400798 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500799 for i in range(_lib.sk_GENERAL_NAME_num(names)):
800 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400801 try:
802 label = self._prefixes[name.type]
803 except KeyError:
804 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500805 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500806 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400807 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500808 value = _native(
809 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
810 parts.append(label + ":" + value)
811 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400812
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800813 def __str__(self):
814 """
815 :return: a nice text representation of the extension
816 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500817 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400818 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800819
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400820 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500821 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400822 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800823
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500824 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800825
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800826 def get_critical(self):
827 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200828 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800829
830 :return: The critical field.
831 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500832 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800833
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800834 def get_short_name(self):
835 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200836 Returns the short type name of this X.509 extension.
837
838 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800839
840 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200841 :rtype: :py:data:`bytes`
842
843 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800844 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500845 obj = _lib.X509_EXTENSION_get_object(self._extension)
846 nid = _lib.OBJ_obj2nid(obj)
847 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800848
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800849 def get_data(self):
850 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200851 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800852
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200853 :return: The ASN.1 encoded data of this X509 extension.
854 :rtype: :py:data:`bytes`
855
856 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800857 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500858 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
859 string_result = _ffi.cast('ASN1_STRING*', octet_result)
860 char_result = _lib.ASN1_STRING_data(string_result)
861 result_length = _lib.ASN1_STRING_length(string_result)
862 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800863
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200864
Alex Gaynor10d30832017-06-29 15:31:39 -0700865X509ExtensionType = deprecated(
866 X509Extension, __name__,
867 "X509ExtensionType has been deprecated, use X509Extension instead",
868 DeprecationWarning
869)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800870
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800871
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 (
892 _CertificateSigningRequest
893 )
894 backend = _get_backend()
895 return _CertificateSigningRequest(backend, self._req)
896
897 @classmethod
898 def from_cryptography(cls, crypto_req):
899 """
900 Construct based on a ``cryptography`` *crypto_req*.
901
902 :param crypto_req: A ``cryptography`` X.509 certificate signing request
903 :type crypto_req: ``cryptography.x509.CertificateSigningRequest``
904
905 :rtype: PKey
906
907 .. versionadded:: 17.1.0
908 """
909 if not isinstance(crypto_req, x509.CertificateSigningRequest):
910 raise TypeError("Must be a certificate signing request")
911
912 req = cls()
913 req._req = crypto_req._x509_req
914 return req
915
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800916 def set_pubkey(self, pkey):
917 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200918 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800919
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200920 :param pkey: The public key to use.
921 :type pkey: :py:class:`PKey`
922
Dan Sully44e767a2016-06-04 18:05:27 -0700923 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800924 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500925 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400926 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800927
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800928 def get_pubkey(self):
929 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200930 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800931
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200932 :return: The public key.
933 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800934 """
935 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500936 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700937 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500938 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800939 pkey._only_public = True
940 return pkey
941
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800942 def set_version(self, version):
943 """
944 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
945 request.
946
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200947 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700948 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800949 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500950 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400951 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800952
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800953 def get_version(self):
954 """
955 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
956 request.
957
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200958 :return: The value of the version subfield.
959 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800960 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800962
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800963 def get_subject(self):
964 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200965 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800966
Cory Benfield881dc8d2015-12-09 08:25:14 +0000967 This creates a new :class:`X509Name` that wraps the underlying subject
968 name field on the certificate signing request. Modifying it will modify
969 the underlying signing request, and will have the effect of modifying
970 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200971
972 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000973 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800974 """
975 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500976 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700977 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800978
979 # The name is owned by the X509Req structure. As long as the X509Name
980 # Python object is alive, keep the X509Req Python object alive.
981 name._owner = self
982
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800983 return name
984
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800985 def add_extensions(self, extensions):
986 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200987 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800988
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200989 :param extensions: The X.509 extensions to add.
990 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700991 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800992 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500993 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700994 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800995
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500996 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800997
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800998 for ext in extensions:
999 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -08001000 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001001
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001002 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001004
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001005 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001006 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001007
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001008 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001009 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001010 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001011
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001012 :return: The X.509 extensions in this request.
1013 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
1014
1015 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001016 """
1017 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -05001018 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -05001019 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001020 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -05001021 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -08001022 exts.append(ext)
1023 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -08001024
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001025 def sign(self, pkey, digest):
1026 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001027 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001028
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001029 :param pkey: The key pair to sign with.
1030 :type pkey: :py:class:`PKey`
1031 :param digest: The name of the message digest to use for the signature,
Alex Gaynor239e2d32016-09-11 12:36:35 -04001032 e.g. :py:data:`b"sha256"`.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001033 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -07001034 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001035 """
1036 if pkey._only_public:
1037 raise ValueError("Key has only public part")
1038
1039 if not pkey._initialized:
1040 raise ValueError("Key is uninitialized")
1041
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001042 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001043 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001044 raise ValueError("No such digest method")
1045
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001046 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001047 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -08001048
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001049 def verify(self, pkey):
1050 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +02001051 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001052
Hynek Schlawack01c31672016-12-11 15:14:09 +01001053 :param PKey key: A public key.
1054
1055 :return: ``True`` if the signature is correct.
1056 :rtype: bool
1057
1058 :raises OpenSSL.crypto.Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001059 problem verifying the signature.
1060 """
1061 if not isinstance(pkey, PKey):
1062 raise TypeError("pkey must be a PKey instance")
1063
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001064 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001065 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001066 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -08001067
1068 return result
1069
1070
Alex Gaynor10d30832017-06-29 15:31:39 -07001071X509ReqType = deprecated(
1072 X509Req, __name__,
1073 "X509ReqType has been deprecated, use X509Req instead",
1074 DeprecationWarning
1075)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001076
1077
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001078class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001079 """
1080 An X.509 certificate.
1081 """
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001082 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001083 x509 = _lib.X509_new()
Hynek Schlawack8a2dd772016-07-31 13:46:20 +02001084 _openssl_assert(x509 != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001086
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001087 self._issuer_invalidator = _X509NameInvalidator()
1088 self._subject_invalidator = _X509NameInvalidator()
1089
1090 @classmethod
1091 def _from_raw_x509_ptr(cls, x509):
1092 cert = cls.__new__(cls)
1093 cert._x509 = _ffi.gc(x509, _lib.X509_free)
1094 cert._issuer_invalidator = _X509NameInvalidator()
1095 cert._subject_invalidator = _X509NameInvalidator()
1096 return cert
1097
Alex Gaynor9939ba12017-06-25 16:28:24 -04001098 def to_cryptography(self):
1099 """
1100 Export as a ``cryptography`` certificate.
1101
1102 :rtype: ``cryptography.x509.Certificate``
1103
1104 .. versionadded:: 17.1.0
1105 """
1106 from cryptography.hazmat.backends.openssl.x509 import _Certificate
1107 backend = _get_backend()
1108 return _Certificate(backend, self._x509)
1109
1110 @classmethod
1111 def from_cryptography(cls, crypto_cert):
1112 """
1113 Construct based on a ``cryptography`` *crypto_cert*.
1114
1115 :param crypto_key: A ``cryptography`` X.509 certificate.
1116 :type crypto_key: ``cryptography.x509.Certificate``
1117
1118 :rtype: PKey
1119
1120 .. versionadded:: 17.1.0
1121 """
1122 if not isinstance(crypto_cert, x509.Certificate):
1123 raise TypeError("Must be a certificate")
1124
1125 cert = cls()
1126 cert._x509 = crypto_cert._x509
1127 return cert
1128
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001129 def set_version(self, version):
1130 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001131 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001132
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001133 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001134 :type version: :py:class:`int`
1135
Dan Sully44e767a2016-06-04 18:05:27 -07001136 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001137 """
1138 if not isinstance(version, int):
1139 raise TypeError("version must be an integer")
1140
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001142
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001143 def get_version(self):
1144 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001145 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001146
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001147 :return: The version number of the certificate.
1148 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001149 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001150 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001151
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001152 def get_pubkey(self):
1153 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001154 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001155
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001156 :return: The public key.
1157 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001158 """
1159 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1161 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001162 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001164 pkey._only_public = True
1165 return pkey
1166
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001167 def set_pubkey(self, pkey):
1168 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001169 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001170
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001171 :param pkey: The public key.
1172 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001173
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001174 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001175 """
1176 if not isinstance(pkey, PKey):
1177 raise TypeError("pkey must be a PKey instance")
1178
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001180 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001181
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001182 def sign(self, pkey, digest):
1183 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001184 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001185
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001186 :param pkey: The key to sign with.
1187 :type pkey: :py:class:`PKey`
1188
1189 :param digest: The name of the message digest to use.
1190 :type digest: :py:class:`bytes`
1191
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001192 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001193 """
1194 if not isinstance(pkey, PKey):
1195 raise TypeError("pkey must be a PKey instance")
1196
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001197 if pkey._only_public:
1198 raise ValueError("Key only has public part")
1199
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001200 if not pkey._initialized:
1201 raise ValueError("Key is uninitialized")
1202
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001203 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001205 raise ValueError("No such digest method")
1206
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001207 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001208 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001209
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001210 def get_signature_algorithm(self):
1211 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001212 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001213
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001214 :return: The name of the algorithm.
1215 :rtype: :py:class:`bytes`
1216
1217 :raises ValueError: If the signature algorithm is undefined.
1218
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001219 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001220 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001221 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1222 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001223 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001224 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001225 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001226
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001227 def digest(self, digest_name):
1228 """
1229 Return the digest of the X509 object.
1230
1231 :param digest_name: The name of the digest algorithm to use.
1232 :type digest_name: :py:class:`bytes`
1233
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001234 :return: The digest of the object, formatted as
1235 :py:const:`b":"`-delimited hex pairs.
1236 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001237 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001238 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001239 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001240 raise ValueError("No such digest method")
1241
Paul Kehrer9f9113a2016-09-20 20:10:25 -05001242 result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001243 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001244 result_length[0] = len(result_buffer)
1245
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001246 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001247 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001248 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001249
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001250 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001251 b16encode(ch).upper() for ch
1252 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001253
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001254 def subject_name_hash(self):
1255 """
1256 Return the hash of the X509 subject.
1257
1258 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001259 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001260 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001261 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001262
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001263 def set_serial_number(self, serial):
1264 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001265 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001266
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001267 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001268 :type serial: :py:class:`int`
1269
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001270 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001271 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001272 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001273 raise TypeError("serial must be an integer")
1274
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001275 hex_serial = hex(serial)[2:]
1276 if not isinstance(hex_serial, bytes):
1277 hex_serial = hex_serial.encode('ascii')
1278
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001279 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001280
1281 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001282 # it. If bignum is still NULL after this call, then the return value
1283 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001285
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001286 if bignum_serial[0] == _ffi.NULL:
1287 set_result = _lib.ASN1_INTEGER_set(
1288 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001289 if set_result:
1290 # TODO Not tested
1291 _raise_current_error()
1292 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001293 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1294 _lib.BN_free(bignum_serial[0])
1295 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001296 # TODO Not tested
1297 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001298 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1299 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001300 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001301
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001302 def get_serial_number(self):
1303 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001304 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001305
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001306 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001307 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001308 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001309 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1310 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001311 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001312 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001313 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001314 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001315 serial = int(hexstring_serial, 16)
1316 return serial
1317 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001319 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001320 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001321
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001322 def gmtime_adj_notAfter(self, amount):
1323 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001324 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001325
Dan Sully44e767a2016-06-04 18:05:27 -07001326 :param int amount: The number of seconds by which to adjust the
1327 timestamp.
1328 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001329 """
1330 if not isinstance(amount, int):
1331 raise TypeError("amount must be an integer")
1332
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001333 notAfter = _lib.X509_get_notAfter(self._x509)
1334 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001335
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001336 def gmtime_adj_notBefore(self, amount):
1337 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001338 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001339
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001340 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001341 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001342 """
1343 if not isinstance(amount, int):
1344 raise TypeError("amount must be an integer")
1345
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001346 notBefore = _lib.X509_get_notBefore(self._x509)
1347 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001348
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001349 def has_expired(self):
1350 """
1351 Check whether the certificate has expired.
1352
Dan Sully44e767a2016-06-04 18:05:27 -07001353 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1354 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001355 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001356 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001357 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001358
Paul Kehrerfde45c92016-01-21 12:57:37 -06001359 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001360
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001361 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001362 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001363
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001364 def get_notBefore(self):
1365 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001366 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001367
Paul Kehrerce98ee62017-06-21 06:59:58 -10001368 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001369
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001370 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001371
Dan Sully44e767a2016-06-04 18:05:27 -07001372 :return: A timestamp string, or ``None`` if there is none.
1373 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001374 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001375 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001376
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001377 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001378 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001379
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001380 def set_notBefore(self, when):
1381 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001382 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001383
Paul Kehrerce98ee62017-06-21 06:59:58 -10001384 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001385
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001386 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001387
Dan Sully44e767a2016-06-04 18:05:27 -07001388 :param bytes when: A timestamp string.
1389 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001390 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001391 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001392
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001393 def get_notAfter(self):
1394 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001395 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001396
Paul Kehrerce98ee62017-06-21 06:59:58 -10001397 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001398
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001399 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001400
Dan Sully44e767a2016-06-04 18:05:27 -07001401 :return: A timestamp string, or ``None`` if there is none.
1402 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001403 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001404 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001405
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001406 def set_notAfter(self, when):
1407 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001408 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001409
Paul Kehrerce98ee62017-06-21 06:59:58 -10001410 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001411
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001412 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001413
Dan Sully44e767a2016-06-04 18:05:27 -07001414 :param bytes when: A timestamp string.
1415 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001416 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001417 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001418
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001419 def _get_name(self, which):
1420 name = X509Name.__new__(X509Name)
1421 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001422 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001423
1424 # The name is owned by the X509 structure. As long as the X509Name
1425 # Python object is alive, keep the X509 Python object alive.
1426 name._owner = self
1427
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001428 return name
1429
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001430 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001431 if not isinstance(name, X509Name):
1432 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001433 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001434 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001435
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001436 def get_issuer(self):
1437 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001438 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001439
Cory Benfielde6bcce82015-12-09 08:40:03 +00001440 This creates a new :class:`X509Name` that wraps the underlying issuer
1441 name field on the certificate. Modifying it will modify the underlying
1442 certificate, and will have the effect of modifying any other
1443 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001444
1445 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001446 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001447 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001448 name = self._get_name(_lib.X509_get_issuer_name)
1449 self._issuer_invalidator.add(name)
1450 return name
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001451
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001452 def set_issuer(self, issuer):
1453 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001454 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001455
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001456 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001457 :type issuer: :py:class:`X509Name`
1458
Dan Sully44e767a2016-06-04 18:05:27 -07001459 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001460 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001461 self._set_name(_lib.X509_set_issuer_name, issuer)
1462 self._issuer_invalidator.clear()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001463
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001464 def get_subject(self):
1465 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001466 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001467
Cory Benfielde6bcce82015-12-09 08:40:03 +00001468 This creates a new :class:`X509Name` that wraps the underlying subject
1469 name field on the certificate. Modifying it will modify the underlying
1470 certificate, and will have the effect of modifying any other
1471 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001472
1473 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001474 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001475 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001476 name = self._get_name(_lib.X509_get_subject_name)
1477 self._subject_invalidator.add(name)
1478 return name
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001479
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001480 def set_subject(self, subject):
1481 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001482 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001483
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001484 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001485 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001486
Dan Sully44e767a2016-06-04 18:05:27 -07001487 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001488 """
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001489 self._set_name(_lib.X509_set_subject_name, subject)
1490 self._subject_invalidator.clear()
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001491
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001492 def get_extension_count(self):
1493 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001494 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001495
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001496 :return: The number of extensions.
1497 :rtype: :py:class:`int`
1498
1499 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001500 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001501 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001502
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001503 def add_extensions(self, extensions):
1504 """
1505 Add extensions to the certificate.
1506
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001507 :param extensions: The extensions to add.
1508 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001509 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001510 """
1511 for ext in extensions:
1512 if not isinstance(ext, X509Extension):
1513 raise ValueError("One of the elements is not an X509Extension")
1514
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001515 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001516 if not add_result:
1517 _raise_current_error()
1518
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001519 def get_extension(self, index):
1520 """
1521 Get a specific extension of the certificate by index.
1522
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001523 Extensions on a certificate are kept in order. The index
1524 parameter selects which extension will be returned.
1525
1526 :param int index: The index of the extension to retrieve.
1527 :return: The extension at the specified index.
1528 :rtype: :py:class:`X509Extension`
1529 :raises IndexError: If the extension index was out of bounds.
1530
1531 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001532 """
1533 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001534 ext._extension = _lib.X509_get_ext(self._x509, index)
1535 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001536 raise IndexError("extension index out of bounds")
1537
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001538 extension = _lib.X509_EXTENSION_dup(ext._extension)
1539 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001540 return ext
1541
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001542
Alex Gaynor10d30832017-06-29 15:31:39 -07001543X509Type = deprecated(
1544 X509, __name__,
1545 "X509Type has been deprecated, use X509 instead",
1546 DeprecationWarning
1547)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001548
1549
Dan Sully44e767a2016-06-04 18:05:27 -07001550class X509StoreFlags(object):
1551 """
1552 Flags for X509 verification, used to change the behavior of
1553 :class:`X509Store`.
1554
1555 See `OpenSSL Verification Flags`_ for details.
1556
1557 .. _OpenSSL Verification Flags:
Alex Chan54005ce2017-03-21 08:08:17 +00001558 https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html
Dan Sully44e767a2016-06-04 18:05:27 -07001559 """
1560 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1561 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1562 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1563 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1564 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1565 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1566 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1567 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1568 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1569 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1570 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1571
1572
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001573class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001574 """
Dan Sully44e767a2016-06-04 18:05:27 -07001575 An X.509 store.
1576
1577 An X.509 store is used to describe a context in which to verify a
1578 certificate. A description of a context may include a set of certificates
1579 to trust, a set of certificate revocation lists, verification flags and
1580 more.
1581
1582 An X.509 store, being only a description, cannot be used by itself to
1583 verify a certificate. To carry out the actual verification process, see
1584 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001585 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001586
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001587 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001588 store = _lib.X509_STORE_new()
1589 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001590
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001591 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001592 """
Dan Sully44e767a2016-06-04 18:05:27 -07001593 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001594
Dan Sully44e767a2016-06-04 18:05:27 -07001595 Adding a certificate with this method adds this certificate as a
1596 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001597
1598 :param X509 cert: The certificate to add to this store.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001599
Dan Sully44e767a2016-06-04 18:05:27 -07001600 :raises TypeError: If the certificate is not an :class:`X509`.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001601
1602 :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your
1603 certificate.
1604
Dan Sully44e767a2016-06-04 18:05:27 -07001605 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001606 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001607 if not isinstance(cert, X509):
1608 raise TypeError()
1609
Paul Kehrer0e6c5532018-08-23 10:52:15 -05001610 # As of OpenSSL 1.1.0i adding the same cert to the store more than
1611 # once doesn't cause an error. Accordingly, this code now silences
1612 # the error for OpenSSL < 1.1.0i as well.
1613 if _lib.X509_STORE_add_cert(self._store, cert._x509) == 0:
1614 code = _lib.ERR_peek_error()
1615 err_reason = _lib.ERR_GET_REASON(code)
1616 _openssl_assert(
1617 err_reason == _lib.X509_R_CERT_ALREADY_IN_HASH_TABLE
1618 )
1619 _lib.ERR_clear_error()
Dan Sully44e767a2016-06-04 18:05:27 -07001620
1621 def add_crl(self, crl):
1622 """
1623 Add a certificate revocation list to this store.
1624
1625 The certificate revocation lists added to a store will only be used if
1626 the associated flags are configured to check certificate revocation
1627 lists.
1628
1629 .. versionadded:: 16.1.0
1630
1631 :param CRL crl: The certificate revocation list to add to this store.
1632 :return: ``None`` if the certificate revocation list was added
1633 successfully.
1634 """
1635 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1636
1637 def set_flags(self, flags):
1638 """
1639 Set verification flags to this store.
1640
1641 Verification flags can be combined by oring them together.
1642
1643 .. note::
1644
1645 Setting a verification flag sometimes requires clients to add
1646 additional information to the store, otherwise a suitable error will
1647 be raised.
1648
1649 For example, in setting flags to enable CRL checking a
1650 suitable CRL must be added to the store otherwise an error will be
1651 raised.
1652
1653 .. versionadded:: 16.1.0
1654
1655 :param int flags: The verification flags to set on this store.
1656 See :class:`X509StoreFlags` for available constants.
1657 :return: ``None`` if the verification flags were successfully set.
1658 """
1659 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001660
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001661 def set_time(self, vfy_time):
1662 """
1663 Set the time against which the certificates are verified.
1664
1665 Normally the current time is used.
1666
1667 .. note::
1668
1669 For example, you can determine if a certificate was valid at a given
1670 time.
1671
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001672 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001673
1674 :param datetime vfy_time: The verification time to set on this store.
1675 :return: ``None`` if the verification time was successfully set.
1676 """
1677 param = _lib.X509_VERIFY_PARAM_new()
1678 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1679
1680 _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s')))
1681 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1682
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001683
Alex Gaynor10d30832017-06-29 15:31:39 -07001684X509StoreType = deprecated(
1685 X509Store, __name__,
1686 "X509StoreType has been deprecated, use X509Store instead",
1687 DeprecationWarning
1688)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001689
1690
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001691class X509StoreContextError(Exception):
1692 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001693 An exception raised when an error occurred while verifying a certificate
1694 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001695
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001696 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001697 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001698 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001699
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001700 def __init__(self, message, certificate):
1701 super(X509StoreContextError, self).__init__(message)
1702 self.certificate = certificate
1703
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001704
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001705class X509StoreContext(object):
1706 """
1707 An X.509 store context.
1708
Dan Sully44e767a2016-06-04 18:05:27 -07001709 An X.509 store context is used to carry out the actual verification process
1710 of a certificate in a described context. For describing such a context, see
1711 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001712
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001713 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1714 instance. It is dynamically allocated and automatically garbage
1715 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001716 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001717 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001718 :param X509Store store: The certificates which will be trusted for the
1719 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001720 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001721 """
1722
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001723 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001724 store_ctx = _lib.X509_STORE_CTX_new()
1725 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1726 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001727 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001728 # Make the store context available for use after instantiating this
1729 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001730 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001731 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001732
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001733 def _init(self):
1734 """
1735 Set up the store context for a subsequent verification operation.
Jeremy Cline58193f12017-09-13 21:14:53 -04001736
1737 Calling this method more than once without first calling
1738 :meth:`_cleanup` will leak memory.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001739 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001740 ret = _lib.X509_STORE_CTX_init(
1741 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1742 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001743 if ret <= 0:
1744 _raise_current_error()
1745
1746 def _cleanup(self):
1747 """
1748 Internally cleans up the store context.
1749
Dan Sully44e767a2016-06-04 18:05:27 -07001750 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001751 """
1752 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1753
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001754 def _exception_from_context(self):
1755 """
1756 Convert an OpenSSL native context error failure into a Python
1757 exception.
1758
Alex Gaynor5945ea82015-09-05 14:59:06 -04001759 When a call to native OpenSSL X509_verify_cert fails, additional
1760 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001761 """
1762 errors = [
1763 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1764 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1765 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001766 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001767 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001768 # A context error should always be associated with a certificate, so we
1769 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001770 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001771 _cert = _lib.X509_dup(_x509)
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001772 pycert = X509._from_raw_x509_ptr(_cert)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001773 return X509StoreContextError(errors, pycert)
1774
Stephen Holsapple46a09252015-02-12 14:45:43 -08001775 def set_store(self, store):
1776 """
Dan Sully44e767a2016-06-04 18:05:27 -07001777 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001778
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001779 .. versionadded:: 0.15
1780
Dan Sully44e767a2016-06-04 18:05:27 -07001781 :param X509Store store: The store description which will be used for
1782 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001783 """
1784 self._store = store
1785
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001786 def verify_certificate(self):
1787 """
1788 Verify a certificate in a context.
1789
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001790 .. versionadded:: 0.15
1791
Alex Gaynorca87ff62015-09-04 23:31:03 -04001792 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001793 certificate in the context. Sets ``certificate`` attribute to
1794 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001795 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001796 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001797 # :meth:`verify_certificate` is called multiple times.
Jeremy Cline58193f12017-09-13 21:14:53 -04001798 #
1799 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1800 # before _init to ensure memory is not leaked.
1801 self._cleanup()
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001802 self._init()
1803 ret = _lib.X509_verify_cert(self._store_ctx)
1804 self._cleanup()
1805 if ret <= 0:
1806 raise self._exception_from_context()
1807
1808
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001809def load_certificate(type, buffer):
1810 """
Alex Chand072cae2018-02-15 09:57:59 +00001811 Load a certificate (X509) from the string *buffer* encoded with the
1812 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001813
1814 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1815
Dan Sully44e767a2016-06-04 18:05:27 -07001816 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001817
1818 :return: The X509 object
1819 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001820 if isinstance(buffer, _text_type):
1821 buffer = buffer.encode("ascii")
1822
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001823 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001824
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001825 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001826 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001827 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001828 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001829 else:
1830 raise ValueError(
1831 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001832
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001833 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001834 _raise_current_error()
1835
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001836 return X509._from_raw_x509_ptr(x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001837
1838
1839def dump_certificate(type, cert):
1840 """
Alex Chand072cae2018-02-15 09:57:59 +00001841 Dump the certificate *cert* into a buffer string encoded with the type
1842 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001843
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001844 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1845 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001846 :param cert: The certificate to dump
1847 :return: The buffer with the dumped certificate in
1848 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001849 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001850
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001851 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001852 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001853 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001855 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001856 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001857 else:
1858 raise ValueError(
1859 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1860 "FILETYPE_TEXT")
1861
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001862 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001863 return _bio_to_string(bio)
1864
1865
Cory Benfield6492f7c2015-10-27 16:57:58 +09001866def dump_publickey(type, pkey):
1867 """
Cory Benfield11c10192015-10-27 17:23:03 +09001868 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001869
Cory Benfield9c590b92015-10-28 14:55:05 +09001870 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001871 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001872 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001873 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001874 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001875 """
1876 bio = _new_mem_buf()
1877 if type == FILETYPE_PEM:
1878 write_bio = _lib.PEM_write_bio_PUBKEY
1879 elif type == FILETYPE_ASN1:
1880 write_bio = _lib.i2d_PUBKEY_bio
1881 else:
1882 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1883
1884 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001885 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001886 _raise_current_error()
1887
1888 return _bio_to_string(bio)
1889
1890
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001891def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1892 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001893 Dump the private key *pkey* into a buffer string encoded with the type
1894 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1895 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001896
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001897 :param type: The file type (one of :const:`FILETYPE_PEM`,
1898 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1899 :param PKey pkey: The PKey to dump
1900 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001901 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001902 the passphrase to use, or a callback for providing the passphrase.
1903
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001904 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001905 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001906 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001907 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001908
Paul Kehrercded9932017-06-29 18:43:42 -05001909 if not isinstance(pkey, PKey):
1910 raise TypeError("pkey must be a PKey")
1911
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001912 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001913 if passphrase is None:
1914 raise TypeError(
1915 "if a value is given for cipher "
1916 "one must also be given for passphrase")
1917 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001918 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001919 raise ValueError("Invalid cipher name")
1920 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001921 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001922
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001923 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001924 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001925 result_code = _lib.PEM_write_bio_PrivateKey(
1926 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001927 helper.callback, helper.callback_args)
1928 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001929 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001930 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001931 elif type == FILETYPE_TEXT:
Paul Kehrercded9932017-06-29 18:43:42 -05001932 if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:
1933 raise TypeError("Only RSA keys are supported for FILETYPE_TEXT")
1934
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001935 rsa = _ffi.gc(
1936 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1937 _lib.RSA_free
1938 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001939 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001940 else:
1941 raise ValueError(
1942 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1943 "FILETYPE_TEXT")
1944
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001945 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001946
1947 return _bio_to_string(bio)
1948
1949
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001950class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001951 """
1952 A certificate revocation.
1953 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001954 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1955 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1956 # OCSP_crl_reason_str. We use the latter, just like the command line
1957 # program.
1958 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001959 b"unspecified",
1960 b"keyCompromise",
1961 b"CACompromise",
1962 b"affiliationChanged",
1963 b"superseded",
1964 b"cessationOfOperation",
1965 b"certificateHold",
1966 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001967 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001968
1969 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001970 revoked = _lib.X509_REVOKED_new()
1971 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001972
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001973 def set_serial(self, hex_str):
1974 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001975 Set the serial number.
1976
1977 The serial number is formatted as a hexadecimal number encoded in
1978 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001979
Dan Sully44e767a2016-06-04 18:05:27 -07001980 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001981
Dan Sully44e767a2016-06-04 18:05:27 -07001982 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001983 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001984 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1985 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001986 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001987 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001988 if not bn_result:
1989 raise ValueError("bad hex string")
1990
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001991 asn1_serial = _ffi.gc(
1992 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1993 _lib.ASN1_INTEGER_free)
1994 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001995
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001996 def get_serial(self):
1997 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001998 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001999
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002000 The serial number is formatted as a hexadecimal number encoded in
2001 ASCII.
2002
2003 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07002004 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002005 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002006 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002007
Alex Gaynor67903a62016-06-02 10:37:13 -07002008 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
2009 _openssl_assert(asn1_int != _ffi.NULL)
2010 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
2011 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002012 return _bio_to_string(bio)
2013
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002014 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07002015 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2016 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002017 obj = _lib.X509_EXTENSION_get_object(ext)
2018 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002019 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07002020 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002021 break
2022
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002023 def set_reason(self, reason):
2024 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002025 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002026
Dan Sully44e767a2016-06-04 18:05:27 -07002027 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002028
2029 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07002030 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002031
Dan Sully44e767a2016-06-04 18:05:27 -07002032 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002033
2034 .. seealso::
2035
Dan Sully44e767a2016-06-04 18:05:27 -07002036 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002037 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002038 """
2039 if reason is None:
2040 self._delete_reason()
2041 elif not isinstance(reason, bytes):
2042 raise TypeError("reason must be None or a byte string")
2043 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002044 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002045 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
2046
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002047 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002048 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002049 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002050
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002051 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002052 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002053
2054 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002055 add_result = _lib.X509_REVOKED_add1_ext_i2d(
2056 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002057 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002058
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002059 def get_reason(self):
2060 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04002061 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002062
Dan Sully44e767a2016-06-04 18:05:27 -07002063 :return: The reason, or ``None`` if there is none.
2064 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002065
2066 .. seealso::
2067
Dan Sully44e767a2016-06-04 18:05:27 -07002068 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002069 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002070 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002071 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2072 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002073 obj = _lib.X509_EXTENSION_get_object(ext)
2074 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002075 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002076
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002077 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002078 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002079 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002080 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04002081 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002082 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002083
2084 return _bio_to_string(bio)
2085
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002086 def all_reasons(self):
2087 """
2088 Return a list of all the supported reason strings.
2089
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002090 This list is a copy; modifying it does not change the supported reason
2091 strings.
2092
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002093 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07002094 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002095 """
2096 return self._crl_reasons[:]
2097
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002098 def set_rev_date(self, when):
2099 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002100 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002101
Dan Sully44e767a2016-06-04 18:05:27 -07002102 :param bytes when: The timestamp of the revocation,
Paul Kehrerce98ee62017-06-21 06:59:58 -10002103 as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002104 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002105 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002106 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2107 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002108
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002109 def get_rev_date(self):
2110 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002111 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002112
Paul Kehrerce98ee62017-06-21 06:59:58 -10002113 :return: The timestamp of the revocation, as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002114 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002115 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002116 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2117 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002118
2119
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002120class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002121 """
2122 A certificate revocation list.
2123 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002124
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002125 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002126 crl = _lib.X509_CRL_new()
2127 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002128
Paul Kehrer41c10242017-06-29 18:24:17 -05002129 def to_cryptography(self):
2130 """
2131 Export as a ``cryptography`` CRL.
2132
2133 :rtype: ``cryptography.x509.CertificateRevocationList``
2134
2135 .. versionadded:: 17.1.0
2136 """
2137 from cryptography.hazmat.backends.openssl.x509 import (
2138 _CertificateRevocationList
2139 )
2140 backend = _get_backend()
2141 return _CertificateRevocationList(backend, self._crl)
2142
2143 @classmethod
2144 def from_cryptography(cls, crypto_crl):
2145 """
2146 Construct based on a ``cryptography`` *crypto_crl*.
2147
2148 :param crypto_crl: A ``cryptography`` certificate revocation list
2149 :type crypto_crl: ``cryptography.x509.CertificateRevocationList``
2150
2151 :rtype: CRL
2152
2153 .. versionadded:: 17.1.0
2154 """
2155 if not isinstance(crypto_crl, x509.CertificateRevocationList):
2156 raise TypeError("Must be a certificate revocation list")
2157
2158 crl = cls()
2159 crl._crl = crypto_crl._x509_crl
2160 return crl
2161
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002162 def get_revoked(self):
2163 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002164 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002165
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002166 These revocations will be provided by value, not by reference.
2167 That means it's okay to mutate them: it won't affect this CRL.
2168
2169 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002170 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002171 """
2172 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07002173 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002174 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
2175 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04002176 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002177 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002178 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002179 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002180 if results:
2181 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002182
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002183 def add_revoked(self, revoked):
2184 """
2185 Add a revoked (by value not reference) to the CRL structure
2186
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002187 This revocation will be added by value, not by reference. That
2188 means it's okay to mutate it after adding: it won't affect
2189 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002190
Dan Sully44e767a2016-06-04 18:05:27 -07002191 :param Revoked revoked: The new revocation.
2192 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002193 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04002194 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002195 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002196
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002197 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002198 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002199
Dan Sully44e767a2016-06-04 18:05:27 -07002200 def get_issuer(self):
2201 """
2202 Get the CRL's issuer.
2203
2204 .. versionadded:: 16.1.0
2205
2206 :rtype: X509Name
2207 """
2208 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2209 _openssl_assert(_issuer != _ffi.NULL)
2210 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2211 issuer = X509Name.__new__(X509Name)
2212 issuer._name = _issuer
2213 return issuer
2214
2215 def set_version(self, version):
2216 """
2217 Set the CRL version.
2218
2219 .. versionadded:: 16.1.0
2220
2221 :param int version: The version of the CRL.
2222 :return: ``None``
2223 """
2224 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2225
2226 def _set_boundary_time(self, which, when):
2227 return _set_asn1_time(which(self._crl), when)
2228
2229 def set_lastUpdate(self, when):
2230 """
2231 Set when the CRL was last updated.
2232
Paul Kehrerce98ee62017-06-21 06:59:58 -10002233 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002234
2235 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002236
2237 .. versionadded:: 16.1.0
2238
2239 :param bytes when: A timestamp string.
2240 :return: ``None``
2241 """
2242 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2243
2244 def set_nextUpdate(self, when):
2245 """
2246 Set when the CRL will next be udpated.
2247
Paul Kehrerce98ee62017-06-21 06:59:58 -10002248 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002249
2250 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002251
2252 .. versionadded:: 16.1.0
2253
2254 :param bytes when: A timestamp string.
2255 :return: ``None``
2256 """
2257 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2258
2259 def sign(self, issuer_cert, issuer_key, digest):
2260 """
2261 Sign the CRL.
2262
2263 Signing a CRL enables clients to associate the CRL itself with an
2264 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2265 be signed by an issuer.
2266
2267 This method implicitly sets the issuer's name based on the issuer
2268 certificate and private key used to sign the CRL.
2269
2270 .. versionadded:: 16.1.0
2271
2272 :param X509 issuer_cert: The issuer's certificate.
2273 :param PKey issuer_key: The issuer's private key.
2274 :param bytes digest: The digest method to sign the CRL with.
2275 """
2276 digest_obj = _lib.EVP_get_digestbyname(digest)
2277 _openssl_assert(digest_obj != _ffi.NULL)
2278 _lib.X509_CRL_set_issuer_name(
2279 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2280 _lib.X509_CRL_sort(self._crl)
2281 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2282 _openssl_assert(result != 0)
2283
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002284 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002285 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002286 """
Dan Sully44e767a2016-06-04 18:05:27 -07002287 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002288
Dan Sully44e767a2016-06-04 18:05:27 -07002289 :param X509 cert: The certificate used to sign the CRL.
2290 :param PKey key: The key used to sign the CRL.
2291 :param int type: The export format, either :data:`FILETYPE_PEM`,
2292 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002293 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002294 :param bytes digest: The name of the message digest to use (eg
Alex Gaynor239e2d32016-09-11 12:36:35 -04002295 ``b"sha2566"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002296 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002297 """
Dan Sully44e767a2016-06-04 18:05:27 -07002298
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002299 if not isinstance(cert, X509):
2300 raise TypeError("cert must be an X509 instance")
2301 if not isinstance(key, PKey):
2302 raise TypeError("key must be a PKey instance")
2303 if not isinstance(type, int):
2304 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002305
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002306 if digest is _UNSPECIFIED:
Alex Gaynor173e4ba2017-06-30 08:01:12 -07002307 raise TypeError("digest must be provided")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002308
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002309 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002310 if digest_obj == _ffi.NULL:
2311 raise ValueError("No such digest method")
2312
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002313 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002314 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002315
Alex Gaynora738ed52015-09-05 11:17:10 -04002316 # A scratch time object to give different values to different CRL
2317 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002318 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002319 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002320
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002321 _lib.X509_gmtime_adj(sometime, 0)
2322 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002323
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002324 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2325 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002326
Alex Gaynor5945ea82015-09-05 14:59:06 -04002327 _lib.X509_CRL_set_issuer_name(
2328 self._crl, _lib.X509_get_subject_name(cert._x509)
2329 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002330
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002331 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002332 if not sign_result:
2333 _raise_current_error()
2334
Dominic Chenf05b2122015-10-13 16:32:35 +00002335 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002336
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002337
Alex Gaynor10d30832017-06-29 15:31:39 -07002338CRLType = deprecated(
2339 CRL, __name__,
2340 "CRLType has been deprecated, use CRL instead",
2341 DeprecationWarning
2342)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002343
2344
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002345class PKCS7(object):
2346 def type_is_signed(self):
2347 """
2348 Check if this NID_pkcs7_signed object
2349
2350 :return: True if the PKCS7 is of type signed
2351 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002352 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002353
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002354 def type_is_enveloped(self):
2355 """
2356 Check if this NID_pkcs7_enveloped object
2357
2358 :returns: True if the PKCS7 is of type enveloped
2359 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002360 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002361
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002362 def type_is_signedAndEnveloped(self):
2363 """
2364 Check if this NID_pkcs7_signedAndEnveloped object
2365
2366 :returns: True if the PKCS7 is of type signedAndEnveloped
2367 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002368 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002369
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002370 def type_is_data(self):
2371 """
2372 Check if this NID_pkcs7_data object
2373
2374 :return: True if the PKCS7 is of type data
2375 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002376 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002377
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002378 def get_type_name(self):
2379 """
2380 Returns the type name of the PKCS7 structure
2381
2382 :return: A string with the typename
2383 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002384 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2385 string_type = _lib.OBJ_nid2sn(nid)
2386 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002387
Alex Chanc6077062016-11-18 13:53:39 +00002388
Alex Gaynor10d30832017-06-29 15:31:39 -07002389PKCS7Type = deprecated(
2390 PKCS7, __name__,
2391 "PKCS7Type has been deprecated, use PKCS7 instead",
2392 DeprecationWarning
2393)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002394
2395
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002396class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002397 """
2398 A PKCS #12 archive.
2399 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002400
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002401 def __init__(self):
2402 self._pkey = None
2403 self._cert = None
2404 self._cacerts = None
2405 self._friendlyname = None
2406
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002407 def get_certificate(self):
2408 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002409 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002410
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002411 :return: The certificate, or :py:const:`None` if there is none.
2412 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002413 """
2414 return self._cert
2415
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002416 def set_certificate(self, cert):
2417 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002418 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002419
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002420 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002421 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002422
Dan Sully44e767a2016-06-04 18:05:27 -07002423 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002424 """
2425 if not isinstance(cert, X509):
2426 raise TypeError("cert must be an X509 instance")
2427 self._cert = cert
2428
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002429 def get_privatekey(self):
2430 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002431 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002432
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002433 :return: The private key, or :py:const:`None` if there is none.
2434 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002435 """
2436 return self._pkey
2437
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002438 def set_privatekey(self, pkey):
2439 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002440 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002441
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002442 :param pkey: The new private key, or :py:const:`None` to unset it.
2443 :type pkey: :py:class:`PKey` or :py:const:`None`
2444
Dan Sully44e767a2016-06-04 18:05:27 -07002445 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002446 """
2447 if not isinstance(pkey, PKey):
2448 raise TypeError("pkey must be a PKey instance")
2449 self._pkey = pkey
2450
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002451 def get_ca_certificates(self):
2452 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002453 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002454
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002455 :return: A tuple with the CA certificates in the chain, or
2456 :py:const:`None` if there are none.
2457 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002458 """
2459 if self._cacerts is not None:
2460 return tuple(self._cacerts)
2461
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002462 def set_ca_certificates(self, cacerts):
2463 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002464 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002465
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002466 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2467 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002468 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002469
Dan Sully44e767a2016-06-04 18:05:27 -07002470 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002471 """
2472 if cacerts is None:
2473 self._cacerts = None
2474 else:
2475 cacerts = list(cacerts)
2476 for cert in cacerts:
2477 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002478 raise TypeError(
2479 "iterable must only contain X509 instances"
2480 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002481 self._cacerts = cacerts
2482
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002483 def set_friendlyname(self, name):
2484 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002485 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002486
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002487 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002488 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002489
Dan Sully44e767a2016-06-04 18:05:27 -07002490 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002491 """
2492 if name is None:
2493 self._friendlyname = None
2494 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002495 raise TypeError(
2496 "name must be a byte string or None (not %r)" % (name,)
2497 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002498 self._friendlyname = name
2499
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002500 def get_friendlyname(self):
2501 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002502 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002503
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002504 :returns: The friendly name, or :py:const:`None` if there is none.
2505 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002506 """
2507 return self._friendlyname
2508
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002509 def export(self, passphrase=None, iter=2048, maciter=1):
2510 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002511 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002512
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002513 For more information, see the :c:func:`PKCS12_create` man page.
2514
2515 :param passphrase: The passphrase used to encrypt the structure. Unlike
2516 some other passphrase arguments, this *must* be a string, not a
2517 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002518 :type passphrase: :py:data:`bytes`
2519
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002520 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002521 :type iter: :py:data:`int`
2522
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002523 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002524 :type maciter: :py:data:`int`
2525
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002526 :return: The string representation of the PKCS #12 structure.
2527 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002528 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002529 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002530
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002531 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002532 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002533 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002534 cacerts = _lib.sk_X509_new_null()
2535 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002536 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002537 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002538
2539 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002540 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002541
2542 friendlyname = self._friendlyname
2543 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002544 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002545
2546 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002547 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002548 else:
2549 pkey = self._pkey._pkey
2550
2551 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002552 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002553 else:
2554 cert = self._cert._x509
2555
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002556 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002557 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002558 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2559 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002560 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002561 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002562 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002563 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002564
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002565 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002566 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002567 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002568
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002569
Alex Gaynor10d30832017-06-29 15:31:39 -07002570PKCS12Type = deprecated(
2571 PKCS12, __name__,
2572 "PKCS12Type has been deprecated, use PKCS12 instead",
2573 DeprecationWarning
2574)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002575
2576
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002577class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002578 """
2579 A Netscape SPKI object.
2580 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002581
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002582 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002583 spki = _lib.NETSCAPE_SPKI_new()
2584 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002585
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002586 def sign(self, pkey, digest):
2587 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002588 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002589
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002590 :param pkey: The private key to sign with.
2591 :type pkey: :py:class:`PKey`
2592
2593 :param digest: The message digest to use.
2594 :type digest: :py:class:`bytes`
2595
Dan Sully44e767a2016-06-04 18:05:27 -07002596 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002597 """
2598 if pkey._only_public:
2599 raise ValueError("Key has only public part")
2600
2601 if not pkey._initialized:
2602 raise ValueError("Key is uninitialized")
2603
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002604 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002605 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002606 raise ValueError("No such digest method")
2607
Alex Gaynor5945ea82015-09-05 14:59:06 -04002608 sign_result = _lib.NETSCAPE_SPKI_sign(
2609 self._spki, pkey._pkey, digest_obj
2610 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002611 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002612
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002613 def verify(self, key):
2614 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002615 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002616
Hynek Schlawack01c31672016-12-11 15:14:09 +01002617 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002618
Hynek Schlawack01c31672016-12-11 15:14:09 +01002619 :return: ``True`` if the signature is correct.
2620 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002621
Hynek Schlawack01c31672016-12-11 15:14:09 +01002622 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2623 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002624 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002625 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002626 if answer <= 0:
2627 _raise_current_error()
2628 return True
2629
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002630 def b64_encode(self):
2631 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002632 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002633
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002634 :return: The base64 encoded string.
2635 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002636 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002637 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2638 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002639 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002640 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002641
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002642 def get_pubkey(self):
2643 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002644 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002645
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002646 :return: The public key.
2647 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002648 """
2649 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002650 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002651 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002652 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002653 pkey._only_public = True
2654 return pkey
2655
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002656 def set_pubkey(self, pkey):
2657 """
2658 Set the public key of the certificate
2659
2660 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002661 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002662 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002663 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002664 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002665
2666
Alex Gaynor10d30832017-06-29 15:31:39 -07002667NetscapeSPKIType = deprecated(
2668 NetscapeSPKI, __name__,
2669 "NetscapeSPKIType has been deprecated, use NetscapeSPKI instead",
2670 DeprecationWarning
2671)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002672
2673
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002674class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002675 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002676 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002677 raise ValueError(
2678 "only FILETYPE_PEM key format supports encryption"
2679 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002680 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002681 self._more_args = more_args
2682 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002683 self._problems = []
2684
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002685 @property
2686 def callback(self):
2687 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002688 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002689 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002690 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002691 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002692 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002693 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002694 raise TypeError(
2695 "Last argument must be a byte string or a callable."
2696 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002697
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002698 @property
2699 def callback_args(self):
2700 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002701 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002702 elif isinstance(self._passphrase, bytes):
2703 return self._passphrase
2704 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002705 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002706 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002707 raise TypeError(
2708 "Last argument must be a byte string or a callable."
2709 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002710
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002711 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002712 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002713
2714 # Flush the OpenSSL error queue
2715 try:
2716 _exception_from_error_queue(exceptionType)
2717 except exceptionType:
2718 pass
2719
2720 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002721
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002722 def _read_passphrase(self, buf, size, rwflag, userdata):
2723 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002724 if self._more_args:
2725 result = self._passphrase(size, rwflag, userdata)
2726 else:
2727 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002728 if not isinstance(result, bytes):
2729 raise ValueError("String expected")
2730 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002731 if self._truncate:
2732 result = result[:size]
2733 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002734 raise ValueError(
2735 "passphrase returned by callback is too long"
2736 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002737 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002738 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002739 return len(result)
2740 except Exception as e:
2741 self._problems.append(e)
2742 return 0
2743
2744
Cory Benfield6492f7c2015-10-27 16:57:58 +09002745def load_publickey(type, buffer):
2746 """
Cory Benfield11c10192015-10-27 17:23:03 +09002747 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002748
Cory Benfield9c590b92015-10-28 14:55:05 +09002749 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002750 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002751 :param buffer: The buffer the key is stored in.
2752 :type buffer: A Python string object, either unicode or bytestring.
2753 :return: The PKey object.
2754 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002755 """
2756 if isinstance(buffer, _text_type):
2757 buffer = buffer.encode("ascii")
2758
2759 bio = _new_mem_buf(buffer)
2760
2761 if type == FILETYPE_PEM:
2762 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2763 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2764 elif type == FILETYPE_ASN1:
2765 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2766 else:
2767 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2768
2769 if evp_pkey == _ffi.NULL:
2770 _raise_current_error()
2771
2772 pkey = PKey.__new__(PKey)
2773 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002774 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002775 return pkey
2776
2777
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002778def load_privatekey(type, buffer, passphrase=None):
2779 """
Alex Chand072cae2018-02-15 09:57:59 +00002780 Load a private key (PKey) from the string *buffer* encoded with the type
2781 *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002782
2783 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2784 :param buffer: The buffer the key is stored in
2785 :param passphrase: (optional) if encrypted PEM format, this can be
2786 either the passphrase to use, or a callback for
2787 providing the passphrase.
2788
2789 :return: The PKey object
2790 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002791 if isinstance(buffer, _text_type):
2792 buffer = buffer.encode("ascii")
2793
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002794 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002795
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002796 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002797 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002798 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2799 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002800 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002801 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002802 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002803 else:
2804 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2805
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002806 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002807 _raise_current_error()
2808
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002809 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002810 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002811 return pkey
2812
2813
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002814def dump_certificate_request(type, req):
2815 """
Alex Chand072cae2018-02-15 09:57:59 +00002816 Dump the certificate request *req* into a buffer string encoded with the
2817 type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002818
2819 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2820 :param req: The certificate request to dump
2821 :return: The buffer with the dumped certificate request in
2822 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002823 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002824
2825 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002826 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002827 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002828 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002829 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002830 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002831 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002832 raise ValueError(
2833 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2834 "FILETYPE_TEXT"
2835 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002836
Alex Gaynor09a386e2016-07-03 09:32:44 -04002837 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002838
2839 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002840
2841
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002842def load_certificate_request(type, buffer):
2843 """
Alex Chand072cae2018-02-15 09:57:59 +00002844 Load a certificate request (X509Req) from the string *buffer* encoded with
2845 the type *type*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002846
2847 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2848 :param buffer: The buffer the certificate request is stored in
2849 :return: The X509Req object
2850 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002851 if isinstance(buffer, _text_type):
2852 buffer = buffer.encode("ascii")
2853
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002854 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002855
2856 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002857 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002858 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002859 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002860 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002861 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002862
Alex Gaynoradd5b072016-06-04 21:04:00 -07002863 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002864
2865 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002866 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002867 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002868
2869
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002870def sign(pkey, data, digest):
2871 """
Alex Chand072cae2018-02-15 09:57:59 +00002872 Sign a data string using the given key and message digest.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002873
Alex Chand072cae2018-02-15 09:57:59 +00002874 :param pkey: PKey to sign with
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002875 :param data: data to be signed
2876 :param digest: message digest to use
2877 :return: signature
Alex Chand072cae2018-02-15 09:57:59 +00002878
2879 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002880 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002881 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002882
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002883 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002884 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002885 raise ValueError("No such digest method")
2886
Alex Gaynor67903a62016-06-02 10:37:13 -07002887 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002888 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002890 _lib.EVP_SignInit(md_ctx, digest_obj)
2891 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002892
Paul Kehrer59d26252017-07-20 10:45:54 +02002893 length = _lib.EVP_PKEY_size(pkey._pkey)
2894 _openssl_assert(length > 0)
2895 signature_buffer = _ffi.new("unsigned char[]", length)
2896 signature_length = _ffi.new("unsigned int *")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002897 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002898 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002899 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002900
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002901 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002902
2903
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002904def verify(cert, signature, data, digest):
2905 """
Alex Chand072cae2018-02-15 09:57:59 +00002906 Verify the signature for a data string.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002907
Alex Chand072cae2018-02-15 09:57:59 +00002908 :param cert: signing certificate (X509 object) corresponding to the
2909 private key which generated the signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002910 :param signature: signature returned by sign function
2911 :param data: data to be verified
2912 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002913 :return: ``None`` if the signature is correct, raise exception otherwise.
Alex Chand072cae2018-02-15 09:57:59 +00002914
2915 .. versionadded:: 0.11
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002916 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002917 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002918
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002919 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002920 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002921 raise ValueError("No such digest method")
2922
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002923 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002924 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002925 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002926
Alex Gaynor67903a62016-06-02 10:37:13 -07002927 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002928 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002929
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002930 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2931 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002932 verify_result = _lib.EVP_VerifyFinal(
2933 md_ctx, signature, len(signature), pkey
2934 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002935
2936 if verify_result != 1:
2937 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002938
2939
Dominic Chenf05b2122015-10-13 16:32:35 +00002940def dump_crl(type, crl):
2941 """
2942 Dump a certificate revocation list to a buffer.
2943
2944 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2945 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002946 :param CRL crl: The CRL to dump.
2947
Dominic Chenf05b2122015-10-13 16:32:35 +00002948 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002949 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002950 """
2951 bio = _new_mem_buf()
2952
2953 if type == FILETYPE_PEM:
2954 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2955 elif type == FILETYPE_ASN1:
2956 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2957 elif type == FILETYPE_TEXT:
2958 ret = _lib.X509_CRL_print(bio, crl._crl)
2959 else:
2960 raise ValueError(
2961 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2962 "FILETYPE_TEXT")
2963
2964 assert ret == 1
2965 return _bio_to_string(bio)
2966
2967
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002968def load_crl(type, buffer):
2969 """
Alex Chand072cae2018-02-15 09:57:59 +00002970 Load Certificate Revocation List (CRL) data from a string *buffer*.
2971 *buffer* encoded with the type *type*.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002972
2973 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2974 :param buffer: The buffer the CRL is stored in
2975
2976 :return: The PKey object
2977 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002978 if isinstance(buffer, _text_type):
2979 buffer = buffer.encode("ascii")
2980
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002981 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002982
2983 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002984 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002985 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002986 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002987 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002988 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2989
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002990 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002991 _raise_current_error()
2992
2993 result = CRL.__new__(CRL)
Jeremy Cline9e15eca2017-09-07 20:11:08 -04002994 result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002995 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002996
2997
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002998def load_pkcs7_data(type, buffer):
2999 """
Alex Chand072cae2018-02-15 09:57:59 +00003000 Load pkcs7 data from the string *buffer* encoded with the type
3001 *type*.
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003002
3003 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
3004 :param buffer: The buffer with the pkcs7 data.
3005 :return: The PKCS7 object
3006 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003007 if isinstance(buffer, _text_type):
3008 buffer = buffer.encode("ascii")
3009
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003010 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003011
3012 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003013 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003014 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07003015 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003016 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003017 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
3018
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003019 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08003020 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003021
3022 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003023 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003024 return pypkcs7
3025
3026
Stephen Holsapple38482622014-04-05 20:29:34 -07003027def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003028 """
Alex Chand072cae2018-02-15 09:57:59 +00003029 Load pkcs12 data from the string *buffer*. If the pkcs12 structure is
3030 encrypted, a *passphrase* must be included. The MAC is always
3031 checked and thus required.
3032
3033 See also the man page for the C function :py:func:`PKCS12_parse`.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003034
3035 :param buffer: The buffer the certificate is stored in
3036 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
3037 :returns: The PKCS12 object
3038 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003039 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00003040
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003041 if isinstance(buffer, _text_type):
3042 buffer = buffer.encode("ascii")
3043
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003044 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003045
Stephen Holsapple38482622014-04-05 20:29:34 -07003046 # Use null passphrase if passphrase is None or empty string. With PKCS#12
3047 # password based encryption no password and a zero length password are two
3048 # different things, but OpenSSL implementation will try both to figure out
3049 # which one works.
3050 if not passphrase:
3051 passphrase = _ffi.NULL
3052
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003053 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
3054 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003055 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003056 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003057
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003058 pkey = _ffi.new("EVP_PKEY**")
3059 cert = _ffi.new("X509**")
3060 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003061
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003062 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003063 if not parse_result:
3064 _raise_current_error()
3065
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003066 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08003067
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003068 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
3069 # queue for no particular reason. This error isn't interesting to anyone
3070 # outside this function. It's not even interesting to us. Get rid of it.
3071 try:
3072 _raise_current_error()
3073 except Error:
3074 pass
3075
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003076 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003077 pykey = None
3078 else:
3079 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003080 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003081
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003082 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003083 pycert = None
3084 friendlyname = None
3085 else:
Paul Kehrere7381862017-11-30 20:55:25 +08003086 pycert = X509._from_raw_x509_ptr(cert[0])
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003087
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003088 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04003089 friendlyname_buffer = _lib.X509_alias_get0(
3090 cert[0], friendlyname_length
3091 )
3092 friendlyname = _ffi.buffer(
3093 friendlyname_buffer, friendlyname_length[0]
3094 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003095 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003096 friendlyname = None
3097
3098 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003099 for i in range(_lib.sk_X509_num(cacerts)):
Paul Kehrere7381862017-11-30 20:55:25 +08003100 x509 = _lib.sk_X509_value(cacerts, i)
3101 pycacert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003102 pycacerts.append(pycacert)
3103 if not pycacerts:
3104 pycacerts = None
3105
3106 pkcs12 = PKCS12.__new__(PKCS12)
3107 pkcs12._pkey = pykey
3108 pkcs12._cert = pycert
3109 pkcs12._cacerts = pycacerts
3110 pkcs12._friendlyname = friendlyname
3111 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05003112
3113
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05003114# There are no direct unit tests for this initialization. It is tested
3115# indirectly since it is necessary for functions like dump_privatekey when
3116# using encryption.
3117#
3118# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
3119# and some other similar tests may fail without this (though they may not if
3120# the Python runtime has already done some initialization of the underlying
3121# OpenSSL library (and is linked against the same one that cryptography is
3122# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05003123_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05003124
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05003125# This is similar but exercised mainly by exception_from_error_queue. It calls
3126# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
3127_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003128
3129
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003130# Set the default string mask to match OpenSSL upstream (since 2005) and
3131# RFC5280 recommendations.
3132_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')