blob: 12b4db0db5aad93ac47c8382c700ee3d097293f0 [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 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500292 exponent = _lib.BN_new()
293 exponent = _ffi.gc(exponent, _lib.BN_free)
294 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800295
296 if type == TYPE_RSA:
297 if bits <= 0:
298 raise ValueError("Invalid number of bits")
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
Dan Sully44e767a2016-06-04 18:05:27 -07001610 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1611
1612 def add_crl(self, crl):
1613 """
1614 Add a certificate revocation list to this store.
1615
1616 The certificate revocation lists added to a store will only be used if
1617 the associated flags are configured to check certificate revocation
1618 lists.
1619
1620 .. versionadded:: 16.1.0
1621
1622 :param CRL crl: The certificate revocation list to add to this store.
1623 :return: ``None`` if the certificate revocation list was added
1624 successfully.
1625 """
1626 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1627
1628 def set_flags(self, flags):
1629 """
1630 Set verification flags to this store.
1631
1632 Verification flags can be combined by oring them together.
1633
1634 .. note::
1635
1636 Setting a verification flag sometimes requires clients to add
1637 additional information to the store, otherwise a suitable error will
1638 be raised.
1639
1640 For example, in setting flags to enable CRL checking a
1641 suitable CRL must be added to the store otherwise an error will be
1642 raised.
1643
1644 .. versionadded:: 16.1.0
1645
1646 :param int flags: The verification flags to set on this store.
1647 See :class:`X509StoreFlags` for available constants.
1648 :return: ``None`` if the verification flags were successfully set.
1649 """
1650 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001651
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001652 def set_time(self, vfy_time):
1653 """
1654 Set the time against which the certificates are verified.
1655
1656 Normally the current time is used.
1657
1658 .. note::
1659
1660 For example, you can determine if a certificate was valid at a given
1661 time.
1662
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001663 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001664
1665 :param datetime vfy_time: The verification time to set on this store.
1666 :return: ``None`` if the verification time was successfully set.
1667 """
1668 param = _lib.X509_VERIFY_PARAM_new()
1669 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1670
1671 _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s')))
1672 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1673
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001674
Alex Gaynor10d30832017-06-29 15:31:39 -07001675X509StoreType = deprecated(
1676 X509Store, __name__,
1677 "X509StoreType has been deprecated, use X509Store instead",
1678 DeprecationWarning
1679)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001680
1681
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001682class X509StoreContextError(Exception):
1683 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001684 An exception raised when an error occurred while verifying a certificate
1685 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001686
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001687 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001688 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001689 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001690
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001691 def __init__(self, message, certificate):
1692 super(X509StoreContextError, self).__init__(message)
1693 self.certificate = certificate
1694
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001695
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001696class X509StoreContext(object):
1697 """
1698 An X.509 store context.
1699
Dan Sully44e767a2016-06-04 18:05:27 -07001700 An X.509 store context is used to carry out the actual verification process
1701 of a certificate in a described context. For describing such a context, see
1702 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001703
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001704 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1705 instance. It is dynamically allocated and automatically garbage
1706 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001707 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001708 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001709 :param X509Store store: The certificates which will be trusted for the
1710 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001711 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001712 """
1713
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001714 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001715 store_ctx = _lib.X509_STORE_CTX_new()
1716 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1717 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001718 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001719 # Make the store context available for use after instantiating this
1720 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001721 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001722 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001723
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001724 def _init(self):
1725 """
1726 Set up the store context for a subsequent verification operation.
Jeremy Cline58193f12017-09-13 21:14:53 -04001727
1728 Calling this method more than once without first calling
1729 :meth:`_cleanup` will leak memory.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001730 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001731 ret = _lib.X509_STORE_CTX_init(
1732 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1733 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001734 if ret <= 0:
1735 _raise_current_error()
1736
1737 def _cleanup(self):
1738 """
1739 Internally cleans up the store context.
1740
Dan Sully44e767a2016-06-04 18:05:27 -07001741 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001742 """
1743 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1744
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001745 def _exception_from_context(self):
1746 """
1747 Convert an OpenSSL native context error failure into a Python
1748 exception.
1749
Alex Gaynor5945ea82015-09-05 14:59:06 -04001750 When a call to native OpenSSL X509_verify_cert fails, additional
1751 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001752 """
1753 errors = [
1754 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1755 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1756 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001757 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001758 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001759 # A context error should always be associated with a certificate, so we
1760 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001761 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001762 _cert = _lib.X509_dup(_x509)
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001763 pycert = X509._from_raw_x509_ptr(_cert)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001764 return X509StoreContextError(errors, pycert)
1765
Stephen Holsapple46a09252015-02-12 14:45:43 -08001766 def set_store(self, store):
1767 """
Dan Sully44e767a2016-06-04 18:05:27 -07001768 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001769
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001770 .. versionadded:: 0.15
1771
Dan Sully44e767a2016-06-04 18:05:27 -07001772 :param X509Store store: The store description which will be used for
1773 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001774 """
1775 self._store = store
1776
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001777 def verify_certificate(self):
1778 """
1779 Verify a certificate in a context.
1780
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001781 .. versionadded:: 0.15
1782
Alex Gaynorca87ff62015-09-04 23:31:03 -04001783 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001784 certificate in the context. Sets ``certificate`` attribute to
1785 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001786 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001787 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001788 # :meth:`verify_certificate` is called multiple times.
Jeremy Cline58193f12017-09-13 21:14:53 -04001789 #
1790 # :meth:`_init` is called in :meth:`__init__` so _cleanup is called
1791 # before _init to ensure memory is not leaked.
1792 self._cleanup()
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001793 self._init()
1794 ret = _lib.X509_verify_cert(self._store_ctx)
1795 self._cleanup()
1796 if ret <= 0:
1797 raise self._exception_from_context()
1798
1799
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001800def load_certificate(type, buffer):
1801 """
1802 Load a certificate from a buffer
1803
1804 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1805
Dan Sully44e767a2016-06-04 18:05:27 -07001806 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001807
1808 :return: The X509 object
1809 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001810 if isinstance(buffer, _text_type):
1811 buffer = buffer.encode("ascii")
1812
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001813 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001814
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001815 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001816 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001817 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001818 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001819 else:
1820 raise ValueError(
1821 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001822
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001823 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001824 _raise_current_error()
1825
Alex Gaynor4aa52c32017-11-20 09:04:08 -05001826 return X509._from_raw_x509_ptr(x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001827
1828
1829def dump_certificate(type, cert):
1830 """
1831 Dump a certificate to a buffer
1832
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001833 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1834 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001835 :param cert: The certificate to dump
1836 :return: The buffer with the dumped certificate in
1837 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001838 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001839
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001840 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001841 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001842 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001843 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001844 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001845 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001846 else:
1847 raise ValueError(
1848 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1849 "FILETYPE_TEXT")
1850
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001851 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001852 return _bio_to_string(bio)
1853
1854
Cory Benfield6492f7c2015-10-27 16:57:58 +09001855def dump_publickey(type, pkey):
1856 """
Cory Benfield11c10192015-10-27 17:23:03 +09001857 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001858
Cory Benfield9c590b92015-10-28 14:55:05 +09001859 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001860 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001861 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001862 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001863 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001864 """
1865 bio = _new_mem_buf()
1866 if type == FILETYPE_PEM:
1867 write_bio = _lib.PEM_write_bio_PUBKEY
1868 elif type == FILETYPE_ASN1:
1869 write_bio = _lib.i2d_PUBKEY_bio
1870 else:
1871 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1872
1873 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001874 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001875 _raise_current_error()
1876
1877 return _bio_to_string(bio)
1878
1879
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001880def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1881 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001882 Dump the private key *pkey* into a buffer string encoded with the type
1883 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1884 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001885
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001886 :param type: The file type (one of :const:`FILETYPE_PEM`,
1887 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1888 :param PKey pkey: The PKey to dump
1889 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001890 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001891 the passphrase to use, or a callback for providing the passphrase.
1892
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001893 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001894 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001895 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001896 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001897
Paul Kehrercded9932017-06-29 18:43:42 -05001898 if not isinstance(pkey, PKey):
1899 raise TypeError("pkey must be a PKey")
1900
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001901 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001902 if passphrase is None:
1903 raise TypeError(
1904 "if a value is given for cipher "
1905 "one must also be given for passphrase")
1906 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001907 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001908 raise ValueError("Invalid cipher name")
1909 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001910 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001911
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001912 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001913 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001914 result_code = _lib.PEM_write_bio_PrivateKey(
1915 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001916 helper.callback, helper.callback_args)
1917 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001918 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001919 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001920 elif type == FILETYPE_TEXT:
Paul Kehrercded9932017-06-29 18:43:42 -05001921 if _lib.EVP_PKEY_id(pkey._pkey) != _lib.EVP_PKEY_RSA:
1922 raise TypeError("Only RSA keys are supported for FILETYPE_TEXT")
1923
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001924 rsa = _ffi.gc(
1925 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1926 _lib.RSA_free
1927 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001928 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001929 else:
1930 raise ValueError(
1931 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1932 "FILETYPE_TEXT")
1933
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001934 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001935
1936 return _bio_to_string(bio)
1937
1938
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001939class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001940 """
1941 A certificate revocation.
1942 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001943 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1944 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1945 # OCSP_crl_reason_str. We use the latter, just like the command line
1946 # program.
1947 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001948 b"unspecified",
1949 b"keyCompromise",
1950 b"CACompromise",
1951 b"affiliationChanged",
1952 b"superseded",
1953 b"cessationOfOperation",
1954 b"certificateHold",
1955 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001956 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001957
1958 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001959 revoked = _lib.X509_REVOKED_new()
1960 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001961
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001962 def set_serial(self, hex_str):
1963 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001964 Set the serial number.
1965
1966 The serial number is formatted as a hexadecimal number encoded in
1967 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001968
Dan Sully44e767a2016-06-04 18:05:27 -07001969 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001970
Dan Sully44e767a2016-06-04 18:05:27 -07001971 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001972 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001973 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1974 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001975 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001976 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001977 if not bn_result:
1978 raise ValueError("bad hex string")
1979
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001980 asn1_serial = _ffi.gc(
1981 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1982 _lib.ASN1_INTEGER_free)
1983 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001984
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001985 def get_serial(self):
1986 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001987 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001988
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001989 The serial number is formatted as a hexadecimal number encoded in
1990 ASCII.
1991
1992 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001993 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001994 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001995 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001996
Alex Gaynor67903a62016-06-02 10:37:13 -07001997 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1998 _openssl_assert(asn1_int != _ffi.NULL)
1999 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
2000 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002001 return _bio_to_string(bio)
2002
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002003 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07002004 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2005 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002006 obj = _lib.X509_EXTENSION_get_object(ext)
2007 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002008 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07002009 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002010 break
2011
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002012 def set_reason(self, reason):
2013 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002014 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002015
Dan Sully44e767a2016-06-04 18:05:27 -07002016 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002017
2018 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07002019 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002020
Dan Sully44e767a2016-06-04 18:05:27 -07002021 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002022
2023 .. seealso::
2024
Dan Sully44e767a2016-06-04 18:05:27 -07002025 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002026 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002027 """
2028 if reason is None:
2029 self._delete_reason()
2030 elif not isinstance(reason, bytes):
2031 raise TypeError("reason must be None or a byte string")
2032 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002033 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002034 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
2035
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002036 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002037 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002038 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002039
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002040 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002041 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002042
2043 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002044 add_result = _lib.X509_REVOKED_add1_ext_i2d(
2045 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002046 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002047
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002048 def get_reason(self):
2049 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04002050 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002051
Dan Sully44e767a2016-06-04 18:05:27 -07002052 :return: The reason, or ``None`` if there is none.
2053 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002054
2055 .. seealso::
2056
Dan Sully44e767a2016-06-04 18:05:27 -07002057 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002058 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002059 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002060 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
2061 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002062 obj = _lib.X509_EXTENSION_get_object(ext)
2063 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08002064 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002065
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002066 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002067 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002068 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04002069 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04002070 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002071 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002072
2073 return _bio_to_string(bio)
2074
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002075 def all_reasons(self):
2076 """
2077 Return a list of all the supported reason strings.
2078
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002079 This list is a copy; modifying it does not change the supported reason
2080 strings.
2081
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002082 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07002083 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002084 """
2085 return self._crl_reasons[:]
2086
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002087 def set_rev_date(self, when):
2088 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002089 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002090
Dan Sully44e767a2016-06-04 18:05:27 -07002091 :param bytes when: The timestamp of the revocation,
Paul Kehrerce98ee62017-06-21 06:59:58 -10002092 as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002093 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002094 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002095 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2096 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002097
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002098 def get_rev_date(self):
2099 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02002100 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002101
Paul Kehrerce98ee62017-06-21 06:59:58 -10002102 :return: The timestamp of the revocation, as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07002103 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002104 """
Alex Gaynor67903a62016-06-02 10:37:13 -07002105 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
2106 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002107
2108
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002109class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002110 """
2111 A certificate revocation list.
2112 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002113
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002114 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002115 crl = _lib.X509_CRL_new()
2116 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002117
Paul Kehrer41c10242017-06-29 18:24:17 -05002118 def to_cryptography(self):
2119 """
2120 Export as a ``cryptography`` CRL.
2121
2122 :rtype: ``cryptography.x509.CertificateRevocationList``
2123
2124 .. versionadded:: 17.1.0
2125 """
2126 from cryptography.hazmat.backends.openssl.x509 import (
2127 _CertificateRevocationList
2128 )
2129 backend = _get_backend()
2130 return _CertificateRevocationList(backend, self._crl)
2131
2132 @classmethod
2133 def from_cryptography(cls, crypto_crl):
2134 """
2135 Construct based on a ``cryptography`` *crypto_crl*.
2136
2137 :param crypto_crl: A ``cryptography`` certificate revocation list
2138 :type crypto_crl: ``cryptography.x509.CertificateRevocationList``
2139
2140 :rtype: CRL
2141
2142 .. versionadded:: 17.1.0
2143 """
2144 if not isinstance(crypto_crl, x509.CertificateRevocationList):
2145 raise TypeError("Must be a certificate revocation list")
2146
2147 crl = cls()
2148 crl._crl = crypto_crl._x509_crl
2149 return crl
2150
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002151 def get_revoked(self):
2152 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002153 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002154
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002155 These revocations will be provided by value, not by reference.
2156 That means it's okay to mutate them: it won't affect this CRL.
2157
2158 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002159 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002160 """
2161 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07002162 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002163 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
2164 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04002165 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002166 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002167 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002168 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002169 if results:
2170 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002171
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002172 def add_revoked(self, revoked):
2173 """
2174 Add a revoked (by value not reference) to the CRL structure
2175
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002176 This revocation will be added by value, not by reference. That
2177 means it's okay to mutate it after adding: it won't affect
2178 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002179
Dan Sully44e767a2016-06-04 18:05:27 -07002180 :param Revoked revoked: The new revocation.
2181 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002182 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04002183 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002184 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002185
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002186 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002187 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002188
Dan Sully44e767a2016-06-04 18:05:27 -07002189 def get_issuer(self):
2190 """
2191 Get the CRL's issuer.
2192
2193 .. versionadded:: 16.1.0
2194
2195 :rtype: X509Name
2196 """
2197 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2198 _openssl_assert(_issuer != _ffi.NULL)
2199 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2200 issuer = X509Name.__new__(X509Name)
2201 issuer._name = _issuer
2202 return issuer
2203
2204 def set_version(self, version):
2205 """
2206 Set the CRL version.
2207
2208 .. versionadded:: 16.1.0
2209
2210 :param int version: The version of the CRL.
2211 :return: ``None``
2212 """
2213 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2214
2215 def _set_boundary_time(self, which, when):
2216 return _set_asn1_time(which(self._crl), when)
2217
2218 def set_lastUpdate(self, when):
2219 """
2220 Set when the CRL was last updated.
2221
Paul Kehrerce98ee62017-06-21 06:59:58 -10002222 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002223
2224 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002225
2226 .. versionadded:: 16.1.0
2227
2228 :param bytes when: A timestamp string.
2229 :return: ``None``
2230 """
2231 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2232
2233 def set_nextUpdate(self, when):
2234 """
2235 Set when the CRL will next be udpated.
2236
Paul Kehrerce98ee62017-06-21 06:59:58 -10002237 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002238
2239 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002240
2241 .. versionadded:: 16.1.0
2242
2243 :param bytes when: A timestamp string.
2244 :return: ``None``
2245 """
2246 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2247
2248 def sign(self, issuer_cert, issuer_key, digest):
2249 """
2250 Sign the CRL.
2251
2252 Signing a CRL enables clients to associate the CRL itself with an
2253 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2254 be signed by an issuer.
2255
2256 This method implicitly sets the issuer's name based on the issuer
2257 certificate and private key used to sign the CRL.
2258
2259 .. versionadded:: 16.1.0
2260
2261 :param X509 issuer_cert: The issuer's certificate.
2262 :param PKey issuer_key: The issuer's private key.
2263 :param bytes digest: The digest method to sign the CRL with.
2264 """
2265 digest_obj = _lib.EVP_get_digestbyname(digest)
2266 _openssl_assert(digest_obj != _ffi.NULL)
2267 _lib.X509_CRL_set_issuer_name(
2268 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2269 _lib.X509_CRL_sort(self._crl)
2270 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2271 _openssl_assert(result != 0)
2272
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002273 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002274 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002275 """
Dan Sully44e767a2016-06-04 18:05:27 -07002276 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002277
Dan Sully44e767a2016-06-04 18:05:27 -07002278 :param X509 cert: The certificate used to sign the CRL.
2279 :param PKey key: The key used to sign the CRL.
2280 :param int type: The export format, either :data:`FILETYPE_PEM`,
2281 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002282 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002283 :param bytes digest: The name of the message digest to use (eg
Alex Gaynor239e2d32016-09-11 12:36:35 -04002284 ``b"sha2566"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002285 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002286 """
Dan Sully44e767a2016-06-04 18:05:27 -07002287
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002288 if not isinstance(cert, X509):
2289 raise TypeError("cert must be an X509 instance")
2290 if not isinstance(key, PKey):
2291 raise TypeError("key must be a PKey instance")
2292 if not isinstance(type, int):
2293 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002294
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002295 if digest is _UNSPECIFIED:
Alex Gaynor173e4ba2017-06-30 08:01:12 -07002296 raise TypeError("digest must be provided")
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002297
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002298 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002299 if digest_obj == _ffi.NULL:
2300 raise ValueError("No such digest method")
2301
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002302 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002303 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002304
Alex Gaynora738ed52015-09-05 11:17:10 -04002305 # A scratch time object to give different values to different CRL
2306 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002307 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002308 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002309
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002310 _lib.X509_gmtime_adj(sometime, 0)
2311 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002312
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002313 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2314 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002315
Alex Gaynor5945ea82015-09-05 14:59:06 -04002316 _lib.X509_CRL_set_issuer_name(
2317 self._crl, _lib.X509_get_subject_name(cert._x509)
2318 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002319
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002320 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002321 if not sign_result:
2322 _raise_current_error()
2323
Dominic Chenf05b2122015-10-13 16:32:35 +00002324 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002325
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002326
Alex Gaynor10d30832017-06-29 15:31:39 -07002327CRLType = deprecated(
2328 CRL, __name__,
2329 "CRLType has been deprecated, use CRL instead",
2330 DeprecationWarning
2331)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002332
2333
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002334class PKCS7(object):
2335 def type_is_signed(self):
2336 """
2337 Check if this NID_pkcs7_signed object
2338
2339 :return: True if the PKCS7 is of type signed
2340 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002341 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002342
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002343 def type_is_enveloped(self):
2344 """
2345 Check if this NID_pkcs7_enveloped object
2346
2347 :returns: True if the PKCS7 is of type enveloped
2348 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002349 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002350
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002351 def type_is_signedAndEnveloped(self):
2352 """
2353 Check if this NID_pkcs7_signedAndEnveloped object
2354
2355 :returns: True if the PKCS7 is of type signedAndEnveloped
2356 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002357 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002358
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002359 def type_is_data(self):
2360 """
2361 Check if this NID_pkcs7_data object
2362
2363 :return: True if the PKCS7 is of type data
2364 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002365 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002366
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002367 def get_type_name(self):
2368 """
2369 Returns the type name of the PKCS7 structure
2370
2371 :return: A string with the typename
2372 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002373 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2374 string_type = _lib.OBJ_nid2sn(nid)
2375 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002376
Alex Chanc6077062016-11-18 13:53:39 +00002377
Alex Gaynor10d30832017-06-29 15:31:39 -07002378PKCS7Type = deprecated(
2379 PKCS7, __name__,
2380 "PKCS7Type has been deprecated, use PKCS7 instead",
2381 DeprecationWarning
2382)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002383
2384
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002385class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002386 """
2387 A PKCS #12 archive.
2388 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002389
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002390 def __init__(self):
2391 self._pkey = None
2392 self._cert = None
2393 self._cacerts = None
2394 self._friendlyname = None
2395
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002396 def get_certificate(self):
2397 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002398 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002399
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002400 :return: The certificate, or :py:const:`None` if there is none.
2401 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002402 """
2403 return self._cert
2404
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002405 def set_certificate(self, cert):
2406 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002407 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002408
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002409 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002410 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002411
Dan Sully44e767a2016-06-04 18:05:27 -07002412 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002413 """
2414 if not isinstance(cert, X509):
2415 raise TypeError("cert must be an X509 instance")
2416 self._cert = cert
2417
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002418 def get_privatekey(self):
2419 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002420 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002421
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002422 :return: The private key, or :py:const:`None` if there is none.
2423 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002424 """
2425 return self._pkey
2426
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002427 def set_privatekey(self, pkey):
2428 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002429 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002430
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002431 :param pkey: The new private key, or :py:const:`None` to unset it.
2432 :type pkey: :py:class:`PKey` or :py:const:`None`
2433
Dan Sully44e767a2016-06-04 18:05:27 -07002434 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002435 """
2436 if not isinstance(pkey, PKey):
2437 raise TypeError("pkey must be a PKey instance")
2438 self._pkey = pkey
2439
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002440 def get_ca_certificates(self):
2441 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002442 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002443
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002444 :return: A tuple with the CA certificates in the chain, or
2445 :py:const:`None` if there are none.
2446 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002447 """
2448 if self._cacerts is not None:
2449 return tuple(self._cacerts)
2450
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002451 def set_ca_certificates(self, cacerts):
2452 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002453 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002454
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002455 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2456 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002457 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002458
Dan Sully44e767a2016-06-04 18:05:27 -07002459 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002460 """
2461 if cacerts is None:
2462 self._cacerts = None
2463 else:
2464 cacerts = list(cacerts)
2465 for cert in cacerts:
2466 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002467 raise TypeError(
2468 "iterable must only contain X509 instances"
2469 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002470 self._cacerts = cacerts
2471
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002472 def set_friendlyname(self, name):
2473 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002474 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002475
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002476 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002477 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002478
Dan Sully44e767a2016-06-04 18:05:27 -07002479 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002480 """
2481 if name is None:
2482 self._friendlyname = None
2483 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002484 raise TypeError(
2485 "name must be a byte string or None (not %r)" % (name,)
2486 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002487 self._friendlyname = name
2488
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002489 def get_friendlyname(self):
2490 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002491 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002492
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002493 :returns: The friendly name, or :py:const:`None` if there is none.
2494 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002495 """
2496 return self._friendlyname
2497
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002498 def export(self, passphrase=None, iter=2048, maciter=1):
2499 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002500 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002501
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002502 For more information, see the :c:func:`PKCS12_create` man page.
2503
2504 :param passphrase: The passphrase used to encrypt the structure. Unlike
2505 some other passphrase arguments, this *must* be a string, not a
2506 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002507 :type passphrase: :py:data:`bytes`
2508
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002509 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002510 :type iter: :py:data:`int`
2511
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002512 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002513 :type maciter: :py:data:`int`
2514
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002515 :return: The string representation of the PKCS #12 structure.
2516 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002517 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002518 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002519
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002520 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002521 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002522 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002523 cacerts = _lib.sk_X509_new_null()
2524 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002525 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002526 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002527
2528 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002529 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002530
2531 friendlyname = self._friendlyname
2532 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002533 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002534
2535 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002536 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002537 else:
2538 pkey = self._pkey._pkey
2539
2540 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002541 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002542 else:
2543 cert = self._cert._x509
2544
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002545 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002546 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002547 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2548 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002549 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002550 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002551 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002552 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002553
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002554 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002555 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002556 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002557
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002558
Alex Gaynor10d30832017-06-29 15:31:39 -07002559PKCS12Type = deprecated(
2560 PKCS12, __name__,
2561 "PKCS12Type has been deprecated, use PKCS12 instead",
2562 DeprecationWarning
2563)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002564
2565
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002566class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002567 """
2568 A Netscape SPKI object.
2569 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002570
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002571 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002572 spki = _lib.NETSCAPE_SPKI_new()
2573 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002574
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002575 def sign(self, pkey, digest):
2576 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002577 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002578
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002579 :param pkey: The private key to sign with.
2580 :type pkey: :py:class:`PKey`
2581
2582 :param digest: The message digest to use.
2583 :type digest: :py:class:`bytes`
2584
Dan Sully44e767a2016-06-04 18:05:27 -07002585 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002586 """
2587 if pkey._only_public:
2588 raise ValueError("Key has only public part")
2589
2590 if not pkey._initialized:
2591 raise ValueError("Key is uninitialized")
2592
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002593 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002594 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002595 raise ValueError("No such digest method")
2596
Alex Gaynor5945ea82015-09-05 14:59:06 -04002597 sign_result = _lib.NETSCAPE_SPKI_sign(
2598 self._spki, pkey._pkey, digest_obj
2599 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002600 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002601
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002602 def verify(self, key):
2603 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002604 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002605
Hynek Schlawack01c31672016-12-11 15:14:09 +01002606 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002607
Hynek Schlawack01c31672016-12-11 15:14:09 +01002608 :return: ``True`` if the signature is correct.
2609 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002610
Hynek Schlawack01c31672016-12-11 15:14:09 +01002611 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2612 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002613 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002614 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002615 if answer <= 0:
2616 _raise_current_error()
2617 return True
2618
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002619 def b64_encode(self):
2620 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002621 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002622
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002623 :return: The base64 encoded string.
2624 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002625 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002626 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2627 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002628 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002629 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002630
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002631 def get_pubkey(self):
2632 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002633 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002634
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002635 :return: The public key.
2636 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002637 """
2638 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002639 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002640 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002641 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002642 pkey._only_public = True
2643 return pkey
2644
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002645 def set_pubkey(self, pkey):
2646 """
2647 Set the public key of the certificate
2648
2649 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002650 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002651 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002652 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002653 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002654
2655
Alex Gaynor10d30832017-06-29 15:31:39 -07002656NetscapeSPKIType = deprecated(
2657 NetscapeSPKI, __name__,
2658 "NetscapeSPKIType has been deprecated, use NetscapeSPKI instead",
2659 DeprecationWarning
2660)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002661
2662
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002663class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002664 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002665 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002666 raise ValueError(
2667 "only FILETYPE_PEM key format supports encryption"
2668 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002669 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002670 self._more_args = more_args
2671 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002672 self._problems = []
2673
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002674 @property
2675 def callback(self):
2676 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002677 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002678 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002679 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002680 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002681 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002682 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002683 raise TypeError(
2684 "Last argument must be a byte string or a callable."
2685 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002686
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002687 @property
2688 def callback_args(self):
2689 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002690 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002691 elif isinstance(self._passphrase, bytes):
2692 return self._passphrase
2693 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002694 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002695 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002696 raise TypeError(
2697 "Last argument must be a byte string or a callable."
2698 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002699
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002700 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002701 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002702
2703 # Flush the OpenSSL error queue
2704 try:
2705 _exception_from_error_queue(exceptionType)
2706 except exceptionType:
2707 pass
2708
2709 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002710
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002711 def _read_passphrase(self, buf, size, rwflag, userdata):
2712 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002713 if self._more_args:
2714 result = self._passphrase(size, rwflag, userdata)
2715 else:
2716 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002717 if not isinstance(result, bytes):
2718 raise ValueError("String expected")
2719 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002720 if self._truncate:
2721 result = result[:size]
2722 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002723 raise ValueError(
2724 "passphrase returned by callback is too long"
2725 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002726 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002727 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002728 return len(result)
2729 except Exception as e:
2730 self._problems.append(e)
2731 return 0
2732
2733
Cory Benfield6492f7c2015-10-27 16:57:58 +09002734def load_publickey(type, buffer):
2735 """
Cory Benfield11c10192015-10-27 17:23:03 +09002736 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002737
Cory Benfield9c590b92015-10-28 14:55:05 +09002738 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002739 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002740 :param buffer: The buffer the key is stored in.
2741 :type buffer: A Python string object, either unicode or bytestring.
2742 :return: The PKey object.
2743 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002744 """
2745 if isinstance(buffer, _text_type):
2746 buffer = buffer.encode("ascii")
2747
2748 bio = _new_mem_buf(buffer)
2749
2750 if type == FILETYPE_PEM:
2751 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2752 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2753 elif type == FILETYPE_ASN1:
2754 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2755 else:
2756 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2757
2758 if evp_pkey == _ffi.NULL:
2759 _raise_current_error()
2760
2761 pkey = PKey.__new__(PKey)
2762 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002763 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002764 return pkey
2765
2766
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002767def load_privatekey(type, buffer, passphrase=None):
2768 """
2769 Load a private key from a buffer
2770
2771 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2772 :param buffer: The buffer the key is stored in
2773 :param passphrase: (optional) if encrypted PEM format, this can be
2774 either the passphrase to use, or a callback for
2775 providing the passphrase.
2776
2777 :return: The PKey object
2778 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002779 if isinstance(buffer, _text_type):
2780 buffer = buffer.encode("ascii")
2781
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002782 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002783
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002784 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002785 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002786 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2787 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002788 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002789 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002790 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002791 else:
2792 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2793
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002794 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002795 _raise_current_error()
2796
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002797 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002798 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002799 return pkey
2800
2801
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002802def dump_certificate_request(type, req):
2803 """
2804 Dump a certificate request to a buffer
2805
2806 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2807 :param req: The certificate request to dump
2808 :return: The buffer with the dumped certificate request in
2809 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002810 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002811
2812 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002813 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002814 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002815 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002816 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002817 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002818 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002819 raise ValueError(
2820 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2821 "FILETYPE_TEXT"
2822 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002823
Alex Gaynor09a386e2016-07-03 09:32:44 -04002824 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002825
2826 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002827
2828
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002829def load_certificate_request(type, buffer):
2830 """
2831 Load a certificate request from a buffer
2832
2833 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2834 :param buffer: The buffer the certificate request is stored in
2835 :return: The X509Req object
2836 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002837 if isinstance(buffer, _text_type):
2838 buffer = buffer.encode("ascii")
2839
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002840 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002841
2842 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002843 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002844 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002845 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002846 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002847 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002848
Alex Gaynoradd5b072016-06-04 21:04:00 -07002849 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002850
2851 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002852 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002853 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002854
2855
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002856def sign(pkey, data, digest):
2857 """
2858 Sign data with a digest
2859
2860 :param pkey: Pkey to sign with
2861 :param data: data to be signed
2862 :param digest: message digest to use
2863 :return: signature
2864 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002865 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002866
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002867 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002868 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002869 raise ValueError("No such digest method")
2870
Alex Gaynor67903a62016-06-02 10:37:13 -07002871 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002872 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002873
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002874 _lib.EVP_SignInit(md_ctx, digest_obj)
2875 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002876
Paul Kehrer59d26252017-07-20 10:45:54 +02002877 length = _lib.EVP_PKEY_size(pkey._pkey)
2878 _openssl_assert(length > 0)
2879 signature_buffer = _ffi.new("unsigned char[]", length)
2880 signature_length = _ffi.new("unsigned int *")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002881 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002882 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002883 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002885 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002886
2887
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002888def verify(cert, signature, data, digest):
2889 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002890 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002891
2892 :param cert: signing certificate (X509 object)
2893 :param signature: signature returned by sign function
2894 :param data: data to be verified
2895 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002896 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002897 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002898 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002899
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002900 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002901 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002902 raise ValueError("No such digest method")
2903
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002904 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002905 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002906 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002907
Alex Gaynor67903a62016-06-02 10:37:13 -07002908 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002909 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002910
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002911 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2912 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002913 verify_result = _lib.EVP_VerifyFinal(
2914 md_ctx, signature, len(signature), pkey
2915 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002916
2917 if verify_result != 1:
2918 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002919
2920
Dominic Chenf05b2122015-10-13 16:32:35 +00002921def dump_crl(type, crl):
2922 """
2923 Dump a certificate revocation list to a buffer.
2924
2925 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2926 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002927 :param CRL crl: The CRL to dump.
2928
Dominic Chenf05b2122015-10-13 16:32:35 +00002929 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002930 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002931 """
2932 bio = _new_mem_buf()
2933
2934 if type == FILETYPE_PEM:
2935 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2936 elif type == FILETYPE_ASN1:
2937 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2938 elif type == FILETYPE_TEXT:
2939 ret = _lib.X509_CRL_print(bio, crl._crl)
2940 else:
2941 raise ValueError(
2942 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2943 "FILETYPE_TEXT")
2944
2945 assert ret == 1
2946 return _bio_to_string(bio)
2947
2948
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002949def load_crl(type, buffer):
2950 """
2951 Load a certificate revocation list from a buffer
2952
2953 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2954 :param buffer: The buffer the CRL is stored in
2955
2956 :return: The PKey object
2957 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002958 if isinstance(buffer, _text_type):
2959 buffer = buffer.encode("ascii")
2960
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002961 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002962
2963 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002964 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002965 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002966 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002967 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002968 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2969
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002970 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002971 _raise_current_error()
2972
2973 result = CRL.__new__(CRL)
Jeremy Cline9e15eca2017-09-07 20:11:08 -04002974 result._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002975 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002976
2977
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002978def load_pkcs7_data(type, buffer):
2979 """
2980 Load pkcs7 data from a buffer
2981
2982 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2983 :param buffer: The buffer with the pkcs7 data.
2984 :return: The PKCS7 object
2985 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002986 if isinstance(buffer, _text_type):
2987 buffer = buffer.encode("ascii")
2988
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002989 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002990
2991 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002992 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002993 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002994 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002995 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002996 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2997
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002998 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002999 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003000
3001 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003002 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08003003 return pypkcs7
3004
3005
Stephen Holsapple38482622014-04-05 20:29:34 -07003006def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003007 """
3008 Load a PKCS12 object from a buffer
3009
3010 :param buffer: The buffer the certificate is stored in
3011 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
3012 :returns: The PKCS12 object
3013 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04003014 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00003015
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05003016 if isinstance(buffer, _text_type):
3017 buffer = buffer.encode("ascii")
3018
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08003019 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003020
Stephen Holsapple38482622014-04-05 20:29:34 -07003021 # Use null passphrase if passphrase is None or empty string. With PKCS#12
3022 # password based encryption no password and a zero length password are two
3023 # different things, but OpenSSL implementation will try both to figure out
3024 # which one works.
3025 if not passphrase:
3026 passphrase = _ffi.NULL
3027
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003028 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
3029 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003030 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003031 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003032
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003033 pkey = _ffi.new("EVP_PKEY**")
3034 cert = _ffi.new("X509**")
3035 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003036
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003037 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003038 if not parse_result:
3039 _raise_current_error()
3040
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003041 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08003042
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003043 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
3044 # queue for no particular reason. This error isn't interesting to anyone
3045 # outside this function. It's not even interesting to us. Get rid of it.
3046 try:
3047 _raise_current_error()
3048 except Error:
3049 pass
3050
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003051 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003052 pykey = None
3053 else:
3054 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003055 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003056
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003057 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003058 pycert = None
3059 friendlyname = None
3060 else:
Paul Kehrere7381862017-11-30 20:55:25 +08003061 pycert = X509._from_raw_x509_ptr(cert[0])
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003062
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003063 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04003064 friendlyname_buffer = _lib.X509_alias_get0(
3065 cert[0], friendlyname_length
3066 )
3067 friendlyname = _ffi.buffer(
3068 friendlyname_buffer, friendlyname_length[0]
3069 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003070 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003071 friendlyname = None
3072
3073 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05003074 for i in range(_lib.sk_X509_num(cacerts)):
Paul Kehrere7381862017-11-30 20:55:25 +08003075 x509 = _lib.sk_X509_value(cacerts, i)
3076 pycacert = X509._from_raw_x509_ptr(x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08003077 pycacerts.append(pycacert)
3078 if not pycacerts:
3079 pycacerts = None
3080
3081 pkcs12 = PKCS12.__new__(PKCS12)
3082 pkcs12._pkey = pykey
3083 pkcs12._cert = pycert
3084 pkcs12._cacerts = pycacerts
3085 pkcs12._friendlyname = friendlyname
3086 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05003087
3088
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05003089# There are no direct unit tests for this initialization. It is tested
3090# indirectly since it is necessary for functions like dump_privatekey when
3091# using encryption.
3092#
3093# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
3094# and some other similar tests may fail without this (though they may not if
3095# the Python runtime has already done some initialization of the underlying
3096# OpenSSL library (and is linked against the same one that cryptography is
3097# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05003098_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05003099
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05003100# This is similar but exercised mainly by exception_from_error_queue. It calls
3101# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
3102_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003103
3104
D.S. Ljungmark349e1362014-05-31 18:40:38 +02003105# Set the default string mask to match OpenSSL upstream (since 2005) and
3106# RFC5280 recommendations.
3107_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')