blob: 116cc51c874c87599663b1355d06be3134d44f96 [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 """
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800985 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500986 x509 = _lib.X509_new()
Hynek Schlawack8a2dd772016-07-31 13:46:20 +0200987 _openssl_assert(x509 != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800989
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800990 def set_version(self, version):
991 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200992 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800993
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200994 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800995 :type version: :py:class:`int`
996
Dan Sully44e767a2016-06-04 18:05:27 -0700997 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800998 """
999 if not isinstance(version, int):
1000 raise TypeError("version must be an integer")
1001
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001002 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001003
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001004 def get_version(self):
1005 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001006 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001007
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001008 :return: The version number of the certificate.
1009 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001010 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001011 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001012
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001013 def get_pubkey(self):
1014 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001015 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001016
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001017 :return: The public key.
1018 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001019 """
1020 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001021 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1022 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001023 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001024 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001025 pkey._only_public = True
1026 return pkey
1027
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001028 def set_pubkey(self, pkey):
1029 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001030 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001031
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001032 :param pkey: The public key.
1033 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001034
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001035 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001036 """
1037 if not isinstance(pkey, PKey):
1038 raise TypeError("pkey must be a PKey instance")
1039
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001040 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001041 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001042
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001043 def sign(self, pkey, digest):
1044 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001045 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001046
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001047 :param pkey: The key to sign with.
1048 :type pkey: :py:class:`PKey`
1049
1050 :param digest: The name of the message digest to use.
1051 :type digest: :py:class:`bytes`
1052
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001053 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001054 """
1055 if not isinstance(pkey, PKey):
1056 raise TypeError("pkey must be a PKey instance")
1057
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001058 if pkey._only_public:
1059 raise ValueError("Key only has public part")
1060
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001061 if not pkey._initialized:
1062 raise ValueError("Key is uninitialized")
1063
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001064 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001065 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001066 raise ValueError("No such digest method")
1067
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001068 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001069 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001070
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001071 def get_signature_algorithm(self):
1072 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001073 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001074
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001075 :return: The name of the algorithm.
1076 :rtype: :py:class:`bytes`
1077
1078 :raises ValueError: If the signature algorithm is undefined.
1079
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001080 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001081 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001082 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1083 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001084 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001085 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001086 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001087
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001088 def digest(self, digest_name):
1089 """
1090 Return the digest of the X509 object.
1091
1092 :param digest_name: The name of the digest algorithm to use.
1093 :type digest_name: :py:class:`bytes`
1094
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001095 :return: The digest of the object, formatted as
1096 :py:const:`b":"`-delimited hex pairs.
1097 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001098 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001099 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001100 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001101 raise ValueError("No such digest method")
1102
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001103 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1104 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001105 result_length[0] = len(result_buffer)
1106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001108 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001109 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001110
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001111 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001112 b16encode(ch).upper() for ch
1113 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001114
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001115 def subject_name_hash(self):
1116 """
1117 Return the hash of the X509 subject.
1118
1119 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001120 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001121 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001122 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001123
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001124 def set_serial_number(self, serial):
1125 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001126 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001127
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001128 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001129 :type serial: :py:class:`int`
1130
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001131 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001132 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001133 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001134 raise TypeError("serial must be an integer")
1135
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001136 hex_serial = hex(serial)[2:]
1137 if not isinstance(hex_serial, bytes):
1138 hex_serial = hex_serial.encode('ascii')
1139
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001140 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001141
1142 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001143 # it. If bignum is still NULL after this call, then the return value
1144 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001146
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001147 if bignum_serial[0] == _ffi.NULL:
1148 set_result = _lib.ASN1_INTEGER_set(
1149 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001150 if set_result:
1151 # TODO Not tested
1152 _raise_current_error()
1153 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1155 _lib.BN_free(bignum_serial[0])
1156 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001157 # TODO Not tested
1158 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001159 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1160 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001161 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001162
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001163 def get_serial_number(self):
1164 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001165 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001166
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001167 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001168 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001169 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1171 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001172 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001174 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001175 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001176 serial = int(hexstring_serial, 16)
1177 return serial
1178 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001180 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001182
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001183 def gmtime_adj_notAfter(self, amount):
1184 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001185 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001186
Dan Sully44e767a2016-06-04 18:05:27 -07001187 :param int amount: The number of seconds by which to adjust the
1188 timestamp.
1189 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001190 """
1191 if not isinstance(amount, int):
1192 raise TypeError("amount must be an integer")
1193
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001194 notAfter = _lib.X509_get_notAfter(self._x509)
1195 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001196
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001197 def gmtime_adj_notBefore(self, amount):
1198 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001199 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001200
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001201 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001202 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001203 """
1204 if not isinstance(amount, int):
1205 raise TypeError("amount must be an integer")
1206
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001207 notBefore = _lib.X509_get_notBefore(self._x509)
1208 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001209
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001210 def has_expired(self):
1211 """
1212 Check whether the certificate has expired.
1213
Dan Sully44e767a2016-06-04 18:05:27 -07001214 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1215 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001216 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001217 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001218 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001219
Paul Kehrerfde45c92016-01-21 12:57:37 -06001220 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001221
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001222 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001223 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001224
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001225 def get_notBefore(self):
1226 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001227 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001228
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001229 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001230
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001231 YYYYMMDDhhmmssZ
1232 YYYYMMDDhhmmss+hhmm
1233 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001234
Dan Sully44e767a2016-06-04 18:05:27 -07001235 :return: A timestamp string, or ``None`` if there is none.
1236 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001237 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001238 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001240 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001241 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001242
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001243 def set_notBefore(self, when):
1244 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001245 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001246
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001247 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001248
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001249 YYYYMMDDhhmmssZ
1250 YYYYMMDDhhmmss+hhmm
1251 YYYYMMDDhhmmss-hhmm
1252
Dan Sully44e767a2016-06-04 18:05:27 -07001253 :param bytes when: A timestamp string.
1254 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001255 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001256 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001257
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001258 def get_notAfter(self):
1259 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001260 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001261
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001262 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001263
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001264 YYYYMMDDhhmmssZ
1265 YYYYMMDDhhmmss+hhmm
1266 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001267
Dan Sully44e767a2016-06-04 18:05:27 -07001268 :return: A timestamp string, or ``None`` if there is none.
1269 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001270 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001271 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001272
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001273 def set_notAfter(self, when):
1274 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001275 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001276
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001277 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001278
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001279 YYYYMMDDhhmmssZ
1280 YYYYMMDDhhmmss+hhmm
1281 YYYYMMDDhhmmss-hhmm
1282
Dan Sully44e767a2016-06-04 18:05:27 -07001283 :param bytes when: A timestamp string.
1284 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001285 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001286 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001287
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001288 def _get_name(self, which):
1289 name = X509Name.__new__(X509Name)
1290 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001291 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001292
1293 # The name is owned by the X509 structure. As long as the X509Name
1294 # Python object is alive, keep the X509 Python object alive.
1295 name._owner = self
1296
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001297 return name
1298
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001299 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001300 if not isinstance(name, X509Name):
1301 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001302 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001303 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001304
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305 def get_issuer(self):
1306 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001307 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001308
Cory Benfielde6bcce82015-12-09 08:40:03 +00001309 This creates a new :class:`X509Name` that wraps the underlying issuer
1310 name field on the certificate. Modifying it will modify the underlying
1311 certificate, and will have the effect of modifying any other
1312 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001313
1314 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001315 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001316 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001317 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001318
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001319 def set_issuer(self, issuer):
1320 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001321 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001322
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001323 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001324 :type issuer: :py:class:`X509Name`
1325
Dan Sully44e767a2016-06-04 18:05:27 -07001326 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001327 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001328 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001329
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001330 def get_subject(self):
1331 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001332 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001333
Cory Benfielde6bcce82015-12-09 08:40:03 +00001334 This creates a new :class:`X509Name` that wraps the underlying subject
1335 name field on the certificate. Modifying it will modify the underlying
1336 certificate, and will have the effect of modifying any other
1337 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001338
1339 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001340 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001341 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001342 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001343
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001344 def set_subject(self, subject):
1345 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001346 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001347
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001348 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001349 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001350
Dan Sully44e767a2016-06-04 18:05:27 -07001351 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001352 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001353 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001354
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001355 def get_extension_count(self):
1356 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001357 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001358
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001359 :return: The number of extensions.
1360 :rtype: :py:class:`int`
1361
1362 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001363 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001364 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001365
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001366 def add_extensions(self, extensions):
1367 """
1368 Add extensions to the certificate.
1369
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001370 :param extensions: The extensions to add.
1371 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001372 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001373 """
1374 for ext in extensions:
1375 if not isinstance(ext, X509Extension):
1376 raise ValueError("One of the elements is not an X509Extension")
1377
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001378 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001379 if not add_result:
1380 _raise_current_error()
1381
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001382 def get_extension(self, index):
1383 """
1384 Get a specific extension of the certificate by index.
1385
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001386 Extensions on a certificate are kept in order. The index
1387 parameter selects which extension will be returned.
1388
1389 :param int index: The index of the extension to retrieve.
1390 :return: The extension at the specified index.
1391 :rtype: :py:class:`X509Extension`
1392 :raises IndexError: If the extension index was out of bounds.
1393
1394 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001395 """
1396 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001397 ext._extension = _lib.X509_get_ext(self._x509, index)
1398 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001399 raise IndexError("extension index out of bounds")
1400
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 extension = _lib.X509_EXTENSION_dup(ext._extension)
1402 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001403 return ext
1404
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001405
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001406X509Type = X509
1407
1408
Dan Sully44e767a2016-06-04 18:05:27 -07001409class X509StoreFlags(object):
1410 """
1411 Flags for X509 verification, used to change the behavior of
1412 :class:`X509Store`.
1413
1414 See `OpenSSL Verification Flags`_ for details.
1415
1416 .. _OpenSSL Verification Flags:
1417 https://www.openssl.org/docs/manmaster/crypto/X509_VERIFY_PARAM_set_flags.html
1418 """
1419 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1420 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1421 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1422 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1423 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1424 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1425 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1426 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1427 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1428 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1429 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1430
1431
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001432class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001433 """
Dan Sully44e767a2016-06-04 18:05:27 -07001434 An X.509 store.
1435
1436 An X.509 store is used to describe a context in which to verify a
1437 certificate. A description of a context may include a set of certificates
1438 to trust, a set of certificate revocation lists, verification flags and
1439 more.
1440
1441 An X.509 store, being only a description, cannot be used by itself to
1442 verify a certificate. To carry out the actual verification process, see
1443 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001444 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001445
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001446 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001447 store = _lib.X509_STORE_new()
1448 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001449
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001451 """
Dan Sully44e767a2016-06-04 18:05:27 -07001452 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001453
Dan Sully44e767a2016-06-04 18:05:27 -07001454 Adding a certificate with this method adds this certificate as a
1455 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001456
1457 :param X509 cert: The certificate to add to this store.
Dan Sully44e767a2016-06-04 18:05:27 -07001458 :raises TypeError: If the certificate is not an :class:`X509`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001459 :raises Error: If OpenSSL was unhappy with your certificate.
Dan Sully44e767a2016-06-04 18:05:27 -07001460 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001461 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001462 if not isinstance(cert, X509):
1463 raise TypeError()
1464
Dan Sully44e767a2016-06-04 18:05:27 -07001465 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1466
1467 def add_crl(self, crl):
1468 """
1469 Add a certificate revocation list to this store.
1470
1471 The certificate revocation lists added to a store will only be used if
1472 the associated flags are configured to check certificate revocation
1473 lists.
1474
1475 .. versionadded:: 16.1.0
1476
1477 :param CRL crl: The certificate revocation list to add to this store.
1478 :return: ``None`` if the certificate revocation list was added
1479 successfully.
1480 """
1481 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1482
1483 def set_flags(self, flags):
1484 """
1485 Set verification flags to this store.
1486
1487 Verification flags can be combined by oring them together.
1488
1489 .. note::
1490
1491 Setting a verification flag sometimes requires clients to add
1492 additional information to the store, otherwise a suitable error will
1493 be raised.
1494
1495 For example, in setting flags to enable CRL checking a
1496 suitable CRL must be added to the store otherwise an error will be
1497 raised.
1498
1499 .. versionadded:: 16.1.0
1500
1501 :param int flags: The verification flags to set on this store.
1502 See :class:`X509StoreFlags` for available constants.
1503 :return: ``None`` if the verification flags were successfully set.
1504 """
1505 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001506
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001507
1508X509StoreType = X509Store
1509
1510
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001511class X509StoreContextError(Exception):
1512 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001513 An exception raised when an error occurred while verifying a certificate
1514 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001515
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001516 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001517 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001518 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001519
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001520 def __init__(self, message, certificate):
1521 super(X509StoreContextError, self).__init__(message)
1522 self.certificate = certificate
1523
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001524
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001525class X509StoreContext(object):
1526 """
1527 An X.509 store context.
1528
Dan Sully44e767a2016-06-04 18:05:27 -07001529 An X.509 store context is used to carry out the actual verification process
1530 of a certificate in a described context. For describing such a context, see
1531 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001532
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001533 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1534 instance. It is dynamically allocated and automatically garbage
1535 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001536 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001537 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001538 :param X509Store store: The certificates which will be trusted for the
1539 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001540 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001541 """
1542
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001543 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001544 store_ctx = _lib.X509_STORE_CTX_new()
1545 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1546 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001547 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001548 # Make the store context available for use after instantiating this
1549 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001550 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001551 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001552
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001553 def _init(self):
1554 """
1555 Set up the store context for a subsequent verification operation.
1556 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001557 ret = _lib.X509_STORE_CTX_init(
1558 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1559 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001560 if ret <= 0:
1561 _raise_current_error()
1562
1563 def _cleanup(self):
1564 """
1565 Internally cleans up the store context.
1566
Dan Sully44e767a2016-06-04 18:05:27 -07001567 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001568 """
1569 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1570
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001571 def _exception_from_context(self):
1572 """
1573 Convert an OpenSSL native context error failure into a Python
1574 exception.
1575
Alex Gaynor5945ea82015-09-05 14:59:06 -04001576 When a call to native OpenSSL X509_verify_cert fails, additional
1577 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001578 """
1579 errors = [
1580 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1581 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1582 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001583 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001584 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001585 # A context error should always be associated with a certificate, so we
1586 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001587 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001588 _cert = _lib.X509_dup(_x509)
1589 pycert = X509.__new__(X509)
1590 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001591 return X509StoreContextError(errors, pycert)
1592
Stephen Holsapple46a09252015-02-12 14:45:43 -08001593 def set_store(self, store):
1594 """
Dan Sully44e767a2016-06-04 18:05:27 -07001595 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001596
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001597 .. versionadded:: 0.15
1598
Dan Sully44e767a2016-06-04 18:05:27 -07001599 :param X509Store store: The store description which will be used for
1600 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001601 """
1602 self._store = store
1603
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001604 def verify_certificate(self):
1605 """
1606 Verify a certificate in a context.
1607
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001608 .. versionadded:: 0.15
1609
Alex Gaynorca87ff62015-09-04 23:31:03 -04001610 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001611 certificate in the context. Sets ``certificate`` attribute to
1612 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001613 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001614 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001615 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001616 self._init()
1617 ret = _lib.X509_verify_cert(self._store_ctx)
1618 self._cleanup()
1619 if ret <= 0:
1620 raise self._exception_from_context()
1621
1622
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001623def load_certificate(type, buffer):
1624 """
1625 Load a certificate from a buffer
1626
1627 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1628
Dan Sully44e767a2016-06-04 18:05:27 -07001629 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001630
1631 :return: The X509 object
1632 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001633 if isinstance(buffer, _text_type):
1634 buffer = buffer.encode("ascii")
1635
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001636 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001637
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001638 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001639 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001640 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001641 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001642 else:
1643 raise ValueError(
1644 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001645
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001646 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001647 _raise_current_error()
1648
1649 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001650 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001651 return cert
1652
1653
1654def dump_certificate(type, cert):
1655 """
1656 Dump a certificate to a buffer
1657
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001658 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1659 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001660 :param cert: The certificate to dump
1661 :return: The buffer with the dumped certificate in
1662 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001663 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001664
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001665 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001666 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001667 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001668 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001669 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001670 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001671 else:
1672 raise ValueError(
1673 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1674 "FILETYPE_TEXT")
1675
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001676 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001677 return _bio_to_string(bio)
1678
1679
Cory Benfield6492f7c2015-10-27 16:57:58 +09001680def dump_publickey(type, pkey):
1681 """
Cory Benfield11c10192015-10-27 17:23:03 +09001682 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001683
Cory Benfield9c590b92015-10-28 14:55:05 +09001684 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001685 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001686 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001687 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001688 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001689 """
1690 bio = _new_mem_buf()
1691 if type == FILETYPE_PEM:
1692 write_bio = _lib.PEM_write_bio_PUBKEY
1693 elif type == FILETYPE_ASN1:
1694 write_bio = _lib.i2d_PUBKEY_bio
1695 else:
1696 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1697
1698 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001699 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001700 _raise_current_error()
1701
1702 return _bio_to_string(bio)
1703
1704
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001705def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1706 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001707 Dump the private key *pkey* into a buffer string encoded with the type
1708 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1709 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001710
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001711 :param type: The file type (one of :const:`FILETYPE_PEM`,
1712 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1713 :param PKey pkey: The PKey to dump
1714 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001715 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001716 the passphrase to use, or a callback for providing the passphrase.
1717
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001718 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001719 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001720 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001721 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001722
1723 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001724 if passphrase is None:
1725 raise TypeError(
1726 "if a value is given for cipher "
1727 "one must also be given for passphrase")
1728 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001729 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001730 raise ValueError("Invalid cipher name")
1731 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001732 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001733
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001734 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001735 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001736 result_code = _lib.PEM_write_bio_PrivateKey(
1737 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001738 helper.callback, helper.callback_args)
1739 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001740 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001741 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001742 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001743 rsa = _ffi.gc(
1744 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1745 _lib.RSA_free
1746 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001747 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001748 else:
1749 raise ValueError(
1750 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1751 "FILETYPE_TEXT")
1752
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001753 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001754
1755 return _bio_to_string(bio)
1756
1757
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001758class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001759 """
1760 A certificate revocation.
1761 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001762 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1763 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1764 # OCSP_crl_reason_str. We use the latter, just like the command line
1765 # program.
1766 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001767 b"unspecified",
1768 b"keyCompromise",
1769 b"CACompromise",
1770 b"affiliationChanged",
1771 b"superseded",
1772 b"cessationOfOperation",
1773 b"certificateHold",
1774 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001775 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001776
1777 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001778 revoked = _lib.X509_REVOKED_new()
1779 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001780
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001781 def set_serial(self, hex_str):
1782 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001783 Set the serial number.
1784
1785 The serial number is formatted as a hexadecimal number encoded in
1786 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001787
Dan Sully44e767a2016-06-04 18:05:27 -07001788 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001789
Dan Sully44e767a2016-06-04 18:05:27 -07001790 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001791 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001792 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1793 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001794 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001795 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001796 if not bn_result:
1797 raise ValueError("bad hex string")
1798
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001799 asn1_serial = _ffi.gc(
1800 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1801 _lib.ASN1_INTEGER_free)
1802 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001803
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001804 def get_serial(self):
1805 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001806 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001807
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001808 The serial number is formatted as a hexadecimal number encoded in
1809 ASCII.
1810
1811 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001812 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001813 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001814 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001815
Alex Gaynor67903a62016-06-02 10:37:13 -07001816 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1817 _openssl_assert(asn1_int != _ffi.NULL)
1818 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1819 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001820 return _bio_to_string(bio)
1821
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001822 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001823 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1824 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001825 obj = _lib.X509_EXTENSION_get_object(ext)
1826 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001827 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001828 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001829 break
1830
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001831 def set_reason(self, reason):
1832 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001833 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001834
Dan Sully44e767a2016-06-04 18:05:27 -07001835 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001836
1837 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001838 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001839
Dan Sully44e767a2016-06-04 18:05:27 -07001840 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001841
1842 .. seealso::
1843
Dan Sully44e767a2016-06-04 18:05:27 -07001844 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001845 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001846 """
1847 if reason is None:
1848 self._delete_reason()
1849 elif not isinstance(reason, bytes):
1850 raise TypeError("reason must be None or a byte string")
1851 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001852 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001853 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1854
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001855 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001856 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001857 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001858
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001859 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001860 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001861
1862 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001863 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1864 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001865 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001866
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001867 def get_reason(self):
1868 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001869 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001870
Dan Sully44e767a2016-06-04 18:05:27 -07001871 :return: The reason, or ``None`` if there is none.
1872 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001873
1874 .. seealso::
1875
Dan Sully44e767a2016-06-04 18:05:27 -07001876 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001877 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001878 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001879 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1880 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001881 obj = _lib.X509_EXTENSION_get_object(ext)
1882 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001883 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001885 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001886 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001887 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001888 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001889 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001890 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001891
1892 return _bio_to_string(bio)
1893
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001894 def all_reasons(self):
1895 """
1896 Return a list of all the supported reason strings.
1897
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001898 This list is a copy; modifying it does not change the supported reason
1899 strings.
1900
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001901 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001902 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001903 """
1904 return self._crl_reasons[:]
1905
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001906 def set_rev_date(self, when):
1907 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001908 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001909
Dan Sully44e767a2016-06-04 18:05:27 -07001910 :param bytes when: The timestamp of the revocation,
1911 as ASN.1 GENERALIZEDTIME.
1912 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001913 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001914 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1915 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001916
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001917 def get_rev_date(self):
1918 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001919 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001920
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001921 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001922 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001923 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001924 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1925 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001926
1927
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001928class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001929 """
1930 A certificate revocation list.
1931 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001932
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001933 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001934 crl = _lib.X509_CRL_new()
1935 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001936
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001937 def get_revoked(self):
1938 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001939 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001940
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001941 These revocations will be provided by value, not by reference.
1942 That means it's okay to mutate them: it won't affect this CRL.
1943
1944 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001945 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001946 """
1947 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001948 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001949 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1950 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001951 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001952 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001954 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001955 if results:
1956 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001957
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001958 def add_revoked(self, revoked):
1959 """
1960 Add a revoked (by value not reference) to the CRL structure
1961
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001962 This revocation will be added by value, not by reference. That
1963 means it's okay to mutate it after adding: it won't affect
1964 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001965
Dan Sully44e767a2016-06-04 18:05:27 -07001966 :param Revoked revoked: The new revocation.
1967 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001968 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001969 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001970 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001971
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001972 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001973 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001974
Dan Sully44e767a2016-06-04 18:05:27 -07001975 def get_issuer(self):
1976 """
1977 Get the CRL's issuer.
1978
1979 .. versionadded:: 16.1.0
1980
1981 :rtype: X509Name
1982 """
1983 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
1984 _openssl_assert(_issuer != _ffi.NULL)
1985 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
1986 issuer = X509Name.__new__(X509Name)
1987 issuer._name = _issuer
1988 return issuer
1989
1990 def set_version(self, version):
1991 """
1992 Set the CRL version.
1993
1994 .. versionadded:: 16.1.0
1995
1996 :param int version: The version of the CRL.
1997 :return: ``None``
1998 """
1999 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2000
2001 def _set_boundary_time(self, which, when):
2002 return _set_asn1_time(which(self._crl), when)
2003
2004 def set_lastUpdate(self, when):
2005 """
2006 Set when the CRL was last updated.
2007
2008 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2009
2010 YYYYMMDDhhmmssZ
2011 YYYYMMDDhhmmss+hhmm
2012 YYYYMMDDhhmmss-hhmm
2013
2014 .. versionadded:: 16.1.0
2015
2016 :param bytes when: A timestamp string.
2017 :return: ``None``
2018 """
2019 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2020
2021 def set_nextUpdate(self, when):
2022 """
2023 Set when the CRL will next be udpated.
2024
2025 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2026
2027 YYYYMMDDhhmmssZ
2028 YYYYMMDDhhmmss+hhmm
2029 YYYYMMDDhhmmss-hhmm
2030
2031 .. versionadded:: 16.1.0
2032
2033 :param bytes when: A timestamp string.
2034 :return: ``None``
2035 """
2036 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2037
2038 def sign(self, issuer_cert, issuer_key, digest):
2039 """
2040 Sign the CRL.
2041
2042 Signing a CRL enables clients to associate the CRL itself with an
2043 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2044 be signed by an issuer.
2045
2046 This method implicitly sets the issuer's name based on the issuer
2047 certificate and private key used to sign the CRL.
2048
2049 .. versionadded:: 16.1.0
2050
2051 :param X509 issuer_cert: The issuer's certificate.
2052 :param PKey issuer_key: The issuer's private key.
2053 :param bytes digest: The digest method to sign the CRL with.
2054 """
2055 digest_obj = _lib.EVP_get_digestbyname(digest)
2056 _openssl_assert(digest_obj != _ffi.NULL)
2057 _lib.X509_CRL_set_issuer_name(
2058 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2059 _lib.X509_CRL_sort(self._crl)
2060 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2061 _openssl_assert(result != 0)
2062
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002063 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002064 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002065 """
Dan Sully44e767a2016-06-04 18:05:27 -07002066 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002067
Dan Sully44e767a2016-06-04 18:05:27 -07002068 :param X509 cert: The certificate used to sign the CRL.
2069 :param PKey key: The key used to sign the CRL.
2070 :param int type: The export format, either :data:`FILETYPE_PEM`,
2071 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002072 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002073 :param bytes digest: The name of the message digest to use (eg
2074 ``b"sha1"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002075 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002076 """
Dan Sully44e767a2016-06-04 18:05:27 -07002077
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002078 if not isinstance(cert, X509):
2079 raise TypeError("cert must be an X509 instance")
2080 if not isinstance(key, PKey):
2081 raise TypeError("key must be a PKey instance")
2082 if not isinstance(type, int):
2083 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002084
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002085 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002086 _warn(
2087 "The default message digest (md5) is deprecated. "
2088 "Pass the name of a message digest explicitly.",
2089 category=DeprecationWarning,
2090 stacklevel=2,
2091 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002092 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002093
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002094 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002095 if digest_obj == _ffi.NULL:
2096 raise ValueError("No such digest method")
2097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002098 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002099 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002100
Alex Gaynora738ed52015-09-05 11:17:10 -04002101 # A scratch time object to give different values to different CRL
2102 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002103 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002104 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002105
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002106 _lib.X509_gmtime_adj(sometime, 0)
2107 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002108
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002109 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2110 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002111
Alex Gaynor5945ea82015-09-05 14:59:06 -04002112 _lib.X509_CRL_set_issuer_name(
2113 self._crl, _lib.X509_get_subject_name(cert._x509)
2114 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002115
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002116 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002117 if not sign_result:
2118 _raise_current_error()
2119
Dominic Chenf05b2122015-10-13 16:32:35 +00002120 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002121
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002122
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002123CRLType = CRL
2124
2125
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002126class PKCS7(object):
2127 def type_is_signed(self):
2128 """
2129 Check if this NID_pkcs7_signed object
2130
2131 :return: True if the PKCS7 is of type signed
2132 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002133 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002134
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002135 def type_is_enveloped(self):
2136 """
2137 Check if this NID_pkcs7_enveloped object
2138
2139 :returns: True if the PKCS7 is of type enveloped
2140 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002141 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002142
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002143 def type_is_signedAndEnveloped(self):
2144 """
2145 Check if this NID_pkcs7_signedAndEnveloped object
2146
2147 :returns: True if the PKCS7 is of type signedAndEnveloped
2148 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002149 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002150
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002151 def type_is_data(self):
2152 """
2153 Check if this NID_pkcs7_data object
2154
2155 :return: True if the PKCS7 is of type data
2156 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002157 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002158
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002159 def get_type_name(self):
2160 """
2161 Returns the type name of the PKCS7 structure
2162
2163 :return: A string with the typename
2164 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002165 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2166 string_type = _lib.OBJ_nid2sn(nid)
2167 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002168
2169PKCS7Type = PKCS7
2170
2171
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002172class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002173 """
2174 A PKCS #12 archive.
2175 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002176
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002177 def __init__(self):
2178 self._pkey = None
2179 self._cert = None
2180 self._cacerts = None
2181 self._friendlyname = None
2182
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002183 def get_certificate(self):
2184 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002185 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002186
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002187 :return: The certificate, or :py:const:`None` if there is none.
2188 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002189 """
2190 return self._cert
2191
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002192 def set_certificate(self, cert):
2193 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002194 Set 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 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002197 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002198
Dan Sully44e767a2016-06-04 18:05:27 -07002199 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002200 """
2201 if not isinstance(cert, X509):
2202 raise TypeError("cert must be an X509 instance")
2203 self._cert = cert
2204
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002205 def get_privatekey(self):
2206 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002207 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002208
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002209 :return: The private key, or :py:const:`None` if there is none.
2210 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002211 """
2212 return self._pkey
2213
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002214 def set_privatekey(self, pkey):
2215 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002216 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002218 :param pkey: The new private key, or :py:const:`None` to unset it.
2219 :type pkey: :py:class:`PKey` or :py:const:`None`
2220
Dan Sully44e767a2016-06-04 18:05:27 -07002221 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002222 """
2223 if not isinstance(pkey, PKey):
2224 raise TypeError("pkey must be a PKey instance")
2225 self._pkey = pkey
2226
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002227 def get_ca_certificates(self):
2228 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002229 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002230
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002231 :return: A tuple with the CA certificates in the chain, or
2232 :py:const:`None` if there are none.
2233 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002234 """
2235 if self._cacerts is not None:
2236 return tuple(self._cacerts)
2237
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002238 def set_ca_certificates(self, cacerts):
2239 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002240 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002241
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002242 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2243 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002244 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002245
Dan Sully44e767a2016-06-04 18:05:27 -07002246 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002247 """
2248 if cacerts is None:
2249 self._cacerts = None
2250 else:
2251 cacerts = list(cacerts)
2252 for cert in cacerts:
2253 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002254 raise TypeError(
2255 "iterable must only contain X509 instances"
2256 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002257 self._cacerts = cacerts
2258
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002259 def set_friendlyname(self, name):
2260 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002261 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002262
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002263 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002264 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002265
Dan Sully44e767a2016-06-04 18:05:27 -07002266 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002267 """
2268 if name is None:
2269 self._friendlyname = None
2270 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002271 raise TypeError(
2272 "name must be a byte string or None (not %r)" % (name,)
2273 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002274 self._friendlyname = name
2275
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002276 def get_friendlyname(self):
2277 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002278 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002279
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002280 :returns: The friendly name, or :py:const:`None` if there is none.
2281 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002282 """
2283 return self._friendlyname
2284
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002285 def export(self, passphrase=None, iter=2048, maciter=1):
2286 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002287 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002288
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002289 For more information, see the :c:func:`PKCS12_create` man page.
2290
2291 :param passphrase: The passphrase used to encrypt the structure. Unlike
2292 some other passphrase arguments, this *must* be a string, not a
2293 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002294 :type passphrase: :py:data:`bytes`
2295
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002296 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002297 :type iter: :py:data:`int`
2298
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002299 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002300 :type maciter: :py:data:`int`
2301
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002302 :return: The string representation of the PKCS #12 structure.
2303 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002304 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002305 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002306
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002307 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002308 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002309 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002310 cacerts = _lib.sk_X509_new_null()
2311 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002312 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002313 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002314
2315 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002316 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002317
2318 friendlyname = self._friendlyname
2319 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002320 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002321
2322 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002323 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002324 else:
2325 pkey = self._pkey._pkey
2326
2327 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002328 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002329 else:
2330 cert = self._cert._x509
2331
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002332 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002333 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002334 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2335 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002336 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002337 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002338 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002339 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002340
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002341 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002342 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002343 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002344
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002345
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002346PKCS12Type = PKCS12
2347
2348
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002349class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002350 """
2351 A Netscape SPKI object.
2352 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002353
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002354 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002355 spki = _lib.NETSCAPE_SPKI_new()
2356 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002357
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002358 def sign(self, pkey, digest):
2359 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002360 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002361
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002362 :param pkey: The private key to sign with.
2363 :type pkey: :py:class:`PKey`
2364
2365 :param digest: The message digest to use.
2366 :type digest: :py:class:`bytes`
2367
Dan Sully44e767a2016-06-04 18:05:27 -07002368 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002369 """
2370 if pkey._only_public:
2371 raise ValueError("Key has only public part")
2372
2373 if not pkey._initialized:
2374 raise ValueError("Key is uninitialized")
2375
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002376 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002377 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002378 raise ValueError("No such digest method")
2379
Alex Gaynor5945ea82015-09-05 14:59:06 -04002380 sign_result = _lib.NETSCAPE_SPKI_sign(
2381 self._spki, pkey._pkey, digest_obj
2382 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002383 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002384
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002385 def verify(self, key):
2386 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002387 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002388
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002389 :param key: The public key that signature is supposedly from.
2390 :type pkey: :py:class:`PKey`
2391
2392 :return: :py:const:`True` if the signature is correct.
2393 :rtype: :py:class:`bool`
2394
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002395 :raises Error: If the signature is invalid, or there was a problem
2396 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002397 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002398 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002399 if answer <= 0:
2400 _raise_current_error()
2401 return True
2402
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002403 def b64_encode(self):
2404 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002405 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002406
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002407 :return: The base64 encoded string.
2408 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002409 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002410 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2411 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002412 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002413 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002414
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002415 def get_pubkey(self):
2416 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002417 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002418
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002419 :return: The public key.
2420 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002421 """
2422 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002423 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002424 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002425 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002426 pkey._only_public = True
2427 return pkey
2428
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002429 def set_pubkey(self, pkey):
2430 """
2431 Set the public key of the certificate
2432
2433 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002434 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002435 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002436 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002437 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002438
2439
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002440NetscapeSPKIType = NetscapeSPKI
2441
2442
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002443class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002444 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002445 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002446 raise ValueError(
2447 "only FILETYPE_PEM key format supports encryption"
2448 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002449 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002450 self._more_args = more_args
2451 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002452 self._problems = []
2453
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002454 @property
2455 def callback(self):
2456 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002457 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002458 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002459 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002460 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002461 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002462 else:
2463 raise TypeError("Last argument must be string or callable")
2464
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002465 @property
2466 def callback_args(self):
2467 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002468 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002469 elif isinstance(self._passphrase, bytes):
2470 return self._passphrase
2471 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002472 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002473 else:
2474 raise TypeError("Last argument must be string or callable")
2475
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002476 def raise_if_problem(self, exceptionType=Error):
2477 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002478 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002479 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002480 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002481 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002482 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002483 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002484
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002485 def _read_passphrase(self, buf, size, rwflag, userdata):
2486 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002487 if self._more_args:
2488 result = self._passphrase(size, rwflag, userdata)
2489 else:
2490 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002491 if not isinstance(result, bytes):
2492 raise ValueError("String expected")
2493 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002494 if self._truncate:
2495 result = result[:size]
2496 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002497 raise ValueError(
2498 "passphrase returned by callback is too long"
2499 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002500 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002501 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002502 return len(result)
2503 except Exception as e:
2504 self._problems.append(e)
2505 return 0
2506
2507
Cory Benfield6492f7c2015-10-27 16:57:58 +09002508def load_publickey(type, buffer):
2509 """
Cory Benfield11c10192015-10-27 17:23:03 +09002510 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002511
Cory Benfield9c590b92015-10-28 14:55:05 +09002512 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002513 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002514 :param buffer: The buffer the key is stored in.
2515 :type buffer: A Python string object, either unicode or bytestring.
2516 :return: The PKey object.
2517 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002518 """
2519 if isinstance(buffer, _text_type):
2520 buffer = buffer.encode("ascii")
2521
2522 bio = _new_mem_buf(buffer)
2523
2524 if type == FILETYPE_PEM:
2525 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2526 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2527 elif type == FILETYPE_ASN1:
2528 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2529 else:
2530 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2531
2532 if evp_pkey == _ffi.NULL:
2533 _raise_current_error()
2534
2535 pkey = PKey.__new__(PKey)
2536 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002537 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002538 return pkey
2539
2540
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002541def load_privatekey(type, buffer, passphrase=None):
2542 """
2543 Load a private key from a buffer
2544
2545 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2546 :param buffer: The buffer the key is stored in
2547 :param passphrase: (optional) if encrypted PEM format, this can be
2548 either the passphrase to use, or a callback for
2549 providing the passphrase.
2550
2551 :return: The PKey object
2552 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002553 if isinstance(buffer, _text_type):
2554 buffer = buffer.encode("ascii")
2555
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002556 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002557
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002558 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002559 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002560 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2561 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002562 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002563 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002564 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002565 else:
2566 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2567
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002568 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002569 _raise_current_error()
2570
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002571 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002572 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002573 return pkey
2574
2575
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002576def dump_certificate_request(type, req):
2577 """
2578 Dump a certificate request to a buffer
2579
2580 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2581 :param req: The certificate request to dump
2582 :return: The buffer with the dumped certificate request in
2583 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002584 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002585
2586 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002587 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002588 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002589 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002590 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002591 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002592 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002593 raise ValueError(
2594 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2595 "FILETYPE_TEXT"
2596 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002597
Alex Gaynor09a386e2016-07-03 09:32:44 -04002598 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002599
2600 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002601
2602
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002603def load_certificate_request(type, buffer):
2604 """
2605 Load a certificate request from a buffer
2606
2607 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2608 :param buffer: The buffer the certificate request is stored in
2609 :return: The X509Req object
2610 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002611 if isinstance(buffer, _text_type):
2612 buffer = buffer.encode("ascii")
2613
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002614 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002615
2616 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002617 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002618 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002619 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002620 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002621 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002622
Alex Gaynoradd5b072016-06-04 21:04:00 -07002623 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002624
2625 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002626 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002627 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002628
2629
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002630def sign(pkey, data, digest):
2631 """
2632 Sign data with a digest
2633
2634 :param pkey: Pkey to sign with
2635 :param data: data to be signed
2636 :param digest: message digest to use
2637 :return: signature
2638 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002639 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002640
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002641 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002642 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002643 raise ValueError("No such digest method")
2644
Alex Gaynor67903a62016-06-02 10:37:13 -07002645 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002646 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002647
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002648 _lib.EVP_SignInit(md_ctx, digest_obj)
2649 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002650
Colleen Murphye09399b2016-03-01 17:40:49 -08002651 pkey_length = (PKey.bits(pkey) + 7) // 8
2652 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002653 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002654 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002655 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002656 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002657
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002658 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002659
2660
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002661def verify(cert, signature, data, digest):
2662 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002663 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002664
2665 :param cert: signing certificate (X509 object)
2666 :param signature: signature returned by sign function
2667 :param data: data to be verified
2668 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002669 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002670 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002671 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002672
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002673 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002674 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002675 raise ValueError("No such digest method")
2676
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002677 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002678 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002679 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002680
Alex Gaynor67903a62016-06-02 10:37:13 -07002681 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002682 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002683
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002684 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2685 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002686 verify_result = _lib.EVP_VerifyFinal(
2687 md_ctx, signature, len(signature), pkey
2688 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002689
2690 if verify_result != 1:
2691 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002692
2693
Dominic Chenf05b2122015-10-13 16:32:35 +00002694def dump_crl(type, crl):
2695 """
2696 Dump a certificate revocation list to a buffer.
2697
2698 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2699 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002700 :param CRL crl: The CRL to dump.
2701
Dominic Chenf05b2122015-10-13 16:32:35 +00002702 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002703 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002704 """
2705 bio = _new_mem_buf()
2706
2707 if type == FILETYPE_PEM:
2708 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2709 elif type == FILETYPE_ASN1:
2710 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2711 elif type == FILETYPE_TEXT:
2712 ret = _lib.X509_CRL_print(bio, crl._crl)
2713 else:
2714 raise ValueError(
2715 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2716 "FILETYPE_TEXT")
2717
2718 assert ret == 1
2719 return _bio_to_string(bio)
2720
2721
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002722def load_crl(type, buffer):
2723 """
2724 Load a certificate revocation list from a buffer
2725
2726 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2727 :param buffer: The buffer the CRL is stored in
2728
2729 :return: The PKey object
2730 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002731 if isinstance(buffer, _text_type):
2732 buffer = buffer.encode("ascii")
2733
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002734 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002735
2736 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002737 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002738 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002739 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002740 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002741 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2742
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002743 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002744 _raise_current_error()
2745
2746 result = CRL.__new__(CRL)
2747 result._crl = crl
2748 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002749
2750
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002751def load_pkcs7_data(type, buffer):
2752 """
2753 Load pkcs7 data from a buffer
2754
2755 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2756 :param buffer: The buffer with the pkcs7 data.
2757 :return: The PKCS7 object
2758 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002759 if isinstance(buffer, _text_type):
2760 buffer = buffer.encode("ascii")
2761
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002762 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002763
2764 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002765 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002766 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002767 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002768 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002769 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2770
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002771 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002772 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002773
2774 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002775 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002776 return pypkcs7
2777
2778
Stephen Holsapple38482622014-04-05 20:29:34 -07002779def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002780 """
2781 Load a PKCS12 object from a buffer
2782
2783 :param buffer: The buffer the certificate is stored in
2784 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2785 :returns: The PKCS12 object
2786 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002787 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002788
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002789 if isinstance(buffer, _text_type):
2790 buffer = buffer.encode("ascii")
2791
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002792 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002793
Stephen Holsapple38482622014-04-05 20:29:34 -07002794 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2795 # password based encryption no password and a zero length password are two
2796 # different things, but OpenSSL implementation will try both to figure out
2797 # which one works.
2798 if not passphrase:
2799 passphrase = _ffi.NULL
2800
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002801 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2802 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002803 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002804 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002805
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002806 pkey = _ffi.new("EVP_PKEY**")
2807 cert = _ffi.new("X509**")
2808 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002809
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002810 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002811 if not parse_result:
2812 _raise_current_error()
2813
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002814 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002815
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002816 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2817 # queue for no particular reason. This error isn't interesting to anyone
2818 # outside this function. It's not even interesting to us. Get rid of it.
2819 try:
2820 _raise_current_error()
2821 except Error:
2822 pass
2823
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002824 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002825 pykey = None
2826 else:
2827 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002828 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002829
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002830 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002831 pycert = None
2832 friendlyname = None
2833 else:
2834 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002835 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002836
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002837 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002838 friendlyname_buffer = _lib.X509_alias_get0(
2839 cert[0], friendlyname_length
2840 )
2841 friendlyname = _ffi.buffer(
2842 friendlyname_buffer, friendlyname_length[0]
2843 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002844 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002845 friendlyname = None
2846
2847 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002848 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002849 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002850 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002851 pycacerts.append(pycacert)
2852 if not pycacerts:
2853 pycacerts = None
2854
2855 pkcs12 = PKCS12.__new__(PKCS12)
2856 pkcs12._pkey = pykey
2857 pkcs12._cert = pycert
2858 pkcs12._cacerts = pycacerts
2859 pkcs12._friendlyname = friendlyname
2860 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002861
2862
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002863# There are no direct unit tests for this initialization. It is tested
2864# indirectly since it is necessary for functions like dump_privatekey when
2865# using encryption.
2866#
2867# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2868# and some other similar tests may fail without this (though they may not if
2869# the Python runtime has already done some initialization of the underlying
2870# OpenSSL library (and is linked against the same one that cryptography is
2871# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002872_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002873
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002874# This is similar but exercised mainly by exception_from_error_queue. It calls
2875# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2876_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002877
2878
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002879# Set the default string mask to match OpenSSL upstream (since 2005) and
2880# RFC5280 recommendations.
2881_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')