blob: c37f20bad3ed28726ba7adc7c1aa5fe5564ab4ba [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
Paul Kehrer72d968b2016-07-29 15:31:04 +080013from cryptography.hazmat.backends.openssl.backend import backend
14from cryptography.hazmat.primitives.asymmetric import dsa, rsa
15
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050016from OpenSSL._util import (
17 ffi as _ffi,
18 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050019 exception_from_error_queue as _exception_from_error_queue,
20 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040021 native as _native,
22 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040023 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070024 make_assert as _make_assert,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040025)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080026
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050027FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
28FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080029
30# TODO This was an API mistake. OpenSSL has no such constant.
31FILETYPE_TEXT = 2 ** 16 - 1
32
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050033TYPE_RSA = _lib.EVP_PKEY_RSA
34TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080035
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080036
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050037class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050038 """
39 An error occurred in an `OpenSSL.crypto` API.
40 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050041
42
43_raise_current_error = partial(_exception_from_error_queue, Error)
Alex Gaynor67903a62016-06-02 10:37:13 -070044_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050045
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070046
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050047def _untested_error(where):
48 """
49 An OpenSSL API failed somehow. Additionally, the failure which was
50 encountered isn't one that's exercised by the test suite so future behavior
51 of pyOpenSSL is now somewhat less predictable.
52 """
53 raise RuntimeError("Unknown %s failure" % (where,))
54
55
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050056def _new_mem_buf(buffer=None):
57 """
58 Allocate a new OpenSSL memory BIO.
59
60 Arrange for the garbage collector to clean it up automatically.
61
62 :param buffer: None or some bytes to use to put into the BIO so that they
63 can be read out.
64 """
65 if buffer is None:
66 bio = _lib.BIO_new(_lib.BIO_s_mem())
67 free = _lib.BIO_free
68 else:
69 data = _ffi.new("char[]", buffer)
70 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040071
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050072 # Keep the memory alive as long as the bio is alive!
73 def free(bio, ref=data):
74 return _lib.BIO_free(bio)
75
Alex Gaynorfb8a2a12016-06-04 18:26:26 -070076 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050077
78 bio = _ffi.gc(bio, free)
79 return bio
80
81
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080082def _bio_to_string(bio):
83 """
84 Copy the contents of an OpenSSL BIO object into a Python byte string.
85 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050086 result_buffer = _ffi.new('char**')
87 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
88 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080089
90
Jean-Paul Calderone57122982013-02-21 08:47:05 -080091def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050092 """
93 The the time value of an ASN1 time object.
94
95 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
96 castable to that type) which will have its value set.
97 @param when: A string representation of the desired time value.
98
99 @raise TypeError: If C{when} is not a L{bytes} string.
100 @raise ValueError: If C{when} does not represent a time in the required
101 format.
102 @raise RuntimeError: If the time value cannot be set for some other
103 (unspecified) reason.
104 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800105 if not isinstance(when, bytes):
106 raise TypeError("when must be a byte string")
107
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500108 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
109 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800110 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500111 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
112 _lib.ASN1_STRING_set(dummy, when, len(when))
113 check_result = _lib.ASN1_GENERALIZEDTIME_check(
114 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800115 if not check_result:
116 raise ValueError("Invalid string")
117 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500118 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800119
Alex Gaynor510293e2016-06-02 12:07:59 -0700120
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800121def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500122 """
123 Retrieve the time value of an ASN1 time object.
124
125 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
126 that type) from which the time value will be retrieved.
127
128 @return: The time value from C{timestamp} as a L{bytes} string in a certain
129 format. Or C{None} if the object contains no time value.
130 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500131 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
132 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800133 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400134 elif (
135 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
136 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500137 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800138 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500139 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
140 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
141 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500142 # This may happen:
143 # - if timestamp was not an ASN1_TIME
144 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
145 # - if a copy of the time data from timestamp cannot be made for
146 # the newly allocated ASN1_GENERALIZEDTIME
147 #
148 # These are difficult to test. cffi enforces the ASN1_TIME type.
149 # Memory allocation failures are a pain to trigger
150 # deterministically.
151 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800152 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500153 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800154 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500155 string_data = _lib.ASN1_STRING_data(string_timestamp)
156 string_result = _ffi.string(string_data)
157 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800158 return string_result
159
160
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800161class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200162 """
163 A class representing an DSA or RSA public key or key pair.
164 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800165 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800166 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800167
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800168 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500169 pkey = _lib.EVP_PKEY_new()
170 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800171 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800172
Paul Kehrer72d968b2016-07-29 15:31:04 +0800173 def to_cryptography_key(self):
174 """
175 Export as a ``cryptography`` key.
176
177 :rtype: One of ``cryptography``'s `key interfaces`_.
178
179 .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
180 primitives/asymmetric/rsa/#key-interfaces
181
182 .. versionadded:: 16.1.0
183 """
184 if self._only_public:
185 return backend._evp_pkey_to_public_key(self._pkey)
186 else:
187 return backend._evp_pkey_to_private_key(self._pkey)
188
189 @classmethod
190 def from_cryptography_key(cls, crypto_key):
191 """
192 Construct based on a ``cryptography`` *crypto_key*.
193
194 :param crypto_key: A ``cryptography`` key.
195 :type crypto_key: One of ``cryptography``'s `key interfaces`_.
196
197 :rtype: PKey
198
199 .. versionadded:: 16.1.0
200 """
201 pkey = cls()
202 if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
203 dsa.DSAPublicKey, dsa.DSAPrivateKey)):
204 raise TypeError("Unsupported key type")
205
206 pkey._pkey = crypto_key._evp_pkey
207 if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
208 pkey._only_public = True
209 pkey._initialized = True
210 return pkey
211
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800212 def generate_key(self, type, bits):
213 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700214 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800215
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200216 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800217
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200218 :param type: The key type.
219 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
220 :param bits: The number of bits.
221 :type bits: :py:data:`int` ``>= 0``
222 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
223 of the appropriate type.
224 :raises ValueError: If the number of bits isn't an integer of
225 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700226 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800227 """
228 if not isinstance(type, int):
229 raise TypeError("type must be an integer")
230
231 if not isinstance(bits, int):
232 raise TypeError("bits must be an integer")
233
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800234 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500235 exponent = _lib.BN_new()
236 exponent = _ffi.gc(exponent, _lib.BN_free)
237 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800238
239 if type == TYPE_RSA:
240 if bits <= 0:
241 raise ValueError("Invalid number of bits")
242
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500243 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800244
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500245 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400246 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800247
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500248 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400249 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800250
251 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400252 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700253 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400254
255 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400256 res = _lib.DSA_generate_parameters_ex(
257 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
258 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700259 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400260
261 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
262 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800263 else:
264 raise Error("No such key type")
265
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800266 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800267
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800268 def check(self):
269 """
270 Check the consistency of an RSA private key.
271
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200272 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
273
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800274 :return: True if key is consistent.
275 :raise Error: if the key is inconsistent.
276 :raise TypeError: if the key is of a type which cannot be checked.
277 Only RSA keys can currently be checked.
278 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800279 if self._only_public:
280 raise TypeError("public key only")
281
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100282 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800283 raise TypeError("key type unsupported")
284
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500285 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
286 rsa = _ffi.gc(rsa, _lib.RSA_free)
287 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800288 if result:
289 return True
290 _raise_current_error()
291
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800292 def type(self):
293 """
294 Returns the type of the key
295
296 :return: The type of the key.
297 """
Alex Gaynorc84567b2016-03-16 07:45:09 -0400298 return _lib.Cryptography_EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800299
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800300 def bits(self):
301 """
302 Returns the number of bits of the key
303
304 :return: The number of bits of the key.
305 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500306 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800307PKeyType = PKey
308
309
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400310class _EllipticCurve(object):
311 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400312 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400313
314 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
315 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
316 instances each of which represents one curve supported by the system.
317 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400318 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400319 _curves = None
320
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400321 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400322 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400323 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400324 """
325 Implement cooperation with the right-hand side argument of ``!=``.
326
327 Python 3 seems to have dropped this cooperation in this very narrow
328 circumstance.
329 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400330 if isinstance(other, _EllipticCurve):
331 return super(_EllipticCurve, self).__ne__(other)
332 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400333
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400334 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400335 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400336 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400337 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400338
339 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400340
341 :return: A :py:type:`set` of ``cls`` instances giving the names of the
342 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400343 """
344 if lib.Cryptography_HAS_EC:
345 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
346 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
Alex Gaynor5945ea82015-09-05 14:59:06 -0400347 # The return value on this call should be num_curves again. We
348 # could check it to make sure but if it *isn't* then.. what could
349 # we do? Abort the whole process, I suppose...? -exarkun
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400350 lib.EC_get_builtin_curves(builtin_curves, num_curves)
351 return set(
352 cls.from_nid(lib, c.nid)
353 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400354 return set()
355
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400356 @classmethod
357 def _get_elliptic_curves(cls, lib):
358 """
359 Get, cache, and return the curves supported by OpenSSL.
360
361 :param lib: The OpenSSL library binding object.
362
363 :return: A :py:type:`set` of ``cls`` instances giving the names of the
364 elliptic curves the underlying library supports.
365 """
366 if cls._curves is None:
367 cls._curves = cls._load_elliptic_curves(lib)
368 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400369
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400370 @classmethod
371 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400372 """
373 Instantiate a new :py:class:`_EllipticCurve` associated with the given
374 OpenSSL NID.
375
376 :param lib: The OpenSSL library binding object.
377
378 :param nid: The OpenSSL NID the resulting curve object will represent.
379 This must be a curve NID (and not, for example, a hash NID) or
380 subsequent operations will fail in unpredictable ways.
381 :type nid: :py:class:`int`
382
383 :return: The curve object.
384 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400385 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
386
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400387 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400388 """
389 :param _lib: The :py:mod:`cryptography` binding instance used to
390 interface with OpenSSL.
391
392 :param _nid: The OpenSSL NID identifying the curve this object
393 represents.
394 :type _nid: :py:class:`int`
395
396 :param name: The OpenSSL short name identifying the curve this object
397 represents.
398 :type name: :py:class:`unicode`
399 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400400 self._lib = lib
401 self._nid = nid
402 self.name = name
403
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400404 def __repr__(self):
405 return "<Curve %r>" % (self.name,)
406
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400407 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400408 """
409 Create a new OpenSSL EC_KEY structure initialized to use this curve.
410
411 The structure is automatically garbage collected when the Python object
412 is garbage collected.
413 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400414 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
415 return _ffi.gc(key, _lib.EC_KEY_free)
416
417
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400418def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400419 """
420 Return a set of objects representing the elliptic curves supported in the
421 OpenSSL build in use.
422
423 The curve objects have a :py:class:`unicode` ``name`` attribute by which
424 they identify themselves.
425
426 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400427 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
428 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400429 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400430 return _EllipticCurve._get_elliptic_curves(_lib)
431
432
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400433def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400434 """
435 Return a single curve object selected by name.
436
437 See :py:func:`get_elliptic_curves` for information about curve objects.
438
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400439 :param name: The OpenSSL short name identifying the curve object to
440 retrieve.
441 :type name: :py:class:`unicode`
442
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400443 If the named curve is not supported then :py:class:`ValueError` is raised.
444 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400445 for curve in get_elliptic_curves():
446 if curve.name == name:
447 return curve
448 raise ValueError("unknown curve name", name)
449
450
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800451class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200452 """
453 An X.509 Distinguished Name.
454
455 :ivar countryName: The country of the entity.
456 :ivar C: Alias for :py:attr:`countryName`.
457
458 :ivar stateOrProvinceName: The state or province of the entity.
459 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
460
461 :ivar localityName: The locality of the entity.
462 :ivar L: Alias for :py:attr:`localityName`.
463
464 :ivar organizationName: The organization name of the entity.
465 :ivar O: Alias for :py:attr:`organizationName`.
466
467 :ivar organizationalUnitName: The organizational unit of the entity.
468 :ivar OU: Alias for :py:attr:`organizationalUnitName`
469
470 :ivar commonName: The common name of the entity.
471 :ivar CN: Alias for :py:attr:`commonName`.
472
473 :ivar emailAddress: The e-mail address of the entity.
474 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400475
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800476 def __init__(self, name):
477 """
478 Create a new X509Name, copying the given X509Name instance.
479
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200480 :param name: The name to copy.
481 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800482 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500483 name = _lib.X509_NAME_dup(name._name)
484 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800485
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800486 def __setattr__(self, name, value):
487 if name.startswith('_'):
488 return super(X509Name, self).__setattr__(name, value)
489
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800490 # Note: we really do not want str subclasses here, so we do not use
491 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800492 if type(name) is not str:
493 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400494 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800495
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500496 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500497 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800498 try:
499 _raise_current_error()
500 except Error:
501 pass
502 raise AttributeError("No such attribute")
503
504 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500505 for i in range(_lib.X509_NAME_entry_count(self._name)):
506 ent = _lib.X509_NAME_get_entry(self._name, i)
507 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
508 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800509 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500510 ent = _lib.X509_NAME_delete_entry(self._name, i)
511 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800512 break
513
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500514 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800515 value = value.encode('utf-8')
516
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500517 add_result = _lib.X509_NAME_add_entry_by_NID(
518 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800519 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500520 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800521
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800522 def __getattr__(self, name):
523 """
524 Find attribute. An X509Name object has the following attributes:
525 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400526 organization (alias O), organizationalUnit (alias OU), commonName
527 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800528 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500529 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500530 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800531 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
532 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
533 # push something onto the error queue. If we don't clean that up
534 # now, someone else will bump into it later and be quite confused.
535 # See lp#314814.
536 try:
537 _raise_current_error()
538 except Error:
539 pass
540 return super(X509Name, self).__getattr__(name)
541
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500542 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800543 if entry_index == -1:
544 return None
545
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500546 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
547 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800548
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500549 result_buffer = _ffi.new("unsigned char**")
550 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400551 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800552
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700553 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400554 result = _ffi.buffer(
555 result_buffer[0], data_length
556 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700557 finally:
558 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500559 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800560 return result
561
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500562 def _cmp(op):
563 def f(self, other):
564 if not isinstance(other, X509Name):
565 return NotImplemented
566 result = _lib.X509_NAME_cmp(self._name, other._name)
567 return op(result, 0)
568 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800569
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500570 __eq__ = _cmp(__eq__)
571 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800572
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500573 __lt__ = _cmp(__lt__)
574 __le__ = _cmp(__le__)
575
576 __gt__ = _cmp(__gt__)
577 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800578
579 def __repr__(self):
580 """
581 String representation of an X509Name
582 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400583 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500584 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800585 self._name, result_buffer, len(result_buffer))
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700586 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800587
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500588 return "<X509Name object '%s'>" % (
589 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800590
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591 def hash(self):
592 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200593 Return an integer representation of the first four bytes of the
594 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800595
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200596 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
597
598 :return: The (integer) hash of this name.
599 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800600 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500601 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800602
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800603 def der(self):
604 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200605 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800606
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200607 :return: The DER encoded form of this name.
608 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800609 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500610 result_buffer = _ffi.new('unsigned char**')
611 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400612 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800613
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500614 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
615 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800616 return string_result
617
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800618 def get_components(self):
619 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200620 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800621
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200622 :return: The components of this name.
623 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800624 """
625 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500626 for i in range(_lib.X509_NAME_entry_count(self._name)):
627 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800628
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500629 fname = _lib.X509_NAME_ENTRY_get_object(ent)
630 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800631
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 nid = _lib.OBJ_obj2nid(fname)
633 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800634
635 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400636 _ffi.string(name),
637 _ffi.string(
638 _lib.ASN1_STRING_data(fval),
639 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800640
641 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200642
643
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800644X509NameType = X509Name
645
646
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800647class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200648 """
649 An X.509 v3 certificate extension.
650 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400651
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800652 def __init__(self, type_name, critical, value, subject=None, issuer=None):
653 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200654 Initializes an X509 extension.
655
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100656 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400657 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800658
Alex Gaynor5945ea82015-09-05 14:59:06 -0400659 :param bool critical: A flag indicating whether this is a critical
660 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800661
662 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200663 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800664
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200665 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800666 :type subject: :py:class:`X509`
667
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200668 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800669 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100670
671 .. _extension: https://openssl.org/docs/manmaster/apps/
672 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800673 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500674 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800675
Alex Gaynor5945ea82015-09-05 14:59:06 -0400676 # A context is necessary for any extension which uses the r2i
677 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
678 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500679 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800680
681 # We have no configuration database - but perhaps we should (some
682 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500683 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800684
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800685 # Initialize the subject and issuer, if appropriate. ctx is a local,
686 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400687 # any references, so no need to mess with reference counts or
688 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800689 if issuer is not None:
690 if not isinstance(issuer, X509):
691 raise TypeError("issuer must be an X509 instance")
692 ctx.issuer_cert = issuer._x509
693 if subject is not None:
694 if not isinstance(subject, X509):
695 raise TypeError("subject must be an X509 instance")
696 ctx.subject_cert = subject._x509
697
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800698 if critical:
699 # There are other OpenSSL APIs which would let us pass in critical
700 # separately, but they're harder to use, and since value is already
701 # a pile of crappy junk smuggling a ton of utterly important
702 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400703 # with strings? (However, X509V3_EXT_i2d in particular seems like
704 # it would be a better API to invoke. I do not know where to get
705 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500706 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500708 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
709 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800710 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500711 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800712
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400713 @property
714 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400715 return _lib.OBJ_obj2nid(
716 _lib.X509_EXTENSION_get_object(self._extension)
717 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400718
719 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500720 _lib.GEN_EMAIL: "email",
721 _lib.GEN_DNS: "DNS",
722 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400723 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400724
725 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 method = _lib.X509V3_EXT_get(self._extension)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700727 _openssl_assert(method != _ffi.NULL)
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400728 ext_data = _lib.X509_EXTENSION_get_data(self._extension)
729 payload = ext_data.data
730 length = ext_data.length
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400731
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500732 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400733 payloadptr[0] = payload
734
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500735 if method.it != _ffi.NULL:
736 ptr = _lib.ASN1_ITEM_ptr(method.it)
737 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
738 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400739 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500740 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400741 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500742 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400743
Paul Kehrerb7d79502015-05-04 07:43:51 -0500744 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400745 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 for i in range(_lib.sk_GENERAL_NAME_num(names)):
747 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400748 try:
749 label = self._prefixes[name.type]
750 except KeyError:
751 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500752 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500753 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400754 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500755 value = _native(
756 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
757 parts.append(label + ":" + value)
758 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400759
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800760 def __str__(self):
761 """
762 :return: a nice text representation of the extension
763 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500764 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400765 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800766
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400767 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500768 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400769 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800770
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500771 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800772
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800773 def get_critical(self):
774 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200775 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800776
777 :return: The critical field.
778 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500779 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800780
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800781 def get_short_name(self):
782 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200783 Returns the short type name of this X.509 extension.
784
785 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800786
787 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200788 :rtype: :py:data:`bytes`
789
790 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800791 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500792 obj = _lib.X509_EXTENSION_get_object(self._extension)
793 nid = _lib.OBJ_obj2nid(obj)
794 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800795
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800796 def get_data(self):
797 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200798 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800799
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200800 :return: The ASN.1 encoded data of this X509 extension.
801 :rtype: :py:data:`bytes`
802
803 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800804 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500805 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
806 string_result = _ffi.cast('ASN1_STRING*', octet_result)
807 char_result = _lib.ASN1_STRING_data(string_result)
808 result_length = _lib.ASN1_STRING_length(string_result)
809 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800810
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200811
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800812X509ExtensionType = X509Extension
813
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800814
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800815class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200816 """
817 An X.509 certificate signing requests.
818 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400819
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800820 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500821 req = _lib.X509_REQ_new()
822 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800823
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800824 def set_pubkey(self, pkey):
825 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200826 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800827
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200828 :param pkey: The public key to use.
829 :type pkey: :py:class:`PKey`
830
Dan Sully44e767a2016-06-04 18:05:27 -0700831 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800832 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500833 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400834 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800835
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800836 def get_pubkey(self):
837 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200838 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800839
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200840 :return: The public key.
841 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800842 """
843 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500844 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700845 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500846 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800847 pkey._only_public = True
848 return pkey
849
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800850 def set_version(self, version):
851 """
852 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
853 request.
854
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200855 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700856 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800857 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500858 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400859 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800860
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800861 def get_version(self):
862 """
863 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
864 request.
865
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200866 :return: The value of the version subfield.
867 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800868 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500869 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800870
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800871 def get_subject(self):
872 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200873 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800874
Cory Benfield881dc8d2015-12-09 08:25:14 +0000875 This creates a new :class:`X509Name` that wraps the underlying subject
876 name field on the certificate signing request. Modifying it will modify
877 the underlying signing request, and will have the effect of modifying
878 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200879
880 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000881 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800882 """
883 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500884 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700885 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800886
887 # The name is owned by the X509Req structure. As long as the X509Name
888 # Python object is alive, keep the X509Req Python object alive.
889 name._owner = self
890
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800891 return name
892
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800893 def add_extensions(self, extensions):
894 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200895 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800896
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200897 :param extensions: The X.509 extensions to add.
898 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700899 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800900 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500901 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700902 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800903
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500904 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800905
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800906 for ext in extensions:
907 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800908 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800909
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800910 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500911 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800912
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500913 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400914 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800915
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800916 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800917 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200918 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800919
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200920 :return: The X.509 extensions in this request.
921 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
922
923 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800924 """
925 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500926 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500927 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800928 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500929 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800930 exts.append(ext)
931 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800932
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800933 def sign(self, pkey, digest):
934 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700935 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800936
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200937 :param pkey: The key pair to sign with.
938 :type pkey: :py:class:`PKey`
939 :param digest: The name of the message digest to use for the signature,
940 e.g. :py:data:`b"sha1"`.
941 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -0700942 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800943 """
944 if pkey._only_public:
945 raise ValueError("Key has only public part")
946
947 if not pkey._initialized:
948 raise ValueError("Key is uninitialized")
949
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500950 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500951 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800952 raise ValueError("No such digest method")
953
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500954 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400955 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800956
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800957 def verify(self, pkey):
958 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200959 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800960
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200961 :param key: A public key.
962 :type key: :py:class:`PKey`
963 :return: :py:data:`True` if the signature is correct.
964 :rtype: :py:class:`bool`
965 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800966 problem verifying the signature.
967 """
968 if not isinstance(pkey, PKey):
969 raise TypeError("pkey must be a PKey instance")
970
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500971 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800972 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500973 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800974
975 return result
976
977
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800978X509ReqType = X509Req
979
980
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800981class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200982 """
983 An X.509 certificate.
984 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400985
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800986 def __init__(self):
987 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 x509 = _lib.X509_new()
989 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800990
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800991 def set_version(self, version):
992 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200993 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800994
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200995 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800996 :type version: :py:class:`int`
997
Dan Sully44e767a2016-06-04 18:05:27 -0700998 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800999 """
1000 if not isinstance(version, int):
1001 raise TypeError("version must be an integer")
1002
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001004
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001005 def get_version(self):
1006 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001007 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001008
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001009 :return: The version number of the certificate.
1010 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001011 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001012 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001013
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001014 def get_pubkey(self):
1015 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001016 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001017
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001018 :return: The public key.
1019 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001020 """
1021 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001022 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1023 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001024 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001025 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001026 pkey._only_public = True
1027 return pkey
1028
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001029 def set_pubkey(self, pkey):
1030 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001031 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001032
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001033 :param pkey: The public key.
1034 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001035
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001036 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001037 """
1038 if not isinstance(pkey, PKey):
1039 raise TypeError("pkey must be a PKey instance")
1040
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001041 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001042 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001043
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001044 def sign(self, pkey, digest):
1045 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001046 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001047
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001048 :param pkey: The key to sign with.
1049 :type pkey: :py:class:`PKey`
1050
1051 :param digest: The name of the message digest to use.
1052 :type digest: :py:class:`bytes`
1053
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001054 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001055 """
1056 if not isinstance(pkey, PKey):
1057 raise TypeError("pkey must be a PKey instance")
1058
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001059 if pkey._only_public:
1060 raise ValueError("Key only has public part")
1061
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001062 if not pkey._initialized:
1063 raise ValueError("Key is uninitialized")
1064
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001065 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001066 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001067 raise ValueError("No such digest method")
1068
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001069 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001070 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001071
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001072 def get_signature_algorithm(self):
1073 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001074 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001075
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001076 :return: The name of the algorithm.
1077 :rtype: :py:class:`bytes`
1078
1079 :raises ValueError: If the signature algorithm is undefined.
1080
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001081 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001082 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001083 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1084 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001086 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001088
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001089 def digest(self, digest_name):
1090 """
1091 Return the digest of the X509 object.
1092
1093 :param digest_name: The name of the digest algorithm to use.
1094 :type digest_name: :py:class:`bytes`
1095
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001096 :return: The digest of the object, formatted as
1097 :py:const:`b":"`-delimited hex pairs.
1098 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001099 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001100 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001101 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001102 raise ValueError("No such digest method")
1103
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001104 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1105 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001106 result_length[0] = len(result_buffer)
1107
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001108 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001109 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001110 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001111
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001112 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001113 b16encode(ch).upper() for ch
1114 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001115
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001116 def subject_name_hash(self):
1117 """
1118 Return the hash of the X509 subject.
1119
1120 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001121 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001122 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001123 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001124
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001125 def set_serial_number(self, serial):
1126 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001127 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001128
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001129 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001130 :type serial: :py:class:`int`
1131
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001132 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001133 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001134 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001135 raise TypeError("serial must be an integer")
1136
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001137 hex_serial = hex(serial)[2:]
1138 if not isinstance(hex_serial, bytes):
1139 hex_serial = hex_serial.encode('ascii')
1140
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001142
1143 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001144 # it. If bignum is still NULL after this call, then the return value
1145 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001146 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001147
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 if bignum_serial[0] == _ffi.NULL:
1149 set_result = _lib.ASN1_INTEGER_set(
1150 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001151 if set_result:
1152 # TODO Not tested
1153 _raise_current_error()
1154 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001155 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1156 _lib.BN_free(bignum_serial[0])
1157 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001158 # TODO Not tested
1159 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001160 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1161 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001162 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001163
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001164 def get_serial_number(self):
1165 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001166 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001167
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001168 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001169 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001170 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1172 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001173 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001174 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001175 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001176 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001177 serial = int(hexstring_serial, 16)
1178 return serial
1179 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001180 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001181 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001183
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001184 def gmtime_adj_notAfter(self, amount):
1185 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001186 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001187
Dan Sully44e767a2016-06-04 18:05:27 -07001188 :param int amount: The number of seconds by which to adjust the
1189 timestamp.
1190 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001191 """
1192 if not isinstance(amount, int):
1193 raise TypeError("amount must be an integer")
1194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001195 notAfter = _lib.X509_get_notAfter(self._x509)
1196 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001197
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001198 def gmtime_adj_notBefore(self, amount):
1199 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001200 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001201
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001202 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001203 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001204 """
1205 if not isinstance(amount, int):
1206 raise TypeError("amount must be an integer")
1207
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001208 notBefore = _lib.X509_get_notBefore(self._x509)
1209 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001210
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001211 def has_expired(self):
1212 """
1213 Check whether the certificate has expired.
1214
Dan Sully44e767a2016-06-04 18:05:27 -07001215 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1216 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001217 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001218 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001219 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001220
Paul Kehrerfde45c92016-01-21 12:57:37 -06001221 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001222
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001223 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001224 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001225
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001226 def get_notBefore(self):
1227 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001228 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001229
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001230 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001231
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001232 YYYYMMDDhhmmssZ
1233 YYYYMMDDhhmmss+hhmm
1234 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001235
Dan Sully44e767a2016-06-04 18:05:27 -07001236 :return: A timestamp string, or ``None`` if there is none.
1237 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001238 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001239 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001240
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001241 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001242 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001243
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001244 def set_notBefore(self, when):
1245 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001246 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001247
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001248 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001249
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001250 YYYYMMDDhhmmssZ
1251 YYYYMMDDhhmmss+hhmm
1252 YYYYMMDDhhmmss-hhmm
1253
Dan Sully44e767a2016-06-04 18:05:27 -07001254 :param bytes when: A timestamp string.
1255 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001256 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001257 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001258
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001259 def get_notAfter(self):
1260 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001261 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001262
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001263 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001264
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001265 YYYYMMDDhhmmssZ
1266 YYYYMMDDhhmmss+hhmm
1267 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001268
Dan Sully44e767a2016-06-04 18:05:27 -07001269 :return: A timestamp string, or ``None`` if there is none.
1270 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001271 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001272 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001273
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001274 def set_notAfter(self, when):
1275 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001276 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001277
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001278 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001279
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001280 YYYYMMDDhhmmssZ
1281 YYYYMMDDhhmmss+hhmm
1282 YYYYMMDDhhmmss-hhmm
1283
Dan Sully44e767a2016-06-04 18:05:27 -07001284 :param bytes when: A timestamp string.
1285 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001286 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001288
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001289 def _get_name(self, which):
1290 name = X509Name.__new__(X509Name)
1291 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001292 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001293
1294 # The name is owned by the X509 structure. As long as the X509Name
1295 # Python object is alive, keep the X509 Python object alive.
1296 name._owner = self
1297
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001298 return name
1299
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001300 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001301 if not isinstance(name, X509Name):
1302 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001303 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001304 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001306 def get_issuer(self):
1307 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001308 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001309
Cory Benfielde6bcce82015-12-09 08:40:03 +00001310 This creates a new :class:`X509Name` that wraps the underlying issuer
1311 name field on the certificate. Modifying it will modify the underlying
1312 certificate, and will have the effect of modifying any other
1313 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001314
1315 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001316 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001317 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001319
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001320 def set_issuer(self, issuer):
1321 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001322 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001323
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001324 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001325 :type issuer: :py:class:`X509Name`
1326
Dan Sully44e767a2016-06-04 18:05:27 -07001327 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001328 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001329 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001330
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001331 def get_subject(self):
1332 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001333 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001334
Cory Benfielde6bcce82015-12-09 08:40:03 +00001335 This creates a new :class:`X509Name` that wraps the underlying subject
1336 name field on the certificate. Modifying it will modify the underlying
1337 certificate, and will have the effect of modifying any other
1338 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001339
1340 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001341 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001342 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001343 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001344
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001345 def set_subject(self, subject):
1346 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001347 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001348
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001349 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001350 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001351
Dan Sully44e767a2016-06-04 18:05:27 -07001352 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001353 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001355
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001356 def get_extension_count(self):
1357 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001358 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001359
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001360 :return: The number of extensions.
1361 :rtype: :py:class:`int`
1362
1363 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001364 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001365 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001366
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001367 def add_extensions(self, extensions):
1368 """
1369 Add extensions to the certificate.
1370
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001371 :param extensions: The extensions to add.
1372 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001373 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001374 """
1375 for ext in extensions:
1376 if not isinstance(ext, X509Extension):
1377 raise ValueError("One of the elements is not an X509Extension")
1378
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001379 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001380 if not add_result:
1381 _raise_current_error()
1382
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001383 def get_extension(self, index):
1384 """
1385 Get a specific extension of the certificate by index.
1386
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001387 Extensions on a certificate are kept in order. The index
1388 parameter selects which extension will be returned.
1389
1390 :param int index: The index of the extension to retrieve.
1391 :return: The extension at the specified index.
1392 :rtype: :py:class:`X509Extension`
1393 :raises IndexError: If the extension index was out of bounds.
1394
1395 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001396 """
1397 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001398 ext._extension = _lib.X509_get_ext(self._x509, index)
1399 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001400 raise IndexError("extension index out of bounds")
1401
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001402 extension = _lib.X509_EXTENSION_dup(ext._extension)
1403 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001404 return ext
1405
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001406
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001407X509Type = X509
1408
1409
Dan Sully44e767a2016-06-04 18:05:27 -07001410class X509StoreFlags(object):
1411 """
1412 Flags for X509 verification, used to change the behavior of
1413 :class:`X509Store`.
1414
1415 See `OpenSSL Verification Flags`_ for details.
1416
1417 .. _OpenSSL Verification Flags:
1418 https://www.openssl.org/docs/manmaster/crypto/X509_VERIFY_PARAM_set_flags.html
1419 """
1420 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1421 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1422 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1423 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1424 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1425 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1426 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1427 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1428 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1429 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1430 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1431
1432
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001434 """
Dan Sully44e767a2016-06-04 18:05:27 -07001435 An X.509 store.
1436
1437 An X.509 store is used to describe a context in which to verify a
1438 certificate. A description of a context may include a set of certificates
1439 to trust, a set of certificate revocation lists, verification flags and
1440 more.
1441
1442 An X.509 store, being only a description, cannot be used by itself to
1443 verify a certificate. To carry out the actual verification process, see
1444 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001445 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001446
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001447 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001448 store = _lib.X509_STORE_new()
1449 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001451 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001452 """
Dan Sully44e767a2016-06-04 18:05:27 -07001453 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001454
Dan Sully44e767a2016-06-04 18:05:27 -07001455 Adding a certificate with this method adds this certificate as a
1456 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001457
1458 :param X509 cert: The certificate to add to this store.
Dan Sully44e767a2016-06-04 18:05:27 -07001459 :raises TypeError: If the certificate is not an :class:`X509`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001460 :raises Error: If OpenSSL was unhappy with your certificate.
Dan Sully44e767a2016-06-04 18:05:27 -07001461 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001462 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001463 if not isinstance(cert, X509):
1464 raise TypeError()
1465
Dan Sully44e767a2016-06-04 18:05:27 -07001466 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1467
1468 def add_crl(self, crl):
1469 """
1470 Add a certificate revocation list to this store.
1471
1472 The certificate revocation lists added to a store will only be used if
1473 the associated flags are configured to check certificate revocation
1474 lists.
1475
1476 .. versionadded:: 16.1.0
1477
1478 :param CRL crl: The certificate revocation list to add to this store.
1479 :return: ``None`` if the certificate revocation list was added
1480 successfully.
1481 """
1482 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1483
1484 def set_flags(self, flags):
1485 """
1486 Set verification flags to this store.
1487
1488 Verification flags can be combined by oring them together.
1489
1490 .. note::
1491
1492 Setting a verification flag sometimes requires clients to add
1493 additional information to the store, otherwise a suitable error will
1494 be raised.
1495
1496 For example, in setting flags to enable CRL checking a
1497 suitable CRL must be added to the store otherwise an error will be
1498 raised.
1499
1500 .. versionadded:: 16.1.0
1501
1502 :param int flags: The verification flags to set on this store.
1503 See :class:`X509StoreFlags` for available constants.
1504 :return: ``None`` if the verification flags were successfully set.
1505 """
1506 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001507
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001508
1509X509StoreType = X509Store
1510
1511
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001512class X509StoreContextError(Exception):
1513 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001514 An exception raised when an error occurred while verifying a certificate
1515 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001516
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001517 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001518 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001519 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001520
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001521 def __init__(self, message, certificate):
1522 super(X509StoreContextError, self).__init__(message)
1523 self.certificate = certificate
1524
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001525
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001526class X509StoreContext(object):
1527 """
1528 An X.509 store context.
1529
Dan Sully44e767a2016-06-04 18:05:27 -07001530 An X.509 store context is used to carry out the actual verification process
1531 of a certificate in a described context. For describing such a context, see
1532 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001533
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001534 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1535 instance. It is dynamically allocated and automatically garbage
1536 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001537 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001538 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001539 :param X509Store store: The certificates which will be trusted for the
1540 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001541 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001542 """
1543
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001544 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001545 store_ctx = _lib.X509_STORE_CTX_new()
1546 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1547 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001548 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001549 # Make the store context available for use after instantiating this
1550 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001551 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001552 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001553
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001554 def _init(self):
1555 """
1556 Set up the store context for a subsequent verification operation.
1557 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001558 ret = _lib.X509_STORE_CTX_init(
1559 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1560 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001561 if ret <= 0:
1562 _raise_current_error()
1563
1564 def _cleanup(self):
1565 """
1566 Internally cleans up the store context.
1567
Dan Sully44e767a2016-06-04 18:05:27 -07001568 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001569 """
1570 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1571
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001572 def _exception_from_context(self):
1573 """
1574 Convert an OpenSSL native context error failure into a Python
1575 exception.
1576
Alex Gaynor5945ea82015-09-05 14:59:06 -04001577 When a call to native OpenSSL X509_verify_cert fails, additional
1578 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001579 """
1580 errors = [
1581 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1582 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1583 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001584 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001585 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001586 # A context error should always be associated with a certificate, so we
1587 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001588 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001589 _cert = _lib.X509_dup(_x509)
1590 pycert = X509.__new__(X509)
1591 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001592 return X509StoreContextError(errors, pycert)
1593
Stephen Holsapple46a09252015-02-12 14:45:43 -08001594 def set_store(self, store):
1595 """
Dan Sully44e767a2016-06-04 18:05:27 -07001596 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001597
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001598 .. versionadded:: 0.15
1599
Dan Sully44e767a2016-06-04 18:05:27 -07001600 :param X509Store store: The store description which will be used for
1601 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001602 """
1603 self._store = store
1604
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001605 def verify_certificate(self):
1606 """
1607 Verify a certificate in a context.
1608
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001609 .. versionadded:: 0.15
1610
Alex Gaynorca87ff62015-09-04 23:31:03 -04001611 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001612 certificate in the context. Sets ``certificate`` attribute to
1613 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001614 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001615 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001616 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001617 self._init()
1618 ret = _lib.X509_verify_cert(self._store_ctx)
1619 self._cleanup()
1620 if ret <= 0:
1621 raise self._exception_from_context()
1622
1623
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001624def load_certificate(type, buffer):
1625 """
1626 Load a certificate from a buffer
1627
1628 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1629
Dan Sully44e767a2016-06-04 18:05:27 -07001630 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001631
1632 :return: The X509 object
1633 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001634 if isinstance(buffer, _text_type):
1635 buffer = buffer.encode("ascii")
1636
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001637 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001638
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001639 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001640 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001641 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001642 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001643 else:
1644 raise ValueError(
1645 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001646
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001647 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001648 _raise_current_error()
1649
1650 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001652 return cert
1653
1654
1655def dump_certificate(type, cert):
1656 """
1657 Dump a certificate to a buffer
1658
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001659 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1660 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001661 :param cert: The certificate to dump
1662 :return: The buffer with the dumped certificate in
1663 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001664 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001665
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001666 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001667 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001668 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001669 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001670 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001671 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001672 else:
1673 raise ValueError(
1674 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1675 "FILETYPE_TEXT")
1676
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001677 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001678 return _bio_to_string(bio)
1679
1680
Cory Benfield6492f7c2015-10-27 16:57:58 +09001681def dump_publickey(type, pkey):
1682 """
Cory Benfield11c10192015-10-27 17:23:03 +09001683 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001684
Cory Benfield9c590b92015-10-28 14:55:05 +09001685 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001686 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001687 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001688 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001689 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001690 """
1691 bio = _new_mem_buf()
1692 if type == FILETYPE_PEM:
1693 write_bio = _lib.PEM_write_bio_PUBKEY
1694 elif type == FILETYPE_ASN1:
1695 write_bio = _lib.i2d_PUBKEY_bio
1696 else:
1697 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1698
1699 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001700 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001701 _raise_current_error()
1702
1703 return _bio_to_string(bio)
1704
1705
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001706def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1707 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001708 Dump the private key *pkey* into a buffer string encoded with the type
1709 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1710 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001711
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001712 :param type: The file type (one of :const:`FILETYPE_PEM`,
1713 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1714 :param PKey pkey: The PKey to dump
1715 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001716 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001717 the passphrase to use, or a callback for providing the passphrase.
1718
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001719 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001720 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001721 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001722 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001723
1724 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001725 if passphrase is None:
1726 raise TypeError(
1727 "if a value is given for cipher "
1728 "one must also be given for passphrase")
1729 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001730 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001731 raise ValueError("Invalid cipher name")
1732 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001733 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001734
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001735 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001736 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001737 result_code = _lib.PEM_write_bio_PrivateKey(
1738 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001739 helper.callback, helper.callback_args)
1740 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001741 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001742 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001743 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001744 rsa = _ffi.gc(
1745 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1746 _lib.RSA_free
1747 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001749 else:
1750 raise ValueError(
1751 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1752 "FILETYPE_TEXT")
1753
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001754 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001755
1756 return _bio_to_string(bio)
1757
1758
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001759class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001760 """
1761 A certificate revocation.
1762 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001763 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1764 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1765 # OCSP_crl_reason_str. We use the latter, just like the command line
1766 # program.
1767 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001768 b"unspecified",
1769 b"keyCompromise",
1770 b"CACompromise",
1771 b"affiliationChanged",
1772 b"superseded",
1773 b"cessationOfOperation",
1774 b"certificateHold",
1775 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001776 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001777
1778 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001779 revoked = _lib.X509_REVOKED_new()
1780 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001781
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001782 def set_serial(self, hex_str):
1783 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001784 Set the serial number.
1785
1786 The serial number is formatted as a hexadecimal number encoded in
1787 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001788
Dan Sully44e767a2016-06-04 18:05:27 -07001789 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001790
Dan Sully44e767a2016-06-04 18:05:27 -07001791 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001792 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001793 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1794 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001795 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001796 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001797 if not bn_result:
1798 raise ValueError("bad hex string")
1799
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001800 asn1_serial = _ffi.gc(
1801 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1802 _lib.ASN1_INTEGER_free)
1803 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001804
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001805 def get_serial(self):
1806 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001807 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001808
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001809 The serial number is formatted as a hexadecimal number encoded in
1810 ASCII.
1811
1812 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001813 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001814 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001815 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001816
Alex Gaynor67903a62016-06-02 10:37:13 -07001817 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1818 _openssl_assert(asn1_int != _ffi.NULL)
1819 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1820 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001821 return _bio_to_string(bio)
1822
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001823 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001824 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1825 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001826 obj = _lib.X509_EXTENSION_get_object(ext)
1827 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001828 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001829 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001830 break
1831
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001832 def set_reason(self, reason):
1833 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001834 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001835
Dan Sully44e767a2016-06-04 18:05:27 -07001836 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001837
1838 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001839 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001840
Dan Sully44e767a2016-06-04 18:05:27 -07001841 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001842
1843 .. seealso::
1844
Dan Sully44e767a2016-06-04 18:05:27 -07001845 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001846 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 """
1848 if reason is None:
1849 self._delete_reason()
1850 elif not isinstance(reason, bytes):
1851 raise TypeError("reason must be None or a byte string")
1852 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001853 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001854 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1855
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001856 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001857 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001858 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001859
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001860 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001861 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001862
1863 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001864 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1865 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001866 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001867
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001868 def get_reason(self):
1869 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001870 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001871
Dan Sully44e767a2016-06-04 18:05:27 -07001872 :return: The reason, or ``None`` if there is none.
1873 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001874
1875 .. seealso::
1876
Dan Sully44e767a2016-06-04 18:05:27 -07001877 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001878 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001879 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001880 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1881 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001882 obj = _lib.X509_EXTENSION_get_object(ext)
1883 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001884 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001885
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001887 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001888 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001889 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001890 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001891 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001892
1893 return _bio_to_string(bio)
1894
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001895 def all_reasons(self):
1896 """
1897 Return a list of all the supported reason strings.
1898
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001899 This list is a copy; modifying it does not change the supported reason
1900 strings.
1901
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001902 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001903 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001904 """
1905 return self._crl_reasons[:]
1906
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001907 def set_rev_date(self, when):
1908 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001909 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001910
Dan Sully44e767a2016-06-04 18:05:27 -07001911 :param bytes when: The timestamp of the revocation,
1912 as ASN.1 GENERALIZEDTIME.
1913 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001914 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001915 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1916 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001917
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001918 def get_rev_date(self):
1919 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001920 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001921
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001922 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001923 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001924 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001925 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1926 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001927
1928
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001929class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001930 """
1931 A certificate revocation list.
1932 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001933
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001934 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001935 crl = _lib.X509_CRL_new()
1936 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001937
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001938 def get_revoked(self):
1939 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001940 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001941
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001942 These revocations will be provided by value, not by reference.
1943 That means it's okay to mutate them: it won't affect this CRL.
1944
1945 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001946 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001947 """
1948 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001949 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001950 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1951 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001952 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001953 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001954 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001955 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001956 if results:
1957 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001958
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001959 def add_revoked(self, revoked):
1960 """
1961 Add a revoked (by value not reference) to the CRL structure
1962
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001963 This revocation will be added by value, not by reference. That
1964 means it's okay to mutate it after adding: it won't affect
1965 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001966
Dan Sully44e767a2016-06-04 18:05:27 -07001967 :param Revoked revoked: The new revocation.
1968 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001969 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001970 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001971 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001972
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001973 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001974 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001975
Dan Sully44e767a2016-06-04 18:05:27 -07001976 def get_issuer(self):
1977 """
1978 Get the CRL's issuer.
1979
1980 .. versionadded:: 16.1.0
1981
1982 :rtype: X509Name
1983 """
1984 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
1985 _openssl_assert(_issuer != _ffi.NULL)
1986 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
1987 issuer = X509Name.__new__(X509Name)
1988 issuer._name = _issuer
1989 return issuer
1990
1991 def set_version(self, version):
1992 """
1993 Set the CRL version.
1994
1995 .. versionadded:: 16.1.0
1996
1997 :param int version: The version of the CRL.
1998 :return: ``None``
1999 """
2000 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2001
2002 def _set_boundary_time(self, which, when):
2003 return _set_asn1_time(which(self._crl), when)
2004
2005 def set_lastUpdate(self, when):
2006 """
2007 Set when the CRL was last updated.
2008
2009 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2010
2011 YYYYMMDDhhmmssZ
2012 YYYYMMDDhhmmss+hhmm
2013 YYYYMMDDhhmmss-hhmm
2014
2015 .. versionadded:: 16.1.0
2016
2017 :param bytes when: A timestamp string.
2018 :return: ``None``
2019 """
2020 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2021
2022 def set_nextUpdate(self, when):
2023 """
2024 Set when the CRL will next be udpated.
2025
2026 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2027
2028 YYYYMMDDhhmmssZ
2029 YYYYMMDDhhmmss+hhmm
2030 YYYYMMDDhhmmss-hhmm
2031
2032 .. versionadded:: 16.1.0
2033
2034 :param bytes when: A timestamp string.
2035 :return: ``None``
2036 """
2037 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2038
2039 def sign(self, issuer_cert, issuer_key, digest):
2040 """
2041 Sign the CRL.
2042
2043 Signing a CRL enables clients to associate the CRL itself with an
2044 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2045 be signed by an issuer.
2046
2047 This method implicitly sets the issuer's name based on the issuer
2048 certificate and private key used to sign the CRL.
2049
2050 .. versionadded:: 16.1.0
2051
2052 :param X509 issuer_cert: The issuer's certificate.
2053 :param PKey issuer_key: The issuer's private key.
2054 :param bytes digest: The digest method to sign the CRL with.
2055 """
2056 digest_obj = _lib.EVP_get_digestbyname(digest)
2057 _openssl_assert(digest_obj != _ffi.NULL)
2058 _lib.X509_CRL_set_issuer_name(
2059 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2060 _lib.X509_CRL_sort(self._crl)
2061 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2062 _openssl_assert(result != 0)
2063
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002064 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002065 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002066 """
Dan Sully44e767a2016-06-04 18:05:27 -07002067 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002068
Dan Sully44e767a2016-06-04 18:05:27 -07002069 :param X509 cert: The certificate used to sign the CRL.
2070 :param PKey key: The key used to sign the CRL.
2071 :param int type: The export format, either :data:`FILETYPE_PEM`,
2072 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002073 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002074 :param bytes digest: The name of the message digest to use (eg
2075 ``b"sha1"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002076 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002077 """
Dan Sully44e767a2016-06-04 18:05:27 -07002078
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002079 if not isinstance(cert, X509):
2080 raise TypeError("cert must be an X509 instance")
2081 if not isinstance(key, PKey):
2082 raise TypeError("key must be a PKey instance")
2083 if not isinstance(type, int):
2084 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002085
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002086 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002087 _warn(
2088 "The default message digest (md5) is deprecated. "
2089 "Pass the name of a message digest explicitly.",
2090 category=DeprecationWarning,
2091 stacklevel=2,
2092 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002093 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002094
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002095 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002096 if digest_obj == _ffi.NULL:
2097 raise ValueError("No such digest method")
2098
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002099 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002100 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002101
Alex Gaynora738ed52015-09-05 11:17:10 -04002102 # A scratch time object to give different values to different CRL
2103 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002104 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002105 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002107 _lib.X509_gmtime_adj(sometime, 0)
2108 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002109
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002110 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2111 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002112
Alex Gaynor5945ea82015-09-05 14:59:06 -04002113 _lib.X509_CRL_set_issuer_name(
2114 self._crl, _lib.X509_get_subject_name(cert._x509)
2115 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002116
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002117 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002118 if not sign_result:
2119 _raise_current_error()
2120
Dominic Chenf05b2122015-10-13 16:32:35 +00002121 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002122
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002123
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002124CRLType = CRL
2125
2126
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002127class PKCS7(object):
2128 def type_is_signed(self):
2129 """
2130 Check if this NID_pkcs7_signed object
2131
2132 :return: True if the PKCS7 is of type signed
2133 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002134 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002135 return True
2136 return False
2137
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002138 def type_is_enveloped(self):
2139 """
2140 Check if this NID_pkcs7_enveloped object
2141
2142 :returns: True if the PKCS7 is of type enveloped
2143 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002144 if _lib.PKCS7_type_is_enveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002145 return True
2146 return False
2147
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002148 def type_is_signedAndEnveloped(self):
2149 """
2150 Check if this NID_pkcs7_signedAndEnveloped object
2151
2152 :returns: True if the PKCS7 is of type signedAndEnveloped
2153 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002154 if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002155 return True
2156 return False
2157
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002158 def type_is_data(self):
2159 """
2160 Check if this NID_pkcs7_data object
2161
2162 :return: True if the PKCS7 is of type data
2163 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002164 if _lib.PKCS7_type_is_data(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002165 return True
2166 return False
2167
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002168 def get_type_name(self):
2169 """
2170 Returns the type name of the PKCS7 structure
2171
2172 :return: A string with the typename
2173 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002174 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2175 string_type = _lib.OBJ_nid2sn(nid)
2176 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002177
2178PKCS7Type = PKCS7
2179
2180
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002181class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002182 """
2183 A PKCS #12 archive.
2184 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002185
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002186 def __init__(self):
2187 self._pkey = None
2188 self._cert = None
2189 self._cacerts = None
2190 self._friendlyname = None
2191
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002192 def get_certificate(self):
2193 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002194 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002195
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002196 :return: The certificate, or :py:const:`None` if there is none.
2197 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002198 """
2199 return self._cert
2200
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002201 def set_certificate(self, cert):
2202 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002203 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002204
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002205 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002206 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002207
Dan Sully44e767a2016-06-04 18:05:27 -07002208 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002209 """
2210 if not isinstance(cert, X509):
2211 raise TypeError("cert must be an X509 instance")
2212 self._cert = cert
2213
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002214 def get_privatekey(self):
2215 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002216 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002218 :return: The private key, or :py:const:`None` if there is none.
2219 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002220 """
2221 return self._pkey
2222
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002223 def set_privatekey(self, pkey):
2224 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002225 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002226
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002227 :param pkey: The new private key, or :py:const:`None` to unset it.
2228 :type pkey: :py:class:`PKey` or :py:const:`None`
2229
Dan Sully44e767a2016-06-04 18:05:27 -07002230 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002231 """
2232 if not isinstance(pkey, PKey):
2233 raise TypeError("pkey must be a PKey instance")
2234 self._pkey = pkey
2235
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002236 def get_ca_certificates(self):
2237 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002238 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002239
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002240 :return: A tuple with the CA certificates in the chain, or
2241 :py:const:`None` if there are none.
2242 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002243 """
2244 if self._cacerts is not None:
2245 return tuple(self._cacerts)
2246
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002247 def set_ca_certificates(self, cacerts):
2248 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002249 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002250
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002251 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2252 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002253 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002254
Dan Sully44e767a2016-06-04 18:05:27 -07002255 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002256 """
2257 if cacerts is None:
2258 self._cacerts = None
2259 else:
2260 cacerts = list(cacerts)
2261 for cert in cacerts:
2262 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002263 raise TypeError(
2264 "iterable must only contain X509 instances"
2265 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002266 self._cacerts = cacerts
2267
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002268 def set_friendlyname(self, name):
2269 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002270 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002271
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002272 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002273 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002274
Dan Sully44e767a2016-06-04 18:05:27 -07002275 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002276 """
2277 if name is None:
2278 self._friendlyname = None
2279 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002280 raise TypeError(
2281 "name must be a byte string or None (not %r)" % (name,)
2282 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002283 self._friendlyname = name
2284
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002285 def get_friendlyname(self):
2286 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002287 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002288
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002289 :returns: The friendly name, or :py:const:`None` if there is none.
2290 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002291 """
2292 return self._friendlyname
2293
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002294 def export(self, passphrase=None, iter=2048, maciter=1):
2295 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002296 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002297
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002298 For more information, see the :c:func:`PKCS12_create` man page.
2299
2300 :param passphrase: The passphrase used to encrypt the structure. Unlike
2301 some other passphrase arguments, this *must* be a string, not a
2302 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002303 :type passphrase: :py:data:`bytes`
2304
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002305 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002306 :type iter: :py:data:`int`
2307
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002308 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002309 :type maciter: :py:data:`int`
2310
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002311 :return: The string representation of the PKCS #12 structure.
2312 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002313 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002314 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002315
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002316 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002317 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002318 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002319 cacerts = _lib.sk_X509_new_null()
2320 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002321 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002322 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002323
2324 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002325 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002326
2327 friendlyname = self._friendlyname
2328 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002329 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002330
2331 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002332 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002333 else:
2334 pkey = self._pkey._pkey
2335
2336 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002337 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002338 else:
2339 cert = self._cert._x509
2340
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002341 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002342 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002343 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2344 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002345 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002346 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002347 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002348 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002349
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002350 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002351 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002352 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002353
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002354
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002355PKCS12Type = PKCS12
2356
2357
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002358class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002359 """
2360 A Netscape SPKI object.
2361 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002362
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002363 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002364 spki = _lib.NETSCAPE_SPKI_new()
2365 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002366
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002367 def sign(self, pkey, digest):
2368 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002369 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002370
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002371 :param pkey: The private key to sign with.
2372 :type pkey: :py:class:`PKey`
2373
2374 :param digest: The message digest to use.
2375 :type digest: :py:class:`bytes`
2376
Dan Sully44e767a2016-06-04 18:05:27 -07002377 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002378 """
2379 if pkey._only_public:
2380 raise ValueError("Key has only public part")
2381
2382 if not pkey._initialized:
2383 raise ValueError("Key is uninitialized")
2384
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002385 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002386 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002387 raise ValueError("No such digest method")
2388
Alex Gaynor5945ea82015-09-05 14:59:06 -04002389 sign_result = _lib.NETSCAPE_SPKI_sign(
2390 self._spki, pkey._pkey, digest_obj
2391 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002392 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002393
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002394 def verify(self, key):
2395 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002396 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002397
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002398 :param key: The public key that signature is supposedly from.
2399 :type pkey: :py:class:`PKey`
2400
2401 :return: :py:const:`True` if the signature is correct.
2402 :rtype: :py:class:`bool`
2403
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002404 :raises Error: If the signature is invalid, or there was a problem
2405 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002406 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002407 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002408 if answer <= 0:
2409 _raise_current_error()
2410 return True
2411
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002412 def b64_encode(self):
2413 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002414 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002415
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002416 :return: The base64 encoded string.
2417 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002418 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002419 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2420 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002421 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002422 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002423
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002424 def get_pubkey(self):
2425 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002426 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002427
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002428 :return: The public key.
2429 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002430 """
2431 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002432 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002433 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002434 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002435 pkey._only_public = True
2436 return pkey
2437
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002438 def set_pubkey(self, pkey):
2439 """
2440 Set the public key of the certificate
2441
2442 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002443 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002444 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002445 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002446 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002447
2448
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002449NetscapeSPKIType = NetscapeSPKI
2450
2451
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002452class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002453 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002454 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002455 raise ValueError(
2456 "only FILETYPE_PEM key format supports encryption"
2457 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002458 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002459 self._more_args = more_args
2460 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002461 self._problems = []
2462
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002463 @property
2464 def callback(self):
2465 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002466 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002467 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002468 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002469 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002470 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002471 else:
2472 raise TypeError("Last argument must be string or callable")
2473
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002474 @property
2475 def callback_args(self):
2476 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002477 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002478 elif isinstance(self._passphrase, bytes):
2479 return self._passphrase
2480 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002481 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002482 else:
2483 raise TypeError("Last argument must be string or callable")
2484
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002485 def raise_if_problem(self, exceptionType=Error):
2486 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002487 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002488 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002489 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002490 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002491 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002492 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002493
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002494 def _read_passphrase(self, buf, size, rwflag, userdata):
2495 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002496 if self._more_args:
2497 result = self._passphrase(size, rwflag, userdata)
2498 else:
2499 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002500 if not isinstance(result, bytes):
2501 raise ValueError("String expected")
2502 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002503 if self._truncate:
2504 result = result[:size]
2505 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002506 raise ValueError(
2507 "passphrase returned by callback is too long"
2508 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002509 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002510 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002511 return len(result)
2512 except Exception as e:
2513 self._problems.append(e)
2514 return 0
2515
2516
Cory Benfield6492f7c2015-10-27 16:57:58 +09002517def load_publickey(type, buffer):
2518 """
Cory Benfield11c10192015-10-27 17:23:03 +09002519 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002520
Cory Benfield9c590b92015-10-28 14:55:05 +09002521 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002522 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002523 :param buffer: The buffer the key is stored in.
2524 :type buffer: A Python string object, either unicode or bytestring.
2525 :return: The PKey object.
2526 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002527 """
2528 if isinstance(buffer, _text_type):
2529 buffer = buffer.encode("ascii")
2530
2531 bio = _new_mem_buf(buffer)
2532
2533 if type == FILETYPE_PEM:
2534 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2535 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2536 elif type == FILETYPE_ASN1:
2537 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2538 else:
2539 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2540
2541 if evp_pkey == _ffi.NULL:
2542 _raise_current_error()
2543
2544 pkey = PKey.__new__(PKey)
2545 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002546 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002547 return pkey
2548
2549
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002550def load_privatekey(type, buffer, passphrase=None):
2551 """
2552 Load a private key from a buffer
2553
2554 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2555 :param buffer: The buffer the key is stored in
2556 :param passphrase: (optional) if encrypted PEM format, this can be
2557 either the passphrase to use, or a callback for
2558 providing the passphrase.
2559
2560 :return: The PKey object
2561 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002562 if isinstance(buffer, _text_type):
2563 buffer = buffer.encode("ascii")
2564
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002565 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002566
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002567 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002568 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002569 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2570 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002571 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002572 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002573 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002574 else:
2575 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2576
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002577 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002578 _raise_current_error()
2579
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002580 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002581 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002582 return pkey
2583
2584
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002585def dump_certificate_request(type, req):
2586 """
2587 Dump a certificate request to a buffer
2588
2589 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2590 :param req: The certificate request to dump
2591 :return: The buffer with the dumped certificate request in
2592 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002593 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002594
2595 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002596 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002597 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002598 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002599 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002600 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002601 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002602 raise ValueError(
2603 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2604 "FILETYPE_TEXT"
2605 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002606
Alex Gaynor09a386e2016-07-03 09:32:44 -04002607 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002608
2609 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002610
2611
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002612def load_certificate_request(type, buffer):
2613 """
2614 Load a certificate request from a buffer
2615
2616 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2617 :param buffer: The buffer the certificate request is stored in
2618 :return: The X509Req object
2619 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002620 if isinstance(buffer, _text_type):
2621 buffer = buffer.encode("ascii")
2622
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002623 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002624
2625 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002626 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002627 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002628 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002629 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002630 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002631
Alex Gaynoradd5b072016-06-04 21:04:00 -07002632 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002633
2634 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002635 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002636 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002637
2638
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002639def sign(pkey, data, digest):
2640 """
2641 Sign data with a digest
2642
2643 :param pkey: Pkey to sign with
2644 :param data: data to be signed
2645 :param digest: message digest to use
2646 :return: signature
2647 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002648 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002649
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002650 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002651 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002652 raise ValueError("No such digest method")
2653
Alex Gaynor67903a62016-06-02 10:37:13 -07002654 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002655 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002656
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002657 _lib.EVP_SignInit(md_ctx, digest_obj)
2658 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002659
Colleen Murphye09399b2016-03-01 17:40:49 -08002660 pkey_length = (PKey.bits(pkey) + 7) // 8
2661 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002662 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002663 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002664 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002665 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002666
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002667 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002668
2669
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002670def verify(cert, signature, data, digest):
2671 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002672 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002673
2674 :param cert: signing certificate (X509 object)
2675 :param signature: signature returned by sign function
2676 :param data: data to be verified
2677 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002678 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002679 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002680 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002681
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002682 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002683 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002684 raise ValueError("No such digest method")
2685
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002686 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002687 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002688 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002689
Alex Gaynor67903a62016-06-02 10:37:13 -07002690 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002691 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002692
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002693 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2694 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002695 verify_result = _lib.EVP_VerifyFinal(
2696 md_ctx, signature, len(signature), pkey
2697 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002698
2699 if verify_result != 1:
2700 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002701
2702
Dominic Chenf05b2122015-10-13 16:32:35 +00002703def dump_crl(type, crl):
2704 """
2705 Dump a certificate revocation list to a buffer.
2706
2707 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2708 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002709 :param CRL crl: The CRL to dump.
2710
Dominic Chenf05b2122015-10-13 16:32:35 +00002711 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002712 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002713 """
2714 bio = _new_mem_buf()
2715
2716 if type == FILETYPE_PEM:
2717 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2718 elif type == FILETYPE_ASN1:
2719 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2720 elif type == FILETYPE_TEXT:
2721 ret = _lib.X509_CRL_print(bio, crl._crl)
2722 else:
2723 raise ValueError(
2724 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2725 "FILETYPE_TEXT")
2726
2727 assert ret == 1
2728 return _bio_to_string(bio)
2729
2730
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002731def load_crl(type, buffer):
2732 """
2733 Load a certificate revocation list from a buffer
2734
2735 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2736 :param buffer: The buffer the CRL is stored in
2737
2738 :return: The PKey object
2739 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002740 if isinstance(buffer, _text_type):
2741 buffer = buffer.encode("ascii")
2742
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002743 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002744
2745 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002746 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002747 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002748 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002749 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002750 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2751
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002752 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002753 _raise_current_error()
2754
2755 result = CRL.__new__(CRL)
2756 result._crl = crl
2757 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002758
2759
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002760def load_pkcs7_data(type, buffer):
2761 """
2762 Load pkcs7 data from a buffer
2763
2764 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2765 :param buffer: The buffer with the pkcs7 data.
2766 :return: The PKCS7 object
2767 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002768 if isinstance(buffer, _text_type):
2769 buffer = buffer.encode("ascii")
2770
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002771 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002772
2773 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002774 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002775 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002776 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002777 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002778 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2779
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002780 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002781 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002782
2783 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002784 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002785 return pypkcs7
2786
2787
Stephen Holsapple38482622014-04-05 20:29:34 -07002788def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002789 """
2790 Load a PKCS12 object from a buffer
2791
2792 :param buffer: The buffer the certificate is stored in
2793 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2794 :returns: The PKCS12 object
2795 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002796 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002797
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002798 if isinstance(buffer, _text_type):
2799 buffer = buffer.encode("ascii")
2800
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002801 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002802
Stephen Holsapple38482622014-04-05 20:29:34 -07002803 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2804 # password based encryption no password and a zero length password are two
2805 # different things, but OpenSSL implementation will try both to figure out
2806 # which one works.
2807 if not passphrase:
2808 passphrase = _ffi.NULL
2809
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002810 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2811 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002812 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002813 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002814
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002815 pkey = _ffi.new("EVP_PKEY**")
2816 cert = _ffi.new("X509**")
2817 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002818
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002819 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002820 if not parse_result:
2821 _raise_current_error()
2822
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002823 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002824
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002825 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2826 # queue for no particular reason. This error isn't interesting to anyone
2827 # outside this function. It's not even interesting to us. Get rid of it.
2828 try:
2829 _raise_current_error()
2830 except Error:
2831 pass
2832
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002833 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002834 pykey = None
2835 else:
2836 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002837 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002838
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002839 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002840 pycert = None
2841 friendlyname = None
2842 else:
2843 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002844 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002845
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002846 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002847 friendlyname_buffer = _lib.X509_alias_get0(
2848 cert[0], friendlyname_length
2849 )
2850 friendlyname = _ffi.buffer(
2851 friendlyname_buffer, friendlyname_length[0]
2852 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002853 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002854 friendlyname = None
2855
2856 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002857 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002858 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002859 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002860 pycacerts.append(pycacert)
2861 if not pycacerts:
2862 pycacerts = None
2863
2864 pkcs12 = PKCS12.__new__(PKCS12)
2865 pkcs12._pkey = pykey
2866 pkcs12._cert = pycert
2867 pkcs12._cacerts = pycacerts
2868 pkcs12._friendlyname = friendlyname
2869 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002870
2871
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002872# There are no direct unit tests for this initialization. It is tested
2873# indirectly since it is necessary for functions like dump_privatekey when
2874# using encryption.
2875#
2876# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2877# and some other similar tests may fail without this (though they may not if
2878# the Python runtime has already done some initialization of the underlying
2879# OpenSSL library (and is linked against the same one that cryptography is
2880# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002881_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002882
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002883# This is similar but exercised mainly by exception_from_error_queue. It calls
2884# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2885_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002886
2887
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002888# Set the default string mask to match OpenSSL upstream (since 2005) and
2889# RFC5280 recommendations.
2890_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')