blob: 91cc8c8bad2db83cda91056583f6f84ebf6da03b [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)
Alex Gaynor7778e792016-07-03 23:38:48 -04001000 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001001
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001002 def sign(self, pkey, digest):
1003 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001004 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001005
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001006 :param pkey: The key to sign with.
1007 :type pkey: :py:class:`PKey`
1008
1009 :param digest: The name of the message digest to use.
1010 :type digest: :py:class:`bytes`
1011
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001012 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001013 """
1014 if not isinstance(pkey, PKey):
1015 raise TypeError("pkey must be a PKey instance")
1016
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001017 if pkey._only_public:
1018 raise ValueError("Key only has public part")
1019
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001020 if not pkey._initialized:
1021 raise ValueError("Key is uninitialized")
1022
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001023 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001024 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001025 raise ValueError("No such digest method")
1026
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001027 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001028 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001029
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001030 def get_signature_algorithm(self):
1031 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001032 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001033
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001034 :return: The name of the algorithm.
1035 :rtype: :py:class:`bytes`
1036
1037 :raises ValueError: If the signature algorithm is undefined.
1038
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001039 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001040 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001041 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1042 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001043 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001044 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001045 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001046
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001047 def digest(self, digest_name):
1048 """
1049 Return the digest of the X509 object.
1050
1051 :param digest_name: The name of the digest algorithm to use.
1052 :type digest_name: :py:class:`bytes`
1053
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001054 :return: The digest of the object, formatted as
1055 :py:const:`b":"`-delimited hex pairs.
1056 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001057 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001058 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001059 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001060 raise ValueError("No such digest method")
1061
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001062 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1063 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001064 result_length[0] = len(result_buffer)
1065
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001066 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001067 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001068 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001069
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001070 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001071 b16encode(ch).upper() for ch
1072 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001073
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001074 def subject_name_hash(self):
1075 """
1076 Return the hash of the X509 subject.
1077
1078 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001079 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001080 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001082
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001083 def set_serial_number(self, serial):
1084 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001085 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001086
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001087 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001088 :type serial: :py:class:`int`
1089
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001090 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001091 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001092 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001093 raise TypeError("serial must be an integer")
1094
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001095 hex_serial = hex(serial)[2:]
1096 if not isinstance(hex_serial, bytes):
1097 hex_serial = hex_serial.encode('ascii')
1098
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001099 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001100
1101 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001102 # it. If bignum is still NULL after this call, then the return value
1103 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001104 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001105
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001106 if bignum_serial[0] == _ffi.NULL:
1107 set_result = _lib.ASN1_INTEGER_set(
1108 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001109 if set_result:
1110 # TODO Not tested
1111 _raise_current_error()
1112 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001113 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1114 _lib.BN_free(bignum_serial[0])
1115 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001116 # TODO Not tested
1117 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001118 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1119 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001120 if not set_result:
1121 # TODO Not tested
1122 _raise_current_error()
1123
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001124 def get_serial_number(self):
1125 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001126 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001127
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001128 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001129 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001130 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001131 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1132 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001133 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001134 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001135 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001136 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001137 serial = int(hexstring_serial, 16)
1138 return serial
1139 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001140 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001141 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001142 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001143
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001144 def gmtime_adj_notAfter(self, amount):
1145 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001146 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001147
Dan Sully44e767a2016-06-04 18:05:27 -07001148 :param int amount: The number of seconds by which to adjust the
1149 timestamp.
1150 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001151 """
1152 if not isinstance(amount, int):
1153 raise TypeError("amount must be an integer")
1154
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 notAfter = _lib.X509_get_notAfter(self._x509)
1156 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001157
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001158 def gmtime_adj_notBefore(self, amount):
1159 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001160 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001161
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001162 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001163 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001164 """
1165 if not isinstance(amount, int):
1166 raise TypeError("amount must be an integer")
1167
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 notBefore = _lib.X509_get_notBefore(self._x509)
1169 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001170
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001171 def has_expired(self):
1172 """
1173 Check whether the certificate has expired.
1174
Dan Sully44e767a2016-06-04 18:05:27 -07001175 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1176 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001177 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001178 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001179 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001180
Paul Kehrerfde45c92016-01-21 12:57:37 -06001181 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001182
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001183 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001184 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001185
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001186 def get_notBefore(self):
1187 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001188 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001189
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001190 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001191
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001192 YYYYMMDDhhmmssZ
1193 YYYYMMDDhhmmss+hhmm
1194 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001195
Dan Sully44e767a2016-06-04 18:05:27 -07001196 :return: A timestamp string, or ``None`` if there is none.
1197 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001198 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001199 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001200
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001201 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001202 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001203
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001204 def set_notBefore(self, when):
1205 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001206 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001207
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001208 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001209
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001210 YYYYMMDDhhmmssZ
1211 YYYYMMDDhhmmss+hhmm
1212 YYYYMMDDhhmmss-hhmm
1213
Dan Sully44e767a2016-06-04 18:05:27 -07001214 :param bytes when: A timestamp string.
1215 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001216 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001217 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001218
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001219 def get_notAfter(self):
1220 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001221 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001222
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001223 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001224
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001225 YYYYMMDDhhmmssZ
1226 YYYYMMDDhhmmss+hhmm
1227 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001228
Dan Sully44e767a2016-06-04 18:05:27 -07001229 :return: A timestamp string, or ``None`` if there is none.
1230 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001231 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001232 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001233
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001234 def set_notAfter(self, when):
1235 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001236 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001237
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001238 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001239
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001240 YYYYMMDDhhmmssZ
1241 YYYYMMDDhhmmss+hhmm
1242 YYYYMMDDhhmmss-hhmm
1243
Dan Sully44e767a2016-06-04 18:05:27 -07001244 :param bytes when: A timestamp string.
1245 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001246 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001247 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001248
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001249 def _get_name(self, which):
1250 name = X509Name.__new__(X509Name)
1251 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001252 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001253
1254 # The name is owned by the X509 structure. As long as the X509Name
1255 # Python object is alive, keep the X509 Python object alive.
1256 name._owner = self
1257
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001258 return name
1259
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001260 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001261 if not isinstance(name, X509Name):
1262 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001263 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001264 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001265
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001266 def get_issuer(self):
1267 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001268 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001269
Cory Benfielde6bcce82015-12-09 08:40:03 +00001270 This creates a new :class:`X509Name` that wraps the underlying issuer
1271 name field on the certificate. Modifying it will modify the underlying
1272 certificate, and will have the effect of modifying any other
1273 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001274
1275 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001276 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001277 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001278 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001279
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001280 def set_issuer(self, issuer):
1281 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001282 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001283
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001284 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001285 :type issuer: :py:class:`X509Name`
1286
Dan Sully44e767a2016-06-04 18:05:27 -07001287 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001288 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001289 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001290
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001291 def get_subject(self):
1292 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001293 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001294
Cory Benfielde6bcce82015-12-09 08:40:03 +00001295 This creates a new :class:`X509Name` that wraps the underlying subject
1296 name field on the certificate. Modifying it will modify the underlying
1297 certificate, and will have the effect of modifying any other
1298 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001299
1300 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001301 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001302 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001304
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001305 def set_subject(self, subject):
1306 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001307 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001308
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001309 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001310 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001311
Dan Sully44e767a2016-06-04 18:05:27 -07001312 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001313 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001314 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001315
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001316 def get_extension_count(self):
1317 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001318 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001319
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001320 :return: The number of extensions.
1321 :rtype: :py:class:`int`
1322
1323 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001324 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001325 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001326
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001327 def add_extensions(self, extensions):
1328 """
1329 Add extensions to the certificate.
1330
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001331 :param extensions: The extensions to add.
1332 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001333 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001334 """
1335 for ext in extensions:
1336 if not isinstance(ext, X509Extension):
1337 raise ValueError("One of the elements is not an X509Extension")
1338
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001339 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001340 if not add_result:
1341 _raise_current_error()
1342
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001343 def get_extension(self, index):
1344 """
1345 Get a specific extension of the certificate by index.
1346
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001347 Extensions on a certificate are kept in order. The index
1348 parameter selects which extension will be returned.
1349
1350 :param int index: The index of the extension to retrieve.
1351 :return: The extension at the specified index.
1352 :rtype: :py:class:`X509Extension`
1353 :raises IndexError: If the extension index was out of bounds.
1354
1355 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001356 """
1357 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001358 ext._extension = _lib.X509_get_ext(self._x509, index)
1359 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001360 raise IndexError("extension index out of bounds")
1361
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001362 extension = _lib.X509_EXTENSION_dup(ext._extension)
1363 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001364 return ext
1365
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001366
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001367X509Type = X509
1368
1369
Dan Sully44e767a2016-06-04 18:05:27 -07001370class X509StoreFlags(object):
1371 """
1372 Flags for X509 verification, used to change the behavior of
1373 :class:`X509Store`.
1374
1375 See `OpenSSL Verification Flags`_ for details.
1376
1377 .. _OpenSSL Verification Flags:
1378 https://www.openssl.org/docs/manmaster/crypto/X509_VERIFY_PARAM_set_flags.html
1379 """
1380 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1381 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1382 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1383 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1384 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1385 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1386 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1387 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1388 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1389 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1390 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1391
1392
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001393class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001394 """
Dan Sully44e767a2016-06-04 18:05:27 -07001395 An X.509 store.
1396
1397 An X.509 store is used to describe a context in which to verify a
1398 certificate. A description of a context may include a set of certificates
1399 to trust, a set of certificate revocation lists, verification flags and
1400 more.
1401
1402 An X.509 store, being only a description, cannot be used by itself to
1403 verify a certificate. To carry out the actual verification process, see
1404 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001405 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001406
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001407 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001408 store = _lib.X509_STORE_new()
1409 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001410
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001411 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001412 """
Dan Sully44e767a2016-06-04 18:05:27 -07001413 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001414
Dan Sully44e767a2016-06-04 18:05:27 -07001415 Adding a certificate with this method adds this certificate as a
1416 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001417
1418 :param X509 cert: The certificate to add to this store.
Dan Sully44e767a2016-06-04 18:05:27 -07001419 :raises TypeError: If the certificate is not an :class:`X509`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001420 :raises Error: If OpenSSL was unhappy with your certificate.
Dan Sully44e767a2016-06-04 18:05:27 -07001421 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001422 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001423 if not isinstance(cert, X509):
1424 raise TypeError()
1425
Dan Sully44e767a2016-06-04 18:05:27 -07001426 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1427
1428 def add_crl(self, crl):
1429 """
1430 Add a certificate revocation list to this store.
1431
1432 The certificate revocation lists added to a store will only be used if
1433 the associated flags are configured to check certificate revocation
1434 lists.
1435
1436 .. versionadded:: 16.1.0
1437
1438 :param CRL crl: The certificate revocation list to add to this store.
1439 :return: ``None`` if the certificate revocation list was added
1440 successfully.
1441 """
1442 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1443
1444 def set_flags(self, flags):
1445 """
1446 Set verification flags to this store.
1447
1448 Verification flags can be combined by oring them together.
1449
1450 .. note::
1451
1452 Setting a verification flag sometimes requires clients to add
1453 additional information to the store, otherwise a suitable error will
1454 be raised.
1455
1456 For example, in setting flags to enable CRL checking a
1457 suitable CRL must be added to the store otherwise an error will be
1458 raised.
1459
1460 .. versionadded:: 16.1.0
1461
1462 :param int flags: The verification flags to set on this store.
1463 See :class:`X509StoreFlags` for available constants.
1464 :return: ``None`` if the verification flags were successfully set.
1465 """
1466 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001467
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001468
1469X509StoreType = X509Store
1470
1471
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001472class X509StoreContextError(Exception):
1473 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001474 An exception raised when an error occurred while verifying a certificate
1475 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001476
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001477 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001478 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001479 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001480
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001481 def __init__(self, message, certificate):
1482 super(X509StoreContextError, self).__init__(message)
1483 self.certificate = certificate
1484
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001485
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001486class X509StoreContext(object):
1487 """
1488 An X.509 store context.
1489
Dan Sully44e767a2016-06-04 18:05:27 -07001490 An X.509 store context is used to carry out the actual verification process
1491 of a certificate in a described context. For describing such a context, see
1492 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001493
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001494 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1495 instance. It is dynamically allocated and automatically garbage
1496 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001497 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001498 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001499 :param X509Store store: The certificates which will be trusted for the
1500 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001501 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001502 """
1503
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001504 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001505 store_ctx = _lib.X509_STORE_CTX_new()
1506 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1507 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001508 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001509 # Make the store context available for use after instantiating this
1510 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001511 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001512 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001513
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001514 def _init(self):
1515 """
1516 Set up the store context for a subsequent verification operation.
1517 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001518 ret = _lib.X509_STORE_CTX_init(
1519 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1520 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001521 if ret <= 0:
1522 _raise_current_error()
1523
1524 def _cleanup(self):
1525 """
1526 Internally cleans up the store context.
1527
Dan Sully44e767a2016-06-04 18:05:27 -07001528 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001529 """
1530 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1531
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001532 def _exception_from_context(self):
1533 """
1534 Convert an OpenSSL native context error failure into a Python
1535 exception.
1536
Alex Gaynor5945ea82015-09-05 14:59:06 -04001537 When a call to native OpenSSL X509_verify_cert fails, additional
1538 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001539 """
1540 errors = [
1541 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1542 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1543 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001544 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001545 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001546 # A context error should always be associated with a certificate, so we
1547 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001548 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001549 _cert = _lib.X509_dup(_x509)
1550 pycert = X509.__new__(X509)
1551 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001552 return X509StoreContextError(errors, pycert)
1553
Stephen Holsapple46a09252015-02-12 14:45:43 -08001554 def set_store(self, store):
1555 """
Dan Sully44e767a2016-06-04 18:05:27 -07001556 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001557
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001558 .. versionadded:: 0.15
1559
Dan Sully44e767a2016-06-04 18:05:27 -07001560 :param X509Store store: The store description which will be used for
1561 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001562 """
1563 self._store = store
1564
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001565 def verify_certificate(self):
1566 """
1567 Verify a certificate in a context.
1568
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001569 .. versionadded:: 0.15
1570
Alex Gaynorca87ff62015-09-04 23:31:03 -04001571 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001572 certificate in the context. Sets ``certificate`` attribute to
1573 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001574 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001575 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001576 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001577 self._init()
1578 ret = _lib.X509_verify_cert(self._store_ctx)
1579 self._cleanup()
1580 if ret <= 0:
1581 raise self._exception_from_context()
1582
1583
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001584def load_certificate(type, buffer):
1585 """
1586 Load a certificate from a buffer
1587
1588 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1589
Dan Sully44e767a2016-06-04 18:05:27 -07001590 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001591
1592 :return: The X509 object
1593 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001594 if isinstance(buffer, _text_type):
1595 buffer = buffer.encode("ascii")
1596
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001597 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001598
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001599 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001600 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001601 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001602 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001603 else:
1604 raise ValueError(
1605 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001606
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001607 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001608 _raise_current_error()
1609
1610 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001611 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001612 return cert
1613
1614
1615def dump_certificate(type, cert):
1616 """
1617 Dump a certificate to a buffer
1618
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001619 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1620 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001621 :param cert: The certificate to dump
1622 :return: The buffer with the dumped certificate in
1623 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001624 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001625
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001626 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001627 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001628 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001629 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001630 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001631 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001632 else:
1633 raise ValueError(
1634 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1635 "FILETYPE_TEXT")
1636
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001637 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001638 return _bio_to_string(bio)
1639
1640
Cory Benfield6492f7c2015-10-27 16:57:58 +09001641def dump_publickey(type, pkey):
1642 """
Cory Benfield11c10192015-10-27 17:23:03 +09001643 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001644
Cory Benfield9c590b92015-10-28 14:55:05 +09001645 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001646 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001647 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001648 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001649 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001650 """
1651 bio = _new_mem_buf()
1652 if type == FILETYPE_PEM:
1653 write_bio = _lib.PEM_write_bio_PUBKEY
1654 elif type == FILETYPE_ASN1:
1655 write_bio = _lib.i2d_PUBKEY_bio
1656 else:
1657 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1658
1659 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001660 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001661 _raise_current_error()
1662
1663 return _bio_to_string(bio)
1664
1665
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001666def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1667 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001668 Dump the private key *pkey* into a buffer string encoded with the type
1669 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1670 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001671
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001672 :param type: The file type (one of :const:`FILETYPE_PEM`,
1673 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1674 :param PKey pkey: The PKey to dump
1675 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001676 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001677 the passphrase to use, or a callback for providing the passphrase.
1678
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001679 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001680 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001681 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001682 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001683
1684 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001685 if passphrase is None:
1686 raise TypeError(
1687 "if a value is given for cipher "
1688 "one must also be given for passphrase")
1689 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001690 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001691 raise ValueError("Invalid cipher name")
1692 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001694
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001695 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001696 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001697 result_code = _lib.PEM_write_bio_PrivateKey(
1698 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001699 helper.callback, helper.callback_args)
1700 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001701 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001702 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001703 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001704 rsa = _ffi.gc(
1705 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1706 _lib.RSA_free
1707 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001708 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001709 else:
1710 raise ValueError(
1711 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1712 "FILETYPE_TEXT")
1713
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001714 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001715
1716 return _bio_to_string(bio)
1717
1718
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001719class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001720 """
1721 A certificate revocation.
1722 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001723 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1724 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1725 # OCSP_crl_reason_str. We use the latter, just like the command line
1726 # program.
1727 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001728 b"unspecified",
1729 b"keyCompromise",
1730 b"CACompromise",
1731 b"affiliationChanged",
1732 b"superseded",
1733 b"cessationOfOperation",
1734 b"certificateHold",
1735 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001736 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001737
1738 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 revoked = _lib.X509_REVOKED_new()
1740 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001741
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001742 def set_serial(self, hex_str):
1743 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001744 Set the serial number.
1745
1746 The serial number is formatted as a hexadecimal number encoded in
1747 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001748
Dan Sully44e767a2016-06-04 18:05:27 -07001749 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001750
Dan Sully44e767a2016-06-04 18:05:27 -07001751 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001752 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001753 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1754 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001755 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001756 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001757 if not bn_result:
1758 raise ValueError("bad hex string")
1759
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001760 asn1_serial = _ffi.gc(
1761 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1762 _lib.ASN1_INTEGER_free)
1763 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001764
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001765 def get_serial(self):
1766 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001767 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001768
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001769 The serial number is formatted as a hexadecimal number encoded in
1770 ASCII.
1771
1772 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001773 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001774 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001775 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001776
Alex Gaynor67903a62016-06-02 10:37:13 -07001777 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1778 _openssl_assert(asn1_int != _ffi.NULL)
1779 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1780 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001781 return _bio_to_string(bio)
1782
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001783 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001784 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1785 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001786 obj = _lib.X509_EXTENSION_get_object(ext)
1787 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001788 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001789 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001790 break
1791
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001792 def set_reason(self, reason):
1793 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001794 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001795
Dan Sully44e767a2016-06-04 18:05:27 -07001796 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001797
1798 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001799 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001800
Dan Sully44e767a2016-06-04 18:05:27 -07001801 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001802
1803 .. seealso::
1804
Dan Sully44e767a2016-06-04 18:05:27 -07001805 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001806 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001807 """
1808 if reason is None:
1809 self._delete_reason()
1810 elif not isinstance(reason, bytes):
1811 raise TypeError("reason must be None or a byte string")
1812 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001813 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001814 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1815
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001816 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001817 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001818 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001819
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001820 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001821 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001822
1823 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001824 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1825 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001826 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001827
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001828 def get_reason(self):
1829 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001830 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001831
Dan Sully44e767a2016-06-04 18:05:27 -07001832 :return: The reason, or ``None`` if there is none.
1833 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001834
1835 .. seealso::
1836
Dan Sully44e767a2016-06-04 18:05:27 -07001837 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001838 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001839 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001840 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1841 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001842 obj = _lib.X509_EXTENSION_get_object(ext)
1843 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001844 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001845
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001846 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001848 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001849 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001850 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001851 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001852
1853 return _bio_to_string(bio)
1854
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001855 def all_reasons(self):
1856 """
1857 Return a list of all the supported reason strings.
1858
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001859 This list is a copy; modifying it does not change the supported reason
1860 strings.
1861
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001862 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001863 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001864 """
1865 return self._crl_reasons[:]
1866
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001867 def set_rev_date(self, when):
1868 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001869 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001870
Dan Sully44e767a2016-06-04 18:05:27 -07001871 :param bytes when: The timestamp of the revocation,
1872 as ASN.1 GENERALIZEDTIME.
1873 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001874 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001875 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1876 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001877
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001878 def get_rev_date(self):
1879 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001880 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001881
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001882 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001883 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001884 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001885 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1886 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001887
1888
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001889class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001890 """
1891 A certificate revocation list.
1892 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001893
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001894 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001895 crl = _lib.X509_CRL_new()
1896 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001897
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001898 def get_revoked(self):
1899 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001900 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001901
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001902 These revocations will be provided by value, not by reference.
1903 That means it's okay to mutate them: it won't affect this CRL.
1904
1905 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001906 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001907 """
1908 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001909 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001910 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1911 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001912 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001913 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001914 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001915 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001916 if results:
1917 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001918
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001919 def add_revoked(self, revoked):
1920 """
1921 Add a revoked (by value not reference) to the CRL structure
1922
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001923 This revocation will be added by value, not by reference. That
1924 means it's okay to mutate it after adding: it won't affect
1925 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001926
Dan Sully44e767a2016-06-04 18:05:27 -07001927 :param Revoked revoked: The new revocation.
1928 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001929 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001930 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001931 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001932
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001933 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001934 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001935
Dan Sully44e767a2016-06-04 18:05:27 -07001936 def get_issuer(self):
1937 """
1938 Get the CRL's issuer.
1939
1940 .. versionadded:: 16.1.0
1941
1942 :rtype: X509Name
1943 """
1944 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
1945 _openssl_assert(_issuer != _ffi.NULL)
1946 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
1947 issuer = X509Name.__new__(X509Name)
1948 issuer._name = _issuer
1949 return issuer
1950
1951 def set_version(self, version):
1952 """
1953 Set the CRL version.
1954
1955 .. versionadded:: 16.1.0
1956
1957 :param int version: The version of the CRL.
1958 :return: ``None``
1959 """
1960 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
1961
1962 def _set_boundary_time(self, which, when):
1963 return _set_asn1_time(which(self._crl), when)
1964
1965 def set_lastUpdate(self, when):
1966 """
1967 Set when the CRL was last updated.
1968
1969 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
1970
1971 YYYYMMDDhhmmssZ
1972 YYYYMMDDhhmmss+hhmm
1973 YYYYMMDDhhmmss-hhmm
1974
1975 .. versionadded:: 16.1.0
1976
1977 :param bytes when: A timestamp string.
1978 :return: ``None``
1979 """
1980 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
1981
1982 def set_nextUpdate(self, when):
1983 """
1984 Set when the CRL will next be udpated.
1985
1986 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
1987
1988 YYYYMMDDhhmmssZ
1989 YYYYMMDDhhmmss+hhmm
1990 YYYYMMDDhhmmss-hhmm
1991
1992 .. versionadded:: 16.1.0
1993
1994 :param bytes when: A timestamp string.
1995 :return: ``None``
1996 """
1997 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
1998
1999 def sign(self, issuer_cert, issuer_key, digest):
2000 """
2001 Sign the CRL.
2002
2003 Signing a CRL enables clients to associate the CRL itself with an
2004 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2005 be signed by an issuer.
2006
2007 This method implicitly sets the issuer's name based on the issuer
2008 certificate and private key used to sign the CRL.
2009
2010 .. versionadded:: 16.1.0
2011
2012 :param X509 issuer_cert: The issuer's certificate.
2013 :param PKey issuer_key: The issuer's private key.
2014 :param bytes digest: The digest method to sign the CRL with.
2015 """
2016 digest_obj = _lib.EVP_get_digestbyname(digest)
2017 _openssl_assert(digest_obj != _ffi.NULL)
2018 _lib.X509_CRL_set_issuer_name(
2019 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2020 _lib.X509_CRL_sort(self._crl)
2021 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2022 _openssl_assert(result != 0)
2023
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002024 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002025 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002026 """
Dan Sully44e767a2016-06-04 18:05:27 -07002027 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002028
Dan Sully44e767a2016-06-04 18:05:27 -07002029 :param X509 cert: The certificate used to sign the CRL.
2030 :param PKey key: The key used to sign the CRL.
2031 :param int type: The export format, either :data:`FILETYPE_PEM`,
2032 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002033 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002034 :param bytes digest: The name of the message digest to use (eg
2035 ``b"sha1"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002036 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002037 """
Dan Sully44e767a2016-06-04 18:05:27 -07002038
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002039 if not isinstance(cert, X509):
2040 raise TypeError("cert must be an X509 instance")
2041 if not isinstance(key, PKey):
2042 raise TypeError("key must be a PKey instance")
2043 if not isinstance(type, int):
2044 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002045
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002046 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002047 _warn(
2048 "The default message digest (md5) is deprecated. "
2049 "Pass the name of a message digest explicitly.",
2050 category=DeprecationWarning,
2051 stacklevel=2,
2052 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002053 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002054
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002055 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002056 if digest_obj == _ffi.NULL:
2057 raise ValueError("No such digest method")
2058
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002059 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002060 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002061
Alex Gaynora738ed52015-09-05 11:17:10 -04002062 # A scratch time object to give different values to different CRL
2063 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002064 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002065 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002066
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002067 _lib.X509_gmtime_adj(sometime, 0)
2068 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002069
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002070 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2071 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002072
Alex Gaynor5945ea82015-09-05 14:59:06 -04002073 _lib.X509_CRL_set_issuer_name(
2074 self._crl, _lib.X509_get_subject_name(cert._x509)
2075 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002076
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002077 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002078 if not sign_result:
2079 _raise_current_error()
2080
Dominic Chenf05b2122015-10-13 16:32:35 +00002081 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002082
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002083
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002084CRLType = CRL
2085
2086
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002087class PKCS7(object):
2088 def type_is_signed(self):
2089 """
2090 Check if this NID_pkcs7_signed object
2091
2092 :return: True if the PKCS7 is of type signed
2093 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002094 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002095 return True
2096 return False
2097
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002098 def type_is_enveloped(self):
2099 """
2100 Check if this NID_pkcs7_enveloped object
2101
2102 :returns: True if the PKCS7 is of type enveloped
2103 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002104 if _lib.PKCS7_type_is_enveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002105 return True
2106 return False
2107
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002108 def type_is_signedAndEnveloped(self):
2109 """
2110 Check if this NID_pkcs7_signedAndEnveloped object
2111
2112 :returns: True if the PKCS7 is of type signedAndEnveloped
2113 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002114 if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002115 return True
2116 return False
2117
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002118 def type_is_data(self):
2119 """
2120 Check if this NID_pkcs7_data object
2121
2122 :return: True if the PKCS7 is of type data
2123 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002124 if _lib.PKCS7_type_is_data(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002125 return True
2126 return False
2127
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002128 def get_type_name(self):
2129 """
2130 Returns the type name of the PKCS7 structure
2131
2132 :return: A string with the typename
2133 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002134 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2135 string_type = _lib.OBJ_nid2sn(nid)
2136 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002137
2138PKCS7Type = PKCS7
2139
2140
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002141class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002142 """
2143 A PKCS #12 archive.
2144 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002145
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002146 def __init__(self):
2147 self._pkey = None
2148 self._cert = None
2149 self._cacerts = None
2150 self._friendlyname = None
2151
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002152 def get_certificate(self):
2153 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002154 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002155
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002156 :return: The certificate, or :py:const:`None` if there is none.
2157 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002158 """
2159 return self._cert
2160
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002161 def set_certificate(self, cert):
2162 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002163 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002164
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002165 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002166 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002167
Dan Sully44e767a2016-06-04 18:05:27 -07002168 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002169 """
2170 if not isinstance(cert, X509):
2171 raise TypeError("cert must be an X509 instance")
2172 self._cert = cert
2173
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002174 def get_privatekey(self):
2175 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002176 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002177
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002178 :return: The private key, or :py:const:`None` if there is none.
2179 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002180 """
2181 return self._pkey
2182
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002183 def set_privatekey(self, pkey):
2184 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002185 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002186
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002187 :param pkey: The new private key, or :py:const:`None` to unset it.
2188 :type pkey: :py:class:`PKey` or :py:const:`None`
2189
Dan Sully44e767a2016-06-04 18:05:27 -07002190 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002191 """
2192 if not isinstance(pkey, PKey):
2193 raise TypeError("pkey must be a PKey instance")
2194 self._pkey = pkey
2195
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002196 def get_ca_certificates(self):
2197 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002198 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002199
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002200 :return: A tuple with the CA certificates in the chain, or
2201 :py:const:`None` if there are none.
2202 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002203 """
2204 if self._cacerts is not None:
2205 return tuple(self._cacerts)
2206
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002207 def set_ca_certificates(self, cacerts):
2208 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002209 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002210
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002211 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2212 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002213 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002214
Dan Sully44e767a2016-06-04 18:05:27 -07002215 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002216 """
2217 if cacerts is None:
2218 self._cacerts = None
2219 else:
2220 cacerts = list(cacerts)
2221 for cert in cacerts:
2222 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002223 raise TypeError(
2224 "iterable must only contain X509 instances"
2225 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002226 self._cacerts = cacerts
2227
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002228 def set_friendlyname(self, name):
2229 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002230 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002231
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002232 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002233 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002234
Dan Sully44e767a2016-06-04 18:05:27 -07002235 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002236 """
2237 if name is None:
2238 self._friendlyname = None
2239 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002240 raise TypeError(
2241 "name must be a byte string or None (not %r)" % (name,)
2242 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002243 self._friendlyname = name
2244
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002245 def get_friendlyname(self):
2246 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002247 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002248
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002249 :returns: The friendly name, or :py:const:`None` if there is none.
2250 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002251 """
2252 return self._friendlyname
2253
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002254 def export(self, passphrase=None, iter=2048, maciter=1):
2255 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002256 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002257
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002258 For more information, see the :c:func:`PKCS12_create` man page.
2259
2260 :param passphrase: The passphrase used to encrypt the structure. Unlike
2261 some other passphrase arguments, this *must* be a string, not a
2262 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002263 :type passphrase: :py:data:`bytes`
2264
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002265 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002266 :type iter: :py:data:`int`
2267
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002268 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002269 :type maciter: :py:data:`int`
2270
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002271 :return: The string representation of the PKCS #12 structure.
2272 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002273 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002274 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002275
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002276 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002277 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002278 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002279 cacerts = _lib.sk_X509_new_null()
2280 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002281 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002282 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002283
2284 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002285 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002286
2287 friendlyname = self._friendlyname
2288 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002289 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002290
2291 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002292 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002293 else:
2294 pkey = self._pkey._pkey
2295
2296 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002297 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002298 else:
2299 cert = self._cert._x509
2300
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002301 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002302 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002303 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2304 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002305 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002306 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002307 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002308 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002309
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002310 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002311 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002312 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002313
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002314
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002315PKCS12Type = PKCS12
2316
2317
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002318class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002319 """
2320 A Netscape SPKI object.
2321 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002322
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002323 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002324 spki = _lib.NETSCAPE_SPKI_new()
2325 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002326
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002327 def sign(self, pkey, digest):
2328 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002329 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002330
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002331 :param pkey: The private key to sign with.
2332 :type pkey: :py:class:`PKey`
2333
2334 :param digest: The message digest to use.
2335 :type digest: :py:class:`bytes`
2336
Dan Sully44e767a2016-06-04 18:05:27 -07002337 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002338 """
2339 if pkey._only_public:
2340 raise ValueError("Key has only public part")
2341
2342 if not pkey._initialized:
2343 raise ValueError("Key is uninitialized")
2344
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002345 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002346 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002347 raise ValueError("No such digest method")
2348
Alex Gaynor5945ea82015-09-05 14:59:06 -04002349 sign_result = _lib.NETSCAPE_SPKI_sign(
2350 self._spki, pkey._pkey, digest_obj
2351 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002352 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002353
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002354 def verify(self, key):
2355 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002356 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002357
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002358 :param key: The public key that signature is supposedly from.
2359 :type pkey: :py:class:`PKey`
2360
2361 :return: :py:const:`True` if the signature is correct.
2362 :rtype: :py:class:`bool`
2363
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002364 :raises Error: If the signature is invalid, or there was a problem
2365 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002366 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002367 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002368 if answer <= 0:
2369 _raise_current_error()
2370 return True
2371
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002372 def b64_encode(self):
2373 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002374 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002375
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002376 :return: The base64 encoded string.
2377 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002378 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002379 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2380 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002381 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002382 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002383
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002384 def get_pubkey(self):
2385 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002386 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002387
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002388 :return: The public key.
2389 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002390 """
2391 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002392 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002393 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002394 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002395 pkey._only_public = True
2396 return pkey
2397
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002398 def set_pubkey(self, pkey):
2399 """
2400 Set the public key of the certificate
2401
2402 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002403 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002404 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002405 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002406 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002407
2408
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002409NetscapeSPKIType = NetscapeSPKI
2410
2411
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002412class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002413 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002414 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002415 raise ValueError(
2416 "only FILETYPE_PEM key format supports encryption"
2417 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002418 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002419 self._more_args = more_args
2420 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002421 self._problems = []
2422
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002423 @property
2424 def callback(self):
2425 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002426 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002427 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002428 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002429 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002430 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002431 else:
2432 raise TypeError("Last argument must be string or callable")
2433
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002434 @property
2435 def callback_args(self):
2436 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002437 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002438 elif isinstance(self._passphrase, bytes):
2439 return self._passphrase
2440 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002441 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002442 else:
2443 raise TypeError("Last argument must be string or callable")
2444
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002445 def raise_if_problem(self, exceptionType=Error):
2446 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002447 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002448 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002449 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002450 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002451 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002452 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002453
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002454 def _read_passphrase(self, buf, size, rwflag, userdata):
2455 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002456 if self._more_args:
2457 result = self._passphrase(size, rwflag, userdata)
2458 else:
2459 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002460 if not isinstance(result, bytes):
2461 raise ValueError("String expected")
2462 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002463 if self._truncate:
2464 result = result[:size]
2465 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002466 raise ValueError(
2467 "passphrase returned by callback is too long"
2468 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002469 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002470 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002471 return len(result)
2472 except Exception as e:
2473 self._problems.append(e)
2474 return 0
2475
2476
Cory Benfield6492f7c2015-10-27 16:57:58 +09002477def load_publickey(type, buffer):
2478 """
Cory Benfield11c10192015-10-27 17:23:03 +09002479 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002480
Cory Benfield9c590b92015-10-28 14:55:05 +09002481 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002482 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002483 :param buffer: The buffer the key is stored in.
2484 :type buffer: A Python string object, either unicode or bytestring.
2485 :return: The PKey object.
2486 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002487 """
2488 if isinstance(buffer, _text_type):
2489 buffer = buffer.encode("ascii")
2490
2491 bio = _new_mem_buf(buffer)
2492
2493 if type == FILETYPE_PEM:
2494 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2495 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2496 elif type == FILETYPE_ASN1:
2497 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2498 else:
2499 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2500
2501 if evp_pkey == _ffi.NULL:
2502 _raise_current_error()
2503
2504 pkey = PKey.__new__(PKey)
2505 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002506 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002507 return pkey
2508
2509
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002510def load_privatekey(type, buffer, passphrase=None):
2511 """
2512 Load a private key from a buffer
2513
2514 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2515 :param buffer: The buffer the key is stored in
2516 :param passphrase: (optional) if encrypted PEM format, this can be
2517 either the passphrase to use, or a callback for
2518 providing the passphrase.
2519
2520 :return: The PKey object
2521 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002522 if isinstance(buffer, _text_type):
2523 buffer = buffer.encode("ascii")
2524
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002525 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002526
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002527 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002528 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002529 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2530 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002531 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002532 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002533 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002534 else:
2535 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2536
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002537 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002538 _raise_current_error()
2539
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002540 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002541 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002542 return pkey
2543
2544
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002545def dump_certificate_request(type, req):
2546 """
2547 Dump a certificate request to a buffer
2548
2549 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2550 :param req: The certificate request to dump
2551 :return: The buffer with the dumped certificate request in
2552 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002553 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002554
2555 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002556 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002557 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002558 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002559 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002560 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002561 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002562 raise ValueError(
2563 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2564 "FILETYPE_TEXT"
2565 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002566
Alex Gaynor09a386e2016-07-03 09:32:44 -04002567 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002568
2569 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002570
2571
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002572def load_certificate_request(type, buffer):
2573 """
2574 Load a certificate request from a buffer
2575
2576 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2577 :param buffer: The buffer the certificate request is stored in
2578 :return: The X509Req object
2579 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002580 if isinstance(buffer, _text_type):
2581 buffer = buffer.encode("ascii")
2582
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002583 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002584
2585 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002586 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002587 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002588 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002589 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002590 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002591
Alex Gaynoradd5b072016-06-04 21:04:00 -07002592 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002593
2594 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002595 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002596 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002597
2598
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002599def sign(pkey, data, digest):
2600 """
2601 Sign data with a digest
2602
2603 :param pkey: Pkey to sign with
2604 :param data: data to be signed
2605 :param digest: message digest to use
2606 :return: signature
2607 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002608 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002609
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002610 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002611 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002612 raise ValueError("No such digest method")
2613
Alex Gaynor67903a62016-06-02 10:37:13 -07002614 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002615 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002617 _lib.EVP_SignInit(md_ctx, digest_obj)
2618 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002619
Colleen Murphye09399b2016-03-01 17:40:49 -08002620 pkey_length = (PKey.bits(pkey) + 7) // 8
2621 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002622 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002623 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002624 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002625 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002626
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002627 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002628
2629
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002630def verify(cert, signature, data, digest):
2631 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002632 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002633
2634 :param cert: signing certificate (X509 object)
2635 :param signature: signature returned by sign function
2636 :param data: data to be verified
2637 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002638 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002639 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002640 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002641
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002642 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002643 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002644 raise ValueError("No such digest method")
2645
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002646 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002647 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002648 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002649
Alex Gaynor67903a62016-06-02 10:37:13 -07002650 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002651 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002652
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002653 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2654 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002655 verify_result = _lib.EVP_VerifyFinal(
2656 md_ctx, signature, len(signature), pkey
2657 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002658
2659 if verify_result != 1:
2660 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002661
2662
Dominic Chenf05b2122015-10-13 16:32:35 +00002663def dump_crl(type, crl):
2664 """
2665 Dump a certificate revocation list to a buffer.
2666
2667 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2668 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002669 :param CRL crl: The CRL to dump.
2670
Dominic Chenf05b2122015-10-13 16:32:35 +00002671 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002672 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002673 """
2674 bio = _new_mem_buf()
2675
2676 if type == FILETYPE_PEM:
2677 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2678 elif type == FILETYPE_ASN1:
2679 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2680 elif type == FILETYPE_TEXT:
2681 ret = _lib.X509_CRL_print(bio, crl._crl)
2682 else:
2683 raise ValueError(
2684 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2685 "FILETYPE_TEXT")
2686
2687 assert ret == 1
2688 return _bio_to_string(bio)
2689
2690
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002691def load_crl(type, buffer):
2692 """
2693 Load a certificate revocation list from a buffer
2694
2695 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2696 :param buffer: The buffer the CRL is stored in
2697
2698 :return: The PKey object
2699 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002700 if isinstance(buffer, _text_type):
2701 buffer = buffer.encode("ascii")
2702
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002703 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002704
2705 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002706 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002707 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002708 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002709 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002710 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2711
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002712 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002713 _raise_current_error()
2714
2715 result = CRL.__new__(CRL)
2716 result._crl = crl
2717 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002718
2719
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002720def load_pkcs7_data(type, buffer):
2721 """
2722 Load pkcs7 data from a buffer
2723
2724 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2725 :param buffer: The buffer with the pkcs7 data.
2726 :return: The PKCS7 object
2727 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002728 if isinstance(buffer, _text_type):
2729 buffer = buffer.encode("ascii")
2730
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002731 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002732
2733 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002734 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002735 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002736 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002737 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002738 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2739
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002740 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002741 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002742
2743 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002744 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002745 return pypkcs7
2746
2747
Stephen Holsapple38482622014-04-05 20:29:34 -07002748def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002749 """
2750 Load a PKCS12 object from a buffer
2751
2752 :param buffer: The buffer the certificate is stored in
2753 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2754 :returns: The PKCS12 object
2755 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002756 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002757
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002758 if isinstance(buffer, _text_type):
2759 buffer = buffer.encode("ascii")
2760
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002761 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002762
Stephen Holsapple38482622014-04-05 20:29:34 -07002763 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2764 # password based encryption no password and a zero length password are two
2765 # different things, but OpenSSL implementation will try both to figure out
2766 # which one works.
2767 if not passphrase:
2768 passphrase = _ffi.NULL
2769
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002770 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2771 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002772 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002773 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002774
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002775 pkey = _ffi.new("EVP_PKEY**")
2776 cert = _ffi.new("X509**")
2777 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002778
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002779 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002780 if not parse_result:
2781 _raise_current_error()
2782
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002783 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002784
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002785 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2786 # queue for no particular reason. This error isn't interesting to anyone
2787 # outside this function. It's not even interesting to us. Get rid of it.
2788 try:
2789 _raise_current_error()
2790 except Error:
2791 pass
2792
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002793 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002794 pykey = None
2795 else:
2796 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002797 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002798
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002799 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002800 pycert = None
2801 friendlyname = None
2802 else:
2803 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002804 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002805
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002806 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002807 friendlyname_buffer = _lib.X509_alias_get0(
2808 cert[0], friendlyname_length
2809 )
2810 friendlyname = _ffi.buffer(
2811 friendlyname_buffer, friendlyname_length[0]
2812 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002813 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002814 friendlyname = None
2815
2816 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002817 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002818 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002819 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002820 pycacerts.append(pycacert)
2821 if not pycacerts:
2822 pycacerts = None
2823
2824 pkcs12 = PKCS12.__new__(PKCS12)
2825 pkcs12._pkey = pykey
2826 pkcs12._cert = pycert
2827 pkcs12._cacerts = pycacerts
2828 pkcs12._friendlyname = friendlyname
2829 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002830
2831
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002832# There are no direct unit tests for this initialization. It is tested
2833# indirectly since it is necessary for functions like dump_privatekey when
2834# using encryption.
2835#
2836# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2837# and some other similar tests may fail without this (though they may not if
2838# the Python runtime has already done some initialization of the underlying
2839# OpenSSL library (and is linked against the same one that cryptography is
2840# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002841_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002842
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002843# This is similar but exercised mainly by exception_from_error_queue. It calls
2844# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2845_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002846
2847
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002848# Set the default string mask to match OpenSSL upstream (since 2005) and
2849# RFC5280 recommendations.
2850_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')