blob: 2362f6d7d179be94b4d0d2b51344a59708f20760 [file] [log] [blame]
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001import datetime
Paul Kehrer8d887e12015-10-24 09:09:55 -05002
3from time import mktime
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05004from base64 import b16encode
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05005from functools import partial
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05006from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
Jean-Paul Calderone60432792015-04-13 12:26:07 -04007from warnings import warn as _warn
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05008
9from six import (
10 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -040011 text_type as _text_type,
12 PY3 as _PY3)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080013
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050014from OpenSSL._util import (
15 ffi as _ffi,
16 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050017 exception_from_error_queue as _exception_from_error_queue,
18 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040019 native as _native,
20 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040021 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040022)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080023
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050024FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
25FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080026
27# TODO This was an API mistake. OpenSSL has no such constant.
28FILETYPE_TEXT = 2 ** 16 - 1
29
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050030TYPE_RSA = _lib.EVP_PKEY_RSA
31TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080032
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080033
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050034class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050035 """
36 An error occurred in an `OpenSSL.crypto` API.
37 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050038
39
40_raise_current_error = partial(_exception_from_error_queue, Error)
41
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070042
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050043def _untested_error(where):
44 """
45 An OpenSSL API failed somehow. Additionally, the failure which was
46 encountered isn't one that's exercised by the test suite so future behavior
47 of pyOpenSSL is now somewhat less predictable.
48 """
49 raise RuntimeError("Unknown %s failure" % (where,))
50
51
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050052def _new_mem_buf(buffer=None):
53 """
54 Allocate a new OpenSSL memory BIO.
55
56 Arrange for the garbage collector to clean it up automatically.
57
58 :param buffer: None or some bytes to use to put into the BIO so that they
59 can be read out.
60 """
61 if buffer is None:
62 bio = _lib.BIO_new(_lib.BIO_s_mem())
63 free = _lib.BIO_free
64 else:
65 data = _ffi.new("char[]", buffer)
66 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040067
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050068 # Keep the memory alive as long as the bio is alive!
69 def free(bio, ref=data):
70 return _lib.BIO_free(bio)
71
72 if bio == _ffi.NULL:
73 # TODO: This is untested.
74 _raise_current_error()
75
76 bio = _ffi.gc(bio, free)
77 return bio
78
79
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080080def _bio_to_string(bio):
81 """
82 Copy the contents of an OpenSSL BIO object into a Python byte string.
83 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050084 result_buffer = _ffi.new('char**')
85 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
86 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080087
88
Jean-Paul Calderone57122982013-02-21 08:47:05 -080089def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050090 """
91 The the time value of an ASN1 time object.
92
93 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
94 castable to that type) which will have its value set.
95 @param when: A string representation of the desired time value.
96
97 @raise TypeError: If C{when} is not a L{bytes} string.
98 @raise ValueError: If C{when} does not represent a time in the required
99 format.
100 @raise RuntimeError: If the time value cannot be set for some other
101 (unspecified) reason.
102 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800103 if not isinstance(when, bytes):
104 raise TypeError("when must be a byte string")
105
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500106 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
107 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800108 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500109 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
110 _lib.ASN1_STRING_set(dummy, when, len(when))
111 check_result = _lib.ASN1_GENERALIZEDTIME_check(
112 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800113 if not check_result:
114 raise ValueError("Invalid string")
115 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500116 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800117
118
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800119def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500120 """
121 Retrieve the time value of an ASN1 time object.
122
123 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
124 that type) from which the time value will be retrieved.
125
126 @return: The time value from C{timestamp} as a L{bytes} string in a certain
127 format. Or C{None} if the object contains no time value.
128 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500129 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
130 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800131 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400132 elif (
133 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
134 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500135 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800136 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500137 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
138 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
139 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500140 # This may happen:
141 # - if timestamp was not an ASN1_TIME
142 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
143 # - if a copy of the time data from timestamp cannot be made for
144 # the newly allocated ASN1_GENERALIZEDTIME
145 #
146 # These are difficult to test. cffi enforces the ASN1_TIME type.
147 # Memory allocation failures are a pain to trigger
148 # deterministically.
149 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800150 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500151 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800152 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500153 string_data = _lib.ASN1_STRING_data(string_timestamp)
154 string_result = _ffi.string(string_data)
155 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800156 return string_result
157
158
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800159class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200160 """
161 A class representing an DSA or RSA public key or key pair.
162 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800163 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800164 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800165
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800166 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500167 pkey = _lib.EVP_PKEY_new()
168 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800169 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800170
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800171 def generate_key(self, type, bits):
172 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700173 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800174
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200175 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800176
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200177 :param type: The key type.
178 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
179 :param bits: The number of bits.
180 :type bits: :py:data:`int` ``>= 0``
181 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
182 of the appropriate type.
183 :raises ValueError: If the number of bits isn't an integer of
184 the appropriate size.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200185 :return: :py:const:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800186 """
187 if not isinstance(type, int):
188 raise TypeError("type must be an integer")
189
190 if not isinstance(bits, int):
191 raise TypeError("bits must be an integer")
192
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800193 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500194 exponent = _lib.BN_new()
195 exponent = _ffi.gc(exponent, _lib.BN_free)
196 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800197
198 if type == TYPE_RSA:
199 if bits <= 0:
200 raise ValueError("Invalid number of bits")
201
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500202 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500204 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500205 if result == 0:
206 # TODO: The test for this case is commented out. Different
207 # builds of OpenSSL appear to have different failure modes that
208 # make it hard to test. Visual inspection of the OpenSSL
209 # source reveals that a return value of 0 signals an error.
210 # Manual testing on a particular build of OpenSSL suggests that
211 # this is probably the appropriate way to handle those errors.
212 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800213
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500214 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800215 if not result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500216 # TODO: It appears as though this can fail if an engine is in
217 # use which does not support RSA.
218 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800219
220 elif type == TYPE_DSA:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500221 dsa = _lib.DSA_generate_parameters(
222 bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)
223 if dsa == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500224 # TODO: This is untested.
225 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500226 if not _lib.DSA_generate_key(dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500227 # TODO: This is untested.
228 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500229 if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500230 # TODO: This is untested.
231 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800232 else:
233 raise Error("No such key type")
234
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800235 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800236
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800237 def check(self):
238 """
239 Check the consistency of an RSA private key.
240
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200241 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
242
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800243 :return: True if key is consistent.
244 :raise Error: if the key is inconsistent.
245 :raise TypeError: if the key is of a type which cannot be checked.
246 Only RSA keys can currently be checked.
247 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800248 if self._only_public:
249 raise TypeError("public key only")
250
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500251 if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800252 raise TypeError("key type unsupported")
253
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500254 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
255 rsa = _ffi.gc(rsa, _lib.RSA_free)
256 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800257 if result:
258 return True
259 _raise_current_error()
260
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800261 def type(self):
262 """
263 Returns the type of the key
264
265 :return: The type of the key.
266 """
267 return self._pkey.type
268
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800269 def bits(self):
270 """
271 Returns the number of bits of the key
272
273 :return: The number of bits of the key.
274 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500275 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800276PKeyType = PKey
277
278
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400279class _EllipticCurve(object):
280 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400281 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400282
283 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
284 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
285 instances each of which represents one curve supported by the system.
286 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400287 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400288 _curves = None
289
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400290 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400291 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400292 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400293 """
294 Implement cooperation with the right-hand side argument of ``!=``.
295
296 Python 3 seems to have dropped this cooperation in this very narrow
297 circumstance.
298 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400299 if isinstance(other, _EllipticCurve):
300 return super(_EllipticCurve, self).__ne__(other)
301 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400302
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400303 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400304 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400305 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400306 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400307
308 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400309
310 :return: A :py:type:`set` of ``cls`` instances giving the names of the
311 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400312 """
313 if lib.Cryptography_HAS_EC:
314 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
315 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
Alex Gaynor5945ea82015-09-05 14:59:06 -0400316 # The return value on this call should be num_curves again. We
317 # could check it to make sure but if it *isn't* then.. what could
318 # we do? Abort the whole process, I suppose...? -exarkun
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400319 lib.EC_get_builtin_curves(builtin_curves, num_curves)
320 return set(
321 cls.from_nid(lib, c.nid)
322 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400323 return set()
324
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400325 @classmethod
326 def _get_elliptic_curves(cls, lib):
327 """
328 Get, cache, and return the curves supported by OpenSSL.
329
330 :param lib: The OpenSSL library binding object.
331
332 :return: A :py:type:`set` of ``cls`` instances giving the names of the
333 elliptic curves the underlying library supports.
334 """
335 if cls._curves is None:
336 cls._curves = cls._load_elliptic_curves(lib)
337 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400338
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400339 @classmethod
340 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400341 """
342 Instantiate a new :py:class:`_EllipticCurve` associated with the given
343 OpenSSL NID.
344
345 :param lib: The OpenSSL library binding object.
346
347 :param nid: The OpenSSL NID the resulting curve object will represent.
348 This must be a curve NID (and not, for example, a hash NID) or
349 subsequent operations will fail in unpredictable ways.
350 :type nid: :py:class:`int`
351
352 :return: The curve object.
353 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400354 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
355
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400356 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400357 """
358 :param _lib: The :py:mod:`cryptography` binding instance used to
359 interface with OpenSSL.
360
361 :param _nid: The OpenSSL NID identifying the curve this object
362 represents.
363 :type _nid: :py:class:`int`
364
365 :param name: The OpenSSL short name identifying the curve this object
366 represents.
367 :type name: :py:class:`unicode`
368 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400369 self._lib = lib
370 self._nid = nid
371 self.name = name
372
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400373 def __repr__(self):
374 return "<Curve %r>" % (self.name,)
375
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400376 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400377 """
378 Create a new OpenSSL EC_KEY structure initialized to use this curve.
379
380 The structure is automatically garbage collected when the Python object
381 is garbage collected.
382 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400383 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
384 return _ffi.gc(key, _lib.EC_KEY_free)
385
386
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400387def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400388 """
389 Return a set of objects representing the elliptic curves supported in the
390 OpenSSL build in use.
391
392 The curve objects have a :py:class:`unicode` ``name`` attribute by which
393 they identify themselves.
394
395 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400396 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
397 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400398 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400399 return _EllipticCurve._get_elliptic_curves(_lib)
400
401
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400402def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400403 """
404 Return a single curve object selected by name.
405
406 See :py:func:`get_elliptic_curves` for information about curve objects.
407
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400408 :param name: The OpenSSL short name identifying the curve object to
409 retrieve.
410 :type name: :py:class:`unicode`
411
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400412 If the named curve is not supported then :py:class:`ValueError` is raised.
413 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400414 for curve in get_elliptic_curves():
415 if curve.name == name:
416 return curve
417 raise ValueError("unknown curve name", name)
418
419
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800420class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200421 """
422 An X.509 Distinguished Name.
423
424 :ivar countryName: The country of the entity.
425 :ivar C: Alias for :py:attr:`countryName`.
426
427 :ivar stateOrProvinceName: The state or province of the entity.
428 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
429
430 :ivar localityName: The locality of the entity.
431 :ivar L: Alias for :py:attr:`localityName`.
432
433 :ivar organizationName: The organization name of the entity.
434 :ivar O: Alias for :py:attr:`organizationName`.
435
436 :ivar organizationalUnitName: The organizational unit of the entity.
437 :ivar OU: Alias for :py:attr:`organizationalUnitName`
438
439 :ivar commonName: The common name of the entity.
440 :ivar CN: Alias for :py:attr:`commonName`.
441
442 :ivar emailAddress: The e-mail address of the entity.
443 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400444
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800445 def __init__(self, name):
446 """
447 Create a new X509Name, copying the given X509Name instance.
448
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200449 :param name: The name to copy.
450 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800451 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500452 name = _lib.X509_NAME_dup(name._name)
453 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800454
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800455 def __setattr__(self, name, value):
456 if name.startswith('_'):
457 return super(X509Name, self).__setattr__(name, value)
458
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800459 # Note: we really do not want str subclasses here, so we do not use
460 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800461 if type(name) is not str:
462 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400463 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800464
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500465 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500466 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800467 try:
468 _raise_current_error()
469 except Error:
470 pass
471 raise AttributeError("No such attribute")
472
473 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500474 for i in range(_lib.X509_NAME_entry_count(self._name)):
475 ent = _lib.X509_NAME_get_entry(self._name, i)
476 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
477 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800478 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500479 ent = _lib.X509_NAME_delete_entry(self._name, i)
480 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800481 break
482
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500483 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800484 value = value.encode('utf-8')
485
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500486 add_result = _lib.X509_NAME_add_entry_by_NID(
487 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800488 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500489 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800490
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800491 def __getattr__(self, name):
492 """
493 Find attribute. An X509Name object has the following attributes:
494 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400495 organization (alias O), organizationalUnit (alias OU), commonName
496 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800497 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500498 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500499 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800500 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
501 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
502 # push something onto the error queue. If we don't clean that up
503 # now, someone else will bump into it later and be quite confused.
504 # See lp#314814.
505 try:
506 _raise_current_error()
507 except Error:
508 pass
509 return super(X509Name, self).__getattr__(name)
510
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500511 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800512 if entry_index == -1:
513 return None
514
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500515 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
516 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800517
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500518 result_buffer = _ffi.new("unsigned char**")
519 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800520 if data_length < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500521 # TODO: This is untested.
522 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800523
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700524 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400525 result = _ffi.buffer(
526 result_buffer[0], data_length
527 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700528 finally:
529 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500530 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800531 return result
532
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500533 def _cmp(op):
534 def f(self, other):
535 if not isinstance(other, X509Name):
536 return NotImplemented
537 result = _lib.X509_NAME_cmp(self._name, other._name)
538 return op(result, 0)
539 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800540
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500541 __eq__ = _cmp(__eq__)
542 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800543
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500544 __lt__ = _cmp(__lt__)
545 __le__ = _cmp(__le__)
546
547 __gt__ = _cmp(__gt__)
548 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800549
550 def __repr__(self):
551 """
552 String representation of an X509Name
553 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400554 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500555 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800556 self._name, result_buffer, len(result_buffer))
557
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500558 if format_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500559 # TODO: This is untested.
560 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800561
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500562 return "<X509Name object '%s'>" % (
563 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800564
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800565 def hash(self):
566 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200567 Return an integer representation of the first four bytes of the
568 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800569
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200570 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
571
572 :return: The (integer) hash of this name.
573 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800574 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500575 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800576
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800577 def der(self):
578 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200579 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800580
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200581 :return: The DER encoded form of this name.
582 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800583 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500584 result_buffer = _ffi.new('unsigned char**')
585 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800586 if encode_result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500587 # TODO: This is untested.
588 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500590 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
591 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800592 return string_result
593
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800594 def get_components(self):
595 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200596 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800597
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200598 :return: The components of this name.
599 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800600 """
601 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500602 for i in range(_lib.X509_NAME_entry_count(self._name)):
603 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800604
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500605 fname = _lib.X509_NAME_ENTRY_get_object(ent)
606 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800607
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500608 nid = _lib.OBJ_obj2nid(fname)
609 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800610
611 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400612 _ffi.string(name),
613 _ffi.string(
614 _lib.ASN1_STRING_data(fval),
615 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800616
617 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200618
619
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800620X509NameType = X509Name
621
622
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800623class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200624 """
625 An X.509 v3 certificate extension.
626 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400627
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800628 def __init__(self, type_name, critical, value, subject=None, issuer=None):
629 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200630 Initializes an X509 extension.
631
Alex Gaynor6f719912015-09-20 09:21:29 -0400632 :param type_name: The name of the type of extension to create. See
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200633 http://openssl.org/docs/apps/x509v3_config.html#STANDARD_EXTENSIONS
Alex Gaynor6f719912015-09-20 09:21:29 -0400634 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800635
Alex Gaynor5945ea82015-09-05 14:59:06 -0400636 :param bool critical: A flag indicating whether this is a critical
637 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800638
639 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200640 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800641
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200642 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800643 :type subject: :py:class:`X509`
644
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200645 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800646 :type issuer: :py:class:`X509`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800647 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500648 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800649
Alex Gaynor5945ea82015-09-05 14:59:06 -0400650 # A context is necessary for any extension which uses the r2i
651 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
652 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500653 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800654
655 # We have no configuration database - but perhaps we should (some
656 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500657 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800658
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800659 # Initialize the subject and issuer, if appropriate. ctx is a local,
660 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400661 # any references, so no need to mess with reference counts or
662 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800663 if issuer is not None:
664 if not isinstance(issuer, X509):
665 raise TypeError("issuer must be an X509 instance")
666 ctx.issuer_cert = issuer._x509
667 if subject is not None:
668 if not isinstance(subject, X509):
669 raise TypeError("subject must be an X509 instance")
670 ctx.subject_cert = subject._x509
671
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800672 if critical:
673 # There are other OpenSSL APIs which would let us pass in critical
674 # separately, but they're harder to use, and since value is already
675 # a pile of crappy junk smuggling a ton of utterly important
676 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400677 # with strings? (However, X509V3_EXT_i2d in particular seems like
678 # it would be a better API to invoke. I do not know where to get
679 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500680 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800681
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500682 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
683 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800684 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500685 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800686
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400687 @property
688 def _nid(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 return _lib.OBJ_obj2nid(self._extension.object)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400690
691 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500692 _lib.GEN_EMAIL: "email",
693 _lib.GEN_DNS: "DNS",
694 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400695 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400696
697 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500698 method = _lib.X509V3_EXT_get(self._extension)
699 if method == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500700 # TODO: This is untested.
701 _raise_current_error()
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400702 payload = self._extension.value.data
703 length = self._extension.value.length
704
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500705 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400706 payloadptr[0] = payload
707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500708 if method.it != _ffi.NULL:
709 ptr = _lib.ASN1_ITEM_ptr(method.it)
710 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
711 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400712 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500713 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400714 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500715 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400716
Paul Kehrerb7d79502015-05-04 07:43:51 -0500717 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400718 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500719 for i in range(_lib.sk_GENERAL_NAME_num(names)):
720 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400721 try:
722 label = self._prefixes[name.type]
723 except KeyError:
724 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500725 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500726 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400727 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500728 value = _native(
729 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
730 parts.append(label + ":" + value)
731 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400732
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800733 def __str__(self):
734 """
735 :return: a nice text representation of the extension
736 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500737 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400738 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800739
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400740 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500741 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800742 if not print_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500743 # TODO: This is untested.
744 _raise_current_error()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800745
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500746 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800747
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800748 def get_critical(self):
749 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200750 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800751
752 :return: The critical field.
753 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500754 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800755
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800756 def get_short_name(self):
757 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200758 Returns the short type name of this X.509 extension.
759
760 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800761
762 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200763 :rtype: :py:data:`bytes`
764
765 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800766 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 obj = _lib.X509_EXTENSION_get_object(self._extension)
768 nid = _lib.OBJ_obj2nid(obj)
769 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800770
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800771 def get_data(self):
772 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200773 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800774
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200775 :return: The ASN.1 encoded data of this X509 extension.
776 :rtype: :py:data:`bytes`
777
778 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800779 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500780 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
781 string_result = _ffi.cast('ASN1_STRING*', octet_result)
782 char_result = _lib.ASN1_STRING_data(string_result)
783 result_length = _lib.ASN1_STRING_length(string_result)
784 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800785
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200786
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800787X509ExtensionType = X509Extension
788
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800789
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800790class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200791 """
792 An X.509 certificate signing requests.
793 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400794
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800795 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500796 req = _lib.X509_REQ_new()
797 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800798
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800799 def set_pubkey(self, pkey):
800 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200801 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800802
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200803 :param pkey: The public key to use.
804 :type pkey: :py:class:`PKey`
805
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200806 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800807 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500808 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800809 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500810 # TODO: This is untested.
811 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800812
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800813 def get_pubkey(self):
814 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200815 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800816
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200817 :return: The public key.
818 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800819 """
820 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500821 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
822 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500823 # TODO: This is untested.
824 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500825 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800826 pkey._only_public = True
827 return pkey
828
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800829 def set_version(self, version):
830 """
831 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
832 request.
833
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200834 :param int version: The version number.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200835 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800836 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500837 set_result = _lib.X509_REQ_set_version(self._req, version)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800838 if not set_result:
839 _raise_current_error()
840
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800841 def get_version(self):
842 """
843 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
844 request.
845
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200846 :return: The value of the version subfield.
847 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800848 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500849 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800850
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800851 def get_subject(self):
852 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200853 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800854
Cory Benfield881dc8d2015-12-09 08:25:14 +0000855 This creates a new :class:`X509Name` that wraps the underlying subject
856 name field on the certificate signing request. Modifying it will modify
857 the underlying signing request, and will have the effect of modifying
858 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200859
860 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000861 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800862 """
863 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500864 name._name = _lib.X509_REQ_get_subject_name(self._req)
865 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500866 # TODO: This is untested.
867 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800868
869 # The name is owned by the X509Req structure. As long as the X509Name
870 # Python object is alive, keep the X509Req Python object alive.
871 name._owner = self
872
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800873 return name
874
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800875 def add_extensions(self, extensions):
876 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200877 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800878
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200879 :param extensions: The X.509 extensions to add.
880 :type extensions: iterable of :py:class:`X509Extension`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200881 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800882 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500883 stack = _lib.sk_X509_EXTENSION_new_null()
884 if stack == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500885 # TODO: This is untested.
886 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800887
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500888 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800889
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800890 for ext in extensions:
891 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800892 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800893
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800894 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500895 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800896
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500897 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800898 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500899 # TODO: This is untested.
900 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800901
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800902 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800903 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200904 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800905
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200906 :return: The X.509 extensions in this request.
907 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
908
909 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800910 """
911 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500912 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500913 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800914 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500915 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800916 exts.append(ext)
917 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800918
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800919 def sign(self, pkey, digest):
920 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700921 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800922
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200923 :param pkey: The key pair to sign with.
924 :type pkey: :py:class:`PKey`
925 :param digest: The name of the message digest to use for the signature,
926 e.g. :py:data:`b"sha1"`.
927 :type digest: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200928 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800929 """
930 if pkey._only_public:
931 raise ValueError("Key has only public part")
932
933 if not pkey._initialized:
934 raise ValueError("Key is uninitialized")
935
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500936 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500937 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800938 raise ValueError("No such digest method")
939
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500940 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800941 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500942 # TODO: This is untested.
943 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800944
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800945 def verify(self, pkey):
946 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200947 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800948
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200949 :param key: A public key.
950 :type key: :py:class:`PKey`
951 :return: :py:data:`True` if the signature is correct.
952 :rtype: :py:class:`bool`
953 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800954 problem verifying the signature.
955 """
956 if not isinstance(pkey, PKey):
957 raise TypeError("pkey must be a PKey instance")
958
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500959 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800960 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500961 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800962
963 return result
964
965
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800966X509ReqType = X509Req
967
968
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800969class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200970 """
971 An X.509 certificate.
972 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400973
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800974 def __init__(self):
975 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500976 x509 = _lib.X509_new()
977 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800978
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800979 def set_version(self, version):
980 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200981 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800982
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200983 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800984 :type version: :py:class:`int`
985
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200986 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800987 """
988 if not isinstance(version, int):
989 raise TypeError("version must be an integer")
990
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500991 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800992
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800993 def get_version(self):
994 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200995 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800996
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200997 :return: The version number of the certificate.
998 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800999 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001000 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001001
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001002 def get_pubkey(self):
1003 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001004 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001005
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001006 :return: The public key.
1007 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001008 """
1009 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001010 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1011 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001012 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001013 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001014 pkey._only_public = True
1015 return pkey
1016
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001017 def set_pubkey(self, pkey):
1018 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001019 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001020
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001021 :param pkey: The public key.
1022 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001023
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001024 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001025 """
1026 if not isinstance(pkey, PKey):
1027 raise TypeError("pkey must be a PKey instance")
1028
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001029 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001030 if not set_result:
1031 _raise_current_error()
1032
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001033 def sign(self, pkey, digest):
1034 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001035 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001036
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001037 :param pkey: The key to sign with.
1038 :type pkey: :py:class:`PKey`
1039
1040 :param digest: The name of the message digest to use.
1041 :type digest: :py:class:`bytes`
1042
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001043 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001044 """
1045 if not isinstance(pkey, PKey):
1046 raise TypeError("pkey must be a PKey instance")
1047
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001048 if pkey._only_public:
1049 raise ValueError("Key only has public part")
1050
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001051 if not pkey._initialized:
1052 raise ValueError("Key is uninitialized")
1053
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001054 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001055 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001056 raise ValueError("No such digest method")
1057
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001058 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001059 if not sign_result:
1060 _raise_current_error()
1061
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001062 def get_signature_algorithm(self):
1063 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001064 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001065
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001066 :return: The name of the algorithm.
1067 :rtype: :py:class:`bytes`
1068
1069 :raises ValueError: If the signature algorithm is undefined.
1070
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001071 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001072 """
1073 alg = self._x509.cert_info.signature.algorithm
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001074 nid = _lib.OBJ_obj2nid(alg)
1075 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001076 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001077 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001078
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001079 def digest(self, digest_name):
1080 """
1081 Return the digest of the X509 object.
1082
1083 :param digest_name: The name of the digest algorithm to use.
1084 :type digest_name: :py:class:`bytes`
1085
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001086 :return: The digest of the object, formatted as
1087 :py:const:`b":"`-delimited hex pairs.
1088 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001089 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001090 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001091 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001092 raise ValueError("No such digest method")
1093
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001094 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1095 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001096 result_length[0] = len(result_buffer)
1097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001098 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001099 self._x509, digest, result_buffer, result_length)
1100
1101 if not digest_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001102 # TODO: This is untested.
1103 _raise_current_error()
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001104
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001105 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001106 b16encode(ch).upper() for ch
1107 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001108
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001109 def subject_name_hash(self):
1110 """
1111 Return the hash of the X509 subject.
1112
1113 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001114 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001115 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001116 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001117
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001118 def set_serial_number(self, serial):
1119 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001120 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001121
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001122 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001123 :type serial: :py:class:`int`
1124
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001125 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001126 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001127 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001128 raise TypeError("serial must be an integer")
1129
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001130 hex_serial = hex(serial)[2:]
1131 if not isinstance(hex_serial, bytes):
1132 hex_serial = hex_serial.encode('ascii')
1133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001134 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001135
1136 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001137 # it. If bignum is still NULL after this call, then the return value
1138 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001139 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001140
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001141 if bignum_serial[0] == _ffi.NULL:
1142 set_result = _lib.ASN1_INTEGER_set(
1143 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001144 if set_result:
1145 # TODO Not tested
1146 _raise_current_error()
1147 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1149 _lib.BN_free(bignum_serial[0])
1150 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001151 # TODO Not tested
1152 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001153 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1154 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001155 if not set_result:
1156 # TODO Not tested
1157 _raise_current_error()
1158
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001159 def get_serial_number(self):
1160 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001161 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001162
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001163 :return: The serial number.
1164 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001165 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1167 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001168 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001169 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001170 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001171 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001172 serial = int(hexstring_serial, 16)
1173 return serial
1174 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001175 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001176 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001177 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001178
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001179 def gmtime_adj_notAfter(self, amount):
1180 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001181 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001182
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001183 :param amount: The number of seconds by which to adjust the timestamp.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001184 :type amount: :py:class:`int`
1185
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001186 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001187 """
1188 if not isinstance(amount, int):
1189 raise TypeError("amount must be an integer")
1190
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001191 notAfter = _lib.X509_get_notAfter(self._x509)
1192 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001193
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001194 def gmtime_adj_notBefore(self, amount):
1195 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001196 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001197
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001198 :param amount: The number of seconds by which to adjust the timestamp.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001199 :return: :py:const:`None`
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001200 """
1201 if not isinstance(amount, int):
1202 raise TypeError("amount must be an integer")
1203
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001204 notBefore = _lib.X509_get_notBefore(self._x509)
1205 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001206
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001207 def has_expired(self):
1208 """
1209 Check whether the certificate has expired.
1210
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001211 :return: :py:const:`True` if the certificate has expired,
1212 :py:const:`False` otherwise.
1213 :rtype: :py:class:`bool`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001214 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001215 time_string = _native(self.get_notAfter())
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001216 timestamp = mktime(datetime.datetime.strptime(
1217 time_string, "%Y%m%d%H%M%SZ").timetuple())
1218 now = mktime(datetime.datetime.utcnow().timetuple())
1219
1220 return timestamp < now
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001221
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001222 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001223 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001224
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001225 def get_notBefore(self):
1226 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001227 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001228
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001229 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001230
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001231 YYYYMMDDhhmmssZ
1232 YYYYMMDDhhmmss+hhmm
1233 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001234
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001235 :return: A timestamp string, or :py:const:`None` if there is none.
1236 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001237 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001238 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001240 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001241 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001242
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001243 def set_notBefore(self, when):
1244 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001245 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001246
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001247 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001248
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001249 YYYYMMDDhhmmssZ
1250 YYYYMMDDhhmmss+hhmm
1251 YYYYMMDDhhmmss-hhmm
1252
1253 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001254 :type when: :py:class:`bytes`
1255
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001256 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001257 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001258 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001259
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001260 def get_notAfter(self):
1261 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001262 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001263
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001264 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001265
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001266 YYYYMMDDhhmmssZ
1267 YYYYMMDDhhmmss+hhmm
1268 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001269
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001270 :return: A timestamp string, or :py:const:`None` if there is none.
1271 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001272 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001273 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001274
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001275 def set_notAfter(self, when):
1276 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001277 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001278
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001279 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001280
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001281 YYYYMMDDhhmmssZ
1282 YYYYMMDDhhmmss+hhmm
1283 YYYYMMDDhhmmss-hhmm
1284
1285 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001286 :type when: :py:class:`bytes`
1287
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001288 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001289 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001290 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001291
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001292 def _get_name(self, which):
1293 name = X509Name.__new__(X509Name)
1294 name._name = which(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001295 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001296 # TODO: This is untested.
1297 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001298
1299 # The name is owned by the X509 structure. As long as the X509Name
1300 # Python object is alive, keep the X509 Python object alive.
1301 name._owner = self
1302
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001303 return name
1304
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001306 if not isinstance(name, X509Name):
1307 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001308 set_result = which(self._x509, name._name)
1309 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001310 # TODO: This is untested.
1311 _raise_current_error()
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001312
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001313 def get_issuer(self):
1314 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001315 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001316
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001317 This creates a new :py:class:`X509Name`: modifying it does not affect
1318 this certificate.
1319
1320 :return: The issuer of this certificate.
1321 :rtype: :py:class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001322 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001323 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001324
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001325 def set_issuer(self, issuer):
1326 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001327 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001328
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001329 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001330 :type issuer: :py:class:`X509Name`
1331
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001332 :return: :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001333 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001334 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001335
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001336 def get_subject(self):
1337 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001338 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001339
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001340 This creates a new :py:class:`X509Name`: modifying it does not affect
1341 this certificate.
1342
1343 :return: The subject of this certificate.
1344 :rtype: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001345 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001346 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001347
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001348 def set_subject(self, subject):
1349 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001350 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001351
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001352 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001353 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001354
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001355 :return: :py:const:`None`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001356 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001357 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001358
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001359 def get_extension_count(self):
1360 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001361 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001362
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001363 :return: The number of extensions.
1364 :rtype: :py:class:`int`
1365
1366 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001367 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001368 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001369
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001370 def add_extensions(self, extensions):
1371 """
1372 Add extensions to the certificate.
1373
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001374 :param extensions: The extensions to add.
1375 :type extensions: An iterable of :py:class:`X509Extension` objects.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001376 :return: :py:const:`None`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001377 """
1378 for ext in extensions:
1379 if not isinstance(ext, X509Extension):
1380 raise ValueError("One of the elements is not an X509Extension")
1381
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001382 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001383 if not add_result:
1384 _raise_current_error()
1385
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001386 def get_extension(self, index):
1387 """
1388 Get a specific extension of the certificate by index.
1389
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001390 Extensions on a certificate are kept in order. The index
1391 parameter selects which extension will be returned.
1392
1393 :param int index: The index of the extension to retrieve.
1394 :return: The extension at the specified index.
1395 :rtype: :py:class:`X509Extension`
1396 :raises IndexError: If the extension index was out of bounds.
1397
1398 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001399 """
1400 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001401 ext._extension = _lib.X509_get_ext(self._x509, index)
1402 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001403 raise IndexError("extension index out of bounds")
1404
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001405 extension = _lib.X509_EXTENSION_dup(ext._extension)
1406 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001407 return ext
1408
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001409
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001410X509Type = X509
1411
1412
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001413class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001414 """
1415 An X509 certificate store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001416 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001417
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001418 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001419 store = _lib.X509_STORE_new()
1420 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001421
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001422 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001423 """
1424 Adds the certificate :py:data:`cert` to this store.
1425
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +02001426 This is the Python equivalent of OpenSSL's ``X509_STORE_add_cert``.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001427
1428 :param X509 cert: The certificate to add to this store.
1429 :raises TypeError: If the certificate is not an :py:class:`X509`.
1430 :raises Error: If OpenSSL was unhappy with your certificate.
Laurens Van Houtven5ee60b32015-04-23 10:51:16 -07001431 :return: :py:data:`None` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001432 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433 if not isinstance(cert, X509):
1434 raise TypeError()
1435
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001436 result = _lib.X509_STORE_add_cert(self._store, cert._x509)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001437 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001438 _raise_current_error()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001439
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001440
1441X509StoreType = X509Store
1442
1443
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001444class X509StoreContextError(Exception):
1445 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001446 An exception raised when an error occurred while verifying a certificate
1447 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001448
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001449 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001450 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001451 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001452
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001453 def __init__(self, message, certificate):
1454 super(X509StoreContextError, self).__init__(message)
1455 self.certificate = certificate
1456
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001457
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001458class X509StoreContext(object):
1459 """
1460 An X.509 store context.
1461
Jean-Paul Calderone13a81682015-01-18 15:49:15 -05001462 An :py:class:`X509StoreContext` is used to define some of the criteria for
1463 certificate verification. The information encapsulated in this object
1464 includes, but is not limited to, a set of trusted certificates,
1465 verification parameters, and revoked certificates.
1466
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001467 .. note::
1468
1469 Currently, one can only set the trusted certificates on an
1470 :py:class:`X509StoreContext`. Future versions of pyOpenSSL will expose
1471 verification parameters and certificate revocation lists.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001472
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001473 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1474 instance. It is dynamically allocated and automatically garbage
1475 collected.
1476
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001477 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001478
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001479 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001480
1481 :param X509Store store: The certificates which will be trusted for the
1482 purposes of any verifications.
1483
1484 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001485 """
1486
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001487 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001488 store_ctx = _lib.X509_STORE_CTX_new()
1489 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1490 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001491 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001492 # Make the store context available for use after instantiating this
1493 # class by initializing it now. Per testing, subsequent calls to
1494 # :py:meth:`_init` have no adverse affect.
1495 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001496
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001497 def _init(self):
1498 """
1499 Set up the store context for a subsequent verification operation.
1500 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001501 ret = _lib.X509_STORE_CTX_init(
1502 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1503 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001504 if ret <= 0:
1505 _raise_current_error()
1506
1507 def _cleanup(self):
1508 """
1509 Internally cleans up the store context.
1510
1511 The store context can then be reused with a new call to
Stephen Holsapple46a09252015-02-12 14:45:43 -08001512 :py:meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001513 """
1514 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1515
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001516 def _exception_from_context(self):
1517 """
1518 Convert an OpenSSL native context error failure into a Python
1519 exception.
1520
Alex Gaynor5945ea82015-09-05 14:59:06 -04001521 When a call to native OpenSSL X509_verify_cert fails, additional
1522 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001523 """
1524 errors = [
1525 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1526 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1527 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001528 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001529 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001530 # A context error should always be associated with a certificate, so we
1531 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001532 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001533 _cert = _lib.X509_dup(_x509)
1534 pycert = X509.__new__(X509)
1535 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001536 return X509StoreContextError(errors, pycert)
1537
Stephen Holsapple46a09252015-02-12 14:45:43 -08001538 def set_store(self, store):
1539 """
1540 Set the context's trust store.
1541
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001542 .. versionadded:: 0.15
1543
Stephen Holsapple46a09252015-02-12 14:45:43 -08001544 :param X509Store store: The certificates which will be trusted for the
1545 purposes of any *future* verifications.
1546 """
1547 self._store = store
1548
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001549 def verify_certificate(self):
1550 """
1551 Verify a certificate in a context.
1552
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001553 .. versionadded:: 0.15
1554
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001555 :param store_ctx: The :py:class:`X509StoreContext` to verify.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001556
Alex Gaynorca87ff62015-09-04 23:31:03 -04001557 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001558 certificate in the context. Sets ``certificate`` attribute to
1559 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001560 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001561 # Always re-initialize the store context in case
1562 # :py:meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001563 self._init()
1564 ret = _lib.X509_verify_cert(self._store_ctx)
1565 self._cleanup()
1566 if ret <= 0:
1567 raise self._exception_from_context()
1568
1569
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001570def load_certificate(type, buffer):
1571 """
1572 Load a certificate from a buffer
1573
1574 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1575
1576 :param buffer: The buffer the certificate is stored in
1577 :type buffer: :py:class:`bytes`
1578
1579 :return: The X509 object
1580 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001581 if isinstance(buffer, _text_type):
1582 buffer = buffer.encode("ascii")
1583
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001584 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001585
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001586 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001587 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001588 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001589 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001590 else:
1591 raise ValueError(
1592 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001593
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001594 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001595 _raise_current_error()
1596
1597 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001598 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001599 return cert
1600
1601
1602def dump_certificate(type, cert):
1603 """
1604 Dump a certificate to a buffer
1605
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001606 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1607 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001608 :param cert: The certificate to dump
1609 :return: The buffer with the dumped certificate in
1610 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001611 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001612
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001613 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001614 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001615 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001616 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001617 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001618 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001619 else:
1620 raise ValueError(
1621 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1622 "FILETYPE_TEXT")
1623
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001624 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001625 return _bio_to_string(bio)
1626
1627
Cory Benfield6492f7c2015-10-27 16:57:58 +09001628def dump_publickey(type, pkey):
1629 """
Cory Benfield11c10192015-10-27 17:23:03 +09001630 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001631
Cory Benfield9c590b92015-10-28 14:55:05 +09001632 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001633 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001634 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001635 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001636 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001637 """
1638 bio = _new_mem_buf()
1639 if type == FILETYPE_PEM:
1640 write_bio = _lib.PEM_write_bio_PUBKEY
1641 elif type == FILETYPE_ASN1:
1642 write_bio = _lib.i2d_PUBKEY_bio
1643 else:
1644 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1645
1646 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001647 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001648 _raise_current_error()
1649
1650 return _bio_to_string(bio)
1651
1652
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001653def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1654 """
1655 Dump a private key to a buffer
1656
Jean-Paul Calderonee66fde22013-04-03 08:35:08 -04001657 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1658 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001659 :param pkey: The PKey to dump
1660 :param cipher: (optional) if encrypted PEM format, the cipher to
1661 use
1662 :param passphrase: (optional) if encrypted PEM format, this can be either
1663 the passphrase to use, or a callback for providing the
1664 passphrase.
1665 :return: The buffer with the dumped key in
Maximilian Hils0de43752015-09-18 15:26:54 +02001666 :rtype: :py:data:`bytes`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001667 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001668 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001669
1670 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001671 if passphrase is None:
1672 raise TypeError(
1673 "if a value is given for cipher "
1674 "one must also be given for passphrase")
1675 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001676 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001677 raise ValueError("Invalid cipher name")
1678 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001679 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001680
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001681 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001682 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001683 result_code = _lib.PEM_write_bio_PrivateKey(
1684 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001685 helper.callback, helper.callback_args)
1686 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001687 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001688 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001689 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001690 rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)
1691 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001692 # TODO RSA_free(rsa)?
1693 else:
1694 raise ValueError(
1695 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1696 "FILETYPE_TEXT")
1697
1698 if result_code == 0:
1699 _raise_current_error()
1700
1701 return _bio_to_string(bio)
1702
1703
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001704def _X509_REVOKED_dup(original):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001705 copy = _lib.X509_REVOKED_new()
1706 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001707 # TODO: This is untested.
1708 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001709
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001710 if original.serialNumber != _ffi.NULL:
Jonathan Giannuzzib5b93222014-03-20 15:54:29 +01001711 _lib.ASN1_INTEGER_free(copy.serialNumber)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001712 copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001713
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001714 if original.revocationDate != _ffi.NULL:
Jonathan Giannuzzib5b93222014-03-20 15:54:29 +01001715 _lib.ASN1_TIME_free(copy.revocationDate)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001716 copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001717
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001718 if original.extensions != _ffi.NULL:
1719 extension_stack = _lib.sk_X509_EXTENSION_new_null()
1720 for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):
1721 original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)
1722 copy_ext = _lib.X509_EXTENSION_dup(original_ext)
1723 _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001724 copy.extensions = extension_stack
1725
1726 copy.sequence = original.sequence
1727 return copy
1728
1729
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001730class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001731 """
1732 A certificate revocation.
1733 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001734 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1735 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1736 # OCSP_crl_reason_str. We use the latter, just like the command line
1737 # program.
1738 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001739 b"unspecified",
1740 b"keyCompromise",
1741 b"CACompromise",
1742 b"affiliationChanged",
1743 b"superseded",
1744 b"cessationOfOperation",
1745 b"certificateHold",
1746 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001747 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001748
1749 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001750 revoked = _lib.X509_REVOKED_new()
1751 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001752
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001753 def set_serial(self, hex_str):
1754 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001755 Set the serial number.
1756
1757 The serial number is formatted as a hexadecimal number encoded in
1758 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001759
1760 :param hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001761 :type hex_str: :py:class:`bytes`
1762
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001763 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001764 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001765 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1766 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001767 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001768 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001769 if not bn_result:
1770 raise ValueError("bad hex string")
1771
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001772 asn1_serial = _ffi.gc(
1773 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1774 _lib.ASN1_INTEGER_free)
1775 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001776
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001777 def get_serial(self):
1778 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001779 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001780
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001781 The serial number is formatted as a hexadecimal number encoded in
1782 ASCII.
1783
1784 :return: The serial number.
1785 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001786 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001787 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001788
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001789 result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001790 if result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001791 # TODO: This is untested.
1792 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001793
1794 return _bio_to_string(bio)
1795
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001796 def _delete_reason(self):
1797 stack = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001798 for i in range(_lib.sk_X509_EXTENSION_num(stack)):
1799 ext = _lib.sk_X509_EXTENSION_value(stack, i)
1800 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
1801 _lib.X509_EXTENSION_free(ext)
1802 _lib.sk_X509_EXTENSION_delete(stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001803 break
1804
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001805 def set_reason(self, reason):
1806 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001807 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001808
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001809 If :py:data:`reason` is :py:const:`None`, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001810
1811 :param reason: The reason string.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001812 :type reason: :py:class:`bytes` or :py:class:`NoneType`
1813
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001814 :return: :py:const:`None`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001815
1816 .. seealso::
1817
1818 :py:meth:`all_reasons`, which gives you a list of all supported
1819 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001820 """
1821 if reason is None:
1822 self._delete_reason()
1823 elif not isinstance(reason, bytes):
1824 raise TypeError("reason must be None or a byte string")
1825 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001826 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001827 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1828
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001829 new_reason_ext = _lib.ASN1_ENUMERATED_new()
1830 if new_reason_ext == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001831 # TODO: This is untested.
1832 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001833 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001834
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001835 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
1836 if set_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001837 # TODO: This is untested.
1838 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001839
1840 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001841 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1842 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001843
1844 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001845 # TODO: This is untested.
1846 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001848 def get_reason(self):
1849 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001850 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001851
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001852 :return: The reason, or :py:const:`None` if there is none.
1853 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1854
1855 .. seealso::
1856
1857 :py:meth:`all_reasons`, which gives you a list of all supported
1858 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001859 """
1860 extensions = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001861 for i in range(_lib.sk_X509_EXTENSION_num(extensions)):
1862 ext = _lib.sk_X509_EXTENSION_value(extensions, i)
1863 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001864 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001865
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001866 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001867 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001868 print_result = _lib.M_ASN1_OCTET_STRING_print(
1869 bio, ext.value
1870 )
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001871 if print_result == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001872 # TODO: This is untested.
1873 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001874
1875 return _bio_to_string(bio)
1876
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001877 def all_reasons(self):
1878 """
1879 Return a list of all the supported reason strings.
1880
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001881 This list is a copy; modifying it does not change the supported reason
1882 strings.
1883
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001884 :return: A list of reason strings.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001885 :rtype: :py:class:`list` of :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001886 """
1887 return self._crl_reasons[:]
1888
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001889 def set_rev_date(self, when):
1890 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001891 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001892
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001893 :param when: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1894 :type when: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001895 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001896 """
1897 return _set_asn1_time(self._revoked.revocationDate, when)
1898
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001899 def get_rev_date(self):
1900 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001901 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001902
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001903 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1904 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001905 """
1906 return _get_asn1_time(self._revoked.revocationDate)
1907
1908
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001909class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001910 """
1911 A certificate revocation list.
1912 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001913
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001914 def __init__(self):
1915 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001916 Create a new empty certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001917 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001918 crl = _lib.X509_CRL_new()
1919 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001920
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001921 def get_revoked(self):
1922 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001923 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001924
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001925 These revocations will be provided by value, not by reference.
1926 That means it's okay to mutate them: it won't affect this CRL.
1927
1928 :return: The revocations in this CRL.
1929 :rtype: :py:class:`tuple` of :py:class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001930 """
1931 results = []
1932 revoked_stack = self._crl.crl.revoked
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001933 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1934 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001935 revoked_copy = _X509_REVOKED_dup(revoked)
1936 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001937 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001938 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001939 if results:
1940 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001941
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001942 def add_revoked(self, revoked):
1943 """
1944 Add a revoked (by value not reference) to the CRL structure
1945
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001946 This revocation will be added by value, not by reference. That
1947 means it's okay to mutate it after adding: it won't affect
1948 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001949
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001950 :param revoked: The new revocation.
1951 :type revoked: :class:`Revoked`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001952
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001953 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001954 """
1955 copy = _X509_REVOKED_dup(revoked._revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001956 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001957 # TODO: This is untested.
1958 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001959
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001960 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001961 if add_result == 0:
1962 # TODO: This is untested.
1963 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001964
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001965 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001966 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001967 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001968 Export a CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001969
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001970 :param cert: The certificate used to sign the CRL.
1971 :type cert: :py:class:`X509`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001972
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001973 :param key: The key used to sign the CRL.
1974 :type key: :py:class:`PKey`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001975
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001976 :param type: The export format, either :py:data:`FILETYPE_PEM`,
1977 :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001978
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04001979 :param int days: The number of days until the next update of this CRL.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04001980
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001981 :param bytes digest: The name of the message digest to use (eg
1982 ``b"sha1"``).
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001983
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001984 :return: :py:data:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001985 """
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001986 if not isinstance(cert, X509):
1987 raise TypeError("cert must be an X509 instance")
1988 if not isinstance(key, PKey):
1989 raise TypeError("key must be a PKey instance")
1990 if not isinstance(type, int):
1991 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001992
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001993 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001994 _warn(
1995 "The default message digest (md5) is deprecated. "
1996 "Pass the name of a message digest explicitly.",
1997 category=DeprecationWarning,
1998 stacklevel=2,
1999 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002000 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04002001
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04002002 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002003 if digest_obj == _ffi.NULL:
2004 raise ValueError("No such digest method")
2005
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002006 bio = _lib.BIO_new(_lib.BIO_s_mem())
2007 if bio == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002008 # TODO: This is untested.
2009 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002010
Alex Gaynora738ed52015-09-05 11:17:10 -04002011 # A scratch time object to give different values to different CRL
2012 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002013 sometime = _lib.ASN1_TIME_new()
2014 if sometime == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002015 # TODO: This is untested.
2016 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002017
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002018 _lib.X509_gmtime_adj(sometime, 0)
2019 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002020
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002021 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2022 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002023
Alex Gaynor5945ea82015-09-05 14:59:06 -04002024 _lib.X509_CRL_set_issuer_name(
2025 self._crl, _lib.X509_get_subject_name(cert._x509)
2026 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002027
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002028 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002029 if not sign_result:
2030 _raise_current_error()
2031
Dominic Chenf05b2122015-10-13 16:32:35 +00002032 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002033
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002034
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002035CRLType = CRL
2036
2037
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002038class PKCS7(object):
2039 def type_is_signed(self):
2040 """
2041 Check if this NID_pkcs7_signed object
2042
2043 :return: True if the PKCS7 is of type signed
2044 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002045 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002046 return True
2047 return False
2048
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002049 def type_is_enveloped(self):
2050 """
2051 Check if this NID_pkcs7_enveloped object
2052
2053 :returns: True if the PKCS7 is of type enveloped
2054 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002055 if _lib.PKCS7_type_is_enveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002056 return True
2057 return False
2058
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002059 def type_is_signedAndEnveloped(self):
2060 """
2061 Check if this NID_pkcs7_signedAndEnveloped object
2062
2063 :returns: True if the PKCS7 is of type signedAndEnveloped
2064 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002065 if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002066 return True
2067 return False
2068
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002069 def type_is_data(self):
2070 """
2071 Check if this NID_pkcs7_data object
2072
2073 :return: True if the PKCS7 is of type data
2074 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002075 if _lib.PKCS7_type_is_data(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002076 return True
2077 return False
2078
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002079 def get_type_name(self):
2080 """
2081 Returns the type name of the PKCS7 structure
2082
2083 :return: A string with the typename
2084 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002085 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2086 string_type = _lib.OBJ_nid2sn(nid)
2087 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002088
2089PKCS7Type = PKCS7
2090
2091
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002092class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002093 """
2094 A PKCS #12 archive.
2095 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002096
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002097 def __init__(self):
2098 self._pkey = None
2099 self._cert = None
2100 self._cacerts = None
2101 self._friendlyname = None
2102
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002103 def get_certificate(self):
2104 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002105 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002106
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002107 :return: The certificate, or :py:const:`None` if there is none.
2108 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002109 """
2110 return self._cert
2111
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002112 def set_certificate(self, cert):
2113 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002114 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002115
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002116 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002117 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002118
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002119 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002120 """
2121 if not isinstance(cert, X509):
2122 raise TypeError("cert must be an X509 instance")
2123 self._cert = cert
2124
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002125 def get_privatekey(self):
2126 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002127 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002128
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002129 :return: The private key, or :py:const:`None` if there is none.
2130 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002131 """
2132 return self._pkey
2133
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002134 def set_privatekey(self, pkey):
2135 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002136 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002137
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002138 :param pkey: The new private key, or :py:const:`None` to unset it.
2139 :type pkey: :py:class:`PKey` or :py:const:`None`
2140
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002141 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002142 """
2143 if not isinstance(pkey, PKey):
2144 raise TypeError("pkey must be a PKey instance")
2145 self._pkey = pkey
2146
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002147 def get_ca_certificates(self):
2148 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002149 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002150
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002151 :return: A tuple with the CA certificates in the chain, or
2152 :py:const:`None` if there are none.
2153 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002154 """
2155 if self._cacerts is not None:
2156 return tuple(self._cacerts)
2157
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002158 def set_ca_certificates(self, cacerts):
2159 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002160 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002161
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002162 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2163 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002164 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002165
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002166 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002167 """
2168 if cacerts is None:
2169 self._cacerts = None
2170 else:
2171 cacerts = list(cacerts)
2172 for cert in cacerts:
2173 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002174 raise TypeError(
2175 "iterable must only contain X509 instances"
2176 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002177 self._cacerts = cacerts
2178
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002179 def set_friendlyname(self, name):
2180 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002181 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002182
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002183 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002184 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002185
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002186 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002187 """
2188 if name is None:
2189 self._friendlyname = None
2190 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002191 raise TypeError(
2192 "name must be a byte string or None (not %r)" % (name,)
2193 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002194 self._friendlyname = name
2195
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002196 def get_friendlyname(self):
2197 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002198 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002199
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002200 :returns: The friendly name, or :py:const:`None` if there is none.
2201 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002202 """
2203 return self._friendlyname
2204
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002205 def export(self, passphrase=None, iter=2048, maciter=1):
2206 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002207 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002208
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002209 For more information, see the :c:func:`PKCS12_create` man page.
2210
2211 :param passphrase: The passphrase used to encrypt the structure. Unlike
2212 some other passphrase arguments, this *must* be a string, not a
2213 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002214 :type passphrase: :py:data:`bytes`
2215
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002216 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217 :type iter: :py:data:`int`
2218
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002219 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002220 :type maciter: :py:data:`int`
2221
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002222 :return: The string representation of the PKCS #12 structure.
2223 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002224 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002225 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002226
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002227 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002228 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002229 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002230 cacerts = _lib.sk_X509_new_null()
2231 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002232 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002233 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002234
2235 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002236 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002237
2238 friendlyname = self._friendlyname
2239 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002240 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002241
2242 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002243 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002244 else:
2245 pkey = self._pkey._pkey
2246
2247 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002248 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002249 else:
2250 cert = self._cert._x509
2251
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002252 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002253 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002254 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2255 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002256 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002257 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002258 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002259 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002260
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002261 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002262 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002263 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002264
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002265
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002266PKCS12Type = PKCS12
2267
2268
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002269class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002270 """
2271 A Netscape SPKI object.
2272 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002273
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002274 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002275 spki = _lib.NETSCAPE_SPKI_new()
2276 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002277
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002278 def sign(self, pkey, digest):
2279 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002280 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002281
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002282 :param pkey: The private key to sign with.
2283 :type pkey: :py:class:`PKey`
2284
2285 :param digest: The message digest to use.
2286 :type digest: :py:class:`bytes`
2287
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002288 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002289 """
2290 if pkey._only_public:
2291 raise ValueError("Key has only public part")
2292
2293 if not pkey._initialized:
2294 raise ValueError("Key is uninitialized")
2295
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002296 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002297 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002298 raise ValueError("No such digest method")
2299
Alex Gaynor5945ea82015-09-05 14:59:06 -04002300 sign_result = _lib.NETSCAPE_SPKI_sign(
2301 self._spki, pkey._pkey, digest_obj
2302 )
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002303 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002304 # TODO: This is untested.
2305 _raise_current_error()
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002306
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002307 def verify(self, key):
2308 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002309 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002310
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002311 :param key: The public key that signature is supposedly from.
2312 :type pkey: :py:class:`PKey`
2313
2314 :return: :py:const:`True` if the signature is correct.
2315 :rtype: :py:class:`bool`
2316
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002317 :raises Error: If the signature is invalid, or there was a problem
2318 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002319 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002320 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002321 if answer <= 0:
2322 _raise_current_error()
2323 return True
2324
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002325 def b64_encode(self):
2326 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002327 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002328
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002329 :return: The base64 encoded string.
2330 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002331 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002332 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2333 result = _ffi.string(encoded)
2334 _lib.CRYPTO_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002335 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002336
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002337 def get_pubkey(self):
2338 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002339 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002340
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002341 :return: The public key.
2342 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002343 """
2344 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002345 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
2346 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002347 # TODO: This is untested.
2348 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002349 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002350 pkey._only_public = True
2351 return pkey
2352
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002353 def set_pubkey(self, pkey):
2354 """
2355 Set the public key of the certificate
2356
2357 :param pkey: The public key
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002358 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002359 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002360 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002361 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002362 # TODO: This is untested.
2363 _raise_current_error()
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002364
2365
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002366NetscapeSPKIType = NetscapeSPKI
2367
2368
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002369class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002370 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002371 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002372 raise ValueError(
2373 "only FILETYPE_PEM key format supports encryption"
2374 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002375 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002376 self._more_args = more_args
2377 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002378 self._problems = []
2379
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002380 @property
2381 def callback(self):
2382 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002383 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002384 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002385 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002386 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002387 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002388 else:
2389 raise TypeError("Last argument must be string or callable")
2390
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002391 @property
2392 def callback_args(self):
2393 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002394 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002395 elif isinstance(self._passphrase, bytes):
2396 return self._passphrase
2397 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002398 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002399 else:
2400 raise TypeError("Last argument must be string or callable")
2401
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002402 def raise_if_problem(self, exceptionType=Error):
2403 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002404 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002405 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002406 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002407 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002408 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002409 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002410
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002411 def _read_passphrase(self, buf, size, rwflag, userdata):
2412 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002413 if self._more_args:
2414 result = self._passphrase(size, rwflag, userdata)
2415 else:
2416 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002417 if not isinstance(result, bytes):
2418 raise ValueError("String expected")
2419 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002420 if self._truncate:
2421 result = result[:size]
2422 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002423 raise ValueError(
2424 "passphrase returned by callback is too long"
2425 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002426 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002427 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002428 return len(result)
2429 except Exception as e:
2430 self._problems.append(e)
2431 return 0
2432
2433
Cory Benfield6492f7c2015-10-27 16:57:58 +09002434def load_publickey(type, buffer):
2435 """
Cory Benfield11c10192015-10-27 17:23:03 +09002436 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002437
Cory Benfield9c590b92015-10-28 14:55:05 +09002438 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002439 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002440 :param buffer: The buffer the key is stored in.
2441 :type buffer: A Python string object, either unicode or bytestring.
2442 :return: The PKey object.
2443 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002444 """
2445 if isinstance(buffer, _text_type):
2446 buffer = buffer.encode("ascii")
2447
2448 bio = _new_mem_buf(buffer)
2449
2450 if type == FILETYPE_PEM:
2451 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2452 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2453 elif type == FILETYPE_ASN1:
2454 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2455 else:
2456 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2457
2458 if evp_pkey == _ffi.NULL:
2459 _raise_current_error()
2460
2461 pkey = PKey.__new__(PKey)
2462 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
2463 return pkey
2464
2465
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002466def load_privatekey(type, buffer, passphrase=None):
2467 """
2468 Load a private key from a buffer
2469
2470 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2471 :param buffer: The buffer the key is stored in
2472 :param passphrase: (optional) if encrypted PEM format, this can be
2473 either the passphrase to use, or a callback for
2474 providing the passphrase.
2475
2476 :return: The PKey object
2477 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002478 if isinstance(buffer, _text_type):
2479 buffer = buffer.encode("ascii")
2480
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002481 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002482
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002483 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002484 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002485 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2486 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002487 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002488 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002489 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002490 else:
2491 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2492
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002493 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002494 _raise_current_error()
2495
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002496 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002497 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002498 return pkey
2499
2500
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002501def dump_certificate_request(type, req):
2502 """
2503 Dump a certificate request to a buffer
2504
2505 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2506 :param req: The certificate request to dump
2507 :return: The buffer with the dumped certificate request in
2508 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002509 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002510
2511 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002512 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002513 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002514 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002515 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002516 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002517 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002518 raise ValueError(
2519 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2520 "FILETYPE_TEXT"
2521 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002522
2523 if result_code == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002524 # TODO: This is untested.
2525 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002526
2527 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002528
2529
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002530def load_certificate_request(type, buffer):
2531 """
2532 Load a certificate request from a buffer
2533
2534 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2535 :param buffer: The buffer the certificate request is stored in
2536 :return: The X509Req object
2537 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002538 if isinstance(buffer, _text_type):
2539 buffer = buffer.encode("ascii")
2540
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002541 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002542
2543 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002544 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002545 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002546 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002547 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002548 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002549
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002550 if req == _ffi.NULL:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002551 # TODO: This is untested.
2552 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002553
2554 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002555 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002556 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002557
2558
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002559def sign(pkey, data, digest):
2560 """
2561 Sign data with a digest
2562
2563 :param pkey: Pkey to sign with
2564 :param data: data to be signed
2565 :param digest: message digest to use
2566 :return: signature
2567 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002568 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002569
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002570 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002571 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002572 raise ValueError("No such digest method")
2573
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002574 md_ctx = _ffi.new("EVP_MD_CTX*")
2575 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002576
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002577 _lib.EVP_SignInit(md_ctx, digest_obj)
2578 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002579
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002580 signature_buffer = _ffi.new("unsigned char[]", 512)
2581 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002582 signature_length[0] = len(signature_buffer)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002583 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002584 md_ctx, signature_buffer, signature_length, pkey._pkey)
2585
2586 if final_result != 1:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002587 # TODO: This is untested.
2588 _raise_current_error()
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002590 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002591
2592
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002593def verify(cert, signature, data, digest):
2594 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002595 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002596
2597 :param cert: signing certificate (X509 object)
2598 :param signature: signature returned by sign function
2599 :param data: data to be verified
2600 :param digest: message digest to use
Alex Gaynor5945ea82015-09-05 14:59:06 -04002601 :return: :py:const:`None` if the signature is correct, raise exception
2602 otherwise
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002603 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002604 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002605
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002606 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002607 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002608 raise ValueError("No such digest method")
2609
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002610 pkey = _lib.X509_get_pubkey(cert._x509)
2611 if pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002612 # TODO: This is untested.
2613 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002614 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002615
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002616 md_ctx = _ffi.new("EVP_MD_CTX*")
2617 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002618
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002619 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2620 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002621 verify_result = _lib.EVP_VerifyFinal(
2622 md_ctx, signature, len(signature), pkey
2623 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002624
2625 if verify_result != 1:
2626 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002627
2628
Dominic Chenf05b2122015-10-13 16:32:35 +00002629def dump_crl(type, crl):
2630 """
2631 Dump a certificate revocation list to a buffer.
2632
2633 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2634 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002635 :param CRL crl: The CRL to dump.
2636
Dominic Chenf05b2122015-10-13 16:32:35 +00002637 :return: The buffer with the CRL.
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002638 :rtype: :data:`bytes`
Dominic Chenf05b2122015-10-13 16:32:35 +00002639 """
2640 bio = _new_mem_buf()
2641
2642 if type == FILETYPE_PEM:
2643 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2644 elif type == FILETYPE_ASN1:
2645 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2646 elif type == FILETYPE_TEXT:
2647 ret = _lib.X509_CRL_print(bio, crl._crl)
2648 else:
2649 raise ValueError(
2650 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2651 "FILETYPE_TEXT")
2652
2653 assert ret == 1
2654 return _bio_to_string(bio)
2655
2656
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002657def load_crl(type, buffer):
2658 """
2659 Load a certificate revocation list from a buffer
2660
2661 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2662 :param buffer: The buffer the CRL is stored in
2663
2664 :return: The PKey object
2665 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002666 if isinstance(buffer, _text_type):
2667 buffer = buffer.encode("ascii")
2668
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002669 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002670
2671 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002672 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002673 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002674 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002675 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002676 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2677
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002678 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002679 _raise_current_error()
2680
2681 result = CRL.__new__(CRL)
2682 result._crl = crl
2683 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002684
2685
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002686def load_pkcs7_data(type, buffer):
2687 """
2688 Load pkcs7 data from a buffer
2689
2690 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2691 :param buffer: The buffer with the pkcs7 data.
2692 :return: The PKCS7 object
2693 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002694 if isinstance(buffer, _text_type):
2695 buffer = buffer.encode("ascii")
2696
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002697 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002698
2699 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002700 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002701 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002702 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002703 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002704 # TODO: This is untested.
2705 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002706 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2707
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002708 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002709 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002710
2711 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002712 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002713 return pypkcs7
2714
2715
Stephen Holsapple38482622014-04-05 20:29:34 -07002716def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002717 """
2718 Load a PKCS12 object from a buffer
2719
2720 :param buffer: The buffer the certificate is stored in
2721 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2722 :returns: The PKCS12 object
2723 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002724 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002725
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002726 if isinstance(buffer, _text_type):
2727 buffer = buffer.encode("ascii")
2728
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002729 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002730
Stephen Holsapple38482622014-04-05 20:29:34 -07002731 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2732 # password based encryption no password and a zero length password are two
2733 # different things, but OpenSSL implementation will try both to figure out
2734 # which one works.
2735 if not passphrase:
2736 passphrase = _ffi.NULL
2737
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002738 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2739 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002740 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002741 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002742
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002743 pkey = _ffi.new("EVP_PKEY**")
2744 cert = _ffi.new("X509**")
2745 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002746
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002747 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002748 if not parse_result:
2749 _raise_current_error()
2750
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002751 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002752
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002753 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2754 # queue for no particular reason. This error isn't interesting to anyone
2755 # outside this function. It's not even interesting to us. Get rid of it.
2756 try:
2757 _raise_current_error()
2758 except Error:
2759 pass
2760
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002761 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002762 pykey = None
2763 else:
2764 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002765 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002766
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002767 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002768 pycert = None
2769 friendlyname = None
2770 else:
2771 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002772 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002773
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002774 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002775 friendlyname_buffer = _lib.X509_alias_get0(
2776 cert[0], friendlyname_length
2777 )
2778 friendlyname = _ffi.buffer(
2779 friendlyname_buffer, friendlyname_length[0]
2780 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002781 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002782 friendlyname = None
2783
2784 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002785 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002786 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002787 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002788 pycacerts.append(pycacert)
2789 if not pycacerts:
2790 pycacerts = None
2791
2792 pkcs12 = PKCS12.__new__(PKCS12)
2793 pkcs12._pkey = pykey
2794 pkcs12._cert = pycert
2795 pkcs12._cacerts = pycacerts
2796 pkcs12._friendlyname = friendlyname
2797 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002798
2799
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002800# There are no direct unit tests for this initialization. It is tested
2801# indirectly since it is necessary for functions like dump_privatekey when
2802# using encryption.
2803#
2804# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2805# and some other similar tests may fail without this (though they may not if
2806# the Python runtime has already done some initialization of the underlying
2807# OpenSSL library (and is linked against the same one that cryptography is
2808# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002809_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002810
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002811# This is similar but exercised mainly by exception_from_error_queue. It calls
2812# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2813_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002814
2815
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002816# Set the default string mask to match OpenSSL upstream (since 2005) and
2817# RFC5280 recommendations.
2818_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')