blob: 98a7c7883c4adbd6ce5543e3e6c222b72a4044bc [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
106 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
107 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
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500119 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
120 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800121 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500122 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
123 _lib.ASN1_STRING_set(dummy, when, len(when))
124 check_result = _lib.ASN1_GENERALIZEDTIME_check(
125 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800126 if not check_result:
127 raise ValueError("Invalid string")
128 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500129 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800130
Alex Gaynor510293e2016-06-02 12:07:59 -0700131
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800132def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500133 """
134 Retrieve the time value of an ASN1 time object.
135
136 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
137 that type) from which the time value will be retrieved.
138
139 @return: The time value from C{timestamp} as a L{bytes} string in a certain
140 format. Or C{None} if the object contains no time value.
141 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500142 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
143 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800144 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400145 elif (
146 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
147 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500148 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800149 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500150 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
151 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
152 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500153 # This may happen:
154 # - if timestamp was not an ASN1_TIME
155 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
156 # - if a copy of the time data from timestamp cannot be made for
157 # the newly allocated ASN1_GENERALIZEDTIME
158 #
159 # These are difficult to test. cffi enforces the ASN1_TIME type.
160 # Memory allocation failures are a pain to trigger
161 # deterministically.
162 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800163 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500164 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800165 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500166 string_data = _lib.ASN1_STRING_data(string_timestamp)
167 string_result = _ffi.string(string_data)
168 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800169 return string_result
170
171
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800172class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200173 """
174 A class representing an DSA or RSA public key or key pair.
175 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800176 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800177 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800178
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800179 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500180 pkey = _lib.EVP_PKEY_new()
181 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800182 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800183
Paul Kehrer72d968b2016-07-29 15:31:04 +0800184 def to_cryptography_key(self):
185 """
186 Export as a ``cryptography`` key.
187
188 :rtype: One of ``cryptography``'s `key interfaces`_.
189
190 .. _key interfaces: https://cryptography.io/en/latest/hazmat/\
191 primitives/asymmetric/rsa/#key-interfaces
192
193 .. versionadded:: 16.1.0
194 """
Paul Kehrereb633842016-10-06 11:22:01 +0200195 backend = _get_backend()
Paul Kehrer72d968b2016-07-29 15:31:04 +0800196 if self._only_public:
197 return backend._evp_pkey_to_public_key(self._pkey)
198 else:
199 return backend._evp_pkey_to_private_key(self._pkey)
200
201 @classmethod
202 def from_cryptography_key(cls, crypto_key):
203 """
204 Construct based on a ``cryptography`` *crypto_key*.
205
206 :param crypto_key: A ``cryptography`` key.
207 :type crypto_key: One of ``cryptography``'s `key interfaces`_.
208
209 :rtype: PKey
210
211 .. versionadded:: 16.1.0
212 """
213 pkey = cls()
214 if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
215 dsa.DSAPublicKey, dsa.DSAPrivateKey)):
216 raise TypeError("Unsupported key type")
217
218 pkey._pkey = crypto_key._evp_pkey
219 if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
220 pkey._only_public = True
221 pkey._initialized = True
222 return pkey
223
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800224 def generate_key(self, type, bits):
225 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700226 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800227
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200228 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800229
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200230 :param type: The key type.
231 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
232 :param bits: The number of bits.
233 :type bits: :py:data:`int` ``>= 0``
234 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
235 of the appropriate type.
236 :raises ValueError: If the number of bits isn't an integer of
237 the appropriate size.
Dan Sully44e767a2016-06-04 18:05:27 -0700238 :return: ``None``
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800239 """
240 if not isinstance(type, int):
241 raise TypeError("type must be an integer")
242
243 if not isinstance(bits, int):
244 raise TypeError("bits must be an integer")
245
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800246 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500247 exponent = _lib.BN_new()
248 exponent = _ffi.gc(exponent, _lib.BN_free)
249 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800250
251 if type == TYPE_RSA:
252 if bits <= 0:
253 raise ValueError("Invalid number of bits")
254
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500255 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800256
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500257 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400258 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800259
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500260 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400261 _openssl_assert(result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800262
263 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400264 dsa = _lib.DSA_new()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700265 _openssl_assert(dsa != _ffi.NULL)
Paul Kehrerafa5a662016-03-10 10:29:28 -0400266
267 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400268 res = _lib.DSA_generate_parameters_ex(
269 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
270 )
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700271 _openssl_assert(res == 1)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400272
273 _openssl_assert(_lib.DSA_generate_key(dsa) == 1)
274 _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800275 else:
276 raise Error("No such key type")
277
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800278 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800279
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800280 def check(self):
281 """
282 Check the consistency of an RSA private key.
283
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200284 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
285
Hynek Schlawack01c31672016-12-11 15:14:09 +0100286 :return: ``True`` if key is consistent.
287
288 :raise OpenSSL.crypto.Error: if the key is inconsistent.
289
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800290 :raise TypeError: if the key is of a type which cannot be checked.
291 Only RSA keys can currently be checked.
292 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800293 if self._only_public:
294 raise TypeError("public key only")
295
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100296 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800297 raise TypeError("key type unsupported")
298
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500299 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
300 rsa = _ffi.gc(rsa, _lib.RSA_free)
301 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800302 if result:
303 return True
304 _raise_current_error()
305
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800306 def type(self):
307 """
308 Returns the type of the key
309
310 :return: The type of the key.
311 """
Alex Gaynorc84567b2016-03-16 07:45:09 -0400312 return _lib.Cryptography_EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800313
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800314 def bits(self):
315 """
316 Returns the number of bits of the key
317
318 :return: The number of bits of the key.
319 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500320 return _lib.EVP_PKEY_bits(self._pkey)
Alex Chanc6077062016-11-18 13:53:39 +0000321
322
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800323PKeyType = PKey
324
325
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400326class _EllipticCurve(object):
327 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400328 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400329
330 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
331 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
332 instances each of which represents one curve supported by the system.
333 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400334 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400335 _curves = None
336
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400337 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400338 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400339 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400340 """
341 Implement cooperation with the right-hand side argument of ``!=``.
342
343 Python 3 seems to have dropped this cooperation in this very narrow
344 circumstance.
345 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400346 if isinstance(other, _EllipticCurve):
347 return super(_EllipticCurve, self).__ne__(other)
348 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400349
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400350 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400351 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400352 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400353 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400354
355 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400356
357 :return: A :py:type:`set` of ``cls`` instances giving the names of the
358 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400359 """
Alex Chan84902a22017-04-20 11:50:47 +0100360 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
361 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
362 # The return value on this call should be num_curves again. We
363 # could check it to make sure but if it *isn't* then.. what could
364 # we do? Abort the whole process, I suppose...? -exarkun
365 lib.EC_get_builtin_curves(builtin_curves, num_curves)
366 return set(
367 cls.from_nid(lib, c.nid)
368 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400369
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400370 @classmethod
371 def _get_elliptic_curves(cls, lib):
372 """
373 Get, cache, and return the curves supported by OpenSSL.
374
375 :param lib: The OpenSSL library binding object.
376
377 :return: A :py:type:`set` of ``cls`` instances giving the names of the
378 elliptic curves the underlying library supports.
379 """
380 if cls._curves is None:
381 cls._curves = cls._load_elliptic_curves(lib)
382 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400383
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400384 @classmethod
385 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400386 """
387 Instantiate a new :py:class:`_EllipticCurve` associated with the given
388 OpenSSL NID.
389
390 :param lib: The OpenSSL library binding object.
391
392 :param nid: The OpenSSL NID the resulting curve object will represent.
393 This must be a curve NID (and not, for example, a hash NID) or
394 subsequent operations will fail in unpredictable ways.
395 :type nid: :py:class:`int`
396
397 :return: The curve object.
398 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400399 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
400
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400401 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400402 """
403 :param _lib: The :py:mod:`cryptography` binding instance used to
404 interface with OpenSSL.
405
406 :param _nid: The OpenSSL NID identifying the curve this object
407 represents.
408 :type _nid: :py:class:`int`
409
410 :param name: The OpenSSL short name identifying the curve this object
411 represents.
412 :type name: :py:class:`unicode`
413 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400414 self._lib = lib
415 self._nid = nid
416 self.name = name
417
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400418 def __repr__(self):
419 return "<Curve %r>" % (self.name,)
420
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400421 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400422 """
423 Create a new OpenSSL EC_KEY structure initialized to use this curve.
424
425 The structure is automatically garbage collected when the Python object
426 is garbage collected.
427 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400428 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
429 return _ffi.gc(key, _lib.EC_KEY_free)
430
431
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400432def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400433 """
434 Return a set of objects representing the elliptic curves supported in the
435 OpenSSL build in use.
436
437 The curve objects have a :py:class:`unicode` ``name`` attribute by which
438 they identify themselves.
439
440 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400441 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
442 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400443 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400444 return _EllipticCurve._get_elliptic_curves(_lib)
445
446
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400447def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400448 """
449 Return a single curve object selected by name.
450
451 See :py:func:`get_elliptic_curves` for information about curve objects.
452
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400453 :param name: The OpenSSL short name identifying the curve object to
454 retrieve.
455 :type name: :py:class:`unicode`
456
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400457 If the named curve is not supported then :py:class:`ValueError` is raised.
458 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400459 for curve in get_elliptic_curves():
460 if curve.name == name:
461 return curve
462 raise ValueError("unknown curve name", name)
463
464
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800465class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200466 """
467 An X.509 Distinguished Name.
468
469 :ivar countryName: The country of the entity.
470 :ivar C: Alias for :py:attr:`countryName`.
471
472 :ivar stateOrProvinceName: The state or province of the entity.
473 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
474
475 :ivar localityName: The locality of the entity.
476 :ivar L: Alias for :py:attr:`localityName`.
477
478 :ivar organizationName: The organization name of the entity.
479 :ivar O: Alias for :py:attr:`organizationName`.
480
481 :ivar organizationalUnitName: The organizational unit of the entity.
482 :ivar OU: Alias for :py:attr:`organizationalUnitName`
483
484 :ivar commonName: The common name of the entity.
485 :ivar CN: Alias for :py:attr:`commonName`.
486
487 :ivar emailAddress: The e-mail address of the entity.
488 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400489
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800490 def __init__(self, name):
491 """
492 Create a new X509Name, copying the given X509Name instance.
493
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200494 :param name: The name to copy.
495 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800496 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500497 name = _lib.X509_NAME_dup(name._name)
498 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800499
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800500 def __setattr__(self, name, value):
501 if name.startswith('_'):
502 return super(X509Name, self).__setattr__(name, value)
503
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800504 # Note: we really do not want str subclasses here, so we do not use
505 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800506 if type(name) is not str:
507 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400508 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800509
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500510 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500511 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800512 try:
513 _raise_current_error()
514 except Error:
515 pass
516 raise AttributeError("No such attribute")
517
518 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500519 for i in range(_lib.X509_NAME_entry_count(self._name)):
520 ent = _lib.X509_NAME_get_entry(self._name, i)
521 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
522 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800523 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500524 ent = _lib.X509_NAME_delete_entry(self._name, i)
525 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800526 break
527
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500528 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800529 value = value.encode('utf-8')
530
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500531 add_result = _lib.X509_NAME_add_entry_by_NID(
532 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800533 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500534 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800535
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800536 def __getattr__(self, name):
537 """
538 Find attribute. An X509Name object has the following attributes:
539 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400540 organization (alias O), organizationalUnit (alias OU), commonName
541 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800542 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500543 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500544 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800545 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
546 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
547 # push something onto the error queue. If we don't clean that up
548 # now, someone else will bump into it later and be quite confused.
549 # See lp#314814.
550 try:
551 _raise_current_error()
552 except Error:
553 pass
554 return super(X509Name, self).__getattr__(name)
555
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500556 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800557 if entry_index == -1:
558 return None
559
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500560 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
561 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800562
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500563 result_buffer = _ffi.new("unsigned char**")
564 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400565 _openssl_assert(data_length >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800566
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700567 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400568 result = _ffi.buffer(
569 result_buffer[0], data_length
570 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700571 finally:
572 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500573 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800574 return result
575
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500576 def _cmp(op):
577 def f(self, other):
578 if not isinstance(other, X509Name):
579 return NotImplemented
580 result = _lib.X509_NAME_cmp(self._name, other._name)
581 return op(result, 0)
582 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800583
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500584 __eq__ = _cmp(__eq__)
585 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800586
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500587 __lt__ = _cmp(__lt__)
588 __le__ = _cmp(__le__)
589
590 __gt__ = _cmp(__gt__)
591 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800592
593 def __repr__(self):
594 """
595 String representation of an X509Name
596 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400597 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500598 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800599 self._name, result_buffer, len(result_buffer))
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700600 _openssl_assert(format_result != _ffi.NULL)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800601
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500602 return "<X509Name object '%s'>" % (
603 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800604
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800605 def hash(self):
606 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200607 Return an integer representation of the first four bytes of the
608 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800609
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200610 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
611
612 :return: The (integer) hash of this name.
613 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800614 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500615 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800616
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800617 def der(self):
618 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200619 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800620
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200621 :return: The DER encoded form of this name.
622 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800623 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500624 result_buffer = _ffi.new('unsigned char**')
625 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400626 _openssl_assert(encode_result >= 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800627
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500628 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
629 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800630 return string_result
631
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800632 def get_components(self):
633 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200634 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800635
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200636 :return: The components of this name.
637 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800638 """
639 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500640 for i in range(_lib.X509_NAME_entry_count(self._name)):
641 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800642
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500643 fname = _lib.X509_NAME_ENTRY_get_object(ent)
644 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800645
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500646 nid = _lib.OBJ_obj2nid(fname)
647 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800648
649 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400650 _ffi.string(name),
651 _ffi.string(
652 _lib.ASN1_STRING_data(fval),
653 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800654
655 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200656
657
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800658X509NameType = X509Name
659
660
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800661class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200662 """
663 An X.509 v3 certificate extension.
664 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400665
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800666 def __init__(self, type_name, critical, value, subject=None, issuer=None):
667 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200668 Initializes an X509 extension.
669
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100670 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400671 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800672
Alex Gaynor5945ea82015-09-05 14:59:06 -0400673 :param bool critical: A flag indicating whether this is a critical
674 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800675
676 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200677 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800678
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200679 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800680 :type subject: :py:class:`X509`
681
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200682 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800683 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100684
Alex Chan54005ce2017-03-21 08:08:17 +0000685 .. _extension: https://www.openssl.org/docs/manmaster/man5/
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100686 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800687 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500688 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800689
Alex Gaynor5945ea82015-09-05 14:59:06 -0400690 # A context is necessary for any extension which uses the r2i
691 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
692 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500693 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800694
695 # We have no configuration database - but perhaps we should (some
696 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500697 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800698
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800699 # Initialize the subject and issuer, if appropriate. ctx is a local,
700 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400701 # any references, so no need to mess with reference counts or
702 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800703 if issuer is not None:
704 if not isinstance(issuer, X509):
705 raise TypeError("issuer must be an X509 instance")
706 ctx.issuer_cert = issuer._x509
707 if subject is not None:
708 if not isinstance(subject, X509):
709 raise TypeError("subject must be an X509 instance")
710 ctx.subject_cert = subject._x509
711
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800712 if critical:
713 # There are other OpenSSL APIs which would let us pass in critical
714 # separately, but they're harder to use, and since value is already
715 # a pile of crappy junk smuggling a ton of utterly important
716 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400717 # with strings? (However, X509V3_EXT_i2d in particular seems like
718 # it would be a better API to invoke. I do not know where to get
719 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500720 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800721
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500722 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
723 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800724 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500725 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800726
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400727 @property
728 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400729 return _lib.OBJ_obj2nid(
730 _lib.X509_EXTENSION_get_object(self._extension)
731 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400732
733 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500734 _lib.GEN_EMAIL: "email",
735 _lib.GEN_DNS: "DNS",
736 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400737 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400738
739 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500740 method = _lib.X509V3_EXT_get(self._extension)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700741 _openssl_assert(method != _ffi.NULL)
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400742 ext_data = _lib.X509_EXTENSION_get_data(self._extension)
743 payload = ext_data.data
744 length = ext_data.length
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400745
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500746 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400747 payloadptr[0] = payload
748
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500749 if method.it != _ffi.NULL:
750 ptr = _lib.ASN1_ITEM_ptr(method.it)
751 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
752 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400753 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500754 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400755 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500756 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400757
Paul Kehrerb7d79502015-05-04 07:43:51 -0500758 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400759 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500760 for i in range(_lib.sk_GENERAL_NAME_num(names)):
761 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400762 try:
763 label = self._prefixes[name.type]
764 except KeyError:
765 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500766 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500767 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400768 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500769 value = _native(
770 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
771 parts.append(label + ":" + value)
772 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400773
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800774 def __str__(self):
775 """
776 :return: a nice text representation of the extension
777 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500778 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400779 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800780
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400781 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500782 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400783 _openssl_assert(print_result != 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800784
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500785 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800786
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800787 def get_critical(self):
788 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200789 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800790
791 :return: The critical field.
792 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500793 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800794
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800795 def get_short_name(self):
796 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200797 Returns the short type name of this X.509 extension.
798
799 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800800
801 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200802 :rtype: :py:data:`bytes`
803
804 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800805 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500806 obj = _lib.X509_EXTENSION_get_object(self._extension)
807 nid = _lib.OBJ_obj2nid(obj)
808 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800809
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800810 def get_data(self):
811 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200812 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800813
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200814 :return: The ASN.1 encoded data of this X509 extension.
815 :rtype: :py:data:`bytes`
816
817 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800818 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500819 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
820 string_result = _ffi.cast('ASN1_STRING*', octet_result)
821 char_result = _lib.ASN1_STRING_data(string_result)
822 result_length = _lib.ASN1_STRING_length(string_result)
823 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800824
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200825
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800826X509ExtensionType = X509Extension
827
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800828
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800829class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200830 """
831 An X.509 certificate signing requests.
832 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400833
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800834 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500835 req = _lib.X509_REQ_new()
836 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Alex Gaynor5af32d02016-09-24 01:52:21 -0400837 # Default to version 0.
838 self.set_version(0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800839
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800840 def set_pubkey(self, pkey):
841 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200842 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800843
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200844 :param pkey: The public key to use.
845 :type pkey: :py:class:`PKey`
846
Dan Sully44e767a2016-06-04 18:05:27 -0700847 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800848 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500849 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400850 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800851
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800852 def get_pubkey(self):
853 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200854 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800855
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200856 :return: The public key.
857 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800858 """
859 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500860 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700861 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500862 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800863 pkey._only_public = True
864 return pkey
865
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800866 def set_version(self, version):
867 """
868 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
869 request.
870
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200871 :param int version: The version number.
Dan Sully44e767a2016-06-04 18:05:27 -0700872 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800873 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500874 set_result = _lib.X509_REQ_set_version(self._req, version)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -0400875 _openssl_assert(set_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800876
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800877 def get_version(self):
878 """
879 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
880 request.
881
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200882 :return: The value of the version subfield.
883 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800884 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500885 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800886
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800887 def get_subject(self):
888 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200889 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800890
Cory Benfield881dc8d2015-12-09 08:25:14 +0000891 This creates a new :class:`X509Name` that wraps the underlying subject
892 name field on the certificate signing request. Modifying it will modify
893 the underlying signing request, and will have the effect of modifying
894 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200895
896 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000897 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800898 """
899 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500900 name._name = _lib.X509_REQ_get_subject_name(self._req)
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700901 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800902
903 # The name is owned by the X509Req structure. As long as the X509Name
904 # Python object is alive, keep the X509Req Python object alive.
905 name._owner = self
906
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800907 return name
908
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800909 def add_extensions(self, extensions):
910 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200911 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800912
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200913 :param extensions: The X.509 extensions to add.
914 :type extensions: iterable of :py:class:`X509Extension`
Dan Sully44e767a2016-06-04 18:05:27 -0700915 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800916 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500917 stack = _lib.sk_X509_EXTENSION_new_null()
Alex Gaynorfb8a2a12016-06-04 18:26:26 -0700918 _openssl_assert(stack != _ffi.NULL)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800919
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500920 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800921
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800922 for ext in extensions:
923 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800924 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800925
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800926 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500927 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800928
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500929 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400930 _openssl_assert(add_result == 1)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800931
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800932 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800933 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200934 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800935
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200936 :return: The X.509 extensions in this request.
937 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
938
939 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800940 """
941 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500942 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500943 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800944 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500945 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800946 exts.append(ext)
947 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800948
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800949 def sign(self, pkey, digest):
950 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700951 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800952
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200953 :param pkey: The key pair to sign with.
954 :type pkey: :py:class:`PKey`
955 :param digest: The name of the message digest to use for the signature,
Alex Gaynor239e2d32016-09-11 12:36:35 -0400956 e.g. :py:data:`b"sha256"`.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200957 :type digest: :py:class:`bytes`
Dan Sully44e767a2016-06-04 18:05:27 -0700958 :return: ``None``
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800959 """
960 if pkey._only_public:
961 raise ValueError("Key has only public part")
962
963 if not pkey._initialized:
964 raise ValueError("Key is uninitialized")
965
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500966 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500967 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800968 raise ValueError("No such digest method")
969
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500970 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Alex Gaynor09a386e2016-07-03 09:32:44 -0400971 _openssl_assert(sign_result > 0)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800972
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800973 def verify(self, pkey):
974 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200975 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800976
Hynek Schlawack01c31672016-12-11 15:14:09 +0100977 :param PKey key: A public key.
978
979 :return: ``True`` if the signature is correct.
980 :rtype: bool
981
982 :raises OpenSSL.crypto.Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800983 problem verifying the signature.
984 """
985 if not isinstance(pkey, PKey):
986 raise TypeError("pkey must be a PKey instance")
987
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500988 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800989 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500990 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800991
992 return result
993
994
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800995X509ReqType = X509Req
996
997
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800998class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200999 """
1000 An X.509 certificate.
1001 """
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001002 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001003 x509 = _lib.X509_new()
Hynek Schlawack8a2dd772016-07-31 13:46:20 +02001004 _openssl_assert(x509 != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001005 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001006
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001007 def set_version(self, version):
1008 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001009 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001010
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001011 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001012 :type version: :py:class:`int`
1013
Dan Sully44e767a2016-06-04 18:05:27 -07001014 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001015 """
1016 if not isinstance(version, int):
1017 raise TypeError("version must be an integer")
1018
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001019 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001020
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001021 def get_version(self):
1022 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001023 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001024
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001025 :return: The version number of the certificate.
1026 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001027 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001028 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001029
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001030 def get_pubkey(self):
1031 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001032 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001033
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001034 :return: The public key.
1035 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001036 """
1037 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001038 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1039 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001040 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001041 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001042 pkey._only_public = True
1043 return pkey
1044
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001045 def set_pubkey(self, pkey):
1046 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001047 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001048
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001049 :param pkey: The public key.
1050 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001051
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001052 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001053 """
1054 if not isinstance(pkey, PKey):
1055 raise TypeError("pkey must be a PKey instance")
1056
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001057 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Alex Gaynor7778e792016-07-03 23:38:48 -04001058 _openssl_assert(set_result == 1)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001059
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001060 def sign(self, pkey, digest):
1061 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001062 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001063
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001064 :param pkey: The key to sign with.
1065 :type pkey: :py:class:`PKey`
1066
1067 :param digest: The name of the message digest to use.
1068 :type digest: :py:class:`bytes`
1069
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001070 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001071 """
1072 if not isinstance(pkey, PKey):
1073 raise TypeError("pkey must be a PKey instance")
1074
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001075 if pkey._only_public:
1076 raise ValueError("Key only has public part")
1077
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001078 if not pkey._initialized:
1079 raise ValueError("Key is uninitialized")
1080
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001081 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001082 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001083 raise ValueError("No such digest method")
1084
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001085 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Alex Gaynor5bb2bd12016-07-03 10:48:32 -04001086 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001087
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001088 def get_signature_algorithm(self):
1089 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001090 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001091
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001092 :return: The name of the algorithm.
1093 :rtype: :py:class:`bytes`
1094
1095 :raises ValueError: If the signature algorithm is undefined.
1096
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001097 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001098 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001099 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1100 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001101 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001102 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001103 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001104
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001105 def digest(self, digest_name):
1106 """
1107 Return the digest of the X509 object.
1108
1109 :param digest_name: The name of the digest algorithm to use.
1110 :type digest_name: :py:class:`bytes`
1111
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001112 :return: The digest of the object, formatted as
1113 :py:const:`b":"`-delimited hex pairs.
1114 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001115 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001116 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001117 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001118 raise ValueError("No such digest method")
1119
Paul Kehrer9f9113a2016-09-20 20:10:25 -05001120 result_buffer = _ffi.new("unsigned char[]", _lib.EVP_MAX_MD_SIZE)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001121 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001122 result_length[0] = len(result_buffer)
1123
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001124 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001125 self._x509, digest, result_buffer, result_length)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001126 _openssl_assert(digest_result == 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001127
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001128 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001129 b16encode(ch).upper() for ch
1130 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001131
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001132 def subject_name_hash(self):
1133 """
1134 Return the hash of the X509 subject.
1135
1136 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001137 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001138 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001139 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001140
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001141 def set_serial_number(self, serial):
1142 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001143 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001144
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001145 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001146 :type serial: :py:class:`int`
1147
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001148 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001149 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001150 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001151 raise TypeError("serial must be an integer")
1152
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001153 hex_serial = hex(serial)[2:]
1154 if not isinstance(hex_serial, bytes):
1155 hex_serial = hex_serial.encode('ascii')
1156
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001158
1159 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001160 # it. If bignum is still NULL after this call, then the return value
1161 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001162 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001163
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001164 if bignum_serial[0] == _ffi.NULL:
1165 set_result = _lib.ASN1_INTEGER_set(
1166 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001167 if set_result:
1168 # TODO Not tested
1169 _raise_current_error()
1170 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1172 _lib.BN_free(bignum_serial[0])
1173 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001174 # TODO Not tested
1175 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001176 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1177 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Alex Gaynor37726112016-07-04 09:51:32 -04001178 _openssl_assert(set_result == 1)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001179
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001180 def get_serial_number(self):
1181 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001182 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001183
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001184 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001185 :rtype: int
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001186 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001187 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1188 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001189 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001190 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001191 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001192 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001193 serial = int(hexstring_serial, 16)
1194 return serial
1195 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001196 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001197 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001198 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001199
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001200 def gmtime_adj_notAfter(self, amount):
1201 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001202 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001203
Dan Sully44e767a2016-06-04 18:05:27 -07001204 :param int amount: The number of seconds by which to adjust the
1205 timestamp.
1206 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001207 """
1208 if not isinstance(amount, int):
1209 raise TypeError("amount must be an integer")
1210
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001211 notAfter = _lib.X509_get_notAfter(self._x509)
1212 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001213
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001214 def gmtime_adj_notBefore(self, amount):
1215 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001216 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001217
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001218 :param amount: The number of seconds by which to adjust the timestamp.
Dan Sully44e767a2016-06-04 18:05:27 -07001219 :return: ``None``
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001220 """
1221 if not isinstance(amount, int):
1222 raise TypeError("amount must be an integer")
1223
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001224 notBefore = _lib.X509_get_notBefore(self._x509)
1225 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001226
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001227 def has_expired(self):
1228 """
1229 Check whether the certificate has expired.
1230
Dan Sully44e767a2016-06-04 18:05:27 -07001231 :return: ``True`` if the certificate has expired, ``False`` otherwise.
1232 :rtype: bool
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001233 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001234 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001235 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001236
Paul Kehrerfde45c92016-01-21 12:57:37 -06001237 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001238
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001240 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001241
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001242 def get_notBefore(self):
1243 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001244 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001245
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001246 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001247
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001248 YYYYMMDDhhmmssZ
1249 YYYYMMDDhhmmss+hhmm
1250 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001251
Dan Sully44e767a2016-06-04 18:05:27 -07001252 :return: A timestamp string, or ``None`` if there is none.
1253 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001254 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001255 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001256
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001257 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001258 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001259
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001260 def set_notBefore(self, when):
1261 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001262 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001263
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001264 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001265
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001266 YYYYMMDDhhmmssZ
1267 YYYYMMDDhhmmss+hhmm
1268 YYYYMMDDhhmmss-hhmm
1269
Dan Sully44e767a2016-06-04 18:05:27 -07001270 :param bytes when: A timestamp string.
1271 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001272 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001273 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001274
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001275 def get_notAfter(self):
1276 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001277 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001278
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001279 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001280
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001281 YYYYMMDDhhmmssZ
1282 YYYYMMDDhhmmss+hhmm
1283 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001284
Dan Sully44e767a2016-06-04 18:05:27 -07001285 :return: A timestamp string, or ``None`` if there is none.
1286 :rtype: bytes or NoneType
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001287 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001288 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001289
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001290 def set_notAfter(self, when):
1291 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001292 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001293
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001294 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001295
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001296 YYYYMMDDhhmmssZ
1297 YYYYMMDDhhmmss+hhmm
1298 YYYYMMDDhhmmss-hhmm
1299
Dan Sully44e767a2016-06-04 18:05:27 -07001300 :param bytes when: A timestamp string.
1301 :return: ``None``
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001302 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001303 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001304
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305 def _get_name(self, which):
1306 name = X509Name.__new__(X509Name)
1307 name._name = which(self._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001308 _openssl_assert(name._name != _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001309
1310 # The name is owned by the X509 structure. As long as the X509Name
1311 # Python object is alive, keep the X509 Python object alive.
1312 name._owner = self
1313
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001314 return name
1315
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001316 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001317 if not isinstance(name, X509Name):
1318 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001319 set_result = which(self._x509, name._name)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001320 _openssl_assert(set_result == 1)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001321
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001322 def get_issuer(self):
1323 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001324 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001325
Cory Benfielde6bcce82015-12-09 08:40:03 +00001326 This creates a new :class:`X509Name` that wraps the underlying issuer
1327 name field on the certificate. Modifying it will modify the underlying
1328 certificate, and will have the effect of modifying any other
1329 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001330
1331 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001332 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001333 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001334 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001335
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001336 def set_issuer(self, issuer):
1337 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001338 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001339
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001340 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001341 :type issuer: :py:class:`X509Name`
1342
Dan Sully44e767a2016-06-04 18:05:27 -07001343 :return: ``None``
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001344 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001345 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001346
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001347 def get_subject(self):
1348 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001349 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001350
Cory Benfielde6bcce82015-12-09 08:40:03 +00001351 This creates a new :class:`X509Name` that wraps the underlying subject
1352 name field on the certificate. Modifying it will modify the underlying
1353 certificate, and will have the effect of modifying any other
1354 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001355
1356 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001357 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001358 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001359 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001360
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001361 def set_subject(self, subject):
1362 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001363 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001364
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001365 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001366 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001367
Dan Sully44e767a2016-06-04 18:05:27 -07001368 :return: ``None``
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001369 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001370 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001371
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001372 def get_extension_count(self):
1373 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001374 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001375
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001376 :return: The number of extensions.
1377 :rtype: :py:class:`int`
1378
1379 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001380 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001381 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001382
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001383 def add_extensions(self, extensions):
1384 """
1385 Add extensions to the certificate.
1386
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001387 :param extensions: The extensions to add.
1388 :type extensions: An iterable of :py:class:`X509Extension` objects.
Dan Sully44e767a2016-06-04 18:05:27 -07001389 :return: ``None``
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001390 """
1391 for ext in extensions:
1392 if not isinstance(ext, X509Extension):
1393 raise ValueError("One of the elements is not an X509Extension")
1394
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001395 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001396 if not add_result:
1397 _raise_current_error()
1398
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001399 def get_extension(self, index):
1400 """
1401 Get a specific extension of the certificate by index.
1402
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001403 Extensions on a certificate are kept in order. The index
1404 parameter selects which extension will be returned.
1405
1406 :param int index: The index of the extension to retrieve.
1407 :return: The extension at the specified index.
1408 :rtype: :py:class:`X509Extension`
1409 :raises IndexError: If the extension index was out of bounds.
1410
1411 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001412 """
1413 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001414 ext._extension = _lib.X509_get_ext(self._x509, index)
1415 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001416 raise IndexError("extension index out of bounds")
1417
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001418 extension = _lib.X509_EXTENSION_dup(ext._extension)
1419 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001420 return ext
1421
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001422
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001423X509Type = X509
1424
1425
Dan Sully44e767a2016-06-04 18:05:27 -07001426class X509StoreFlags(object):
1427 """
1428 Flags for X509 verification, used to change the behavior of
1429 :class:`X509Store`.
1430
1431 See `OpenSSL Verification Flags`_ for details.
1432
1433 .. _OpenSSL Verification Flags:
Alex Chan54005ce2017-03-21 08:08:17 +00001434 https://www.openssl.org/docs/manmaster/man3/X509_VERIFY_PARAM_set_flags.html
Dan Sully44e767a2016-06-04 18:05:27 -07001435 """
1436 CRL_CHECK = _lib.X509_V_FLAG_CRL_CHECK
1437 CRL_CHECK_ALL = _lib.X509_V_FLAG_CRL_CHECK_ALL
1438 IGNORE_CRITICAL = _lib.X509_V_FLAG_IGNORE_CRITICAL
1439 X509_STRICT = _lib.X509_V_FLAG_X509_STRICT
1440 ALLOW_PROXY_CERTS = _lib.X509_V_FLAG_ALLOW_PROXY_CERTS
1441 POLICY_CHECK = _lib.X509_V_FLAG_POLICY_CHECK
1442 EXPLICIT_POLICY = _lib.X509_V_FLAG_EXPLICIT_POLICY
1443 INHIBIT_MAP = _lib.X509_V_FLAG_INHIBIT_MAP
1444 NOTIFY_POLICY = _lib.X509_V_FLAG_NOTIFY_POLICY
1445 CHECK_SS_SIGNATURE = _lib.X509_V_FLAG_CHECK_SS_SIGNATURE
1446 CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
1447
1448
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001449class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001450 """
Dan Sully44e767a2016-06-04 18:05:27 -07001451 An X.509 store.
1452
1453 An X.509 store is used to describe a context in which to verify a
1454 certificate. A description of a context may include a set of certificates
1455 to trust, a set of certificate revocation lists, verification flags and
1456 more.
1457
1458 An X.509 store, being only a description, cannot be used by itself to
1459 verify a certificate. To carry out the actual verification process, see
1460 :class:`X509StoreContext`.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001461 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001462
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001463 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001464 store = _lib.X509_STORE_new()
1465 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001466
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001467 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001468 """
Dan Sully44e767a2016-06-04 18:05:27 -07001469 Adds a trusted certificate to this store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001470
Dan Sully44e767a2016-06-04 18:05:27 -07001471 Adding a certificate with this method adds this certificate as a
1472 *trusted* certificate.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001473
1474 :param X509 cert: The certificate to add to this store.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001475
Dan Sully44e767a2016-06-04 18:05:27 -07001476 :raises TypeError: If the certificate is not an :class:`X509`.
Hynek Schlawack01c31672016-12-11 15:14:09 +01001477
1478 :raises OpenSSL.crypto.Error: If OpenSSL was unhappy with your
1479 certificate.
1480
Dan Sully44e767a2016-06-04 18:05:27 -07001481 :return: ``None`` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001482 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001483 if not isinstance(cert, X509):
1484 raise TypeError()
1485
Dan Sully44e767a2016-06-04 18:05:27 -07001486 _openssl_assert(_lib.X509_STORE_add_cert(self._store, cert._x509) != 0)
1487
1488 def add_crl(self, crl):
1489 """
1490 Add a certificate revocation list to this store.
1491
1492 The certificate revocation lists added to a store will only be used if
1493 the associated flags are configured to check certificate revocation
1494 lists.
1495
1496 .. versionadded:: 16.1.0
1497
1498 :param CRL crl: The certificate revocation list to add to this store.
1499 :return: ``None`` if the certificate revocation list was added
1500 successfully.
1501 """
1502 _openssl_assert(_lib.X509_STORE_add_crl(self._store, crl._crl) != 0)
1503
1504 def set_flags(self, flags):
1505 """
1506 Set verification flags to this store.
1507
1508 Verification flags can be combined by oring them together.
1509
1510 .. note::
1511
1512 Setting a verification flag sometimes requires clients to add
1513 additional information to the store, otherwise a suitable error will
1514 be raised.
1515
1516 For example, in setting flags to enable CRL checking a
1517 suitable CRL must be added to the store otherwise an error will be
1518 raised.
1519
1520 .. versionadded:: 16.1.0
1521
1522 :param int flags: The verification flags to set on this store.
1523 See :class:`X509StoreFlags` for available constants.
1524 :return: ``None`` if the verification flags were successfully set.
1525 """
1526 _openssl_assert(_lib.X509_STORE_set_flags(self._store, flags) != 0)
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001527
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001528 def set_time(self, vfy_time):
1529 """
1530 Set the time against which the certificates are verified.
1531
1532 Normally the current time is used.
1533
1534 .. note::
1535
1536 For example, you can determine if a certificate was valid at a given
1537 time.
1538
Hynek Schlawackf6c96af2017-04-20 12:34:58 +02001539 .. versionadded:: 17.0.0
Thomas Sileoe15e60a2016-11-22 18:13:30 +01001540
1541 :param datetime vfy_time: The verification time to set on this store.
1542 :return: ``None`` if the verification time was successfully set.
1543 """
1544 param = _lib.X509_VERIFY_PARAM_new()
1545 param = _ffi.gc(param, _lib.X509_VERIFY_PARAM_free)
1546
1547 _lib.X509_VERIFY_PARAM_set_time(param, int(vfy_time.strftime('%s')))
1548 _openssl_assert(_lib.X509_STORE_set1_param(self._store, param) != 0)
1549
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001550
1551X509StoreType = X509Store
1552
1553
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001554class X509StoreContextError(Exception):
1555 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001556 An exception raised when an error occurred while verifying a certificate
1557 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001558
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001559 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001560 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001561 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001562
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001563 def __init__(self, message, certificate):
1564 super(X509StoreContextError, self).__init__(message)
1565 self.certificate = certificate
1566
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001567
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001568class X509StoreContext(object):
1569 """
1570 An X.509 store context.
1571
Dan Sully44e767a2016-06-04 18:05:27 -07001572 An X.509 store context is used to carry out the actual verification process
1573 of a certificate in a described context. For describing such a context, see
1574 :class:`X509Store`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001575
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001576 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1577 instance. It is dynamically allocated and automatically garbage
1578 collected.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001579 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001580 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001581 :param X509Store store: The certificates which will be trusted for the
1582 purposes of any verifications.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001583 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001584 """
1585
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001586 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001587 store_ctx = _lib.X509_STORE_CTX_new()
1588 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1589 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001590 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001591 # Make the store context available for use after instantiating this
1592 # class by initializing it now. Per testing, subsequent calls to
Dan Sully44e767a2016-06-04 18:05:27 -07001593 # :meth:`_init` have no adverse affect.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001594 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001595
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001596 def _init(self):
1597 """
1598 Set up the store context for a subsequent verification operation.
1599 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001600 ret = _lib.X509_STORE_CTX_init(
1601 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1602 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001603 if ret <= 0:
1604 _raise_current_error()
1605
1606 def _cleanup(self):
1607 """
1608 Internally cleans up the store context.
1609
Dan Sully44e767a2016-06-04 18:05:27 -07001610 The store context can then be reused with a new call to :meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001611 """
1612 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1613
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001614 def _exception_from_context(self):
1615 """
1616 Convert an OpenSSL native context error failure into a Python
1617 exception.
1618
Alex Gaynor5945ea82015-09-05 14:59:06 -04001619 When a call to native OpenSSL X509_verify_cert fails, additional
1620 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001621 """
1622 errors = [
1623 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1624 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1625 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001626 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001627 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001628 # A context error should always be associated with a certificate, so we
1629 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001630 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001631 _cert = _lib.X509_dup(_x509)
1632 pycert = X509.__new__(X509)
1633 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001634 return X509StoreContextError(errors, pycert)
1635
Stephen Holsapple46a09252015-02-12 14:45:43 -08001636 def set_store(self, store):
1637 """
Dan Sully44e767a2016-06-04 18:05:27 -07001638 Set the context's X.509 store.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001639
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001640 .. versionadded:: 0.15
1641
Dan Sully44e767a2016-06-04 18:05:27 -07001642 :param X509Store store: The store description which will be used for
1643 the purposes of any *future* verifications.
Stephen Holsapple46a09252015-02-12 14:45:43 -08001644 """
1645 self._store = store
1646
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001647 def verify_certificate(self):
1648 """
1649 Verify a certificate in a context.
1650
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001651 .. versionadded:: 0.15
1652
Alex Gaynorca87ff62015-09-04 23:31:03 -04001653 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001654 certificate in the context. Sets ``certificate`` attribute to
1655 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001656 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001657 # Always re-initialize the store context in case
Dan Sully44e767a2016-06-04 18:05:27 -07001658 # :meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001659 self._init()
1660 ret = _lib.X509_verify_cert(self._store_ctx)
1661 self._cleanup()
1662 if ret <= 0:
1663 raise self._exception_from_context()
1664
1665
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001666def load_certificate(type, buffer):
1667 """
1668 Load a certificate from a buffer
1669
1670 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1671
Dan Sully44e767a2016-06-04 18:05:27 -07001672 :param bytes buffer: The buffer the certificate is stored in
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001673
1674 :return: The X509 object
1675 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001676 if isinstance(buffer, _text_type):
1677 buffer = buffer.encode("ascii")
1678
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001679 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001680
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001681 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001682 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001683 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001684 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001685 else:
1686 raise ValueError(
1687 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001688
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001690 _raise_current_error()
1691
1692 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001693 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001694 return cert
1695
1696
1697def dump_certificate(type, cert):
1698 """
1699 Dump a certificate to a buffer
1700
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001701 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1702 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001703 :param cert: The certificate to dump
1704 :return: The buffer with the dumped certificate in
1705 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001706 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001707
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001708 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001709 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001710 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001711 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001712 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001713 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001714 else:
1715 raise ValueError(
1716 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1717 "FILETYPE_TEXT")
1718
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001719 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001720 return _bio_to_string(bio)
1721
1722
Cory Benfield6492f7c2015-10-27 16:57:58 +09001723def dump_publickey(type, pkey):
1724 """
Cory Benfield11c10192015-10-27 17:23:03 +09001725 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001726
Cory Benfield9c590b92015-10-28 14:55:05 +09001727 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001728 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001729 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001730 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001731 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001732 """
1733 bio = _new_mem_buf()
1734 if type == FILETYPE_PEM:
1735 write_bio = _lib.PEM_write_bio_PUBKEY
1736 elif type == FILETYPE_ASN1:
1737 write_bio = _lib.i2d_PUBKEY_bio
1738 else:
1739 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1740
1741 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001742 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001743 _raise_current_error()
1744
1745 return _bio_to_string(bio)
1746
1747
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001748def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1749 """
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001750 Dump the private key *pkey* into a buffer string encoded with the type
1751 *type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
1752 using *cipher* and *passphrase*.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001753
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001754 :param type: The file type (one of :const:`FILETYPE_PEM`,
1755 :const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
1756 :param PKey pkey: The PKey to dump
1757 :param cipher: (optional) if encrypted PEM format, the cipher to use
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001758 :param passphrase: (optional) if encrypted PEM format, this can be either
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001759 the passphrase to use, or a callback for providing the passphrase.
1760
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001761 :return: The buffer with the dumped key in
Dan Sully44e767a2016-06-04 18:05:27 -07001762 :rtype: bytes
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001763 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001764 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001765
1766 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001767 if passphrase is None:
1768 raise TypeError(
1769 "if a value is given for cipher "
1770 "one must also be given for passphrase")
1771 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001772 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001773 raise ValueError("Invalid cipher name")
1774 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001775 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001776
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001777 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001778 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001779 result_code = _lib.PEM_write_bio_PrivateKey(
1780 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001781 helper.callback, helper.callback_args)
1782 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001783 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001784 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001785 elif type == FILETYPE_TEXT:
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001786 rsa = _ffi.gc(
1787 _lib.EVP_PKEY_get1_RSA(pkey._pkey),
1788 _lib.RSA_free
1789 )
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001790 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001791 else:
1792 raise ValueError(
1793 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1794 "FILETYPE_TEXT")
1795
Hynek Schlawack11e43ad2016-07-03 14:40:20 +02001796 _openssl_assert(result_code != 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001797
1798 return _bio_to_string(bio)
1799
1800
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001801class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001802 """
1803 A certificate revocation.
1804 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001805 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1806 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1807 # OCSP_crl_reason_str. We use the latter, just like the command line
1808 # program.
1809 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001810 b"unspecified",
1811 b"keyCompromise",
1812 b"CACompromise",
1813 b"affiliationChanged",
1814 b"superseded",
1815 b"cessationOfOperation",
1816 b"certificateHold",
1817 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001818 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001819
1820 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 revoked = _lib.X509_REVOKED_new()
1822 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001823
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001824 def set_serial(self, hex_str):
1825 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001826 Set the serial number.
1827
1828 The serial number is formatted as a hexadecimal number encoded in
1829 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001830
Dan Sully44e767a2016-06-04 18:05:27 -07001831 :param bytes hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001832
Dan Sully44e767a2016-06-04 18:05:27 -07001833 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001834 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001835 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1836 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001837 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001838 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001839 if not bn_result:
1840 raise ValueError("bad hex string")
1841
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001842 asn1_serial = _ffi.gc(
1843 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1844 _lib.ASN1_INTEGER_free)
1845 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001846
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 def get_serial(self):
1848 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001849 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001850
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001851 The serial number is formatted as a hexadecimal number encoded in
1852 ASCII.
1853
1854 :return: The serial number.
Dan Sully44e767a2016-06-04 18:05:27 -07001855 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001856 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001857 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001858
Alex Gaynor67903a62016-06-02 10:37:13 -07001859 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1860 _openssl_assert(asn1_int != _ffi.NULL)
1861 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1862 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001863 return _bio_to_string(bio)
1864
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001865 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001866 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1867 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001868 obj = _lib.X509_EXTENSION_get_object(ext)
1869 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001870 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001871 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001872 break
1873
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001874 def set_reason(self, reason):
1875 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001876 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001877
Dan Sully44e767a2016-06-04 18:05:27 -07001878 If :data:`reason` is ``None``, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001879
1880 :param reason: The reason string.
Dan Sully44e767a2016-06-04 18:05:27 -07001881 :type reason: :class:`bytes` or :class:`NoneType`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001882
Dan Sully44e767a2016-06-04 18:05:27 -07001883 :return: ``None``
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001884
1885 .. seealso::
1886
Dan Sully44e767a2016-06-04 18:05:27 -07001887 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001888 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001889 """
1890 if reason is None:
1891 self._delete_reason()
1892 elif not isinstance(reason, bytes):
1893 raise TypeError("reason must be None or a byte string")
1894 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001895 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001896 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1897
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001898 new_reason_ext = _lib.ASN1_ENUMERATED_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07001899 _openssl_assert(new_reason_ext != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001900 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001901
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001902 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
Alex Gaynoradd5b072016-06-04 21:04:00 -07001903 _openssl_assert(set_result != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001904
1905 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001906 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1907 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Alex Gaynor09a386e2016-07-03 09:32:44 -04001908 _openssl_assert(add_result == 1)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001909
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001910 def get_reason(self):
1911 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001912 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001913
Dan Sully44e767a2016-06-04 18:05:27 -07001914 :return: The reason, or ``None`` if there is none.
1915 :rtype: bytes or NoneType
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001916
1917 .. seealso::
1918
Dan Sully44e767a2016-06-04 18:05:27 -07001919 :meth:`all_reasons`, which gives you a list of all supported
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001920 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001921 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001922 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1923 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001924 obj = _lib.X509_EXTENSION_get_object(ext)
1925 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001926 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001927
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001928 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001929 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001930 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001931 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001932 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04001933 _openssl_assert(print_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001934
1935 return _bio_to_string(bio)
1936
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001937 def all_reasons(self):
1938 """
1939 Return a list of all the supported reason strings.
1940
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001941 This list is a copy; modifying it does not change the supported reason
1942 strings.
1943
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001944 :return: A list of reason strings.
Dan Sully44e767a2016-06-04 18:05:27 -07001945 :rtype: :class:`list` of :class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001946 """
1947 return self._crl_reasons[:]
1948
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001949 def set_rev_date(self, when):
1950 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001951 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001952
Dan Sully44e767a2016-06-04 18:05:27 -07001953 :param bytes when: The timestamp of the revocation,
1954 as ASN.1 GENERALIZEDTIME.
1955 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001956 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001957 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1958 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001959
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001960 def get_rev_date(self):
1961 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001962 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001963
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001964 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
Dan Sully44e767a2016-06-04 18:05:27 -07001965 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001966 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001967 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1968 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001969
1970
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001971class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001972 """
1973 A certificate revocation list.
1974 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001975
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001976 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001977 crl = _lib.X509_CRL_new()
1978 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001979
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001980 def get_revoked(self):
1981 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001982 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001983
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001984 These revocations will be provided by value, not by reference.
1985 That means it's okay to mutate them: it won't affect this CRL.
1986
1987 :return: The revocations in this CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07001988 :rtype: :class:`tuple` of :class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001989 """
1990 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001991 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001992 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1993 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001994 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001995 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001996 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001997 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001998 if results:
1999 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002000
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002001 def add_revoked(self, revoked):
2002 """
2003 Add a revoked (by value not reference) to the CRL structure
2004
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02002005 This revocation will be added by value, not by reference. That
2006 means it's okay to mutate it after adding: it won't affect
2007 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002008
Dan Sully44e767a2016-06-04 18:05:27 -07002009 :param Revoked revoked: The new revocation.
2010 :return: ``None``
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002011 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04002012 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002013 _openssl_assert(copy != _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002014
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002015 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002016 _openssl_assert(add_result != 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002017
Dan Sully44e767a2016-06-04 18:05:27 -07002018 def get_issuer(self):
2019 """
2020 Get the CRL's issuer.
2021
2022 .. versionadded:: 16.1.0
2023
2024 :rtype: X509Name
2025 """
2026 _issuer = _lib.X509_NAME_dup(_lib.X509_CRL_get_issuer(self._crl))
2027 _openssl_assert(_issuer != _ffi.NULL)
2028 _issuer = _ffi.gc(_issuer, _lib.X509_NAME_free)
2029 issuer = X509Name.__new__(X509Name)
2030 issuer._name = _issuer
2031 return issuer
2032
2033 def set_version(self, version):
2034 """
2035 Set the CRL version.
2036
2037 .. versionadded:: 16.1.0
2038
2039 :param int version: The version of the CRL.
2040 :return: ``None``
2041 """
2042 _openssl_assert(_lib.X509_CRL_set_version(self._crl, version) != 0)
2043
2044 def _set_boundary_time(self, which, when):
2045 return _set_asn1_time(which(self._crl), when)
2046
2047 def set_lastUpdate(self, when):
2048 """
2049 Set when the CRL was last updated.
2050
2051 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2052
2053 YYYYMMDDhhmmssZ
2054 YYYYMMDDhhmmss+hhmm
2055 YYYYMMDDhhmmss-hhmm
2056
2057 .. versionadded:: 16.1.0
2058
2059 :param bytes when: A timestamp string.
2060 :return: ``None``
2061 """
2062 return self._set_boundary_time(_lib.X509_CRL_get_lastUpdate, when)
2063
2064 def set_nextUpdate(self, when):
2065 """
2066 Set when the CRL will next be udpated.
2067
2068 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
2069
2070 YYYYMMDDhhmmssZ
2071 YYYYMMDDhhmmss+hhmm
2072 YYYYMMDDhhmmss-hhmm
2073
2074 .. versionadded:: 16.1.0
2075
2076 :param bytes when: A timestamp string.
2077 :return: ``None``
2078 """
2079 return self._set_boundary_time(_lib.X509_CRL_get_nextUpdate, when)
2080
2081 def sign(self, issuer_cert, issuer_key, digest):
2082 """
2083 Sign the CRL.
2084
2085 Signing a CRL enables clients to associate the CRL itself with an
2086 issuer. Before a CRL is meaningful to other OpenSSL functions, it must
2087 be signed by an issuer.
2088
2089 This method implicitly sets the issuer's name based on the issuer
2090 certificate and private key used to sign the CRL.
2091
2092 .. versionadded:: 16.1.0
2093
2094 :param X509 issuer_cert: The issuer's certificate.
2095 :param PKey issuer_key: The issuer's private key.
2096 :param bytes digest: The digest method to sign the CRL with.
2097 """
2098 digest_obj = _lib.EVP_get_digestbyname(digest)
2099 _openssl_assert(digest_obj != _ffi.NULL)
2100 _lib.X509_CRL_set_issuer_name(
2101 self._crl, _lib.X509_get_subject_name(issuer_cert._x509))
2102 _lib.X509_CRL_sort(self._crl)
2103 result = _lib.X509_CRL_sign(self._crl, issuer_key._pkey, digest_obj)
2104 _openssl_assert(result != 0)
2105
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002106 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002107 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002108 """
Dan Sully44e767a2016-06-04 18:05:27 -07002109 Export the CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002110
Dan Sully44e767a2016-06-04 18:05:27 -07002111 :param X509 cert: The certificate used to sign the CRL.
2112 :param PKey key: The key used to sign the CRL.
2113 :param int type: The export format, either :data:`FILETYPE_PEM`,
2114 :data:`FILETYPE_ASN1`, or :data:`FILETYPE_TEXT`.
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04002115 :param int days: The number of days until the next update of this CRL.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002116 :param bytes digest: The name of the message digest to use (eg
Alex Gaynor239e2d32016-09-11 12:36:35 -04002117 ``b"sha2566"``).
Dan Sully44e767a2016-06-04 18:05:27 -07002118 :rtype: bytes
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002119 """
Dan Sully44e767a2016-06-04 18:05:27 -07002120
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002121 if not isinstance(cert, X509):
2122 raise TypeError("cert must be an X509 instance")
2123 if not isinstance(key, PKey):
2124 raise TypeError("key must be a PKey instance")
2125 if not isinstance(type, int):
2126 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002127
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04002128 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002129 _warn(
2130 "The default message digest (md5) is deprecated. "
2131 "Pass the name of a message digest explicitly.",
2132 category=DeprecationWarning,
2133 stacklevel=2,
2134 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002135 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002136
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002137 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002138 if digest_obj == _ffi.NULL:
2139 raise ValueError("No such digest method")
2140
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002141 bio = _lib.BIO_new(_lib.BIO_s_mem())
Alex Gaynoradd5b072016-06-04 21:04:00 -07002142 _openssl_assert(bio != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002143
Alex Gaynora738ed52015-09-05 11:17:10 -04002144 # A scratch time object to give different values to different CRL
2145 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002146 sometime = _lib.ASN1_TIME_new()
Alex Gaynoradd5b072016-06-04 21:04:00 -07002147 _openssl_assert(sometime != _ffi.NULL)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002148
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002149 _lib.X509_gmtime_adj(sometime, 0)
2150 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002151
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002152 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2153 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002154
Alex Gaynor5945ea82015-09-05 14:59:06 -04002155 _lib.X509_CRL_set_issuer_name(
2156 self._crl, _lib.X509_get_subject_name(cert._x509)
2157 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002158
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002159 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002160 if not sign_result:
2161 _raise_current_error()
2162
Dominic Chenf05b2122015-10-13 16:32:35 +00002163 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002164
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002165
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002166CRLType = CRL
2167
2168
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002169class PKCS7(object):
2170 def type_is_signed(self):
2171 """
2172 Check if this NID_pkcs7_signed object
2173
2174 :return: True if the PKCS7 is of type signed
2175 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002176 return bool(_lib.PKCS7_type_is_signed(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002177
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002178 def type_is_enveloped(self):
2179 """
2180 Check if this NID_pkcs7_enveloped object
2181
2182 :returns: True if the PKCS7 is of type enveloped
2183 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002184 return bool(_lib.PKCS7_type_is_enveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002185
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002186 def type_is_signedAndEnveloped(self):
2187 """
2188 Check if this NID_pkcs7_signedAndEnveloped object
2189
2190 :returns: True if the PKCS7 is of type signedAndEnveloped
2191 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002192 return bool(_lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002193
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002194 def type_is_data(self):
2195 """
2196 Check if this NID_pkcs7_data object
2197
2198 :return: True if the PKCS7 is of type data
2199 """
Alex Gaynor3aeead92016-07-31 11:31:59 -04002200 return bool(_lib.PKCS7_type_is_data(self._pkcs7))
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002201
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002202 def get_type_name(self):
2203 """
2204 Returns the type name of the PKCS7 structure
2205
2206 :return: A string with the typename
2207 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002208 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2209 string_type = _lib.OBJ_nid2sn(nid)
2210 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002211
Alex Chanc6077062016-11-18 13:53:39 +00002212
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002213PKCS7Type = PKCS7
2214
2215
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002216class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002217 """
2218 A PKCS #12 archive.
2219 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002220
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002221 def __init__(self):
2222 self._pkey = None
2223 self._cert = None
2224 self._cacerts = None
2225 self._friendlyname = None
2226
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002227 def get_certificate(self):
2228 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002229 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002230
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002231 :return: The certificate, or :py:const:`None` if there is none.
2232 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002233 """
2234 return self._cert
2235
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002236 def set_certificate(self, cert):
2237 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002238 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002239
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002240 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002241 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002242
Dan Sully44e767a2016-06-04 18:05:27 -07002243 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002244 """
2245 if not isinstance(cert, X509):
2246 raise TypeError("cert must be an X509 instance")
2247 self._cert = cert
2248
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002249 def get_privatekey(self):
2250 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002251 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002252
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002253 :return: The private key, or :py:const:`None` if there is none.
2254 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002255 """
2256 return self._pkey
2257
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002258 def set_privatekey(self, pkey):
2259 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002260 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002261
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002262 :param pkey: The new private key, or :py:const:`None` to unset it.
2263 :type pkey: :py:class:`PKey` or :py:const:`None`
2264
Dan Sully44e767a2016-06-04 18:05:27 -07002265 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002266 """
2267 if not isinstance(pkey, PKey):
2268 raise TypeError("pkey must be a PKey instance")
2269 self._pkey = pkey
2270
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002271 def get_ca_certificates(self):
2272 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002273 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002274
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002275 :return: A tuple with the CA certificates in the chain, or
2276 :py:const:`None` if there are none.
2277 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002278 """
2279 if self._cacerts is not None:
2280 return tuple(self._cacerts)
2281
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002282 def set_ca_certificates(self, cacerts):
2283 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002284 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002285
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002286 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2287 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002288 :type cacerts: An iterable of :py:class:`X509` 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 cacerts is None:
2293 self._cacerts = None
2294 else:
2295 cacerts = list(cacerts)
2296 for cert in cacerts:
2297 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002298 raise TypeError(
2299 "iterable must only contain X509 instances"
2300 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002301 self._cacerts = cacerts
2302
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002303 def set_friendlyname(self, name):
2304 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002305 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002306
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002307 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002308 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002309
Dan Sully44e767a2016-06-04 18:05:27 -07002310 :return: ``None``
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002311 """
2312 if name is None:
2313 self._friendlyname = None
2314 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002315 raise TypeError(
2316 "name must be a byte string or None (not %r)" % (name,)
2317 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002318 self._friendlyname = name
2319
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002320 def get_friendlyname(self):
2321 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002322 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002323
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002324 :returns: The friendly name, or :py:const:`None` if there is none.
2325 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002326 """
2327 return self._friendlyname
2328
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002329 def export(self, passphrase=None, iter=2048, maciter=1):
2330 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002331 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002332
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002333 For more information, see the :c:func:`PKCS12_create` man page.
2334
2335 :param passphrase: The passphrase used to encrypt the structure. Unlike
2336 some other passphrase arguments, this *must* be a string, not a
2337 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002338 :type passphrase: :py:data:`bytes`
2339
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002340 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002341 :type iter: :py:data:`int`
2342
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002343 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002344 :type maciter: :py:data:`int`
2345
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002346 :return: The string representation of the PKCS #12 structure.
2347 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002348 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002349 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002350
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002351 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002352 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002353 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002354 cacerts = _lib.sk_X509_new_null()
2355 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002356 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002357 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002358
2359 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002360 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002361
2362 friendlyname = self._friendlyname
2363 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002364 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002365
2366 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002367 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002368 else:
2369 pkey = self._pkey._pkey
2370
2371 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002372 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002373 else:
2374 cert = self._cert._x509
2375
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002376 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002377 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002378 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2379 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002380 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002381 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002382 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002383 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002384
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002385 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002386 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002387 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002388
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002389
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002390PKCS12Type = PKCS12
2391
2392
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002393class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002394 """
2395 A Netscape SPKI object.
2396 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002397
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002398 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002399 spki = _lib.NETSCAPE_SPKI_new()
2400 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002401
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002402 def sign(self, pkey, digest):
2403 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002404 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002405
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002406 :param pkey: The private key to sign with.
2407 :type pkey: :py:class:`PKey`
2408
2409 :param digest: The message digest to use.
2410 :type digest: :py:class:`bytes`
2411
Dan Sully44e767a2016-06-04 18:05:27 -07002412 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002413 """
2414 if pkey._only_public:
2415 raise ValueError("Key has only public part")
2416
2417 if not pkey._initialized:
2418 raise ValueError("Key is uninitialized")
2419
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002420 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002421 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002422 raise ValueError("No such digest method")
2423
Alex Gaynor5945ea82015-09-05 14:59:06 -04002424 sign_result = _lib.NETSCAPE_SPKI_sign(
2425 self._spki, pkey._pkey, digest_obj
2426 )
Alex Gaynor09a386e2016-07-03 09:32:44 -04002427 _openssl_assert(sign_result > 0)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002428
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002429 def verify(self, key):
2430 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002431 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002432
Hynek Schlawack01c31672016-12-11 15:14:09 +01002433 :param PKey key: The public key that signature is supposedly from.
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002434
Hynek Schlawack01c31672016-12-11 15:14:09 +01002435 :return: ``True`` if the signature is correct.
2436 :rtype: bool
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002437
Hynek Schlawack01c31672016-12-11 15:14:09 +01002438 :raises OpenSSL.crypto.Error: If the signature is invalid, or there was
2439 a problem verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002440 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002441 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002442 if answer <= 0:
2443 _raise_current_error()
2444 return True
2445
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002446 def b64_encode(self):
2447 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002448 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002449
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002450 :return: The base64 encoded string.
2451 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002452 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002453 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2454 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002455 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002456 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002457
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002458 def get_pubkey(self):
2459 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002460 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002461
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002462 :return: The public key.
2463 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002464 """
2465 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002466 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002467 _openssl_assert(pkey._pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002468 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002469 pkey._only_public = True
2470 return pkey
2471
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002472 def set_pubkey(self, pkey):
2473 """
2474 Set the public key of the certificate
2475
2476 :param pkey: The public key
Dan Sully44e767a2016-06-04 18:05:27 -07002477 :return: ``None``
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002478 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002479 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002480 _openssl_assert(set_result == 1)
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002481
2482
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002483NetscapeSPKIType = NetscapeSPKI
2484
2485
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002486class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002487 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002488 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002489 raise ValueError(
2490 "only FILETYPE_PEM key format supports encryption"
2491 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002492 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002493 self._more_args = more_args
2494 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002495 self._problems = []
2496
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002497 @property
2498 def callback(self):
2499 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002500 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002501 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002502 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002503 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002504 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002505 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002506 raise TypeError(
2507 "Last argument must be a byte string or a callable."
2508 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002509
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002510 @property
2511 def callback_args(self):
2512 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002513 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002514 elif isinstance(self._passphrase, bytes):
2515 return self._passphrase
2516 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002517 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002518 else:
Hynek Schlawack33675f92016-11-18 14:55:06 +01002519 raise TypeError(
2520 "Last argument must be a byte string or a callable."
2521 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002522
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002523 def raise_if_problem(self, exceptionType=Error):
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002524 if self._problems:
Greg Bowser36eb2de2017-01-24 11:38:55 -05002525
2526 # Flush the OpenSSL error queue
2527 try:
2528 _exception_from_error_queue(exceptionType)
2529 except exceptionType:
2530 pass
2531
2532 raise self._problems.pop(0)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002533
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002534 def _read_passphrase(self, buf, size, rwflag, userdata):
2535 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002536 if self._more_args:
2537 result = self._passphrase(size, rwflag, userdata)
2538 else:
2539 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002540 if not isinstance(result, bytes):
2541 raise ValueError("String expected")
2542 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002543 if self._truncate:
2544 result = result[:size]
2545 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002546 raise ValueError(
2547 "passphrase returned by callback is too long"
2548 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002549 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002550 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002551 return len(result)
2552 except Exception as e:
2553 self._problems.append(e)
2554 return 0
2555
2556
Cory Benfield6492f7c2015-10-27 16:57:58 +09002557def load_publickey(type, buffer):
2558 """
Cory Benfield11c10192015-10-27 17:23:03 +09002559 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002560
Cory Benfield9c590b92015-10-28 14:55:05 +09002561 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002562 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002563 :param buffer: The buffer the key is stored in.
2564 :type buffer: A Python string object, either unicode or bytestring.
2565 :return: The PKey object.
2566 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002567 """
2568 if isinstance(buffer, _text_type):
2569 buffer = buffer.encode("ascii")
2570
2571 bio = _new_mem_buf(buffer)
2572
2573 if type == FILETYPE_PEM:
2574 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2575 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2576 elif type == FILETYPE_ASN1:
2577 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2578 else:
2579 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2580
2581 if evp_pkey == _ffi.NULL:
2582 _raise_current_error()
2583
2584 pkey = PKey.__new__(PKey)
2585 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Paul Kehrer32fc4e62016-06-03 15:21:44 -07002586 pkey._only_public = True
Cory Benfield6492f7c2015-10-27 16:57:58 +09002587 return pkey
2588
2589
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002590def load_privatekey(type, buffer, passphrase=None):
2591 """
2592 Load a private key from a buffer
2593
2594 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2595 :param buffer: The buffer the key is stored in
2596 :param passphrase: (optional) if encrypted PEM format, this can be
2597 either the passphrase to use, or a callback for
2598 providing the passphrase.
2599
2600 :return: The PKey object
2601 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002602 if isinstance(buffer, _text_type):
2603 buffer = buffer.encode("ascii")
2604
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002605 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002606
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002607 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002608 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002609 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2610 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002611 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002612 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002613 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002614 else:
2615 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002617 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002618 _raise_current_error()
2619
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002620 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002621 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002622 return pkey
2623
2624
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002625def dump_certificate_request(type, req):
2626 """
2627 Dump a certificate request to a buffer
2628
2629 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2630 :param req: The certificate request to dump
2631 :return: The buffer with the dumped certificate request in
2632 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002633 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002634
2635 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002636 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002637 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002638 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002639 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002640 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002641 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002642 raise ValueError(
2643 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2644 "FILETYPE_TEXT"
2645 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002646
Alex Gaynor09a386e2016-07-03 09:32:44 -04002647 _openssl_assert(result_code != 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002648
2649 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002650
2651
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002652def load_certificate_request(type, buffer):
2653 """
2654 Load a certificate request from a buffer
2655
2656 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2657 :param buffer: The buffer the certificate request is stored in
2658 :return: The X509Req object
2659 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002660 if isinstance(buffer, _text_type):
2661 buffer = buffer.encode("ascii")
2662
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002663 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002664
2665 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002666 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002667 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002668 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002669 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002670 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002671
Alex Gaynoradd5b072016-06-04 21:04:00 -07002672 _openssl_assert(req != _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002673
2674 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002675 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002676 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002677
2678
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002679def sign(pkey, data, digest):
2680 """
2681 Sign data with a digest
2682
2683 :param pkey: Pkey to sign with
2684 :param data: data to be signed
2685 :param digest: message digest to use
2686 :return: signature
2687 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002688 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002689
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002690 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002691 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002692 raise ValueError("No such digest method")
2693
Alex Gaynor67903a62016-06-02 10:37:13 -07002694 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002695 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002696
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002697 _lib.EVP_SignInit(md_ctx, digest_obj)
2698 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002699
Colleen Murphye09399b2016-03-01 17:40:49 -08002700 pkey_length = (PKey.bits(pkey) + 7) // 8
2701 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002702 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002703 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002704 md_ctx, signature_buffer, signature_length, pkey._pkey)
Alex Gaynor09a386e2016-07-03 09:32:44 -04002705 _openssl_assert(final_result == 1)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002706
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002707 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002708
2709
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002710def verify(cert, signature, data, digest):
2711 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002712 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002713
2714 :param cert: signing certificate (X509 object)
2715 :param signature: signature returned by sign function
2716 :param data: data to be verified
2717 :param digest: message digest to use
Dan Sully44e767a2016-06-04 18:05:27 -07002718 :return: ``None`` if the signature is correct, raise exception otherwise.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002719 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002720 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002721
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002722 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002723 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002724 raise ValueError("No such digest method")
2725
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002726 pkey = _lib.X509_get_pubkey(cert._x509)
Alex Gaynoradd5b072016-06-04 21:04:00 -07002727 _openssl_assert(pkey != _ffi.NULL)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002728 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002729
Alex Gaynor67903a62016-06-02 10:37:13 -07002730 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002731 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002732
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002733 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2734 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002735 verify_result = _lib.EVP_VerifyFinal(
2736 md_ctx, signature, len(signature), pkey
2737 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002738
2739 if verify_result != 1:
2740 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002741
2742
Dominic Chenf05b2122015-10-13 16:32:35 +00002743def dump_crl(type, crl):
2744 """
2745 Dump a certificate revocation list to a buffer.
2746
2747 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2748 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002749 :param CRL crl: The CRL to dump.
2750
Dominic Chenf05b2122015-10-13 16:32:35 +00002751 :return: The buffer with the CRL.
Dan Sully44e767a2016-06-04 18:05:27 -07002752 :rtype: bytes
Dominic Chenf05b2122015-10-13 16:32:35 +00002753 """
2754 bio = _new_mem_buf()
2755
2756 if type == FILETYPE_PEM:
2757 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2758 elif type == FILETYPE_ASN1:
2759 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2760 elif type == FILETYPE_TEXT:
2761 ret = _lib.X509_CRL_print(bio, crl._crl)
2762 else:
2763 raise ValueError(
2764 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2765 "FILETYPE_TEXT")
2766
2767 assert ret == 1
2768 return _bio_to_string(bio)
2769
2770
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002771def load_crl(type, buffer):
2772 """
2773 Load a certificate revocation list from a buffer
2774
2775 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2776 :param buffer: The buffer the CRL is stored in
2777
2778 :return: The PKey object
2779 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002780 if isinstance(buffer, _text_type):
2781 buffer = buffer.encode("ascii")
2782
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002783 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002784
2785 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002786 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002787 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002788 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002789 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002790 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2791
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002792 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002793 _raise_current_error()
2794
2795 result = CRL.__new__(CRL)
2796 result._crl = crl
2797 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002798
2799
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002800def load_pkcs7_data(type, buffer):
2801 """
2802 Load pkcs7 data from a buffer
2803
2804 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2805 :param buffer: The buffer with the pkcs7 data.
2806 :return: The PKCS7 object
2807 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002808 if isinstance(buffer, _text_type):
2809 buffer = buffer.encode("ascii")
2810
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002811 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002812
2813 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002814 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002815 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002816 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002817 else:
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002818 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2819
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002820 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002821 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002822
2823 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002824 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002825 return pypkcs7
2826
2827
Stephen Holsapple38482622014-04-05 20:29:34 -07002828def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002829 """
2830 Load a PKCS12 object from a buffer
2831
2832 :param buffer: The buffer the certificate is stored in
2833 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2834 :returns: The PKCS12 object
2835 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002836 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002837
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002838 if isinstance(buffer, _text_type):
2839 buffer = buffer.encode("ascii")
2840
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002841 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002842
Stephen Holsapple38482622014-04-05 20:29:34 -07002843 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2844 # password based encryption no password and a zero length password are two
2845 # different things, but OpenSSL implementation will try both to figure out
2846 # which one works.
2847 if not passphrase:
2848 passphrase = _ffi.NULL
2849
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002850 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2851 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002852 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002853 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002854
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002855 pkey = _ffi.new("EVP_PKEY**")
2856 cert = _ffi.new("X509**")
2857 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002858
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002859 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002860 if not parse_result:
2861 _raise_current_error()
2862
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002863 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002864
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002865 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2866 # queue for no particular reason. This error isn't interesting to anyone
2867 # outside this function. It's not even interesting to us. Get rid of it.
2868 try:
2869 _raise_current_error()
2870 except Error:
2871 pass
2872
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002873 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002874 pykey = None
2875 else:
2876 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002877 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002878
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002879 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002880 pycert = None
2881 friendlyname = None
2882 else:
2883 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002884 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002885
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002886 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002887 friendlyname_buffer = _lib.X509_alias_get0(
2888 cert[0], friendlyname_length
2889 )
2890 friendlyname = _ffi.buffer(
2891 friendlyname_buffer, friendlyname_length[0]
2892 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002893 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002894 friendlyname = None
2895
2896 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002897 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002898 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002899 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002900 pycacerts.append(pycacert)
2901 if not pycacerts:
2902 pycacerts = None
2903
2904 pkcs12 = PKCS12.__new__(PKCS12)
2905 pkcs12._pkey = pykey
2906 pkcs12._cert = pycert
2907 pkcs12._cacerts = pycacerts
2908 pkcs12._friendlyname = friendlyname
2909 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002910
2911
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002912# There are no direct unit tests for this initialization. It is tested
2913# indirectly since it is necessary for functions like dump_privatekey when
2914# using encryption.
2915#
2916# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2917# and some other similar tests may fail without this (though they may not if
2918# the Python runtime has already done some initialization of the underlying
2919# OpenSSL library (and is linked against the same one that cryptography is
2920# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002921_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002922
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002923# This is similar but exercised mainly by exception_from_error_queue. It calls
2924# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2925_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002926
2927
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002928# Set the default string mask to match OpenSSL upstream (since 2005) and
2929# RFC5280 recommendations.
2930_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')