blob: ae05edef466035bc9f54871b3eadd69b51f3a561 [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.primitives.asymmetric import dsa, rsa
14
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050015from OpenSSL._util import (
16 ffi as _ffi,
17 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050018 exception_from_error_queue as _exception_from_error_queue,
19 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040020 native as _native,
21 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040022 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070023 make_assert as _make_assert,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040024)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080025
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050026FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
27FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080028
29# TODO This was an API mistake. OpenSSL has no such constant.
30FILETYPE_TEXT = 2 ** 16 - 1
31
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050032TYPE_RSA = _lib.EVP_PKEY_RSA
33TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080034
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080035
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050036class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050037 """
38 An error occurred in an `OpenSSL.crypto` API.
39 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050040
41
42_raise_current_error = partial(_exception_from_error_queue, Error)
Alex Gaynor67903a62016-06-02 10:37:13 -070043_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050044
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070045
Paul Kehrereb633842016-10-06 11:22:01 +020046def _get_backend():
47 """
48 Importing the backend from cryptography has the side effect of activating
49 the osrandom engine. This mutates the global state of OpenSSL in the
50 process and causes issues for various programs that use subinterpreters or
51 embed Python. By putting the import in this function we can avoid
52 triggering this side effect unless _get_backend is called.
53 """
54 from cryptography.hazmat.backends.openssl.backend import backend
55 return backend
56
57
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050058def _untested_error(where):
59 """
60 An OpenSSL API failed somehow. Additionally, the failure which was
61 encountered isn't one that's exercised by the test suite so future behavior
62 of pyOpenSSL is now somewhat less predictable.
63 """
64 raise RuntimeError("Unknown %s failure" % (where,))
65
66
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050067def _new_mem_buf(buffer=None):
68 """
69 Allocate a new OpenSSL memory BIO.
70
71 Arrange for the garbage collector to clean it up automatically.
72
73 :param buffer: None or some bytes to use to put into the BIO so that they
74 can be read out.
75 """
76 if buffer is None:
77 bio = _lib.BIO_new(_lib.BIO_s_mem())
78 free = _lib.BIO_free
79 else:
80 data = _ffi.new("char[]", buffer)
81 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040082
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050083 # Keep the memory alive as long as the bio is alive!
84 def free(bio, ref=data):
85 return _lib.BIO_free(bio)
86
Alex Gaynorfb8a2a12016-06-04 18:26:26 -070087 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050088
89 bio = _ffi.gc(bio, free)
90 return bio
91
92
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080093def _bio_to_string(bio):
94 """
95 Copy the contents of an OpenSSL BIO object into a Python byte string.
96 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050097 result_buffer = _ffi.new('char**')
98 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
99 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800100
101
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800102def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500103 """
104 The the time value of an ASN1 time object.
105
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900106 @param boundary: An ASN1_TIME pointer (or an object safely
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500107 castable to that type) which will have its value set.
108 @param when: A string representation of the desired time value.
109
110 @raise TypeError: If C{when} is not a L{bytes} string.
111 @raise ValueError: If C{when} does not represent a time in the required
112 format.
113 @raise RuntimeError: If the time value cannot be set for some other
114 (unspecified) reason.
115 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800116 if not isinstance(when, bytes):
117 raise TypeError("when must be a byte string")
118
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900119 set_result = _lib.ASN1_TIME_set_string(boundary, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800120 if set_result == 0:
Moriyoshi Koizumi80b25ef2017-06-22 00:54:20 +0900121 raise ValueError("Invalid string")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800122
Alex Gaynor510293e2016-06-02 12:07:59 -0700123
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800124def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500125 """
126 Retrieve the time value of an ASN1 time object.
127
128 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
129 that type) from which the time value will be retrieved.
130
131 @return: The time value from C{timestamp} as a L{bytes} string in a certain
132 format. Or C{None} if the object contains no time value.
133 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
135 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800136 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400137 elif (
138 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
139 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500140 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800141 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500142 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
143 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
144 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500145 # This may happen:
146 # - if timestamp was not an ASN1_TIME
147 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
148 # - if a copy of the time data from timestamp cannot be made for
149 # the newly allocated ASN1_GENERALIZEDTIME
150 #
151 # These are difficult to test. cffi enforces the ASN1_TIME type.
152 # Memory allocation failures are a pain to trigger
153 # deterministically.
154 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800155 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500156 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800157 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500158 string_data = _lib.ASN1_STRING_data(string_timestamp)
159 string_result = _ffi.string(string_data)
160 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800161 return string_result
162
163
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800164class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200165 """
166 A class representing an DSA or RSA public key or key pair.
167 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800168 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800169 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800170
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800171 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500172 pkey = _lib.EVP_PKEY_new()
173 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800174 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800175
Paul Kehrer72d968b2016-07-29 15:31:04 +0800176 def to_cryptography_key(self):
177 """
178 Export as a ``cryptography`` key.
179
180 :rtype: One of ``cryptography``'s `key interfaces`_.
181
182 .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
183 primitives/asymmetric/rsa/#key-interfaces
184
185 .. versionadded:: 16.1.0
186 """
Paul Kehrereb633842016-10-06 11:22:01 +0200187 backend = _get_backend()
Paul Kehrer72d968b2016-07-29 15:31:04 +0800188 if self._only_public:
189 return backend._evp_pkey_to_public_key(self._pkey)
190 else:
191 return backend._evp_pkey_to_private_key(self._pkey)
192
193 @classmethod
194 def from_cryptography_key(cls, crypto_key):
195 """
196 Construct based on a ``cryptography`` *crypto_key*.
197
198 :param crypto_key: A ``cryptography`` key.
199 :type crypto_key: One of ``cryptography``'s `key interfaces`_.
200
201 :rtype: PKey
202
203 .. versionadded:: 16.1.0
204 """
205 pkey = cls()
206 if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
207 dsa.DSAPublicKey, dsa.DSAPrivateKey)):
208 raise TypeError("Unsupported key type")
209
210 pkey._pkey = crypto_key._evp_pkey
211 if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
212 pkey._only_public = True
213 pkey._initialized = True
214 return pkey
215
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800216 def generate_key(self, type, bits):
217 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700218 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800219
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200220 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800221
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200222 :param type: The key type.
223 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
224 :param bits: The number of bits.
225 :type bits: :py:data:`int` ``>= 0``
226 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
227 of the appropriate type.
228 :raises ValueError: If the number of bits isn't an integer of
229 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700230 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800231 """
232 if not isinstance(type, int):
233 raise TypeError("type must be an integer")
234
235 if not isinstance(bits, int):
236 raise TypeError("bits must be an integer")
237
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800238 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500239 exponent = _lib.BN_new()
240 exponent = _ffi.gc(exponent, _lib.BN_free)
241 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800242
243 if type == TYPE_RSA:
244 if bits <= 0:
245 raise ValueError("Invalid number of bits")
246
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500247 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800248
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500249 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400250 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800251
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500252 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400253 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800254
255 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400256 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700257 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400258
259 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400260 res = _lib.DSA_generate_parameters_ex(
261 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
262 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700263 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400264
265 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
266 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800267 else:
268 raise Error("No such key type")
269
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800270 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800271
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800272 def check(self):
273 """
274 Check the consistency of an RSA private key.
275
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200276 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
277
Hynek Schlawack01c31672016-12-11 15:14:09 +0100278 :return: ``True`` if key is consistent.
279
280 :raise OpenSSL.crypto.Error: if the key is inconsistent.
281
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800282 :raise TypeError: if the key is of a type which cannot be checked.
283 Only RSA keys can currently be checked.
284 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800285 if self._only_public:
286 raise TypeError("public key only")
287
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100288 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800289 raise TypeError("key type unsupported")
290
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500291 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
292 rsa = _ffi.gc(rsa, _lib.RSA_free)
293 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800294 if result:
295 return True
296 _raise_current_error()
297
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800298 def type(self):
299 """
300 Returns the type of the key
301
302 :return: The type of the key.
303 """
Alex Gaynor0d2aec52017-05-31 04:26:27 -0400304 return _lib.EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800305
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800306 def bits(self):
307 """
308 Returns the number of bits of the key
309
310 :return: The number of bits of the key.
311 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500312 return _lib.EVP_PKEY_bits(self._pkey)
Alex Chanc6077062016-11-18 13:53:39 +0000313
314
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800315PKeyType = PKey
316
317
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400318class _EllipticCurve(object):
319 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400320 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400321
322 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
323 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
324 instances each of which represents one curve supported by the system.
325 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400326 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400327 _curves = None
328
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400329 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400330 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400331 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400332 """
333 Implement cooperation with the right-hand side argument of ``!=``.
334
335 Python 3 seems to have dropped this cooperation in this very narrow
336 circumstance.
337 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400338 if isinstance(other, _EllipticCurve):
339 return super(_EllipticCurve, self).__ne__(other)
340 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400341
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400342 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400343 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400344 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400345 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400346
347 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400348
349 :return: A :py:type:`set` of ``cls`` instances giving the names of the
350 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400351 """
Alex Chan84902a22017-04-20 11:50:47 +0100352 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
353 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
354 # The return value on this call should be num_curves again. We
355 # could check it to make sure but if it *isn't* then.. what could
356 # we do? Abort the whole process, I suppose...? -exarkun
357 lib.EC_get_builtin_curves(builtin_curves, num_curves)
358 return set(
359 cls.from_nid(lib, c.nid)
360 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400361
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400362 @classmethod
363 def _get_elliptic_curves(cls, lib):
364 """
365 Get, cache, and return the curves supported by OpenSSL.
366
367 :param lib: The OpenSSL library binding object.
368
369 :return: A :py:type:`set` of ``cls`` instances giving the names of the
370 elliptic curves the underlying library supports.
371 """
372 if cls._curves is None:
373 cls._curves = cls._load_elliptic_curves(lib)
374 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400375
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400376 @classmethod
377 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400378 """
379 Instantiate a new :py:class:`_EllipticCurve` associated with the given
380 OpenSSL NID.
381
382 :param lib: The OpenSSL library binding object.
383
384 :param nid: The OpenSSL NID the resulting curve object will represent.
385 This must be a curve NID (and not, for example, a hash NID) or
386 subsequent operations will fail in unpredictable ways.
387 :type nid: :py:class:`int`
388
389 :return: The curve object.
390 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400391 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
392
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400393 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400394 """
395 :param _lib: The :py:mod:`cryptography` binding instance used to
396 interface with OpenSSL.
397
398 :param _nid: The OpenSSL NID identifying the curve this object
399 represents.
400 :type _nid: :py:class:`int`
401
402 :param name: The OpenSSL short name identifying the curve this object
403 represents.
404 :type name: :py:class:`unicode`
405 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400406 self._lib = lib
407 self._nid = nid
408 self.name = name
409
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400410 def __repr__(self):
411 return "<Curve %r>" % (self.name,)
412
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400413 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400414 """
415 Create a new OpenSSL EC_KEY structure initialized to use this curve.
416
417 The structure is automatically garbage collected when the Python object
418 is garbage collected.
419 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400420 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
421 return _ffi.gc(key, _lib.EC_KEY_free)
422
423
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400424def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400425 """
426 Return a set of objects representing the elliptic curves supported in the
427 OpenSSL build in use.
428
429 The curve objects have a :py:class:`unicode` ``name`` attribute by which
430 they identify themselves.
431
432 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400433 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
434 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400435 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400436 return _EllipticCurve._get_elliptic_curves(_lib)
437
438
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400439def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400440 """
441 Return a single curve object selected by name.
442
443 See :py:func:`get_elliptic_curves` for information about curve objects.
444
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400445 :param name: The OpenSSL short name identifying the curve object to
446 retrieve.
447 :type name: :py:class:`unicode`
448
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400449 If the named curve is not supported then :py:class:`ValueError` is raised.
450 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400451 for curve in get_elliptic_curves():
452 if curve.name == name:
453 return curve
454 raise ValueError("unknown curve name", name)
455
456
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800457class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200458 """
459 An X.509 Distinguished Name.
460
461 :ivar countryName: The country of the entity.
462 :ivar C: Alias for :py:attr:`countryName`.
463
464 :ivar stateOrProvinceName: The state or province of the entity.
465 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
466
467 :ivar localityName: The locality of the entity.
468 :ivar L: Alias for :py:attr:`localityName`.
469
470 :ivar organizationName: The organization name of the entity.
471 :ivar O: Alias for :py:attr:`organizationName`.
472
473 :ivar organizationalUnitName: The organizational unit of the entity.
474 :ivar OU: Alias for :py:attr:`organizationalUnitName`
475
476 :ivar commonName: The common name of the entity.
477 :ivar CN: Alias for :py:attr:`commonName`.
478
479 :ivar emailAddress: The e-mail address of the entity.
480 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400481
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800482 def __init__(self, name):
483 """
484 Create a new X509Name, copying the given X509Name instance.
485
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200486 :param name: The name to copy.
487 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800488 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500489 name = _lib.X509_NAME_dup(name._name)
490 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800491
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800492 def __setattr__(self, name, value):
493 if name.startswith('_'):
494 return super(X509Name, self).__setattr__(name, value)
495
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800496 # Note: we really do not want str subclasses here, so we do not use
497 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800498 if type(name) is not str:
499 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400500 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800501
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500502 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500503 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800504 try:
505 _raise_current_error()
506 except Error:
507 pass
508 raise AttributeError("No such attribute")
509
510 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500511 for i in range(_lib.X509_NAME_entry_count(self._name)):
512 ent = _lib.X509_NAME_get_entry(self._name, i)
513 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
514 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800515 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500516 ent = _lib.X509_NAME_delete_entry(self._name, i)
517 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800518 break
519
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500520 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800521 value = value.encode('utf-8')
522
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500523 add_result = _lib.X509_NAME_add_entry_by_NID(
524 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800525 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500526 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800527
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800528 def __getattr__(self, name):
529 """
530 Find attribute. An X509Name object has the following attributes:
531 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400532 organization (alias O), organizationalUnit (alias OU), commonName
533 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800534 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500535 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500536 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800537 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
538 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
539 # push something onto the error queue. If we don't clean that up
540 # now, someone else will bump into it later and be quite confused.
541 # See lp#314814.
542 try:
543 _raise_current_error()
544 except Error:
545 pass
546 return super(X509Name, self).__getattr__(name)
547
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500548 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800549 if entry_index == -1:
550 return None
551
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500552 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
553 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800554
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500555 result_buffer = _ffi.new("unsigned char**")
556 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400557 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800558
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700559 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400560 result = _ffi.buffer(
561 result_buffer[0], data_length
562 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700563 finally:
564 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500565 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800566 return result
567
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500568 def _cmp(op):
569 def f(self, other):
570 if not isinstance(other, X509Name):
571 return NotImplemented
572 result = _lib.X509_NAME_cmp(self._name, other._name)
573 return op(result, 0)
574 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800575
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500576 __eq__ = _cmp(__eq__)
577 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800578
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500579 __lt__ = _cmp(__lt__)
580 __le__ = _cmp(__le__)
581
582 __gt__ = _cmp(__gt__)
583 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800584
585 def __repr__(self):
586 """
587 String representation of an X509Name
588 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400589 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500590 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591 self._name, result_buffer, len(result_buffer))
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700592 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800593
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500594 return "<X509Name object '%s'>" % (
595 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800596
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800597 def hash(self):
598 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200599 Return an integer representation of the first four bytes of the
600 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800601
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200602 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
603
604 :return: The (integer) hash of this name.
605 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800606 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500607 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800608
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800609 def der(self):
610 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200611 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800612
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200613 :return: The DER encoded form of this name.
614 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800615 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500616 result_buffer = _ffi.new('unsigned char**')
617 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400618 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800619
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500620 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
621 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800622 return string_result
623
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800624 def get_components(self):
625 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200626 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800627
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200628 :return: The components of this name.
629 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800630 """
631 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500632 for i in range(_lib.X509_NAME_entry_count(self._name)):
633 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800634
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500635 fname = _lib.X509_NAME_ENTRY_get_object(ent)
636 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800637
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500638 nid = _lib.OBJ_obj2nid(fname)
639 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800640
641 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400642 _ffi.string(name),
643 _ffi.string(
644 _lib.ASN1_STRING_data(fval),
645 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800646
647 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200648
649
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800650X509NameType = X509Name
651
652
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800653class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200654 """
655 An X.509 v3 certificate extension.
656 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400657
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800658 def __init__(self, type_name, critical, value, subject=None, issuer=None):
659 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200660 Initializes an X509 extension.
661
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100662 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400663 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800664
Alex Gaynor5945ea82015-09-05 14:59:06 -0400665 :param bool critical: A flag indicating whether this is a critical
666 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800667
668 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200669 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800670
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200671 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800672 :type subject: :py:class:`X509`
673
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200674 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800675 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100676
Alex Chan54005ce2017-03-21 08:08:17 +0000677 .. _extension: https://www.openssl.org/docs/manmaster/man5/
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100678 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800679 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500680 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800681
Alex Gaynor5945ea82015-09-05 14:59:06 -0400682 # A context is necessary for any extension which uses the r2i
683 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
684 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500685 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800686
687 # We have no configuration database - but perhaps we should (some
688 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800690
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800691 # Initialize the subject and issuer, if appropriate. ctx is a local,
692 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400693 # any references, so no need to mess with reference counts or
694 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800695 if issuer is not None:
696 if not isinstance(issuer, X509):
697 raise TypeError("issuer must be an X509 instance")
698 ctx.issuer_cert = issuer._x509
699 if subject is not None:
700 if not isinstance(subject, X509):
701 raise TypeError("subject must be an X509 instance")
702 ctx.subject_cert = subject._x509
703
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800704 if critical:
705 # There are other OpenSSL APIs which would let us pass in critical
706 # separately, but they're harder to use, and since value is already
707 # a pile of crappy junk smuggling a ton of utterly important
708 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400709 # with strings? (However, X509V3_EXT_i2d in particular seems like
710 # it would be a better API to invoke. I do not know where to get
711 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500712 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800713
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500714 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
715 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800716 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800718
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400719 @property
720 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400721 return _lib.OBJ_obj2nid(
722 _lib.X509_EXTENSION_get_object(self._extension)
723 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400724
725 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500726 _lib.GEN_EMAIL: "email",
727 _lib.GEN_DNS: "DNS",
728 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400729 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400730
731 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500732 method = _lib.X509V3_EXT_get(self._extension)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700733 _openssl_assert(method != _ffi.NULL)
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400734 ext_data = _lib.X509_EXTENSION_get_data(self._extension)
735 payload = ext_data.data
736 length = ext_data.length
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400737
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500738 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400739 payloadptr[0] = payload
740
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500741 if method.it != _ffi.NULL:
742 ptr = _lib.ASN1_ITEM_ptr(method.it)
743 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
744 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400745 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400747 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500748 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400749
Paul Kehrerb7d79502015-05-04 07:43:51 -0500750 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400751 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500752 for i in range(_lib.sk_GENERAL_NAME_num(names)):
753 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400754 try:
755 label = self._prefixes[name.type]
756 except KeyError:
757 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500758 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500759 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400760 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500761 value = _native(
762 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
763 parts.append(label + ":" + value)
764 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400765
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800766 def __str__(self):
767 """
768 :return: a nice text representation of the extension
769 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500770 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400771 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800772
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400773 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500774 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400775 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800776
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500777 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800778
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800779 def get_critical(self):
780 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200781 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800782
783 :return: The critical field.
784 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500785 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800786
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800787 def get_short_name(self):
788 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200789 Returns the short type name of this X.509 extension.
790
791 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800792
793 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200794 :rtype: :py:data:`bytes`
795
796 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800797 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500798 obj = _lib.X509_EXTENSION_get_object(self._extension)
799 nid = _lib.OBJ_obj2nid(obj)
800 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800801
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800802 def get_data(self):
803 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200804 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800805
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200806 :return: The ASN.1 encoded data of this X509 extension.
807 :rtype: :py:data:`bytes`
808
809 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800810 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500811 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
812 string_result = _ffi.cast('ASN1_STRING*', octet_result)
813 char_result = _lib.ASN1_STRING_data(string_result)
814 result_length = _lib.ASN1_STRING_length(string_result)
815 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800816
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200817
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800818X509ExtensionType = X509Extension
819
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800820
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800821class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200822 """
823 An X.509 certificate signing requests.
824 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400825
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800826 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500827 req = _lib.X509_REQ_new()
828 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Alex Gaynor5af32d02016-09-24 01:52:21 -0400829 # Default to version 0.
830 self.set_version(0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800831
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800832 def set_pubkey(self, pkey):
833 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200834 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800835
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200836 :param pkey: The public key to use.
837 :type pkey: :py:class:`PKey`
838
Dan Sully44e767a2016-06-04 18:05:27 -0700839 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800840 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500841 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400842 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800843
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800844 def get_pubkey(self):
845 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200846 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800847
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200848 :return: The public key.
849 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800850 """
851 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500852 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700853 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500854 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800855 pkey._only_public = True
856 return pkey
857
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800858 def set_version(self, version):
859 """
860 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
861 request.
862
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200863 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700864 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800865 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500866 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400867 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800868
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800869 def get_version(self):
870 """
871 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
872 request.
873
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200874 :return: The value of the version subfield.
875 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800876 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500877 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800878
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800879 def get_subject(self):
880 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200881 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800882
Cory Benfield881dc8d2015-12-09 08:25:14 +0000883 This creates a new :class:`X509Name` that wraps the underlying subject
884 name field on the certificate signing request. Modifying it will modify
885 the underlying signing request, and will have the effect of modifying
886 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200887
888 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000889 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800890 """
891 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500892 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700893 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800894
895 # The name is owned by the X509Req structure. As long as the X509Name
896 # Python object is alive, keep the X509Req Python object alive.
897 name._owner = self
898
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800899 return name
900
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800901 def add_extensions(self, extensions):
902 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200903 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800904
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200905 :param extensions: The X.509 extensions to add.
906 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700907 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800908 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500909 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700910 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800911
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500912 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800913
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800914 for ext in extensions:
915 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800916 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800917
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800918 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500919 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800920
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500921 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400922 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800923
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800924 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800925 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200926 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800927
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200928 :return: The X.509 extensions in this request.
929 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
930
931 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800932 """
933 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500934 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500935 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800936 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500937 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800938 exts.append(ext)
939 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800940
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800941 def sign(self, pkey, digest):
942 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700943 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800944
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200945 :param pkey: The key pair to sign with.
946 :type pkey: :py:class:`PKey`
947 :param digest: The name of the message digest to use for the signature,
Alex Gaynor239e2d32016-09-11 12:36:35 -0400948 e.g. :py:data:`b"sha256"`.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200949 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -0700950 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800951 """
952 if pkey._only_public:
953 raise ValueError("Key has only public part")
954
955 if not pkey._initialized:
956 raise ValueError("Key is uninitialized")
957
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500958 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500959 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800960 raise ValueError("No such digest method")
961
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500962 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400963 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800964
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800965 def verify(self, pkey):
966 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200967 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800968
Hynek Schlawack01c31672016-12-11 15:14:09 +0100969 :param PKey key: A public key.
970
971 :return: ``True`` if the signature is correct.
972 :rtype: bool
973
974 :raises OpenSSL.crypto.Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800975 problem verifying the signature.
976 """
977 if not isinstance(pkey, PKey):
978 raise TypeError("pkey must be a PKey instance")
979
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500980 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800981 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500982 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800983
984 return result
985
986
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800987X509ReqType = X509Req
988
989
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800990class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200991 """
992 An X.509 certificate.
993 """
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800994 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500995 x509 = _lib.X509_new()
Hynek Schlawack8a2dd772016-07-31 13:46:20 +0200996 _openssl_assert(x509 != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500997 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800998
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800999 def set_version(self, version):
1000 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001001 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001002
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001003 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001004 :type version: :py:class:`int`
1005
Dan Sully44e767a2016-06-04 18:05:27 -07001006 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001007 """
1008 if not isinstance(version, int):
1009 raise TypeError("version must be an integer")
1010
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001011 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001012
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001013 def get_version(self):
1014 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001015 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001016
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001017 :return: The version number of the certificate.
1018 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001019 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001020 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001021
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001022 def get_pubkey(self):
1023 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001024 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001025
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001026 :return: The public key.
1027 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001028 """
1029 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001030 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1031 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001032 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001033 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001034 pkey._only_public = True
1035 return pkey
1036
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001037 def set_pubkey(self, pkey):
1038 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001039 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001040
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001041 :param pkey: The public key.
1042 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001043
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001044 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001045 """
1046 if not isinstance(pkey, PKey):
1047 raise TypeError("pkey must be a PKey instance")
1048
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001049 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001050 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001051
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001052 def sign(self, pkey, digest):
1053 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001054 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001055
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001056 :param pkey: The key to sign with.
1057 :type pkey: :py:class:`PKey`
1058
1059 :param digest: The name of the message digest to use.
1060 :type digest: :py:class:`bytes`
1061
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001062 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001063 """
1064 if not isinstance(pkey, PKey):
1065 raise TypeError("pkey must be a PKey instance")
1066
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001067 if pkey._only_public:
1068 raise ValueError("Key only has public part")
1069
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001070 if not pkey._initialized:
1071 raise ValueError("Key is uninitialized")
1072
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001073 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001075 raise ValueError("No such digest method")
1076
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001078 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001079
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001080 def get_signature_algorithm(self):
1081 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001082 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001083
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001084 :return: The name of the algorithm.
1085 :rtype: :py:class:`bytes`
1086
1087 :raises ValueError: If the signature algorithm is undefined.
1088
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001089 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001090 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001091 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1092 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001093 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001094 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001095 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001096
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001097 def digest(self, digest_name):
1098 """
1099 Return the digest of the X509 object.
1100
1101 :param digest_name: The name of the digest algorithm to use.
1102 :type digest_name: :py:class:`bytes`
1103
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001104 :return: The digest of the object, formatted as
1105 :py:const:`b":"`-delimited hex pairs.
1106 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001107 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001108 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001109 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001110 raise ValueError("No such digest method")
1111
Paul Kehrer9f9113a2016-09-20 20:10:25 -05001112 result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001113 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001114 result_length[0] = len(result_buffer)
1115
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001116 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001117 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001118 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001119
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001120 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001121 b16encode(ch).upper() for ch
1122 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001123
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001124 def subject_name_hash(self):
1125 """
1126 Return the hash of the X509 subject.
1127
1128 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001129 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001130 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001131 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001132
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001133 def set_serial_number(self, serial):
1134 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001135 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001136
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001137 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001138 :type serial: :py:class:`int`
1139
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001140 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001141 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001142 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001143 raise TypeError("serial must be an integer")
1144
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001145 hex_serial = hex(serial)[2:]
1146 if not isinstance(hex_serial, bytes):
1147 hex_serial = hex_serial.encode('ascii')
1148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001149 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001150
1151 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001152 # it. If bignum is still NULL after this call, then the return value
1153 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001155
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001156 if bignum_serial[0] == _ffi.NULL:
1157 set_result = _lib.ASN1_INTEGER_set(
1158 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001159 if set_result:
1160 # TODO Not tested
1161 _raise_current_error()
1162 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001163 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1164 _lib.BN_free(bignum_serial[0])
1165 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001166 # TODO Not tested
1167 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001168 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1169 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001170 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001171
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001172 def get_serial_number(self):
1173 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001174 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001175
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001176 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001177 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001178 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1180 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001181 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001183 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001184 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001185 serial = int(hexstring_serial, 16)
1186 return serial
1187 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001188 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001189 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001190 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001191
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001192 def gmtime_adj_notAfter(self, amount):
1193 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001194 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001195
Dan Sully44e767a2016-06-04 18:05:27 -07001196 :param int amount: The number of seconds by which to adjust the
1197 timestamp.
1198 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001199 """
1200 if not isinstance(amount, int):
1201 raise TypeError("amount must be an integer")
1202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001203 notAfter = _lib.X509_get_notAfter(self._x509)
1204 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001205
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001206 def gmtime_adj_notBefore(self, amount):
1207 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001208 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001209
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001210 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001211 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001212 """
1213 if not isinstance(amount, int):
1214 raise TypeError("amount must be an integer")
1215
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001216 notBefore = _lib.X509_get_notBefore(self._x509)
1217 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001218
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001219 def has_expired(self):
1220 """
1221 Check whether the certificate has expired.
1222
Dan Sully44e767a2016-06-04 18:05:27 -07001223 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1224 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001225 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001226 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001227 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001228
Paul Kehrerfde45c92016-01-21 12:57:37 -06001229 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001230
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001231 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001232 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001233
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001234 def get_notBefore(self):
1235 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001236 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001237
Paul Kehrerce98ee62017-06-21 06:59:58 -10001238 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001240 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001241
Dan Sully44e767a2016-06-04 18:05:27 -07001242 :return: A timestamp string, or ``None`` if there is none.
1243 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001244 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001245 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001246
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001247 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001248 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001249
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001250 def set_notBefore(self, when):
1251 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001252 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001253
Paul Kehrerce98ee62017-06-21 06:59:58 -10001254 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001255
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001256 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001257
Dan Sully44e767a2016-06-04 18:05:27 -07001258 :param bytes when: A timestamp string.
1259 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001260 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001261 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001262
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001263 def get_notAfter(self):
1264 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001265 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001266
Paul Kehrerce98ee62017-06-21 06:59:58 -10001267 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001268
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001269 YYYYMMDDhhmmssZ
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001270
Dan Sully44e767a2016-06-04 18:05:27 -07001271 :return: A timestamp string, or ``None`` if there is none.
1272 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001273 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001274 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001275
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001276 def set_notAfter(self, when):
1277 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001278 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001279
Paul Kehrerce98ee62017-06-21 06:59:58 -10001280 The timestamp is formatted as an ASN.1 TIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001281
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001282 YYYYMMDDhhmmssZ
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001283
Dan Sully44e767a2016-06-04 18:05:27 -07001284 :param bytes when: A timestamp string.
1285 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001286 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001287 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001288
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001289 def _get_name(self, which):
1290 name = X509Name.__new__(X509Name)
1291 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001292 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001293
1294 # The name is owned by the X509 structure. As long as the X509Name
1295 # Python object is alive, keep the X509 Python object alive.
1296 name._owner = self
1297
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001298 return name
1299
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001300 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001301 if not isinstance(name, X509Name):
1302 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001303 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001304 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001306 def get_issuer(self):
1307 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001308 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001309
Cory Benfielde6bcce82015-12-09 08:40:03 +00001310 This creates a new :class:`X509Name` that wraps the underlying issuer
1311 name field on the certificate. Modifying it will modify the underlying
1312 certificate, and will have the effect of modifying any other
1313 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001314
1315 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001316 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001317 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001318 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001319
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001320 def set_issuer(self, issuer):
1321 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001322 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001323
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001324 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001325 :type issuer: :py:class:`X509Name`
1326
Dan Sully44e767a2016-06-04 18:05:27 -07001327 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001328 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001329 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001330
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001331 def get_subject(self):
1332 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001333 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001334
Cory Benfielde6bcce82015-12-09 08:40:03 +00001335 This creates a new :class:`X509Name` that wraps the underlying subject
1336 name field on the certificate. Modifying it will modify the underlying
1337 certificate, and will have the effect of modifying any other
1338 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001339
1340 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001341 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001342 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001343 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001344
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001345 def set_subject(self, subject):
1346 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001347 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001348
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001349 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001350 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001351
Dan Sully44e767a2016-06-04 18:05:27 -07001352 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001353 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001354 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001355
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001356 def get_extension_count(self):
1357 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001358 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001359
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001360 :return: The number of extensions.
1361 :rtype: :py:class:`int`
1362
1363 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001364 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001365 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001366
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001367 def add_extensions(self, extensions):
1368 """
1369 Add extensions to the certificate.
1370
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001371 :param extensions: The extensions to add.
1372 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001373 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001374 """
1375 for ext in extensions:
1376 if not isinstance(ext, X509Extension):
1377 raise ValueError("One of the elements is not an X509Extension")
1378
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001379 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001380 if not add_result:
1381 _raise_current_error()
1382
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001383 def get_extension(self, index):
1384 """
1385 Get a specific extension of the certificate by index.
1386
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001387 Extensions on a certificate are kept in order. The index
1388 parameter selects which extension will be returned.
1389
1390 :param int index: The index of the extension to retrieve.
1391 :return: The extension at the specified index.
1392 :rtype: :py:class:`X509Extension`
1393 :raises IndexError: If the extension index was out of bounds.
1394
1395 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001396 """
1397 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001398 ext._extension = _lib.X509_get_ext(self._x509, index)
1399 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001400 raise IndexError("extension index out of bounds")
1401
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001402 extension = _lib.X509_EXTENSION_dup(ext._extension)
1403 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001404 return ext
1405
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001406
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001407X509Type = X509
1408
1409
Dan Sully44e767a2016-06-04 18:05:27 -07001410class X509StoreFlags(object):
1411 """
1412 Flags for X509 verification, used to change the behavior of
1413 :class:`X509Store`.
1414
1415 See `OpenSSL Verification Flags`_ for details.
1416
1417 .. _OpenSSL Verification Flags:
Alex Chan54005ce2017-03-21 08:08:17 +00001418 https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html
Dan Sully44e767a2016-06-04 18:05:27 -07001419 """
1420 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1421 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1422 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1423 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1424 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1425 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1426 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1427 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1428 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1429 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1430 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1431
1432
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001434 """
Dan Sully44e767a2016-06-04 18:05:27 -07001435 An X.509 store.
1436
1437 An X.509 store is used to describe a context in which to verify a
1438 certificate. A description of a context may include a set of certificates
1439 to trust, a set of certificate revocation lists, verification flags and
1440 more.
1441
1442 An X.509 store, being only a description, cannot be used by itself to
1443 verify a certificate. To carry out the actual verification process, see
1444 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001445 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001446
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001447 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001448 store = _lib.X509_STORE_new()
1449 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001450
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001451 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001452 """
Dan Sully44e767a2016-06-04 18:05:27 -07001453 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001454
Dan Sully44e767a2016-06-04 18:05:27 -07001455 Adding a certificate with this method adds this certificate as a
1456 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001457
1458 :param X509 cert: The certificate to add to this store.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001459
Dan Sully44e767a2016-06-04 18:05:27 -07001460 :raises TypeError: If the certificate is not an :class:`X509`.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001461
1462 :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your
1463 certificate.
1464
Dan Sully44e767a2016-06-04 18:05:27 -07001465 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001466 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 if not isinstance(cert, X509):
1468 raise TypeError()
1469
Dan Sully44e767a2016-06-04 18:05:27 -07001470 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1471
1472 def add_crl(self, crl):
1473 """
1474 Add a certificate revocation list to this store.
1475
1476 The certificate revocation lists added to a store will only be used if
1477 the associated flags are configured to check certificate revocation
1478 lists.
1479
1480 .. versionadded:: 16.1.0
1481
1482 :param CRL crl: The certificate revocation list to add to this store.
1483 :return: ``None`` if the certificate revocation list was added
1484 successfully.
1485 """
1486 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1487
1488 def set_flags(self, flags):
1489 """
1490 Set verification flags to this store.
1491
1492 Verification flags can be combined by oring them together.
1493
1494 .. note::
1495
1496 Setting a verification flag sometimes requires clients to add
1497 additional information to the store, otherwise a suitable error will
1498 be raised.
1499
1500 For example, in setting flags to enable CRL checking a
1501 suitable CRL must be added to the store otherwise an error will be
1502 raised.
1503
1504 .. versionadded:: 16.1.0
1505
1506 :param int flags: The verification flags to set on this store.
1507 See :class:`X509StoreFlags` for available constants.
1508 :return: ``None`` if the verification flags were successfully set.
1509 """
1510 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001511
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001512 def set_time(self, vfy_time):
1513 """
1514 Set the time against which the certificates are verified.
1515
1516 Normally the current time is used.
1517
1518 .. note::
1519
1520 For example, you can determine if a certificate was valid at a given
1521 time.
1522
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001523 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001524
1525 :param datetime vfy_time: The verification time to set on this store.
1526 :return: ``None`` if the verification time was successfully set.
1527 """
1528 param = _lib.X509_VERIFY_PARAM_new()
1529 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1530
1531 _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s')))
1532 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1533
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001534
1535X509StoreType = X509Store
1536
1537
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001538class X509StoreContextError(Exception):
1539 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001540 An exception raised when an error occurred while verifying a certificate
1541 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001542
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001543 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001544 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001545 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001546
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001547 def __init__(self, message, certificate):
1548 super(X509StoreContextError, self).__init__(message)
1549 self.certificate = certificate
1550
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001551
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001552class X509StoreContext(object):
1553 """
1554 An X.509 store context.
1555
Dan Sully44e767a2016-06-04 18:05:27 -07001556 An X.509 store context is used to carry out the actual verification process
1557 of a certificate in a described context. For describing such a context, see
1558 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001559
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001560 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1561 instance. It is dynamically allocated and automatically garbage
1562 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001563 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001564 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001565 :param X509Store store: The certificates which will be trusted for the
1566 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001567 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001568 """
1569
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001570 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001571 store_ctx = _lib.X509_STORE_CTX_new()
1572 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1573 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001574 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001575 # Make the store context available for use after instantiating this
1576 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001577 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001578 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001579
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001580 def _init(self):
1581 """
1582 Set up the store context for a subsequent verification operation.
1583 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001584 ret = _lib.X509_STORE_CTX_init(
1585 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1586 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001587 if ret <= 0:
1588 _raise_current_error()
1589
1590 def _cleanup(self):
1591 """
1592 Internally cleans up the store context.
1593
Dan Sully44e767a2016-06-04 18:05:27 -07001594 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001595 """
1596 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1597
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001598 def _exception_from_context(self):
1599 """
1600 Convert an OpenSSL native context error failure into a Python
1601 exception.
1602
Alex Gaynor5945ea82015-09-05 14:59:06 -04001603 When a call to native OpenSSL X509_verify_cert fails, additional
1604 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001605 """
1606 errors = [
1607 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1608 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1609 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001610 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001611 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001612 # A context error should always be associated with a certificate, so we
1613 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001614 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001615 _cert = _lib.X509_dup(_x509)
1616 pycert = X509.__new__(X509)
1617 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001618 return X509StoreContextError(errors, pycert)
1619
Stephen Holsapple46a09252015-02-12 14:45:43 -08001620 def set_store(self, store):
1621 """
Dan Sully44e767a2016-06-04 18:05:27 -07001622 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001623
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001624 .. versionadded:: 0.15
1625
Dan Sully44e767a2016-06-04 18:05:27 -07001626 :param X509Store store: The store description which will be used for
1627 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001628 """
1629 self._store = store
1630
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001631 def verify_certificate(self):
1632 """
1633 Verify a certificate in a context.
1634
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001635 .. versionadded:: 0.15
1636
Alex Gaynorca87ff62015-09-04 23:31:03 -04001637 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001638 certificate in the context. Sets ``certificate`` attribute to
1639 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001640 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001641 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001642 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001643 self._init()
1644 ret = _lib.X509_verify_cert(self._store_ctx)
1645 self._cleanup()
1646 if ret <= 0:
1647 raise self._exception_from_context()
1648
1649
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001650def load_certificate(type, buffer):
1651 """
1652 Load a certificate from a buffer
1653
1654 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1655
Dan Sully44e767a2016-06-04 18:05:27 -07001656 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001657
1658 :return: The X509 object
1659 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001660 if isinstance(buffer, _text_type):
1661 buffer = buffer.encode("ascii")
1662
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001663 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001664
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001665 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001666 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001667 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001668 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001669 else:
1670 raise ValueError(
1671 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001672
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001673 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001674 _raise_current_error()
1675
1676 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001677 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001678 return cert
1679
1680
1681def dump_certificate(type, cert):
1682 """
1683 Dump a certificate to a buffer
1684
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001685 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1686 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001687 :param cert: The certificate to dump
1688 :return: The buffer with the dumped certificate in
1689 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001690 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001691
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001692 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001694 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001695 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001696 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001697 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001698 else:
1699 raise ValueError(
1700 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1701 "FILETYPE_TEXT")
1702
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001703 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001704 return _bio_to_string(bio)
1705
1706
Cory Benfield6492f7c2015-10-27 16:57:58 +09001707def dump_publickey(type, pkey):
1708 """
Cory Benfield11c10192015-10-27 17:23:03 +09001709 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001710
Cory Benfield9c590b92015-10-28 14:55:05 +09001711 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001712 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001713 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001714 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001715 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001716 """
1717 bio = _new_mem_buf()
1718 if type == FILETYPE_PEM:
1719 write_bio = _lib.PEM_write_bio_PUBKEY
1720 elif type == FILETYPE_ASN1:
1721 write_bio = _lib.i2d_PUBKEY_bio
1722 else:
1723 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1724
1725 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001726 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001727 _raise_current_error()
1728
1729 return _bio_to_string(bio)
1730
1731
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001732def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1733 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001734 Dump the private key *pkey* into a buffer string encoded with the type
1735 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1736 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001737
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001738 :param type: The file type (one of :const:`FILETYPE_PEM`,
1739 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1740 :param PKey pkey: The PKey to dump
1741 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001742 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001743 the passphrase to use, or a callback for providing the passphrase.
1744
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001745 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001746 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001747 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001748 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001749
1750 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001751 if passphrase is None:
1752 raise TypeError(
1753 "if a value is given for cipher "
1754 "one must also be given for passphrase")
1755 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001756 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001757 raise ValueError("Invalid cipher name")
1758 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001759 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001760
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001761 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001762 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001763 result_code = _lib.PEM_write_bio_PrivateKey(
1764 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001765 helper.callback, helper.callback_args)
1766 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001767 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001768 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001769 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001770 rsa = _ffi.gc(
1771 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1772 _lib.RSA_free
1773 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001774 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001775 else:
1776 raise ValueError(
1777 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1778 "FILETYPE_TEXT")
1779
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001780 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001781
1782 return _bio_to_string(bio)
1783
1784
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001785class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001786 """
1787 A certificate revocation.
1788 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001789 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1790 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1791 # OCSP_crl_reason_str. We use the latter, just like the command line
1792 # program.
1793 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001794 b"unspecified",
1795 b"keyCompromise",
1796 b"CACompromise",
1797 b"affiliationChanged",
1798 b"superseded",
1799 b"cessationOfOperation",
1800 b"certificateHold",
1801 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001802 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001803
1804 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001805 revoked = _lib.X509_REVOKED_new()
1806 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001807
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001808 def set_serial(self, hex_str):
1809 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001810 Set the serial number.
1811
1812 The serial number is formatted as a hexadecimal number encoded in
1813 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001814
Dan Sully44e767a2016-06-04 18:05:27 -07001815 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001816
Dan Sully44e767a2016-06-04 18:05:27 -07001817 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001818 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001819 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1820 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001821 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001822 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001823 if not bn_result:
1824 raise ValueError("bad hex string")
1825
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001826 asn1_serial = _ffi.gc(
1827 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1828 _lib.ASN1_INTEGER_free)
1829 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001830
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001831 def get_serial(self):
1832 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001833 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001834
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001835 The serial number is formatted as a hexadecimal number encoded in
1836 ASCII.
1837
1838 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001839 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001840 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001841 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001842
Alex Gaynor67903a62016-06-02 10:37:13 -07001843 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1844 _openssl_assert(asn1_int != _ffi.NULL)
1845 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1846 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 return _bio_to_string(bio)
1848
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001849 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001850 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1851 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001852 obj = _lib.X509_EXTENSION_get_object(ext)
1853 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001855 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001856 break
1857
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001858 def set_reason(self, reason):
1859 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001860 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001861
Dan Sully44e767a2016-06-04 18:05:27 -07001862 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001863
1864 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001865 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001866
Dan Sully44e767a2016-06-04 18:05:27 -07001867 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001868
1869 .. seealso::
1870
Dan Sully44e767a2016-06-04 18:05:27 -07001871 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001872 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001873 """
1874 if reason is None:
1875 self._delete_reason()
1876 elif not isinstance(reason, bytes):
1877 raise TypeError("reason must be None or a byte string")
1878 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001879 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001880 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1881
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001882 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001883 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001884 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001885
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001886 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001887 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001888
1889 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001890 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1891 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001892 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001893
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001894 def get_reason(self):
1895 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001896 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001897
Dan Sully44e767a2016-06-04 18:05:27 -07001898 :return: The reason, or ``None`` if there is none.
1899 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001900
1901 .. seealso::
1902
Dan Sully44e767a2016-06-04 18:05:27 -07001903 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001904 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001905 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001906 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1907 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001908 obj = _lib.X509_EXTENSION_get_object(ext)
1909 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001910 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001911
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001912 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001913 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001914 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001915 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001916 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001917 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001918
1919 return _bio_to_string(bio)
1920
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001921 def all_reasons(self):
1922 """
1923 Return a list of all the supported reason strings.
1924
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001925 This list is a copy; modifying it does not change the supported reason
1926 strings.
1927
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001928 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001929 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001930 """
1931 return self._crl_reasons[:]
1932
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001933 def set_rev_date(self, when):
1934 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001935 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001936
Dan Sully44e767a2016-06-04 18:05:27 -07001937 :param bytes when: The timestamp of the revocation,
Paul Kehrerce98ee62017-06-21 06:59:58 -10001938 as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001939 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001940 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001941 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1942 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001943
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001944 def get_rev_date(self):
1945 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001946 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001947
Paul Kehrerce98ee62017-06-21 06:59:58 -10001948 :return: The timestamp of the revocation, as ASN.1 TIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001949 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001950 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001951 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1952 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001953
1954
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001955class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001956 """
1957 A certificate revocation list.
1958 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001959
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001960 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001961 crl = _lib.X509_CRL_new()
1962 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001963
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001964 def get_revoked(self):
1965 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001966 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001967
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001968 These revocations will be provided by value, not by reference.
1969 That means it's okay to mutate them: it won't affect this CRL.
1970
1971 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001972 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001973 """
1974 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001975 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001976 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1977 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001978 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001979 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001980 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001981 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001982 if results:
1983 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001984
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001985 def add_revoked(self, revoked):
1986 """
1987 Add a revoked (by value not reference) to the CRL structure
1988
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001989 This revocation will be added by value, not by reference. That
1990 means it's okay to mutate it after adding: it won't affect
1991 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001992
Dan Sully44e767a2016-06-04 18:05:27 -07001993 :param Revoked revoked: The new revocation.
1994 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001995 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001996 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001997 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001998
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001999 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002000 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002001
Dan Sully44e767a2016-06-04 18:05:27 -07002002 def get_issuer(self):
2003 """
2004 Get the CRL's issuer.
2005
2006 .. versionadded:: 16.1.0
2007
2008 :rtype: X509Name
2009 """
2010 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2011 _openssl_assert(_issuer != _ffi.NULL)
2012 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2013 issuer = X509Name.__new__(X509Name)
2014 issuer._name = _issuer
2015 return issuer
2016
2017 def set_version(self, version):
2018 """
2019 Set the CRL version.
2020
2021 .. versionadded:: 16.1.0
2022
2023 :param int version: The version of the CRL.
2024 :return: ``None``
2025 """
2026 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2027
2028 def _set_boundary_time(self, which, when):
2029 return _set_asn1_time(which(self._crl), when)
2030
2031 def set_lastUpdate(self, when):
2032 """
2033 Set when the CRL was last updated.
2034
Paul Kehrerce98ee62017-06-21 06:59:58 -10002035 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002036
2037 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002038
2039 .. versionadded:: 16.1.0
2040
2041 :param bytes when: A timestamp string.
2042 :return: ``None``
2043 """
2044 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2045
2046 def set_nextUpdate(self, when):
2047 """
2048 Set when the CRL will next be udpated.
2049
Paul Kehrerce98ee62017-06-21 06:59:58 -10002050 The timestamp is formatted as an ASN.1 TIME::
Dan Sully44e767a2016-06-04 18:05:27 -07002051
2052 YYYYMMDDhhmmssZ
Dan Sully44e767a2016-06-04 18:05:27 -07002053
2054 .. versionadded:: 16.1.0
2055
2056 :param bytes when: A timestamp string.
2057 :return: ``None``
2058 """
2059 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2060
2061 def sign(self, issuer_cert, issuer_key, digest):
2062 """
2063 Sign the CRL.
2064
2065 Signing a CRL enables clients to associate the CRL itself with an
2066 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2067 be signed by an issuer.
2068
2069 This method implicitly sets the issuer's name based on the issuer
2070 certificate and private key used to sign the CRL.
2071
2072 .. versionadded:: 16.1.0
2073
2074 :param X509 issuer_cert: The issuer's certificate.
2075 :param PKey issuer_key: The issuer's private key.
2076 :param bytes digest: The digest method to sign the CRL with.
2077 """
2078 digest_obj = _lib.EVP_get_digestbyname(digest)
2079 _openssl_assert(digest_obj != _ffi.NULL)
2080 _lib.X509_CRL_set_issuer_name(
2081 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2082 _lib.X509_CRL_sort(self._crl)
2083 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2084 _openssl_assert(result != 0)
2085
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002086 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002087 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002088 """
Dan Sully44e767a2016-06-04 18:05:27 -07002089 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002090
Dan Sully44e767a2016-06-04 18:05:27 -07002091 :param X509 cert: The certificate used to sign the CRL.
2092 :param PKey key: The key used to sign the CRL.
2093 :param int type: The export format, either :data:`FILETYPE_PEM`,
2094 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002095 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002096 :param bytes digest: The name of the message digest to use (eg
Alex Gaynor239e2d32016-09-11 12:36:35 -04002097 ``b"sha2566"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002098 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002099 """
Dan Sully44e767a2016-06-04 18:05:27 -07002100
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002101 if not isinstance(cert, X509):
2102 raise TypeError("cert must be an X509 instance")
2103 if not isinstance(key, PKey):
2104 raise TypeError("key must be a PKey instance")
2105 if not isinstance(type, int):
2106 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002107
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002108 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002109 _warn(
2110 "The default message digest (md5) is deprecated. "
2111 "Pass the name of a message digest explicitly.",
2112 category=DeprecationWarning,
2113 stacklevel=2,
2114 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002115 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002116
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002117 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002118 if digest_obj == _ffi.NULL:
2119 raise ValueError("No such digest method")
2120
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002121 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002122 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002123
Alex Gaynora738ed52015-09-05 11:17:10 -04002124 # A scratch time object to give different values to different CRL
2125 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002126 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002127 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002129 _lib.X509_gmtime_adj(sometime, 0)
2130 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002131
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002132 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2133 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002134
Alex Gaynor5945ea82015-09-05 14:59:06 -04002135 _lib.X509_CRL_set_issuer_name(
2136 self._crl, _lib.X509_get_subject_name(cert._x509)
2137 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002138
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002139 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002140 if not sign_result:
2141 _raise_current_error()
2142
Dominic Chenf05b2122015-10-13 16:32:35 +00002143 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002144
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002145
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002146CRLType = CRL
2147
2148
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002149class PKCS7(object):
2150 def type_is_signed(self):
2151 """
2152 Check if this NID_pkcs7_signed object
2153
2154 :return: True if the PKCS7 is of type signed
2155 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002156 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002157
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002158 def type_is_enveloped(self):
2159 """
2160 Check if this NID_pkcs7_enveloped object
2161
2162 :returns: True if the PKCS7 is of type enveloped
2163 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002164 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002165
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002166 def type_is_signedAndEnveloped(self):
2167 """
2168 Check if this NID_pkcs7_signedAndEnveloped object
2169
2170 :returns: True if the PKCS7 is of type signedAndEnveloped
2171 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002172 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002173
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002174 def type_is_data(self):
2175 """
2176 Check if this NID_pkcs7_data object
2177
2178 :return: True if the PKCS7 is of type data
2179 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002180 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002181
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002182 def get_type_name(self):
2183 """
2184 Returns the type name of the PKCS7 structure
2185
2186 :return: A string with the typename
2187 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002188 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2189 string_type = _lib.OBJ_nid2sn(nid)
2190 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002191
Alex Chanc6077062016-11-18 13:53:39 +00002192
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002193PKCS7Type = PKCS7
2194
2195
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002196class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002197 """
2198 A PKCS #12 archive.
2199 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002200
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002201 def __init__(self):
2202 self._pkey = None
2203 self._cert = None
2204 self._cacerts = None
2205 self._friendlyname = None
2206
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002207 def get_certificate(self):
2208 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002209 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002210
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002211 :return: The certificate, or :py:const:`None` if there is none.
2212 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002213 """
2214 return self._cert
2215
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002216 def set_certificate(self, cert):
2217 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002218 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002219
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002220 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002221 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002222
Dan Sully44e767a2016-06-04 18:05:27 -07002223 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002224 """
2225 if not isinstance(cert, X509):
2226 raise TypeError("cert must be an X509 instance")
2227 self._cert = cert
2228
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002229 def get_privatekey(self):
2230 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002231 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002232
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002233 :return: The private key, or :py:const:`None` if there is none.
2234 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002235 """
2236 return self._pkey
2237
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002238 def set_privatekey(self, pkey):
2239 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002240 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002241
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002242 :param pkey: The new private key, or :py:const:`None` to unset it.
2243 :type pkey: :py:class:`PKey` or :py:const:`None`
2244
Dan Sully44e767a2016-06-04 18:05:27 -07002245 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002246 """
2247 if not isinstance(pkey, PKey):
2248 raise TypeError("pkey must be a PKey instance")
2249 self._pkey = pkey
2250
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002251 def get_ca_certificates(self):
2252 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002253 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002254
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002255 :return: A tuple with the CA certificates in the chain, or
2256 :py:const:`None` if there are none.
2257 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002258 """
2259 if self._cacerts is not None:
2260 return tuple(self._cacerts)
2261
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002262 def set_ca_certificates(self, cacerts):
2263 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002264 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002265
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002266 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2267 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002268 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002269
Dan Sully44e767a2016-06-04 18:05:27 -07002270 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002271 """
2272 if cacerts is None:
2273 self._cacerts = None
2274 else:
2275 cacerts = list(cacerts)
2276 for cert in cacerts:
2277 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002278 raise TypeError(
2279 "iterable must only contain X509 instances"
2280 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002281 self._cacerts = cacerts
2282
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002283 def set_friendlyname(self, name):
2284 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002285 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002286
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002287 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002288 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002289
Dan Sully44e767a2016-06-04 18:05:27 -07002290 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002291 """
2292 if name is None:
2293 self._friendlyname = None
2294 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002295 raise TypeError(
2296 "name must be a byte string or None (not %r)" % (name,)
2297 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002298 self._friendlyname = name
2299
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002300 def get_friendlyname(self):
2301 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002302 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002303
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002304 :returns: The friendly name, or :py:const:`None` if there is none.
2305 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002306 """
2307 return self._friendlyname
2308
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002309 def export(self, passphrase=None, iter=2048, maciter=1):
2310 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002311 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002312
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002313 For more information, see the :c:func:`PKCS12_create` man page.
2314
2315 :param passphrase: The passphrase used to encrypt the structure. Unlike
2316 some other passphrase arguments, this *must* be a string, not a
2317 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002318 :type passphrase: :py:data:`bytes`
2319
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002320 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002321 :type iter: :py:data:`int`
2322
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002323 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002324 :type maciter: :py:data:`int`
2325
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002326 :return: The string representation of the PKCS #12 structure.
2327 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002328 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002329 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002330
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002331 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002332 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002333 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002334 cacerts = _lib.sk_X509_new_null()
2335 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002336 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002337 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002338
2339 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002340 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002341
2342 friendlyname = self._friendlyname
2343 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002344 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002345
2346 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002347 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002348 else:
2349 pkey = self._pkey._pkey
2350
2351 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002352 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002353 else:
2354 cert = self._cert._x509
2355
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002356 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002357 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002358 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2359 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002360 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002361 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002362 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002363 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002364
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002365 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002366 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002367 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002368
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002369
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002370PKCS12Type = PKCS12
2371
2372
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002373class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002374 """
2375 A Netscape SPKI object.
2376 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002377
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002378 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002379 spki = _lib.NETSCAPE_SPKI_new()
2380 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002381
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002382 def sign(self, pkey, digest):
2383 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002384 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002385
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002386 :param pkey: The private key to sign with.
2387 :type pkey: :py:class:`PKey`
2388
2389 :param digest: The message digest to use.
2390 :type digest: :py:class:`bytes`
2391
Dan Sully44e767a2016-06-04 18:05:27 -07002392 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002393 """
2394 if pkey._only_public:
2395 raise ValueError("Key has only public part")
2396
2397 if not pkey._initialized:
2398 raise ValueError("Key is uninitialized")
2399
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002400 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002401 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002402 raise ValueError("No such digest method")
2403
Alex Gaynor5945ea82015-09-05 14:59:06 -04002404 sign_result = _lib.NETSCAPE_SPKI_sign(
2405 self._spki, pkey._pkey, digest_obj
2406 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002407 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002408
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002409 def verify(self, key):
2410 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002411 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002412
Hynek Schlawack01c31672016-12-11 15:14:09 +01002413 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002414
Hynek Schlawack01c31672016-12-11 15:14:09 +01002415 :return: ``True`` if the signature is correct.
2416 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002417
Hynek Schlawack01c31672016-12-11 15:14:09 +01002418 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2419 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002420 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002421 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002422 if answer <= 0:
2423 _raise_current_error()
2424 return True
2425
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002426 def b64_encode(self):
2427 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002428 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002429
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002430 :return: The base64 encoded string.
2431 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002432 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002433 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2434 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002435 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002436 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002437
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002438 def get_pubkey(self):
2439 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002440 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002441
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002442 :return: The public key.
2443 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002444 """
2445 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002446 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002447 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002448 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002449 pkey._only_public = True
2450 return pkey
2451
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002452 def set_pubkey(self, pkey):
2453 """
2454 Set the public key of the certificate
2455
2456 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002457 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002458 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002459 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002460 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002461
2462
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002463NetscapeSPKIType = NetscapeSPKI
2464
2465
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002466class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002467 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002468 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002469 raise ValueError(
2470 "only FILETYPE_PEM key format supports encryption"
2471 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002472 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002473 self._more_args = more_args
2474 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002475 self._problems = []
2476
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002477 @property
2478 def callback(self):
2479 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002480 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002481 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002482 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002483 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002484 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002485 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002486 raise TypeError(
2487 "Last argument must be a byte string or a callable."
2488 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002489
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002490 @property
2491 def callback_args(self):
2492 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002493 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002494 elif isinstance(self._passphrase, bytes):
2495 return self._passphrase
2496 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002497 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002498 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002499 raise TypeError(
2500 "Last argument must be a byte string or a callable."
2501 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002502
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002503 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002504 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002505
2506 # Flush the OpenSSL error queue
2507 try:
2508 _exception_from_error_queue(exceptionType)
2509 except exceptionType:
2510 pass
2511
2512 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002513
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002514 def _read_passphrase(self, buf, size, rwflag, userdata):
2515 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002516 if self._more_args:
2517 result = self._passphrase(size, rwflag, userdata)
2518 else:
2519 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002520 if not isinstance(result, bytes):
2521 raise ValueError("String expected")
2522 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002523 if self._truncate:
2524 result = result[:size]
2525 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002526 raise ValueError(
2527 "passphrase returned by callback is too long"
2528 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002529 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002530 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002531 return len(result)
2532 except Exception as e:
2533 self._problems.append(e)
2534 return 0
2535
2536
Cory Benfield6492f7c2015-10-27 16:57:58 +09002537def load_publickey(type, buffer):
2538 """
Cory Benfield11c10192015-10-27 17:23:03 +09002539 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002540
Cory Benfield9c590b92015-10-28 14:55:05 +09002541 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002542 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002543 :param buffer: The buffer the key is stored in.
2544 :type buffer: A Python string object, either unicode or bytestring.
2545 :return: The PKey object.
2546 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002547 """
2548 if isinstance(buffer, _text_type):
2549 buffer = buffer.encode("ascii")
2550
2551 bio = _new_mem_buf(buffer)
2552
2553 if type == FILETYPE_PEM:
2554 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2555 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2556 elif type == FILETYPE_ASN1:
2557 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2558 else:
2559 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2560
2561 if evp_pkey == _ffi.NULL:
2562 _raise_current_error()
2563
2564 pkey = PKey.__new__(PKey)
2565 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002566 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002567 return pkey
2568
2569
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002570def load_privatekey(type, buffer, passphrase=None):
2571 """
2572 Load a private key from a buffer
2573
2574 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2575 :param buffer: The buffer the key is stored in
2576 :param passphrase: (optional) if encrypted PEM format, this can be
2577 either the passphrase to use, or a callback for
2578 providing the passphrase.
2579
2580 :return: The PKey object
2581 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002582 if isinstance(buffer, _text_type):
2583 buffer = buffer.encode("ascii")
2584
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002585 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002586
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002587 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002588 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002589 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2590 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002591 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002592 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002593 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002594 else:
2595 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2596
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002597 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002598 _raise_current_error()
2599
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002600 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002601 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002602 return pkey
2603
2604
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002605def dump_certificate_request(type, req):
2606 """
2607 Dump a certificate request to a buffer
2608
2609 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2610 :param req: The certificate request to dump
2611 :return: The buffer with the dumped certificate request in
2612 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002613 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002614
2615 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002616 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002617 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002618 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002619 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002620 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002621 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002622 raise ValueError(
2623 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2624 "FILETYPE_TEXT"
2625 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002626
Alex Gaynor09a386e2016-07-03 09:32:44 -04002627 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002628
2629 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002630
2631
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002632def load_certificate_request(type, buffer):
2633 """
2634 Load a certificate request from a buffer
2635
2636 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2637 :param buffer: The buffer the certificate request is stored in
2638 :return: The X509Req object
2639 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002640 if isinstance(buffer, _text_type):
2641 buffer = buffer.encode("ascii")
2642
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002643 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002644
2645 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002646 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002647 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002648 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002649 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002650 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002651
Alex Gaynoradd5b072016-06-04 21:04:00 -07002652 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002653
2654 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002655 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002656 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002657
2658
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002659def sign(pkey, data, digest):
2660 """
2661 Sign data with a digest
2662
2663 :param pkey: Pkey to sign with
2664 :param data: data to be signed
2665 :param digest: message digest to use
2666 :return: signature
2667 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002668 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002669
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002670 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002671 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002672 raise ValueError("No such digest method")
2673
Alex Gaynor67903a62016-06-02 10:37:13 -07002674 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002675 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002676
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002677 _lib.EVP_SignInit(md_ctx, digest_obj)
2678 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002679
Colleen Murphye09399b2016-03-01 17:40:49 -08002680 pkey_length = (PKey.bits(pkey) + 7) // 8
2681 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002682 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002683 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002684 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002685 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002686
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002687 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002688
2689
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002690def verify(cert, signature, data, digest):
2691 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002692 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002693
2694 :param cert: signing certificate (X509 object)
2695 :param signature: signature returned by sign function
2696 :param data: data to be verified
2697 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002698 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002699 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002700 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002701
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002702 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002703 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002704 raise ValueError("No such digest method")
2705
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002706 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002707 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002708 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002709
Alex Gaynor67903a62016-06-02 10:37:13 -07002710 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002711 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002712
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002713 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2714 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002715 verify_result = _lib.EVP_VerifyFinal(
2716 md_ctx, signature, len(signature), pkey
2717 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002718
2719 if verify_result != 1:
2720 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002721
2722
Dominic Chenf05b2122015-10-13 16:32:35 +00002723def dump_crl(type, crl):
2724 """
2725 Dump a certificate revocation list to a buffer.
2726
2727 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2728 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002729 :param CRL crl: The CRL to dump.
2730
Dominic Chenf05b2122015-10-13 16:32:35 +00002731 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002732 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002733 """
2734 bio = _new_mem_buf()
2735
2736 if type == FILETYPE_PEM:
2737 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2738 elif type == FILETYPE_ASN1:
2739 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2740 elif type == FILETYPE_TEXT:
2741 ret = _lib.X509_CRL_print(bio, crl._crl)
2742 else:
2743 raise ValueError(
2744 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2745 "FILETYPE_TEXT")
2746
2747 assert ret == 1
2748 return _bio_to_string(bio)
2749
2750
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002751def load_crl(type, buffer):
2752 """
2753 Load a certificate revocation list from a buffer
2754
2755 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2756 :param buffer: The buffer the CRL is stored in
2757
2758 :return: The PKey object
2759 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002760 if isinstance(buffer, _text_type):
2761 buffer = buffer.encode("ascii")
2762
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002763 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002764
2765 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002766 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002767 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002768 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002769 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002770 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2771
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002772 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002773 _raise_current_error()
2774
2775 result = CRL.__new__(CRL)
2776 result._crl = crl
2777 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002778
2779
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002780def load_pkcs7_data(type, buffer):
2781 """
2782 Load pkcs7 data from a buffer
2783
2784 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2785 :param buffer: The buffer with the pkcs7 data.
2786 :return: The PKCS7 object
2787 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002788 if isinstance(buffer, _text_type):
2789 buffer = buffer.encode("ascii")
2790
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002791 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002792
2793 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002794 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002795 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002796 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002797 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002798 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2799
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002800 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002801 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002802
2803 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002804 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002805 return pypkcs7
2806
2807
Stephen Holsapple38482622014-04-05 20:29:34 -07002808def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002809 """
2810 Load a PKCS12 object from a buffer
2811
2812 :param buffer: The buffer the certificate is stored in
2813 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2814 :returns: The PKCS12 object
2815 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002816 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002817
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002818 if isinstance(buffer, _text_type):
2819 buffer = buffer.encode("ascii")
2820
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002821 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002822
Stephen Holsapple38482622014-04-05 20:29:34 -07002823 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2824 # password based encryption no password and a zero length password are two
2825 # different things, but OpenSSL implementation will try both to figure out
2826 # which one works.
2827 if not passphrase:
2828 passphrase = _ffi.NULL
2829
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002830 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2831 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002832 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002833 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002834
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002835 pkey = _ffi.new("EVP_PKEY**")
2836 cert = _ffi.new("X509**")
2837 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002838
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002839 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002840 if not parse_result:
2841 _raise_current_error()
2842
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002843 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002844
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002845 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2846 # queue for no particular reason. This error isn't interesting to anyone
2847 # outside this function. It's not even interesting to us. Get rid of it.
2848 try:
2849 _raise_current_error()
2850 except Error:
2851 pass
2852
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002853 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002854 pykey = None
2855 else:
2856 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002857 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002858
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002859 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002860 pycert = None
2861 friendlyname = None
2862 else:
2863 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002864 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002865
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002866 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002867 friendlyname_buffer = _lib.X509_alias_get0(
2868 cert[0], friendlyname_length
2869 )
2870 friendlyname = _ffi.buffer(
2871 friendlyname_buffer, friendlyname_length[0]
2872 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002873 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002874 friendlyname = None
2875
2876 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002877 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002878 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002879 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002880 pycacerts.append(pycacert)
2881 if not pycacerts:
2882 pycacerts = None
2883
2884 pkcs12 = PKCS12.__new__(PKCS12)
2885 pkcs12._pkey = pykey
2886 pkcs12._cert = pycert
2887 pkcs12._cacerts = pycacerts
2888 pkcs12._friendlyname = friendlyname
2889 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002890
2891
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002892# There are no direct unit tests for this initialization. It is tested
2893# indirectly since it is necessary for functions like dump_privatekey when
2894# using encryption.
2895#
2896# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2897# and some other similar tests may fail without this (though they may not if
2898# the Python runtime has already done some initialization of the underlying
2899# OpenSSL library (and is linked against the same one that cryptography is
2900# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002901_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002902
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002903# This is similar but exercised mainly by exception_from_error_queue. It calls
2904# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2905_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002906
2907
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002908# Set the default string mask to match OpenSSL upstream (since 2005) and
2909# RFC5280 recommendations.
2910_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')