blob: 869bbb415b972afaee00800c286d2e81f8f873fe [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__
Jean-Paul Calderone60432792015-04-13 12:26:07 -04006from warnings import warn as _warn
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05007
8from six import (
9 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -040010 text_type as _text_type,
11 PY3 as _PY3)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080012
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050013from OpenSSL._util import (
14 ffi as _ffi,
15 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050016 exception_from_error_queue as _exception_from_error_queue,
17 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040018 native as _native,
19 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070021 make_assert as _make_assert,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040022)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080023
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050024FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
25FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080026
27# TODO This was an API mistake. OpenSSL has no such constant.
28FILETYPE_TEXT = 2 ** 16 - 1
29
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050030TYPE_RSA = _lib.EVP_PKEY_RSA
31TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080032
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080033
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050034class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050035 """
36 An error occurred in an `OpenSSL.crypto` API.
37 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050038
39
40_raise_current_error = partial(_exception_from_error_queue, Error)
Alex Gaynor67903a62016-06-02 10:37:13 -070041_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050042
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070043
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050044def _untested_error(where):
45 """
46 An OpenSSL API failed somehow. Additionally, the failure which was
47 encountered isn't one that's exercised by the test suite so future behavior
48 of pyOpenSSL is now somewhat less predictable.
49 """
50 raise RuntimeError("Unknown %s failure" % (where,))
51
52
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050053def _new_mem_buf(buffer=None):
54 """
55 Allocate a new OpenSSL memory BIO.
56
57 Arrange for the garbage collector to clean it up automatically.
58
59 :param buffer: None or some bytes to use to put into the BIO so that they
60 can be read out.
61 """
62 if buffer is None:
63 bio = _lib.BIO_new(_lib.BIO_s_mem())
64 free = _lib.BIO_free
65 else:
66 data = _ffi.new("char[]", buffer)
67 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040068
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050069 # Keep the memory alive as long as the bio is alive!
70 def free(bio, ref=data):
71 return _lib.BIO_free(bio)
72
Alex Gaynorfb8a2a12016-06-04 18:26:26 -070073 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050074
75 bio = _ffi.gc(bio, free)
76 return bio
77
78
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080079def _bio_to_string(bio):
80 """
81 Copy the contents of an OpenSSL BIO object into a Python byte string.
82 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050083 result_buffer = _ffi.new('char**')
84 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
85 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080086
87
Jean-Paul Calderone57122982013-02-21 08:47:05 -080088def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050089 """
90 The the time value of an ASN1 time object.
91
92 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
93 castable to that type) which will have its value set.
94 @param when: A string representation of the desired time value.
95
96 @raise TypeError: If C{when} is not a L{bytes} string.
97 @raise ValueError: If C{when} does not represent a time in the required
98 format.
99 @raise RuntimeError: If the time value cannot be set for some other
100 (unspecified) reason.
101 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800102 if not isinstance(when, bytes):
103 raise TypeError("when must be a byte string")
104
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500105 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
106 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800107 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500108 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
109 _lib.ASN1_STRING_set(dummy, when, len(when))
110 check_result = _lib.ASN1_GENERALIZEDTIME_check(
111 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800112 if not check_result:
113 raise ValueError("Invalid string")
114 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500115 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800116
Alex Gaynor510293e2016-06-02 12:07:59 -0700117
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800118def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500119 """
120 Retrieve the time value of an ASN1 time object.
121
122 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
123 that type) from which the time value will be retrieved.
124
125 @return: The time value from C{timestamp} as a L{bytes} string in a certain
126 format. Or C{None} if the object contains no time value.
127 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
129 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800130 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400131 elif (
132 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
133 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800135 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500136 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
137 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
138 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500139 # This may happen:
140 # - if timestamp was not an ASN1_TIME
141 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
142 # - if a copy of the time data from timestamp cannot be made for
143 # the newly allocated ASN1_GENERALIZEDTIME
144 #
145 # These are difficult to test. cffi enforces the ASN1_TIME type.
146 # Memory allocation failures are a pain to trigger
147 # deterministically.
148 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800149 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500150 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800151 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152 string_data = _lib.ASN1_STRING_data(string_timestamp)
153 string_result = _ffi.string(string_data)
154 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800155 return string_result
156
157
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800158class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200159 """
160 A class representing an DSA or RSA public key or key pair.
161 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800162 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800163 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800164
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800165 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500166 pkey = _lib.EVP_PKEY_new()
167 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800168 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800169
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800170 def generate_key(self, type, bits):
171 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700172 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800173
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200174 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800175
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200176 :param type: The key type.
177 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
178 :param bits: The number of bits.
179 :type bits: :py:data:`int` ``>= 0``
180 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
181 of the appropriate type.
182 :raises ValueError: If the number of bits isn't an integer of
183 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700184 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800185 """
186 if not isinstance(type, int):
187 raise TypeError("type must be an integer")
188
189 if not isinstance(bits, int):
190 raise TypeError("bits must be an integer")
191
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800192 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500193 exponent = _lib.BN_new()
194 exponent = _ffi.gc(exponent, _lib.BN_free)
195 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800196
197 if type == TYPE_RSA:
198 if bits <= 0:
199 raise ValueError("Invalid number of bits")
200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500203 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400204 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800205
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500206 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400207 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800208
209 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400210 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700211 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400212
213 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400214 res = _lib.DSA_generate_parameters_ex(
215 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
216 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700217 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400218
219 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
220 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800221 else:
222 raise Error("No such key type")
223
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800224 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800225
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800226 def check(self):
227 """
228 Check the consistency of an RSA private key.
229
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200230 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
231
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800232 :return: True if key is consistent.
233 :raise Error: if the key is inconsistent.
234 :raise TypeError: if the key is of a type which cannot be checked.
235 Only RSA keys can currently be checked.
236 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800237 if self._only_public:
238 raise TypeError("public key only")
239
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100240 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800241 raise TypeError("key type unsupported")
242
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500243 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
244 rsa = _ffi.gc(rsa, _lib.RSA_free)
245 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800246 if result:
247 return True
248 _raise_current_error()
249
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800250 def type(self):
251 """
252 Returns the type of the key
253
254 :return: The type of the key.
255 """
Alex Gaynorc84567b2016-03-16 07:45:09 -0400256 return _lib.Cryptography_EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800257
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800258 def bits(self):
259 """
260 Returns the number of bits of the key
261
262 :return: The number of bits of the key.
263 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500264 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800265PKeyType = PKey
266
267
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400268class _EllipticCurve(object):
269 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400270 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400271
272 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
273 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
274 instances each of which represents one curve supported by the system.
275 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400276 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400277 _curves = None
278
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400279 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400280 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400281 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400282 """
283 Implement cooperation with the right-hand side argument of ``!=``.
284
285 Python 3 seems to have dropped this cooperation in this very narrow
286 circumstance.
287 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400288 if isinstance(other, _EllipticCurve):
289 return super(_EllipticCurve, self).__ne__(other)
290 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400291
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400292 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400293 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400294 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400295 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400296
297 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400298
299 :return: A :py:type:`set` of ``cls`` instances giving the names of the
300 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400301 """
302 if lib.Cryptography_HAS_EC:
303 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
304 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
Alex Gaynor5945ea82015-09-05 14:59:06 -0400305 # The return value on this call should be num_curves again. We
306 # could check it to make sure but if it *isn't* then.. what could
307 # we do? Abort the whole process, I suppose...? -exarkun
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400308 lib.EC_get_builtin_curves(builtin_curves, num_curves)
309 return set(
310 cls.from_nid(lib, c.nid)
311 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400312 return set()
313
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400314 @classmethod
315 def _get_elliptic_curves(cls, lib):
316 """
317 Get, cache, and return the curves supported by OpenSSL.
318
319 :param lib: The OpenSSL library binding object.
320
321 :return: A :py:type:`set` of ``cls`` instances giving the names of the
322 elliptic curves the underlying library supports.
323 """
324 if cls._curves is None:
325 cls._curves = cls._load_elliptic_curves(lib)
326 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400327
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400328 @classmethod
329 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400330 """
331 Instantiate a new :py:class:`_EllipticCurve` associated with the given
332 OpenSSL NID.
333
334 :param lib: The OpenSSL library binding object.
335
336 :param nid: The OpenSSL NID the resulting curve object will represent.
337 This must be a curve NID (and not, for example, a hash NID) or
338 subsequent operations will fail in unpredictable ways.
339 :type nid: :py:class:`int`
340
341 :return: The curve object.
342 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400343 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
344
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400345 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400346 """
347 :param _lib: The :py:mod:`cryptography` binding instance used to
348 interface with OpenSSL.
349
350 :param _nid: The OpenSSL NID identifying the curve this object
351 represents.
352 :type _nid: :py:class:`int`
353
354 :param name: The OpenSSL short name identifying the curve this object
355 represents.
356 :type name: :py:class:`unicode`
357 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400358 self._lib = lib
359 self._nid = nid
360 self.name = name
361
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400362 def __repr__(self):
363 return "<Curve %r>" % (self.name,)
364
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400365 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400366 """
367 Create a new OpenSSL EC_KEY structure initialized to use this curve.
368
369 The structure is automatically garbage collected when the Python object
370 is garbage collected.
371 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400372 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
373 return _ffi.gc(key, _lib.EC_KEY_free)
374
375
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400376def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400377 """
378 Return a set of objects representing the elliptic curves supported in the
379 OpenSSL build in use.
380
381 The curve objects have a :py:class:`unicode` ``name`` attribute by which
382 they identify themselves.
383
384 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400385 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
386 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400387 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400388 return _EllipticCurve._get_elliptic_curves(_lib)
389
390
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400391def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400392 """
393 Return a single curve object selected by name.
394
395 See :py:func:`get_elliptic_curves` for information about curve objects.
396
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400397 :param name: The OpenSSL short name identifying the curve object to
398 retrieve.
399 :type name: :py:class:`unicode`
400
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400401 If the named curve is not supported then :py:class:`ValueError` is raised.
402 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400403 for curve in get_elliptic_curves():
404 if curve.name == name:
405 return curve
406 raise ValueError("unknown curve name", name)
407
408
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800409class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200410 """
411 An X.509 Distinguished Name.
412
413 :ivar countryName: The country of the entity.
414 :ivar C: Alias for :py:attr:`countryName`.
415
416 :ivar stateOrProvinceName: The state or province of the entity.
417 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
418
419 :ivar localityName: The locality of the entity.
420 :ivar L: Alias for :py:attr:`localityName`.
421
422 :ivar organizationName: The organization name of the entity.
423 :ivar O: Alias for :py:attr:`organizationName`.
424
425 :ivar organizationalUnitName: The organizational unit of the entity.
426 :ivar OU: Alias for :py:attr:`organizationalUnitName`
427
428 :ivar commonName: The common name of the entity.
429 :ivar CN: Alias for :py:attr:`commonName`.
430
431 :ivar emailAddress: The e-mail address of the entity.
432 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400433
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800434 def __init__(self, name):
435 """
436 Create a new X509Name, copying the given X509Name instance.
437
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200438 :param name: The name to copy.
439 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800440 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500441 name = _lib.X509_NAME_dup(name._name)
442 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800443
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800444 def __setattr__(self, name, value):
445 if name.startswith('_'):
446 return super(X509Name, self).__setattr__(name, value)
447
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800448 # Note: we really do not want str subclasses here, so we do not use
449 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800450 if type(name) is not str:
451 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400452 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800453
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500454 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500455 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800456 try:
457 _raise_current_error()
458 except Error:
459 pass
460 raise AttributeError("No such attribute")
461
462 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500463 for i in range(_lib.X509_NAME_entry_count(self._name)):
464 ent = _lib.X509_NAME_get_entry(self._name, i)
465 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
466 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800467 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500468 ent = _lib.X509_NAME_delete_entry(self._name, i)
469 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800470 break
471
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500472 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800473 value = value.encode('utf-8')
474
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500475 add_result = _lib.X509_NAME_add_entry_by_NID(
476 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800477 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500478 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800479
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800480 def __getattr__(self, name):
481 """
482 Find attribute. An X509Name object has the following attributes:
483 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400484 organization (alias O), organizationalUnit (alias OU), commonName
485 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800486 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500487 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500488 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800489 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
490 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
491 # push something onto the error queue. If we don't clean that up
492 # now, someone else will bump into it later and be quite confused.
493 # See lp#314814.
494 try:
495 _raise_current_error()
496 except Error:
497 pass
498 return super(X509Name, self).__getattr__(name)
499
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500500 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800501 if entry_index == -1:
502 return None
503
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500504 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
505 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800506
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500507 result_buffer = _ffi.new("unsigned char**")
508 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400509 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800510
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700511 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400512 result = _ffi.buffer(
513 result_buffer[0], data_length
514 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700515 finally:
516 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500517 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800518 return result
519
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500520 def _cmp(op):
521 def f(self, other):
522 if not isinstance(other, X509Name):
523 return NotImplemented
524 result = _lib.X509_NAME_cmp(self._name, other._name)
525 return op(result, 0)
526 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800527
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500528 __eq__ = _cmp(__eq__)
529 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800530
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500531 __lt__ = _cmp(__lt__)
532 __le__ = _cmp(__le__)
533
534 __gt__ = _cmp(__gt__)
535 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800536
537 def __repr__(self):
538 """
539 String representation of an X509Name
540 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400541 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500542 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800543 self._name, result_buffer, len(result_buffer))
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700544 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800545
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500546 return "<X509Name object '%s'>" % (
547 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800548
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800549 def hash(self):
550 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200551 Return an integer representation of the first four bytes of the
552 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800553
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200554 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
555
556 :return: The (integer) hash of this name.
557 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800558 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500559 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800560
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800561 def der(self):
562 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200563 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800564
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200565 :return: The DER encoded form of this name.
566 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800567 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500568 result_buffer = _ffi.new('unsigned char**')
569 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400570 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800571
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500572 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
573 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800574 return string_result
575
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800576 def get_components(self):
577 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200578 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800579
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200580 :return: The components of this name.
581 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800582 """
583 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500584 for i in range(_lib.X509_NAME_entry_count(self._name)):
585 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800586
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500587 fname = _lib.X509_NAME_ENTRY_get_object(ent)
588 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500590 nid = _lib.OBJ_obj2nid(fname)
591 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800592
593 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400594 _ffi.string(name),
595 _ffi.string(
596 _lib.ASN1_STRING_data(fval),
597 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800598
599 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200600
601
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800602X509NameType = X509Name
603
604
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800605class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200606 """
607 An X.509 v3 certificate extension.
608 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400609
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800610 def __init__(self, type_name, critical, value, subject=None, issuer=None):
611 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200612 Initializes an X509 extension.
613
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100614 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400615 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800616
Alex Gaynor5945ea82015-09-05 14:59:06 -0400617 :param bool critical: A flag indicating whether this is a critical
618 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800619
620 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200621 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800622
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200623 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800624 :type subject: :py:class:`X509`
625
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200626 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800627 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100628
629 .. _extension: https://openssl.org/docs/manmaster/apps/
630 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800631 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800633
Alex Gaynor5945ea82015-09-05 14:59:06 -0400634 # A context is necessary for any extension which uses the r2i
635 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
636 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500637 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800638
639 # We have no configuration database - but perhaps we should (some
640 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500641 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800642
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800643 # Initialize the subject and issuer, if appropriate. ctx is a local,
644 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400645 # any references, so no need to mess with reference counts or
646 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800647 if issuer is not None:
648 if not isinstance(issuer, X509):
649 raise TypeError("issuer must be an X509 instance")
650 ctx.issuer_cert = issuer._x509
651 if subject is not None:
652 if not isinstance(subject, X509):
653 raise TypeError("subject must be an X509 instance")
654 ctx.subject_cert = subject._x509
655
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800656 if critical:
657 # There are other OpenSSL APIs which would let us pass in critical
658 # separately, but they're harder to use, and since value is already
659 # a pile of crappy junk smuggling a ton of utterly important
660 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400661 # with strings? (However, X509V3_EXT_i2d in particular seems like
662 # it would be a better API to invoke. I do not know where to get
663 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500664 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800665
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500666 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
667 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800668 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500669 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800670
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400671 @property
672 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400673 return _lib.OBJ_obj2nid(
674 _lib.X509_EXTENSION_get_object(self._extension)
675 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400676
677 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500678 _lib.GEN_EMAIL: "email",
679 _lib.GEN_DNS: "DNS",
680 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400681 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400682
683 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500684 method = _lib.X509V3_EXT_get(self._extension)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700685 _openssl_assert(method != _ffi.NULL)
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400686 ext_data = _lib.X509_EXTENSION_get_data(self._extension)
687 payload = ext_data.data
688 length = ext_data.length
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400689
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500690 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400691 payloadptr[0] = payload
692
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500693 if method.it != _ffi.NULL:
694 ptr = _lib.ASN1_ITEM_ptr(method.it)
695 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
696 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400697 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500698 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400699 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500700 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400701
Paul Kehrerb7d79502015-05-04 07:43:51 -0500702 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400703 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500704 for i in range(_lib.sk_GENERAL_NAME_num(names)):
705 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400706 try:
707 label = self._prefixes[name.type]
708 except KeyError:
709 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500710 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500711 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400712 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500713 value = _native(
714 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
715 parts.append(label + ":" + value)
716 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400717
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800718 def __str__(self):
719 """
720 :return: a nice text representation of the extension
721 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500722 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400723 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800724
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400725 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400727 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800728
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500729 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800730
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800731 def get_critical(self):
732 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200733 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800734
735 :return: The critical field.
736 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500737 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800738
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800739 def get_short_name(self):
740 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200741 Returns the short type name of this X.509 extension.
742
743 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800744
745 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200746 :rtype: :py:data:`bytes`
747
748 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800749 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500750 obj = _lib.X509_EXTENSION_get_object(self._extension)
751 nid = _lib.OBJ_obj2nid(obj)
752 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800753
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800754 def get_data(self):
755 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200756 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800757
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200758 :return: The ASN.1 encoded data of this X509 extension.
759 :rtype: :py:data:`bytes`
760
761 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800762 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500763 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
764 string_result = _ffi.cast('ASN1_STRING*', octet_result)
765 char_result = _lib.ASN1_STRING_data(string_result)
766 result_length = _lib.ASN1_STRING_length(string_result)
767 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800768
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200769
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800770X509ExtensionType = X509Extension
771
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800772
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800773class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200774 """
775 An X.509 certificate signing requests.
776 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400777
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800778 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500779 req = _lib.X509_REQ_new()
780 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800781
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800782 def set_pubkey(self, pkey):
783 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200784 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800785
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200786 :param pkey: The public key to use.
787 :type pkey: :py:class:`PKey`
788
Dan Sully44e767a2016-06-04 18:05:27 -0700789 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800790 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500791 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400792 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800793
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800794 def get_pubkey(self):
795 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200796 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800797
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200798 :return: The public key.
799 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800800 """
801 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500802 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700803 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500804 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800805 pkey._only_public = True
806 return pkey
807
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800808 def set_version(self, version):
809 """
810 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
811 request.
812
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200813 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700814 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800815 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500816 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400817 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800818
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800819 def get_version(self):
820 """
821 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
822 request.
823
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200824 :return: The value of the version subfield.
825 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800826 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500827 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800828
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800829 def get_subject(self):
830 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200831 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800832
Cory Benfield881dc8d2015-12-09 08:25:14 +0000833 This creates a new :class:`X509Name` that wraps the underlying subject
834 name field on the certificate signing request. Modifying it will modify
835 the underlying signing request, and will have the effect of modifying
836 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200837
838 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000839 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800840 """
841 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500842 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700843 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800844
845 # The name is owned by the X509Req structure. As long as the X509Name
846 # Python object is alive, keep the X509Req Python object alive.
847 name._owner = self
848
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800849 return name
850
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800851 def add_extensions(self, extensions):
852 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200853 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800854
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200855 :param extensions: The X.509 extensions to add.
856 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700857 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800858 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500859 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700860 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800861
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500862 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800863
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800864 for ext in extensions:
865 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800866 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800867
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800868 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500869 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500871 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400872 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800873
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800874 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800875 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200876 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800877
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200878 :return: The X.509 extensions in this request.
879 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
880
881 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800882 """
883 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500884 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500885 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800886 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500887 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800888 exts.append(ext)
889 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800890
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800891 def sign(self, pkey, digest):
892 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700893 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800894
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200895 :param pkey: The key pair to sign with.
896 :type pkey: :py:class:`PKey`
897 :param digest: The name of the message digest to use for the signature,
898 e.g. :py:data:`b"sha1"`.
899 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -0700900 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800901 """
902 if pkey._only_public:
903 raise ValueError("Key has only public part")
904
905 if not pkey._initialized:
906 raise ValueError("Key is uninitialized")
907
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500908 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500909 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800910 raise ValueError("No such digest method")
911
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500912 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400913 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800914
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800915 def verify(self, pkey):
916 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200917 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800918
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200919 :param key: A public key.
920 :type key: :py:class:`PKey`
921 :return: :py:data:`True` if the signature is correct.
922 :rtype: :py:class:`bool`
923 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800924 problem verifying the signature.
925 """
926 if not isinstance(pkey, PKey):
927 raise TypeError("pkey must be a PKey instance")
928
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500929 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800930 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500931 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800932
933 return result
934
935
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800936X509ReqType = X509Req
937
938
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800939class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200940 """
941 An X.509 certificate.
942 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400943
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800944 def __init__(self):
945 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500946 x509 = _lib.X509_new()
947 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800948
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800949 def set_version(self, version):
950 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200951 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800952
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200953 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800954 :type version: :py:class:`int`
955
Dan Sully44e767a2016-06-04 18:05:27 -0700956 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800957 """
958 if not isinstance(version, int):
959 raise TypeError("version must be an integer")
960
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500961 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800962
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800963 def get_version(self):
964 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200965 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800966
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200967 :return: The version number of the certificate.
968 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800969 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500970 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800971
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800972 def get_pubkey(self):
973 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200974 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800975
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200976 :return: The public key.
977 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800978 """
979 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500980 pkey._pkey = _lib.X509_get_pubkey(self._x509)
981 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800982 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500983 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800984 pkey._only_public = True
985 return pkey
986
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800987 def set_pubkey(self, pkey):
988 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200989 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800990
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200991 :param pkey: The public key.
992 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800993
Laurens Van Houtven33fcf122015-04-23 10:50:08 -0700994 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800995 """
996 if not isinstance(pkey, PKey):
997 raise TypeError("pkey must be a PKey instance")
998
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500999 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001000 if not set_result:
1001 _raise_current_error()
1002
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001003 def sign(self, pkey, digest):
1004 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001005 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001006
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001007 :param pkey: The key to sign with.
1008 :type pkey: :py:class:`PKey`
1009
1010 :param digest: The name of the message digest to use.
1011 :type digest: :py:class:`bytes`
1012
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001013 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001014 """
1015 if not isinstance(pkey, PKey):
1016 raise TypeError("pkey must be a PKey instance")
1017
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001018 if pkey._only_public:
1019 raise ValueError("Key only has public part")
1020
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001021 if not pkey._initialized:
1022 raise ValueError("Key is uninitialized")
1023
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001024 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001025 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001026 raise ValueError("No such digest method")
1027
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001028 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001029 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001030
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001031 def get_signature_algorithm(self):
1032 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001033 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001034
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001035 :return: The name of the algorithm.
1036 :rtype: :py:class:`bytes`
1037
1038 :raises ValueError: If the signature algorithm is undefined.
1039
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001040 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001041 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001042 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1043 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001044 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001045 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001046 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001047
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001048 def digest(self, digest_name):
1049 """
1050 Return the digest of the X509 object.
1051
1052 :param digest_name: The name of the digest algorithm to use.
1053 :type digest_name: :py:class:`bytes`
1054
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001055 :return: The digest of the object, formatted as
1056 :py:const:`b":"`-delimited hex pairs.
1057 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001058 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001059 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001060 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001061 raise ValueError("No such digest method")
1062
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001063 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1064 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001065 result_length[0] = len(result_buffer)
1066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001067 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001068 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001069 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001070
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001071 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001072 b16encode(ch).upper() for ch
1073 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001074
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001075 def subject_name_hash(self):
1076 """
1077 Return the hash of the X509 subject.
1078
1079 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001080 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001081 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001083
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001084 def set_serial_number(self, serial):
1085 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001086 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001087
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001088 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001089 :type serial: :py:class:`int`
1090
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001091 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001092 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001093 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001094 raise TypeError("serial must be an integer")
1095
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001096 hex_serial = hex(serial)[2:]
1097 if not isinstance(hex_serial, bytes):
1098 hex_serial = hex_serial.encode('ascii')
1099
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001100 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001101
1102 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001103 # it. If bignum is still NULL after this call, then the return value
1104 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001105 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 if bignum_serial[0] == _ffi.NULL:
1108 set_result = _lib.ASN1_INTEGER_set(
1109 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001110 if set_result:
1111 # TODO Not tested
1112 _raise_current_error()
1113 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001114 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1115 _lib.BN_free(bignum_serial[0])
1116 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001117 # TODO Not tested
1118 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001119 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1120 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001121 if not set_result:
1122 # TODO Not tested
1123 _raise_current_error()
1124
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001125 def get_serial_number(self):
1126 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001127 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001128
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001129 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001130 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001131 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001132 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1133 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001134 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001135 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001136 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001137 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001138 serial = int(hexstring_serial, 16)
1139 return serial
1140 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001142 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001143 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001144
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001145 def gmtime_adj_notAfter(self, amount):
1146 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001147 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001148
Dan Sully44e767a2016-06-04 18:05:27 -07001149 :param int amount: The number of seconds by which to adjust the
1150 timestamp.
1151 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001152 """
1153 if not isinstance(amount, int):
1154 raise TypeError("amount must be an integer")
1155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 notAfter = _lib.X509_get_notAfter(self._x509)
1157 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001158
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001159 def gmtime_adj_notBefore(self, amount):
1160 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001161 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001162
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001163 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001164 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001165 """
1166 if not isinstance(amount, int):
1167 raise TypeError("amount must be an integer")
1168
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 notBefore = _lib.X509_get_notBefore(self._x509)
1170 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001171
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001172 def has_expired(self):
1173 """
1174 Check whether the certificate has expired.
1175
Dan Sully44e767a2016-06-04 18:05:27 -07001176 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1177 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001178 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001179 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001180 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001181
Paul Kehrerfde45c92016-01-21 12:57:37 -06001182 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001183
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001184 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001185 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001186
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001187 def get_notBefore(self):
1188 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001189 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001190
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001191 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001192
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001193 YYYYMMDDhhmmssZ
1194 YYYYMMDDhhmmss+hhmm
1195 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001196
Dan Sully44e767a2016-06-04 18:05:27 -07001197 :return: A timestamp string, or ``None`` if there is none.
1198 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001199 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001200 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001201
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001202 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001203 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001204
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001205 def set_notBefore(self, when):
1206 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001207 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001208
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001209 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001210
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001211 YYYYMMDDhhmmssZ
1212 YYYYMMDDhhmmss+hhmm
1213 YYYYMMDDhhmmss-hhmm
1214
Dan Sully44e767a2016-06-04 18:05:27 -07001215 :param bytes when: A timestamp string.
1216 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001217 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001218 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001219
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001220 def get_notAfter(self):
1221 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001222 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001223
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001224 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001225
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001226 YYYYMMDDhhmmssZ
1227 YYYYMMDDhhmmss+hhmm
1228 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001229
Dan Sully44e767a2016-06-04 18:05:27 -07001230 :return: A timestamp string, or ``None`` if there is none.
1231 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001232 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001233 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001234
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001235 def set_notAfter(self, when):
1236 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001237 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001238
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001239 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001240
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001241 YYYYMMDDhhmmssZ
1242 YYYYMMDDhhmmss+hhmm
1243 YYYYMMDDhhmmss-hhmm
1244
Dan Sully44e767a2016-06-04 18:05:27 -07001245 :param bytes when: A timestamp string.
1246 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001247 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001248 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001249
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001250 def _get_name(self, which):
1251 name = X509Name.__new__(X509Name)
1252 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001253 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001254
1255 # The name is owned by the X509 structure. As long as the X509Name
1256 # Python object is alive, keep the X509 Python object alive.
1257 name._owner = self
1258
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001259 return name
1260
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001261 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001262 if not isinstance(name, X509Name):
1263 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001264 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001265 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001266
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001267 def get_issuer(self):
1268 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001269 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001270
Cory Benfielde6bcce82015-12-09 08:40:03 +00001271 This creates a new :class:`X509Name` that wraps the underlying issuer
1272 name field on the certificate. Modifying it will modify the underlying
1273 certificate, and will have the effect of modifying any other
1274 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001275
1276 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001277 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001278 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001279 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001280
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001281 def set_issuer(self, issuer):
1282 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001283 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001284
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001285 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001286 :type issuer: :py:class:`X509Name`
1287
Dan Sully44e767a2016-06-04 18:05:27 -07001288 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001289 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001290 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001291
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001292 def get_subject(self):
1293 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001294 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001295
Cory Benfielde6bcce82015-12-09 08:40:03 +00001296 This creates a new :class:`X509Name` that wraps the underlying subject
1297 name field on the certificate. Modifying it will modify the underlying
1298 certificate, and will have the effect of modifying any other
1299 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001300
1301 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001302 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001303 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001304 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001305
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001306 def set_subject(self, subject):
1307 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001308 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001309
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001310 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001311 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001312
Dan Sully44e767a2016-06-04 18:05:27 -07001313 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001314 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001315 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001316
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001317 def get_extension_count(self):
1318 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001319 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001320
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001321 :return: The number of extensions.
1322 :rtype: :py:class:`int`
1323
1324 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001325 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001326 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001327
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001328 def add_extensions(self, extensions):
1329 """
1330 Add extensions to the certificate.
1331
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001332 :param extensions: The extensions to add.
1333 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001334 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001335 """
1336 for ext in extensions:
1337 if not isinstance(ext, X509Extension):
1338 raise ValueError("One of the elements is not an X509Extension")
1339
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001340 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001341 if not add_result:
1342 _raise_current_error()
1343
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001344 def get_extension(self, index):
1345 """
1346 Get a specific extension of the certificate by index.
1347
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001348 Extensions on a certificate are kept in order. The index
1349 parameter selects which extension will be returned.
1350
1351 :param int index: The index of the extension to retrieve.
1352 :return: The extension at the specified index.
1353 :rtype: :py:class:`X509Extension`
1354 :raises IndexError: If the extension index was out of bounds.
1355
1356 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001357 """
1358 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001359 ext._extension = _lib.X509_get_ext(self._x509, index)
1360 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001361 raise IndexError("extension index out of bounds")
1362
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001363 extension = _lib.X509_EXTENSION_dup(ext._extension)
1364 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001365 return ext
1366
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001367
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001368X509Type = X509
1369
1370
Dan Sully44e767a2016-06-04 18:05:27 -07001371class X509StoreFlags(object):
1372 """
1373 Flags for X509 verification, used to change the behavior of
1374 :class:`X509Store`.
1375
1376 See `OpenSSL Verification Flags`_ for details.
1377
1378 .. _OpenSSL Verification Flags:
1379 https://www.openssl.org/docs/manmaster/crypto/X509_VERIFY_PARAM_set_flags.html
1380 """
1381 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1382 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1383 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1384 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1385 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1386 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1387 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1388 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1389 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1390 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1391 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1392
1393
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001394class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001395 """
Dan Sully44e767a2016-06-04 18:05:27 -07001396 An X.509 store.
1397
1398 An X.509 store is used to describe a context in which to verify a
1399 certificate. A description of a context may include a set of certificates
1400 to trust, a set of certificate revocation lists, verification flags and
1401 more.
1402
1403 An X.509 store, being only a description, cannot be used by itself to
1404 verify a certificate. To carry out the actual verification process, see
1405 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001406 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001407
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001408 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001409 store = _lib.X509_STORE_new()
1410 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001411
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001412 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001413 """
Dan Sully44e767a2016-06-04 18:05:27 -07001414 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001415
Dan Sully44e767a2016-06-04 18:05:27 -07001416 Adding a certificate with this method adds this certificate as a
1417 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001418
1419 :param X509 cert: The certificate to add to this store.
Dan Sully44e767a2016-06-04 18:05:27 -07001420 :raises TypeError: If the certificate is not an :class:`X509`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001421 :raises Error: If OpenSSL was unhappy with your certificate.
Dan Sully44e767a2016-06-04 18:05:27 -07001422 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001423 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001424 if not isinstance(cert, X509):
1425 raise TypeError()
1426
Dan Sully44e767a2016-06-04 18:05:27 -07001427 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1428
1429 def add_crl(self, crl):
1430 """
1431 Add a certificate revocation list to this store.
1432
1433 The certificate revocation lists added to a store will only be used if
1434 the associated flags are configured to check certificate revocation
1435 lists.
1436
1437 .. versionadded:: 16.1.0
1438
1439 :param CRL crl: The certificate revocation list to add to this store.
1440 :return: ``None`` if the certificate revocation list was added
1441 successfully.
1442 """
1443 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1444
1445 def set_flags(self, flags):
1446 """
1447 Set verification flags to this store.
1448
1449 Verification flags can be combined by oring them together.
1450
1451 .. note::
1452
1453 Setting a verification flag sometimes requires clients to add
1454 additional information to the store, otherwise a suitable error will
1455 be raised.
1456
1457 For example, in setting flags to enable CRL checking a
1458 suitable CRL must be added to the store otherwise an error will be
1459 raised.
1460
1461 .. versionadded:: 16.1.0
1462
1463 :param int flags: The verification flags to set on this store.
1464 See :class:`X509StoreFlags` for available constants.
1465 :return: ``None`` if the verification flags were successfully set.
1466 """
1467 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001468
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001469
1470X509StoreType = X509Store
1471
1472
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001473class X509StoreContextError(Exception):
1474 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001475 An exception raised when an error occurred while verifying a certificate
1476 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001477
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001478 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001479 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001480 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001481
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001482 def __init__(self, message, certificate):
1483 super(X509StoreContextError, self).__init__(message)
1484 self.certificate = certificate
1485
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001486
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001487class X509StoreContext(object):
1488 """
1489 An X.509 store context.
1490
Dan Sully44e767a2016-06-04 18:05:27 -07001491 An X.509 store context is used to carry out the actual verification process
1492 of a certificate in a described context. For describing such a context, see
1493 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001494
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001495 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1496 instance. It is dynamically allocated and automatically garbage
1497 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001498 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001499 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001500 :param X509Store store: The certificates which will be trusted for the
1501 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001502 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001503 """
1504
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001505 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001506 store_ctx = _lib.X509_STORE_CTX_new()
1507 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1508 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001509 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001510 # Make the store context available for use after instantiating this
1511 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001512 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001513 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001514
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001515 def _init(self):
1516 """
1517 Set up the store context for a subsequent verification operation.
1518 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001519 ret = _lib.X509_STORE_CTX_init(
1520 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1521 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001522 if ret <= 0:
1523 _raise_current_error()
1524
1525 def _cleanup(self):
1526 """
1527 Internally cleans up the store context.
1528
Dan Sully44e767a2016-06-04 18:05:27 -07001529 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001530 """
1531 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1532
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001533 def _exception_from_context(self):
1534 """
1535 Convert an OpenSSL native context error failure into a Python
1536 exception.
1537
Alex Gaynor5945ea82015-09-05 14:59:06 -04001538 When a call to native OpenSSL X509_verify_cert fails, additional
1539 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001540 """
1541 errors = [
1542 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1543 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1544 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001545 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001546 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001547 # A context error should always be associated with a certificate, so we
1548 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001549 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001550 _cert = _lib.X509_dup(_x509)
1551 pycert = X509.__new__(X509)
1552 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001553 return X509StoreContextError(errors, pycert)
1554
Stephen Holsapple46a09252015-02-12 14:45:43 -08001555 def set_store(self, store):
1556 """
Dan Sully44e767a2016-06-04 18:05:27 -07001557 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001558
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001559 .. versionadded:: 0.15
1560
Dan Sully44e767a2016-06-04 18:05:27 -07001561 :param X509Store store: The store description which will be used for
1562 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001563 """
1564 self._store = store
1565
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001566 def verify_certificate(self):
1567 """
1568 Verify a certificate in a context.
1569
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001570 .. versionadded:: 0.15
1571
Alex Gaynorca87ff62015-09-04 23:31:03 -04001572 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001573 certificate in the context. Sets ``certificate`` attribute to
1574 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001575 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001576 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001577 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001578 self._init()
1579 ret = _lib.X509_verify_cert(self._store_ctx)
1580 self._cleanup()
1581 if ret <= 0:
1582 raise self._exception_from_context()
1583
1584
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001585def load_certificate(type, buffer):
1586 """
1587 Load a certificate from a buffer
1588
1589 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1590
Dan Sully44e767a2016-06-04 18:05:27 -07001591 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001592
1593 :return: The X509 object
1594 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001595 if isinstance(buffer, _text_type):
1596 buffer = buffer.encode("ascii")
1597
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001598 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001599
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001600 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001601 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001602 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001603 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001604 else:
1605 raise ValueError(
1606 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001607
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001608 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001609 _raise_current_error()
1610
1611 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001612 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001613 return cert
1614
1615
1616def dump_certificate(type, cert):
1617 """
1618 Dump a certificate to a buffer
1619
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001620 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1621 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001622 :param cert: The certificate to dump
1623 :return: The buffer with the dumped certificate in
1624 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001625 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001626
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001627 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001628 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001629 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001630 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001631 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001632 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001633 else:
1634 raise ValueError(
1635 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1636 "FILETYPE_TEXT")
1637
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001638 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001639 return _bio_to_string(bio)
1640
1641
Cory Benfield6492f7c2015-10-27 16:57:58 +09001642def dump_publickey(type, pkey):
1643 """
Cory Benfield11c10192015-10-27 17:23:03 +09001644 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001645
Cory Benfield9c590b92015-10-28 14:55:05 +09001646 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001647 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001648 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001649 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001650 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001651 """
1652 bio = _new_mem_buf()
1653 if type == FILETYPE_PEM:
1654 write_bio = _lib.PEM_write_bio_PUBKEY
1655 elif type == FILETYPE_ASN1:
1656 write_bio = _lib.i2d_PUBKEY_bio
1657 else:
1658 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1659
1660 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001661 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001662 _raise_current_error()
1663
1664 return _bio_to_string(bio)
1665
1666
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001667def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1668 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001669 Dump the private key *pkey* into a buffer string encoded with the type
1670 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1671 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001672
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001673 :param type: The file type (one of :const:`FILETYPE_PEM`,
1674 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1675 :param PKey pkey: The PKey to dump
1676 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001677 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001678 the passphrase to use, or a callback for providing the passphrase.
1679
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001680 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001681 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001682 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001683 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001684
1685 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001686 if passphrase is None:
1687 raise TypeError(
1688 "if a value is given for cipher "
1689 "one must also be given for passphrase")
1690 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001691 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001692 raise ValueError("Invalid cipher name")
1693 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001695
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001696 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001697 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001698 result_code = _lib.PEM_write_bio_PrivateKey(
1699 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001700 helper.callback, helper.callback_args)
1701 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001702 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001704 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001705 rsa = _ffi.gc(
1706 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1707 _lib.RSA_free
1708 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001710 else:
1711 raise ValueError(
1712 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1713 "FILETYPE_TEXT")
1714
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001715 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001716
1717 return _bio_to_string(bio)
1718
1719
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001720class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001721 """
1722 A certificate revocation.
1723 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001724 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1725 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1726 # OCSP_crl_reason_str. We use the latter, just like the command line
1727 # program.
1728 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001729 b"unspecified",
1730 b"keyCompromise",
1731 b"CACompromise",
1732 b"affiliationChanged",
1733 b"superseded",
1734 b"cessationOfOperation",
1735 b"certificateHold",
1736 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001737 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001738
1739 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001740 revoked = _lib.X509_REVOKED_new()
1741 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001742
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001743 def set_serial(self, hex_str):
1744 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001745 Set the serial number.
1746
1747 The serial number is formatted as a hexadecimal number encoded in
1748 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001749
Dan Sully44e767a2016-06-04 18:05:27 -07001750 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001751
Dan Sully44e767a2016-06-04 18:05:27 -07001752 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001753 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1755 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001756 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001757 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001758 if not bn_result:
1759 raise ValueError("bad hex string")
1760
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001761 asn1_serial = _ffi.gc(
1762 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1763 _lib.ASN1_INTEGER_free)
1764 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001765
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001766 def get_serial(self):
1767 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001768 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001769
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001770 The serial number is formatted as a hexadecimal number encoded in
1771 ASCII.
1772
1773 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001774 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001775 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001776 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001777
Alex Gaynor67903a62016-06-02 10:37:13 -07001778 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1779 _openssl_assert(asn1_int != _ffi.NULL)
1780 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1781 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001782 return _bio_to_string(bio)
1783
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001784 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001785 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1786 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001787 obj = _lib.X509_EXTENSION_get_object(ext)
1788 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001789 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001790 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001791 break
1792
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001793 def set_reason(self, reason):
1794 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001795 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001796
Dan Sully44e767a2016-06-04 18:05:27 -07001797 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001798
1799 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001800 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001801
Dan Sully44e767a2016-06-04 18:05:27 -07001802 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001803
1804 .. seealso::
1805
Dan Sully44e767a2016-06-04 18:05:27 -07001806 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001807 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001808 """
1809 if reason is None:
1810 self._delete_reason()
1811 elif not isinstance(reason, bytes):
1812 raise TypeError("reason must be None or a byte string")
1813 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001814 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001815 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1816
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001817 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001818 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001819 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001820
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001822 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001823
1824 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001825 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1826 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001827 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001828
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001829 def get_reason(self):
1830 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001831 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001832
Dan Sully44e767a2016-06-04 18:05:27 -07001833 :return: The reason, or ``None`` if there is none.
1834 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001835
1836 .. seealso::
1837
Dan Sully44e767a2016-06-04 18:05:27 -07001838 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001839 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001840 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001841 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1842 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001843 obj = _lib.X509_EXTENSION_get_object(ext)
1844 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001845 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001846
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001847 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001848 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001849 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001850 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001851 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001852 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001853
1854 return _bio_to_string(bio)
1855
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001856 def all_reasons(self):
1857 """
1858 Return a list of all the supported reason strings.
1859
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001860 This list is a copy; modifying it does not change the supported reason
1861 strings.
1862
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001863 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001864 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001865 """
1866 return self._crl_reasons[:]
1867
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001868 def set_rev_date(self, when):
1869 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001870 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001871
Dan Sully44e767a2016-06-04 18:05:27 -07001872 :param bytes when: The timestamp of the revocation,
1873 as ASN.1 GENERALIZEDTIME.
1874 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001875 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001876 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1877 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001878
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001879 def get_rev_date(self):
1880 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001881 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001882
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001883 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001884 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001885 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001886 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1887 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001888
1889
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001890class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001891 """
1892 A certificate revocation list.
1893 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001894
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001895 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001896 crl = _lib.X509_CRL_new()
1897 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001898
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001899 def get_revoked(self):
1900 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001901 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001902
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001903 These revocations will be provided by value, not by reference.
1904 That means it's okay to mutate them: it won't affect this CRL.
1905
1906 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001907 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001908 """
1909 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001910 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001911 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1912 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001913 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001914 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001915 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001916 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001917 if results:
1918 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001919
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001920 def add_revoked(self, revoked):
1921 """
1922 Add a revoked (by value not reference) to the CRL structure
1923
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001924 This revocation will be added by value, not by reference. That
1925 means it's okay to mutate it after adding: it won't affect
1926 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001927
Dan Sully44e767a2016-06-04 18:05:27 -07001928 :param Revoked revoked: The new revocation.
1929 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001930 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001931 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001932 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001933
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001934 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001935 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001936
Dan Sully44e767a2016-06-04 18:05:27 -07001937 def get_issuer(self):
1938 """
1939 Get the CRL's issuer.
1940
1941 .. versionadded:: 16.1.0
1942
1943 :rtype: X509Name
1944 """
1945 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
1946 _openssl_assert(_issuer != _ffi.NULL)
1947 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
1948 issuer = X509Name.__new__(X509Name)
1949 issuer._name = _issuer
1950 return issuer
1951
1952 def set_version(self, version):
1953 """
1954 Set the CRL version.
1955
1956 .. versionadded:: 16.1.0
1957
1958 :param int version: The version of the CRL.
1959 :return: ``None``
1960 """
1961 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
1962
1963 def _set_boundary_time(self, which, when):
1964 return _set_asn1_time(which(self._crl), when)
1965
1966 def set_lastUpdate(self, when):
1967 """
1968 Set when the CRL was last updated.
1969
1970 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
1971
1972 YYYYMMDDhhmmssZ
1973 YYYYMMDDhhmmss+hhmm
1974 YYYYMMDDhhmmss-hhmm
1975
1976 .. versionadded:: 16.1.0
1977
1978 :param bytes when: A timestamp string.
1979 :return: ``None``
1980 """
1981 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
1982
1983 def set_nextUpdate(self, when):
1984 """
1985 Set when the CRL will next be udpated.
1986
1987 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
1988
1989 YYYYMMDDhhmmssZ
1990 YYYYMMDDhhmmss+hhmm
1991 YYYYMMDDhhmmss-hhmm
1992
1993 .. versionadded:: 16.1.0
1994
1995 :param bytes when: A timestamp string.
1996 :return: ``None``
1997 """
1998 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
1999
2000 def sign(self, issuer_cert, issuer_key, digest):
2001 """
2002 Sign the CRL.
2003
2004 Signing a CRL enables clients to associate the CRL itself with an
2005 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2006 be signed by an issuer.
2007
2008 This method implicitly sets the issuer's name based on the issuer
2009 certificate and private key used to sign the CRL.
2010
2011 .. versionadded:: 16.1.0
2012
2013 :param X509 issuer_cert: The issuer's certificate.
2014 :param PKey issuer_key: The issuer's private key.
2015 :param bytes digest: The digest method to sign the CRL with.
2016 """
2017 digest_obj = _lib.EVP_get_digestbyname(digest)
2018 _openssl_assert(digest_obj != _ffi.NULL)
2019 _lib.X509_CRL_set_issuer_name(
2020 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2021 _lib.X509_CRL_sort(self._crl)
2022 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2023 _openssl_assert(result != 0)
2024
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002025 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002026 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002027 """
Dan Sully44e767a2016-06-04 18:05:27 -07002028 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002029
Dan Sully44e767a2016-06-04 18:05:27 -07002030 :param X509 cert: The certificate used to sign the CRL.
2031 :param PKey key: The key used to sign the CRL.
2032 :param int type: The export format, either :data:`FILETYPE_PEM`,
2033 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002034 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002035 :param bytes digest: The name of the message digest to use (eg
2036 ``b"sha1"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002037 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002038 """
Dan Sully44e767a2016-06-04 18:05:27 -07002039
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002040 if not isinstance(cert, X509):
2041 raise TypeError("cert must be an X509 instance")
2042 if not isinstance(key, PKey):
2043 raise TypeError("key must be a PKey instance")
2044 if not isinstance(type, int):
2045 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002046
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002047 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002048 _warn(
2049 "The default message digest (md5) is deprecated. "
2050 "Pass the name of a message digest explicitly.",
2051 category=DeprecationWarning,
2052 stacklevel=2,
2053 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002054 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002055
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002056 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002057 if digest_obj == _ffi.NULL:
2058 raise ValueError("No such digest method")
2059
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002060 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002061 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002062
Alex Gaynora738ed52015-09-05 11:17:10 -04002063 # A scratch time object to give different values to different CRL
2064 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002065 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002066 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002067
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002068 _lib.X509_gmtime_adj(sometime, 0)
2069 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002070
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002071 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2072 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002073
Alex Gaynor5945ea82015-09-05 14:59:06 -04002074 _lib.X509_CRL_set_issuer_name(
2075 self._crl, _lib.X509_get_subject_name(cert._x509)
2076 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002077
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002078 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002079 if not sign_result:
2080 _raise_current_error()
2081
Dominic Chenf05b2122015-10-13 16:32:35 +00002082 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002083
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002084
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002085CRLType = CRL
2086
2087
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002088class PKCS7(object):
2089 def type_is_signed(self):
2090 """
2091 Check if this NID_pkcs7_signed object
2092
2093 :return: True if the PKCS7 is of type signed
2094 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002095 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002096 return True
2097 return False
2098
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002099 def type_is_enveloped(self):
2100 """
2101 Check if this NID_pkcs7_enveloped object
2102
2103 :returns: True if the PKCS7 is of type enveloped
2104 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002105 if _lib.PKCS7_type_is_enveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002106 return True
2107 return False
2108
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002109 def type_is_signedAndEnveloped(self):
2110 """
2111 Check if this NID_pkcs7_signedAndEnveloped object
2112
2113 :returns: True if the PKCS7 is of type signedAndEnveloped
2114 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002115 if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002116 return True
2117 return False
2118
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002119 def type_is_data(self):
2120 """
2121 Check if this NID_pkcs7_data object
2122
2123 :return: True if the PKCS7 is of type data
2124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002125 if _lib.PKCS7_type_is_data(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002126 return True
2127 return False
2128
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002129 def get_type_name(self):
2130 """
2131 Returns the type name of the PKCS7 structure
2132
2133 :return: A string with the typename
2134 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002135 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2136 string_type = _lib.OBJ_nid2sn(nid)
2137 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002138
2139PKCS7Type = PKCS7
2140
2141
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002142class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002143 """
2144 A PKCS #12 archive.
2145 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002146
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002147 def __init__(self):
2148 self._pkey = None
2149 self._cert = None
2150 self._cacerts = None
2151 self._friendlyname = None
2152
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002153 def get_certificate(self):
2154 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002155 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002156
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002157 :return: The certificate, or :py:const:`None` if there is none.
2158 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002159 """
2160 return self._cert
2161
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002162 def set_certificate(self, cert):
2163 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002164 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002165
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002166 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002167 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002168
Dan Sully44e767a2016-06-04 18:05:27 -07002169 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002170 """
2171 if not isinstance(cert, X509):
2172 raise TypeError("cert must be an X509 instance")
2173 self._cert = cert
2174
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002175 def get_privatekey(self):
2176 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002177 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002178
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002179 :return: The private key, or :py:const:`None` if there is none.
2180 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002181 """
2182 return self._pkey
2183
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002184 def set_privatekey(self, pkey):
2185 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002186 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002187
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002188 :param pkey: The new private key, or :py:const:`None` to unset it.
2189 :type pkey: :py:class:`PKey` or :py:const:`None`
2190
Dan Sully44e767a2016-06-04 18:05:27 -07002191 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002192 """
2193 if not isinstance(pkey, PKey):
2194 raise TypeError("pkey must be a PKey instance")
2195 self._pkey = pkey
2196
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002197 def get_ca_certificates(self):
2198 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002199 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002200
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002201 :return: A tuple with the CA certificates in the chain, or
2202 :py:const:`None` if there are none.
2203 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002204 """
2205 if self._cacerts is not None:
2206 return tuple(self._cacerts)
2207
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002208 def set_ca_certificates(self, cacerts):
2209 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002210 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002211
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002212 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2213 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002214 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002215
Dan Sully44e767a2016-06-04 18:05:27 -07002216 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217 """
2218 if cacerts is None:
2219 self._cacerts = None
2220 else:
2221 cacerts = list(cacerts)
2222 for cert in cacerts:
2223 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002224 raise TypeError(
2225 "iterable must only contain X509 instances"
2226 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002227 self._cacerts = cacerts
2228
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002229 def set_friendlyname(self, name):
2230 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002231 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002232
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002233 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002234 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002235
Dan Sully44e767a2016-06-04 18:05:27 -07002236 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002237 """
2238 if name is None:
2239 self._friendlyname = None
2240 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002241 raise TypeError(
2242 "name must be a byte string or None (not %r)" % (name,)
2243 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002244 self._friendlyname = name
2245
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002246 def get_friendlyname(self):
2247 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002248 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002249
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002250 :returns: The friendly name, or :py:const:`None` if there is none.
2251 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002252 """
2253 return self._friendlyname
2254
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002255 def export(self, passphrase=None, iter=2048, maciter=1):
2256 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002257 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002258
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002259 For more information, see the :c:func:`PKCS12_create` man page.
2260
2261 :param passphrase: The passphrase used to encrypt the structure. Unlike
2262 some other passphrase arguments, this *must* be a string, not a
2263 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002264 :type passphrase: :py:data:`bytes`
2265
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002266 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002267 :type iter: :py:data:`int`
2268
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002269 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002270 :type maciter: :py:data:`int`
2271
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002272 :return: The string representation of the PKCS #12 structure.
2273 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002274 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002275 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002276
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002277 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002278 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002279 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002280 cacerts = _lib.sk_X509_new_null()
2281 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002282 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002283 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002284
2285 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002286 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002287
2288 friendlyname = self._friendlyname
2289 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002290 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002291
2292 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002293 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002294 else:
2295 pkey = self._pkey._pkey
2296
2297 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002298 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002299 else:
2300 cert = self._cert._x509
2301
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002302 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002303 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002304 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2305 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002306 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002307 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002308 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002309 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002310
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002311 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002312 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002313 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002314
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002315
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002316PKCS12Type = PKCS12
2317
2318
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002319class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002320 """
2321 A Netscape SPKI object.
2322 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002323
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002324 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002325 spki = _lib.NETSCAPE_SPKI_new()
2326 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002327
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002328 def sign(self, pkey, digest):
2329 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002330 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002331
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002332 :param pkey: The private key to sign with.
2333 :type pkey: :py:class:`PKey`
2334
2335 :param digest: The message digest to use.
2336 :type digest: :py:class:`bytes`
2337
Dan Sully44e767a2016-06-04 18:05:27 -07002338 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002339 """
2340 if pkey._only_public:
2341 raise ValueError("Key has only public part")
2342
2343 if not pkey._initialized:
2344 raise ValueError("Key is uninitialized")
2345
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002346 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002347 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002348 raise ValueError("No such digest method")
2349
Alex Gaynor5945ea82015-09-05 14:59:06 -04002350 sign_result = _lib.NETSCAPE_SPKI_sign(
2351 self._spki, pkey._pkey, digest_obj
2352 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002353 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002354
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002355 def verify(self, key):
2356 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002357 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002358
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002359 :param key: The public key that signature is supposedly from.
2360 :type pkey: :py:class:`PKey`
2361
2362 :return: :py:const:`True` if the signature is correct.
2363 :rtype: :py:class:`bool`
2364
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002365 :raises Error: If the signature is invalid, or there was a problem
2366 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002367 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002368 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002369 if answer <= 0:
2370 _raise_current_error()
2371 return True
2372
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002373 def b64_encode(self):
2374 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002375 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002376
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002377 :return: The base64 encoded string.
2378 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002379 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002380 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2381 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002382 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002383 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002384
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002385 def get_pubkey(self):
2386 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002387 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002388
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002389 :return: The public key.
2390 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002391 """
2392 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002393 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002394 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002395 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002396 pkey._only_public = True
2397 return pkey
2398
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002399 def set_pubkey(self, pkey):
2400 """
2401 Set the public key of the certificate
2402
2403 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002404 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002405 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002406 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002407 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002408
2409
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002410NetscapeSPKIType = NetscapeSPKI
2411
2412
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002413class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002414 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002415 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002416 raise ValueError(
2417 "only FILETYPE_PEM key format supports encryption"
2418 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002419 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002420 self._more_args = more_args
2421 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002422 self._problems = []
2423
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002424 @property
2425 def callback(self):
2426 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002427 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002428 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002429 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002430 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002431 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002432 else:
2433 raise TypeError("Last argument must be string or callable")
2434
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002435 @property
2436 def callback_args(self):
2437 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002438 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002439 elif isinstance(self._passphrase, bytes):
2440 return self._passphrase
2441 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002442 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002443 else:
2444 raise TypeError("Last argument must be string or callable")
2445
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002446 def raise_if_problem(self, exceptionType=Error):
2447 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002448 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002449 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002450 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002451 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002452 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002453 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002454
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002455 def _read_passphrase(self, buf, size, rwflag, userdata):
2456 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002457 if self._more_args:
2458 result = self._passphrase(size, rwflag, userdata)
2459 else:
2460 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002461 if not isinstance(result, bytes):
2462 raise ValueError("String expected")
2463 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002464 if self._truncate:
2465 result = result[:size]
2466 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002467 raise ValueError(
2468 "passphrase returned by callback is too long"
2469 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002470 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002471 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002472 return len(result)
2473 except Exception as e:
2474 self._problems.append(e)
2475 return 0
2476
2477
Cory Benfield6492f7c2015-10-27 16:57:58 +09002478def load_publickey(type, buffer):
2479 """
Cory Benfield11c10192015-10-27 17:23:03 +09002480 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002481
Cory Benfield9c590b92015-10-28 14:55:05 +09002482 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002483 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002484 :param buffer: The buffer the key is stored in.
2485 :type buffer: A Python string object, either unicode or bytestring.
2486 :return: The PKey object.
2487 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002488 """
2489 if isinstance(buffer, _text_type):
2490 buffer = buffer.encode("ascii")
2491
2492 bio = _new_mem_buf(buffer)
2493
2494 if type == FILETYPE_PEM:
2495 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2496 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2497 elif type == FILETYPE_ASN1:
2498 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2499 else:
2500 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2501
2502 if evp_pkey == _ffi.NULL:
2503 _raise_current_error()
2504
2505 pkey = PKey.__new__(PKey)
2506 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002507 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002508 return pkey
2509
2510
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002511def load_privatekey(type, buffer, passphrase=None):
2512 """
2513 Load a private key from a buffer
2514
2515 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2516 :param buffer: The buffer the key is stored in
2517 :param passphrase: (optional) if encrypted PEM format, this can be
2518 either the passphrase to use, or a callback for
2519 providing the passphrase.
2520
2521 :return: The PKey object
2522 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002523 if isinstance(buffer, _text_type):
2524 buffer = buffer.encode("ascii")
2525
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002526 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002527
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002528 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002529 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002530 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2531 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002532 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002533 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002534 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002535 else:
2536 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2537
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002538 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002539 _raise_current_error()
2540
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002541 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002542 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002543 return pkey
2544
2545
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002546def dump_certificate_request(type, req):
2547 """
2548 Dump a certificate request to a buffer
2549
2550 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2551 :param req: The certificate request to dump
2552 :return: The buffer with the dumped certificate request in
2553 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002554 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002555
2556 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002557 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002558 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002559 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002560 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002561 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002562 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002563 raise ValueError(
2564 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2565 "FILETYPE_TEXT"
2566 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002567
Alex Gaynor09a386e2016-07-03 09:32:44 -04002568 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002569
2570 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002571
2572
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002573def load_certificate_request(type, buffer):
2574 """
2575 Load a certificate request from a buffer
2576
2577 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2578 :param buffer: The buffer the certificate request is stored in
2579 :return: The X509Req object
2580 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002581 if isinstance(buffer, _text_type):
2582 buffer = buffer.encode("ascii")
2583
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002584 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002585
2586 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002587 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002588 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002589 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002590 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002591 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002592
Alex Gaynoradd5b072016-06-04 21:04:00 -07002593 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002594
2595 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002596 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002597 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002598
2599
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002600def sign(pkey, data, digest):
2601 """
2602 Sign data with a digest
2603
2604 :param pkey: Pkey to sign with
2605 :param data: data to be signed
2606 :param digest: message digest to use
2607 :return: signature
2608 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002609 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002610
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002611 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002612 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002613 raise ValueError("No such digest method")
2614
Alex Gaynor67903a62016-06-02 10:37:13 -07002615 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002616 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002617
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002618 _lib.EVP_SignInit(md_ctx, digest_obj)
2619 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002620
Colleen Murphye09399b2016-03-01 17:40:49 -08002621 pkey_length = (PKey.bits(pkey) + 7) // 8
2622 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002623 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002624 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002625 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002626 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002627
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002628 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002629
2630
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002631def verify(cert, signature, data, digest):
2632 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002633 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002634
2635 :param cert: signing certificate (X509 object)
2636 :param signature: signature returned by sign function
2637 :param data: data to be verified
2638 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002639 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002640 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002641 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002642
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002643 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002644 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002645 raise ValueError("No such digest method")
2646
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002647 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002648 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002649 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002650
Alex Gaynor67903a62016-06-02 10:37:13 -07002651 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002652 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002653
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002654 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2655 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002656 verify_result = _lib.EVP_VerifyFinal(
2657 md_ctx, signature, len(signature), pkey
2658 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002659
2660 if verify_result != 1:
2661 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002662
2663
Dominic Chenf05b2122015-10-13 16:32:35 +00002664def dump_crl(type, crl):
2665 """
2666 Dump a certificate revocation list to a buffer.
2667
2668 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2669 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002670 :param CRL crl: The CRL to dump.
2671
Dominic Chenf05b2122015-10-13 16:32:35 +00002672 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002673 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002674 """
2675 bio = _new_mem_buf()
2676
2677 if type == FILETYPE_PEM:
2678 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2679 elif type == FILETYPE_ASN1:
2680 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2681 elif type == FILETYPE_TEXT:
2682 ret = _lib.X509_CRL_print(bio, crl._crl)
2683 else:
2684 raise ValueError(
2685 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2686 "FILETYPE_TEXT")
2687
2688 assert ret == 1
2689 return _bio_to_string(bio)
2690
2691
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002692def load_crl(type, buffer):
2693 """
2694 Load a certificate revocation list from a buffer
2695
2696 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2697 :param buffer: The buffer the CRL is stored in
2698
2699 :return: The PKey object
2700 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002701 if isinstance(buffer, _text_type):
2702 buffer = buffer.encode("ascii")
2703
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002704 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002705
2706 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002707 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002708 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002709 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002710 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002711 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2712
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002713 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002714 _raise_current_error()
2715
2716 result = CRL.__new__(CRL)
2717 result._crl = crl
2718 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002719
2720
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002721def load_pkcs7_data(type, buffer):
2722 """
2723 Load pkcs7 data from a buffer
2724
2725 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2726 :param buffer: The buffer with the pkcs7 data.
2727 :return: The PKCS7 object
2728 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002729 if isinstance(buffer, _text_type):
2730 buffer = buffer.encode("ascii")
2731
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002732 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002733
2734 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002735 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002736 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002737 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002738 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002739 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2740
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002741 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002742 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002743
2744 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002745 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002746 return pypkcs7
2747
2748
Stephen Holsapple38482622014-04-05 20:29:34 -07002749def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002750 """
2751 Load a PKCS12 object from a buffer
2752
2753 :param buffer: The buffer the certificate is stored in
2754 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2755 :returns: The PKCS12 object
2756 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002757 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002758
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002759 if isinstance(buffer, _text_type):
2760 buffer = buffer.encode("ascii")
2761
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002762 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002763
Stephen Holsapple38482622014-04-05 20:29:34 -07002764 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2765 # password based encryption no password and a zero length password are two
2766 # different things, but OpenSSL implementation will try both to figure out
2767 # which one works.
2768 if not passphrase:
2769 passphrase = _ffi.NULL
2770
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002771 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2772 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002773 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002774 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002775
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002776 pkey = _ffi.new("EVP_PKEY**")
2777 cert = _ffi.new("X509**")
2778 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002779
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002780 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002781 if not parse_result:
2782 _raise_current_error()
2783
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002784 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002785
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002786 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2787 # queue for no particular reason. This error isn't interesting to anyone
2788 # outside this function. It's not even interesting to us. Get rid of it.
2789 try:
2790 _raise_current_error()
2791 except Error:
2792 pass
2793
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002794 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002795 pykey = None
2796 else:
2797 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002798 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002799
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002800 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002801 pycert = None
2802 friendlyname = None
2803 else:
2804 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002805 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002806
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002807 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002808 friendlyname_buffer = _lib.X509_alias_get0(
2809 cert[0], friendlyname_length
2810 )
2811 friendlyname = _ffi.buffer(
2812 friendlyname_buffer, friendlyname_length[0]
2813 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002814 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002815 friendlyname = None
2816
2817 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002818 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002819 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002820 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002821 pycacerts.append(pycacert)
2822 if not pycacerts:
2823 pycacerts = None
2824
2825 pkcs12 = PKCS12.__new__(PKCS12)
2826 pkcs12._pkey = pykey
2827 pkcs12._cert = pycert
2828 pkcs12._cacerts = pycacerts
2829 pkcs12._friendlyname = friendlyname
2830 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002831
2832
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002833# There are no direct unit tests for this initialization. It is tested
2834# indirectly since it is necessary for functions like dump_privatekey when
2835# using encryption.
2836#
2837# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2838# and some other similar tests may fail without this (though they may not if
2839# the Python runtime has already done some initialization of the underlying
2840# OpenSSL library (and is linked against the same one that cryptography is
2841# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002842_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002843
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002844# This is similar but exercised mainly by exception_from_error_queue. It calls
2845# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2846_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002847
2848
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002849# Set the default string mask to match OpenSSL upstream (since 2005) and
2850# RFC5280 recommendations.
2851_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')