blob: 21bdadd7a2fac023069741387ea8895dc1cf95b3 [file] [log] [blame]
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001import datetime
Paul Kehrer8d887e12015-10-24 09:09:55 -05002
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05003from base64 import b16encode
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05004from functools import partial
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05005from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
Jean-Paul Calderone60432792015-04-13 12:26:07 -04006from warnings import warn as _warn
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05007
8from six import (
9 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -040010 text_type as _text_type,
11 PY3 as _PY3)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080012
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050013from OpenSSL._util import (
14 ffi as _ffi,
15 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050016 exception_from_error_queue as _exception_from_error_queue,
17 byte_string as _byte_string,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040018 native as _native,
19 UNSPECIFIED as _UNSPECIFIED,
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -040020 text_to_bytes_and_warn as _text_to_bytes_and_warn,
Alex Gaynor67903a62016-06-02 10:37:13 -070021 make_assert as _make_assert,
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)
Alex Gaynor67903a62016-06-02 10:37:13 -070041_openssl_assert = _make_assert(Error)
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050042
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070043
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050044def _untested_error(where):
45 """
46 An OpenSSL API failed somehow. Additionally, the failure which was
47 encountered isn't one that's exercised by the test suite so future behavior
48 of pyOpenSSL is now somewhat less predictable.
49 """
50 raise RuntimeError("Unknown %s failure" % (where,))
51
52
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050053def _new_mem_buf(buffer=None):
54 """
55 Allocate a new OpenSSL memory BIO.
56
57 Arrange for the garbage collector to clean it up automatically.
58
59 :param buffer: None or some bytes to use to put into the BIO so that they
60 can be read out.
61 """
62 if buffer is None:
63 bio = _lib.BIO_new(_lib.BIO_s_mem())
64 free = _lib.BIO_free
65 else:
66 data = _ffi.new("char[]", buffer)
67 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040068
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050069 # Keep the memory alive as long as the bio is alive!
70 def free(bio, ref=data):
71 return _lib.BIO_free(bio)
72
73 if bio == _ffi.NULL:
74 # TODO: This is untested.
75 _raise_current_error()
76
77 bio = _ffi.gc(bio, free)
78 return bio
79
80
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080081def _bio_to_string(bio):
82 """
83 Copy the contents of an OpenSSL BIO object into a Python byte string.
84 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050085 result_buffer = _ffi.new('char**')
86 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
87 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080088
89
Jean-Paul Calderone57122982013-02-21 08:47:05 -080090def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050091 """
92 The the time value of an ASN1 time object.
93
94 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
95 castable to that type) which will have its value set.
96 @param when: A string representation of the desired time value.
97
98 @raise TypeError: If C{when} is not a L{bytes} string.
99 @raise ValueError: If C{when} does not represent a time in the required
100 format.
101 @raise RuntimeError: If the time value cannot be set for some other
102 (unspecified) reason.
103 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800104 if not isinstance(when, bytes):
105 raise TypeError("when must be a byte string")
106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500107 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
108 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800109 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500110 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
111 _lib.ASN1_STRING_set(dummy, when, len(when))
112 check_result = _lib.ASN1_GENERALIZEDTIME_check(
113 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800114 if not check_result:
115 raise ValueError("Invalid string")
116 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500117 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800118
Alex Gaynor510293e2016-06-02 12:07:59 -0700119
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800120def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500121 """
122 Retrieve the time value of an ASN1 time object.
123
124 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
125 that type) from which the time value will be retrieved.
126
127 @return: The time value from C{timestamp} as a L{bytes} string in a certain
128 format. Or C{None} if the object contains no time value.
129 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500130 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
131 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800132 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400133 elif (
134 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
135 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500136 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800137 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500138 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
139 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
140 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500141 # This may happen:
142 # - if timestamp was not an ASN1_TIME
143 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
144 # - if a copy of the time data from timestamp cannot be made for
145 # the newly allocated ASN1_GENERALIZEDTIME
146 #
147 # These are difficult to test. cffi enforces the ASN1_TIME type.
148 # Memory allocation failures are a pain to trigger
149 # deterministically.
150 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800151 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800153 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500154 string_data = _lib.ASN1_STRING_data(string_timestamp)
155 string_result = _ffi.string(string_data)
156 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800157 return string_result
158
159
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800160class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200161 """
162 A class representing an DSA or RSA public key or key pair.
163 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800164 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800165 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800166
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800167 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500168 pkey = _lib.EVP_PKEY_new()
169 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800170 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800171
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800172 def generate_key(self, type, bits):
173 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700174 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800175
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200176 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800177
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200178 :param type: The key type.
179 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
180 :param bits: The number of bits.
181 :type bits: :py:data:`int` ``>= 0``
182 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
183 of the appropriate type.
184 :raises ValueError: If the number of bits isn't an integer of
185 the appropriate size.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200186 :return: :py:const:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800187 """
188 if not isinstance(type, int):
189 raise TypeError("type must be an integer")
190
191 if not isinstance(bits, int):
192 raise TypeError("bits must be an integer")
193
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800194 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500195 exponent = _lib.BN_new()
196 exponent = _ffi.gc(exponent, _lib.BN_free)
197 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800198
199 if type == TYPE_RSA:
200 if bits <= 0:
201 raise ValueError("Invalid number of bits")
202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500203 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800204
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500205 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500206 if result == 0:
207 # TODO: The test for this case is commented out. Different
208 # builds of OpenSSL appear to have different failure modes that
209 # make it hard to test. Visual inspection of the OpenSSL
210 # source reveals that a return value of 0 signals an error.
211 # Manual testing on a particular build of OpenSSL suggests that
212 # this is probably the appropriate way to handle those errors.
213 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800214
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500215 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800216 if not result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500217 # TODO: It appears as though this can fail if an engine is in
218 # use which does not support RSA.
219 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800220
221 elif type == TYPE_DSA:
Paul Kehrera0860b92016-03-09 21:39:27 -0400222 dsa = _lib.DSA_new()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500223 if dsa == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500224 # TODO: This is untested.
225 _raise_current_error()
Paul Kehrerafa5a662016-03-10 10:29:28 -0400226
227 dsa = _ffi.gc(dsa, _lib.DSA_free)
Paul Kehrera0860b92016-03-09 21:39:27 -0400228 res = _lib.DSA_generate_parameters_ex(
229 dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
230 )
231 if not res == 1:
232 # TODO: This is untested.
233 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500234 if not _lib.DSA_generate_key(dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500235 # TODO: This is untested.
236 _raise_current_error()
Paul Kehrerafa5a662016-03-10 10:29:28 -0400237 if not _lib.EVP_PKEY_set1_DSA(self._pkey, dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500238 # TODO: This is untested.
239 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800240 else:
241 raise Error("No such key type")
242
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800243 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800244
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800245 def check(self):
246 """
247 Check the consistency of an RSA private key.
248
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200249 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
250
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800251 :return: True if key is consistent.
252 :raise Error: if the key is inconsistent.
253 :raise TypeError: if the key is of a type which cannot be checked.
254 Only RSA keys can currently be checked.
255 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800256 if self._only_public:
257 raise TypeError("public key only")
258
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100259 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800260 raise TypeError("key type unsupported")
261
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500262 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
263 rsa = _ffi.gc(rsa, _lib.RSA_free)
264 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800265 if result:
266 return True
267 _raise_current_error()
268
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800269 def type(self):
270 """
271 Returns the type of the key
272
273 :return: The type of the key.
274 """
Alex Gaynorc84567b2016-03-16 07:45:09 -0400275 return _lib.Cryptography_EVP_PKEY_id(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800276
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800277 def bits(self):
278 """
279 Returns the number of bits of the key
280
281 :return: The number of bits of the key.
282 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500283 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800284PKeyType = PKey
285
286
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400287class _EllipticCurve(object):
288 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400289 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400290
291 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
292 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
293 instances each of which represents one curve supported by the system.
294 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400295 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400296 _curves = None
297
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400298 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400299 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400300 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400301 """
302 Implement cooperation with the right-hand side argument of ``!=``.
303
304 Python 3 seems to have dropped this cooperation in this very narrow
305 circumstance.
306 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400307 if isinstance(other, _EllipticCurve):
308 return super(_EllipticCurve, self).__ne__(other)
309 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400310
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400311 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400312 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400313 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400314 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400315
316 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400317
318 :return: A :py:type:`set` of ``cls`` instances giving the names of the
319 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400320 """
321 if lib.Cryptography_HAS_EC:
322 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
323 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
Alex Gaynor5945ea82015-09-05 14:59:06 -0400324 # The return value on this call should be num_curves again. We
325 # could check it to make sure but if it *isn't* then.. what could
326 # we do? Abort the whole process, I suppose...? -exarkun
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400327 lib.EC_get_builtin_curves(builtin_curves, num_curves)
328 return set(
329 cls.from_nid(lib, c.nid)
330 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400331 return set()
332
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400333 @classmethod
334 def _get_elliptic_curves(cls, lib):
335 """
336 Get, cache, and return the curves supported by OpenSSL.
337
338 :param lib: The OpenSSL library binding object.
339
340 :return: A :py:type:`set` of ``cls`` instances giving the names of the
341 elliptic curves the underlying library supports.
342 """
343 if cls._curves is None:
344 cls._curves = cls._load_elliptic_curves(lib)
345 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400346
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400347 @classmethod
348 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400349 """
350 Instantiate a new :py:class:`_EllipticCurve` associated with the given
351 OpenSSL NID.
352
353 :param lib: The OpenSSL library binding object.
354
355 :param nid: The OpenSSL NID the resulting curve object will represent.
356 This must be a curve NID (and not, for example, a hash NID) or
357 subsequent operations will fail in unpredictable ways.
358 :type nid: :py:class:`int`
359
360 :return: The curve object.
361 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400362 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
363
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400364 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400365 """
366 :param _lib: The :py:mod:`cryptography` binding instance used to
367 interface with OpenSSL.
368
369 :param _nid: The OpenSSL NID identifying the curve this object
370 represents.
371 :type _nid: :py:class:`int`
372
373 :param name: The OpenSSL short name identifying the curve this object
374 represents.
375 :type name: :py:class:`unicode`
376 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400377 self._lib = lib
378 self._nid = nid
379 self.name = name
380
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400381 def __repr__(self):
382 return "<Curve %r>" % (self.name,)
383
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400384 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400385 """
386 Create a new OpenSSL EC_KEY structure initialized to use this curve.
387
388 The structure is automatically garbage collected when the Python object
389 is garbage collected.
390 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400391 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
392 return _ffi.gc(key, _lib.EC_KEY_free)
393
394
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400395def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400396 """
397 Return a set of objects representing the elliptic curves supported in the
398 OpenSSL build in use.
399
400 The curve objects have a :py:class:`unicode` ``name`` attribute by which
401 they identify themselves.
402
403 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400404 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
405 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400406 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400407 return _EllipticCurve._get_elliptic_curves(_lib)
408
409
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400410def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400411 """
412 Return a single curve object selected by name.
413
414 See :py:func:`get_elliptic_curves` for information about curve objects.
415
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400416 :param name: The OpenSSL short name identifying the curve object to
417 retrieve.
418 :type name: :py:class:`unicode`
419
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400420 If the named curve is not supported then :py:class:`ValueError` is raised.
421 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400422 for curve in get_elliptic_curves():
423 if curve.name == name:
424 return curve
425 raise ValueError("unknown curve name", name)
426
427
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800428class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200429 """
430 An X.509 Distinguished Name.
431
432 :ivar countryName: The country of the entity.
433 :ivar C: Alias for :py:attr:`countryName`.
434
435 :ivar stateOrProvinceName: The state or province of the entity.
436 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
437
438 :ivar localityName: The locality of the entity.
439 :ivar L: Alias for :py:attr:`localityName`.
440
441 :ivar organizationName: The organization name of the entity.
442 :ivar O: Alias for :py:attr:`organizationName`.
443
444 :ivar organizationalUnitName: The organizational unit of the entity.
445 :ivar OU: Alias for :py:attr:`organizationalUnitName`
446
447 :ivar commonName: The common name of the entity.
448 :ivar CN: Alias for :py:attr:`commonName`.
449
450 :ivar emailAddress: The e-mail address of the entity.
451 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400452
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800453 def __init__(self, name):
454 """
455 Create a new X509Name, copying the given X509Name instance.
456
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200457 :param name: The name to copy.
458 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800459 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500460 name = _lib.X509_NAME_dup(name._name)
461 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800462
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800463 def __setattr__(self, name, value):
464 if name.startswith('_'):
465 return super(X509Name, self).__setattr__(name, value)
466
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800467 # Note: we really do not want str subclasses here, so we do not use
468 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800469 if type(name) is not str:
470 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400471 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800472
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500473 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500474 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800475 try:
476 _raise_current_error()
477 except Error:
478 pass
479 raise AttributeError("No such attribute")
480
481 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500482 for i in range(_lib.X509_NAME_entry_count(self._name)):
483 ent = _lib.X509_NAME_get_entry(self._name, i)
484 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
485 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800486 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500487 ent = _lib.X509_NAME_delete_entry(self._name, i)
488 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800489 break
490
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500491 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800492 value = value.encode('utf-8')
493
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500494 add_result = _lib.X509_NAME_add_entry_by_NID(
495 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800496 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500497 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800498
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800499 def __getattr__(self, name):
500 """
501 Find attribute. An X509Name object has the following attributes:
502 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400503 organization (alias O), organizationalUnit (alias OU), commonName
504 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800505 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500506 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500507 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800508 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
509 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
510 # push something onto the error queue. If we don't clean that up
511 # now, someone else will bump into it later and be quite confused.
512 # See lp#314814.
513 try:
514 _raise_current_error()
515 except Error:
516 pass
517 return super(X509Name, self).__getattr__(name)
518
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500519 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800520 if entry_index == -1:
521 return None
522
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500523 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
524 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800525
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500526 result_buffer = _ffi.new("unsigned char**")
527 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800528 if data_length < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500529 # TODO: This is untested.
530 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800531
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700532 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400533 result = _ffi.buffer(
534 result_buffer[0], data_length
535 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700536 finally:
537 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500538 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800539 return result
540
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500541 def _cmp(op):
542 def f(self, other):
543 if not isinstance(other, X509Name):
544 return NotImplemented
545 result = _lib.X509_NAME_cmp(self._name, other._name)
546 return op(result, 0)
547 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800548
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500549 __eq__ = _cmp(__eq__)
550 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800551
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500552 __lt__ = _cmp(__lt__)
553 __le__ = _cmp(__le__)
554
555 __gt__ = _cmp(__gt__)
556 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800557
558 def __repr__(self):
559 """
560 String representation of an X509Name
561 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400562 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500563 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800564 self._name, result_buffer, len(result_buffer))
565
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500566 if format_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500567 # TODO: This is untested.
568 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800569
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500570 return "<X509Name object '%s'>" % (
571 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800572
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800573 def hash(self):
574 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200575 Return an integer representation of the first four bytes of the
576 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800577
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200578 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
579
580 :return: The (integer) hash of this name.
581 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800582 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500583 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800584
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800585 def der(self):
586 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200587 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800588
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200589 :return: The DER encoded form of this name.
590 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500592 result_buffer = _ffi.new('unsigned char**')
593 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800594 if encode_result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500595 # TODO: This is untested.
596 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800597
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500598 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
599 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800600 return string_result
601
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800602 def get_components(self):
603 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200604 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800605
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200606 :return: The components of this name.
607 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800608 """
609 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500610 for i in range(_lib.X509_NAME_entry_count(self._name)):
611 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800612
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500613 fname = _lib.X509_NAME_ENTRY_get_object(ent)
614 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800615
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500616 nid = _lib.OBJ_obj2nid(fname)
617 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800618
619 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400620 _ffi.string(name),
621 _ffi.string(
622 _lib.ASN1_STRING_data(fval),
623 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800624
625 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200626
627
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800628X509NameType = X509Name
629
630
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800631class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200632 """
633 An X.509 v3 certificate extension.
634 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400635
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800636 def __init__(self, type_name, critical, value, subject=None, issuer=None):
637 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200638 Initializes an X509 extension.
639
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100640 :param type_name: The name of the type of extension_ to create.
Alex Gaynor6f719912015-09-20 09:21:29 -0400641 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800642
Alex Gaynor5945ea82015-09-05 14:59:06 -0400643 :param bool critical: A flag indicating whether this is a critical
644 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800645
646 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200647 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800648
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200649 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800650 :type subject: :py:class:`X509`
651
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200652 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800653 :type issuer: :py:class:`X509`
Hynek Schlawack8d4f9762016-03-19 08:15:03 +0100654
655 .. _extension: https://openssl.org/docs/manmaster/apps/
656 x509v3_config.html#STANDARD-EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800657 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500658 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800659
Alex Gaynor5945ea82015-09-05 14:59:06 -0400660 # A context is necessary for any extension which uses the r2i
661 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
662 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500663 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800664
665 # We have no configuration database - but perhaps we should (some
666 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500667 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800668
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800669 # Initialize the subject and issuer, if appropriate. ctx is a local,
670 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400671 # any references, so no need to mess with reference counts or
672 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800673 if issuer is not None:
674 if not isinstance(issuer, X509):
675 raise TypeError("issuer must be an X509 instance")
676 ctx.issuer_cert = issuer._x509
677 if subject is not None:
678 if not isinstance(subject, X509):
679 raise TypeError("subject must be an X509 instance")
680 ctx.subject_cert = subject._x509
681
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800682 if critical:
683 # There are other OpenSSL APIs which would let us pass in critical
684 # separately, but they're harder to use, and since value is already
685 # a pile of crappy junk smuggling a ton of utterly important
686 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400687 # with strings? (However, X509V3_EXT_i2d in particular seems like
688 # it would be a better API to invoke. I do not know where to get
689 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500690 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800691
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500692 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
693 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800694 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500695 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800696
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400697 @property
698 def _nid(self):
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400699 return _lib.OBJ_obj2nid(
700 _lib.X509_EXTENSION_get_object(self._extension)
701 )
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400702
703 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500704 _lib.GEN_EMAIL: "email",
705 _lib.GEN_DNS: "DNS",
706 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400707 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400708
709 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500710 method = _lib.X509V3_EXT_get(self._extension)
711 if method == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500712 # TODO: This is untested.
713 _raise_current_error()
Paul Kehrere8f91cc2016-03-09 21:26:29 -0400714 ext_data = _lib.X509_EXTENSION_get_data(self._extension)
715 payload = ext_data.data
716 length = ext_data.length
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400717
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500718 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400719 payloadptr[0] = payload
720
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500721 if method.it != _ffi.NULL:
722 ptr = _lib.ASN1_ITEM_ptr(method.it)
723 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
724 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400725 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500726 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400727 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500728 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400729
Paul Kehrerb7d79502015-05-04 07:43:51 -0500730 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400731 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500732 for i in range(_lib.sk_GENERAL_NAME_num(names)):
733 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400734 try:
735 label = self._prefixes[name.type]
736 except KeyError:
737 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500738 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500739 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400740 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500741 value = _native(
742 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
743 parts.append(label + ":" + value)
744 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400745
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800746 def __str__(self):
747 """
748 :return: a nice text representation of the extension
749 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500750 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400751 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800752
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400753 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500754 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800755 if not print_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500756 # TODO: This is untested.
757 _raise_current_error()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800758
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500759 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800760
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800761 def get_critical(self):
762 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200763 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800764
765 :return: The critical field.
766 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800768
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800769 def get_short_name(self):
770 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200771 Returns the short type name of this X.509 extension.
772
773 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800774
775 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200776 :rtype: :py:data:`bytes`
777
778 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800779 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500780 obj = _lib.X509_EXTENSION_get_object(self._extension)
781 nid = _lib.OBJ_obj2nid(obj)
782 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800783
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800784 def get_data(self):
785 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200786 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800787
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200788 :return: The ASN.1 encoded data of this X509 extension.
789 :rtype: :py:data:`bytes`
790
791 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800792 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500793 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
794 string_result = _ffi.cast('ASN1_STRING*', octet_result)
795 char_result = _lib.ASN1_STRING_data(string_result)
796 result_length = _lib.ASN1_STRING_length(string_result)
797 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800798
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200799
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800800X509ExtensionType = X509Extension
801
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800802
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800803class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200804 """
805 An X.509 certificate signing requests.
806 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400807
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800808 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500809 req = _lib.X509_REQ_new()
810 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800811
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800812 def set_pubkey(self, pkey):
813 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200814 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800815
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200816 :param pkey: The public key to use.
817 :type pkey: :py:class:`PKey`
818
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200819 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800820 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500821 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800822 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500823 # TODO: This is untested.
824 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800825
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800826 def get_pubkey(self):
827 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200828 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800829
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200830 :return: The public key.
831 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800832 """
833 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500834 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
835 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500836 # TODO: This is untested.
837 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500838 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800839 pkey._only_public = True
840 return pkey
841
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800842 def set_version(self, version):
843 """
844 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
845 request.
846
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200847 :param int version: The version number.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200848 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800849 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500850 set_result = _lib.X509_REQ_set_version(self._req, version)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800851 if not set_result:
852 _raise_current_error()
853
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800854 def get_version(self):
855 """
856 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
857 request.
858
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200859 :return: The value of the version subfield.
860 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800861 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500862 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800863
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800864 def get_subject(self):
865 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200866 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800867
Cory Benfield881dc8d2015-12-09 08:25:14 +0000868 This creates a new :class:`X509Name` that wraps the underlying subject
869 name field on the certificate signing request. Modifying it will modify
870 the underlying signing request, and will have the effect of modifying
871 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200872
873 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000874 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800875 """
876 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500877 name._name = _lib.X509_REQ_get_subject_name(self._req)
878 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500879 # TODO: This is untested.
880 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800881
882 # The name is owned by the X509Req structure. As long as the X509Name
883 # Python object is alive, keep the X509Req Python object alive.
884 name._owner = self
885
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800886 return name
887
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800888 def add_extensions(self, extensions):
889 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200890 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800891
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200892 :param extensions: The X.509 extensions to add.
893 :type extensions: iterable of :py:class:`X509Extension`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200894 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800895 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500896 stack = _lib.sk_X509_EXTENSION_new_null()
897 if stack == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500898 # TODO: This is untested.
899 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800900
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500901 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800902
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800903 for ext in extensions:
904 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800905 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800906
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800907 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500908 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800909
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500910 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800911 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500912 # TODO: This is untested.
913 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800914
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800915 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800916 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200917 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800918
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200919 :return: The X.509 extensions in this request.
920 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
921
922 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800923 """
924 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500925 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500926 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800927 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500928 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800929 exts.append(ext)
930 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800931
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800932 def sign(self, pkey, digest):
933 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700934 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800935
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200936 :param pkey: The key pair to sign with.
937 :type pkey: :py:class:`PKey`
938 :param digest: The name of the message digest to use for the signature,
939 e.g. :py:data:`b"sha1"`.
940 :type digest: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200941 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800942 """
943 if pkey._only_public:
944 raise ValueError("Key has only public part")
945
946 if not pkey._initialized:
947 raise ValueError("Key is uninitialized")
948
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500949 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500950 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800951 raise ValueError("No such digest method")
952
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500953 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800954 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500955 # TODO: This is untested.
956 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800957
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800958 def verify(self, pkey):
959 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200960 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800961
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200962 :param key: A public key.
963 :type key: :py:class:`PKey`
964 :return: :py:data:`True` if the signature is correct.
965 :rtype: :py:class:`bool`
966 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800967 problem verifying the signature.
968 """
969 if not isinstance(pkey, PKey):
970 raise TypeError("pkey must be a PKey instance")
971
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500972 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800973 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500974 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800975
976 return result
977
978
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800979X509ReqType = X509Req
980
981
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800982class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200983 """
984 An X.509 certificate.
985 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400986
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800987 def __init__(self):
988 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500989 x509 = _lib.X509_new()
990 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800991
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800992 def set_version(self, version):
993 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200994 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800995
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200996 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800997 :type version: :py:class:`int`
998
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200999 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001000 """
1001 if not isinstance(version, int):
1002 raise TypeError("version must be an integer")
1003
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001005
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001006 def get_version(self):
1007 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001008 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001009
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001010 :return: The version number of the certificate.
1011 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001012 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001013 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001014
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001015 def get_pubkey(self):
1016 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001017 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001018
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001019 :return: The public key.
1020 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001021 """
1022 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001023 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1024 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001025 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001026 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001027 pkey._only_public = True
1028 return pkey
1029
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001030 def set_pubkey(self, pkey):
1031 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001032 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001033
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001034 :param pkey: The public key.
1035 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001036
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001037 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001038 """
1039 if not isinstance(pkey, PKey):
1040 raise TypeError("pkey must be a PKey instance")
1041
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001042 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001043 if not set_result:
1044 _raise_current_error()
1045
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001046 def sign(self, pkey, digest):
1047 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001048 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001049
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001050 :param pkey: The key to sign with.
1051 :type pkey: :py:class:`PKey`
1052
1053 :param digest: The name of the message digest to use.
1054 :type digest: :py:class:`bytes`
1055
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001056 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001057 """
1058 if not isinstance(pkey, PKey):
1059 raise TypeError("pkey must be a PKey instance")
1060
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001061 if pkey._only_public:
1062 raise ValueError("Key only has public part")
1063
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001064 if not pkey._initialized:
1065 raise ValueError("Key is uninitialized")
1066
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001067 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001068 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001069 raise ValueError("No such digest method")
1070
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001071 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001072 if not sign_result:
1073 _raise_current_error()
1074
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001075 def get_signature_algorithm(self):
1076 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001077 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001078
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001079 :return: The name of the algorithm.
1080 :rtype: :py:class:`bytes`
1081
1082 :raises ValueError: If the signature algorithm is undefined.
1083
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001084 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001085 """
Alex Gaynor39ea5312016-06-02 09:12:10 -07001086 algor = _lib.X509_get0_tbs_sigalg(self._x509)
1087 nid = _lib.OBJ_obj2nid(algor.algorithm)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001088 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001089 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001090 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001091
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001092 def digest(self, digest_name):
1093 """
1094 Return the digest of the X509 object.
1095
1096 :param digest_name: The name of the digest algorithm to use.
1097 :type digest_name: :py:class:`bytes`
1098
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001099 :return: The digest of the object, formatted as
1100 :py:const:`b":"`-delimited hex pairs.
1101 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001102 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001103 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001104 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001105 raise ValueError("No such digest method")
1106
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1108 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001109 result_length[0] = len(result_buffer)
1110
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001111 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001112 self._x509, digest, result_buffer, result_length)
1113
1114 if not digest_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001115 # TODO: This is untested.
1116 _raise_current_error()
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001117
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001118 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001119 b16encode(ch).upper() for ch
1120 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001121
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001122 def subject_name_hash(self):
1123 """
1124 Return the hash of the X509 subject.
1125
1126 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001127 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001128 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001129 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001130
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001131 def set_serial_number(self, serial):
1132 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001133 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001134
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001135 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001136 :type serial: :py:class:`int`
1137
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001138 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001139 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001140 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001141 raise TypeError("serial must be an integer")
1142
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001143 hex_serial = hex(serial)[2:]
1144 if not isinstance(hex_serial, bytes):
1145 hex_serial = hex_serial.encode('ascii')
1146
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001147 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001148
1149 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001150 # it. If bignum is still NULL after this call, then the return value
1151 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001153
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001154 if bignum_serial[0] == _ffi.NULL:
1155 set_result = _lib.ASN1_INTEGER_set(
1156 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001157 if set_result:
1158 # TODO Not tested
1159 _raise_current_error()
1160 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001161 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1162 _lib.BN_free(bignum_serial[0])
1163 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001164 # TODO Not tested
1165 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001166 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1167 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001168 if not set_result:
1169 # TODO Not tested
1170 _raise_current_error()
1171
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001172 def get_serial_number(self):
1173 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001174 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001175
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001176 :return: The serial number.
1177 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001178 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1180 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001181 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001182 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001183 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001184 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001185 serial = int(hexstring_serial, 16)
1186 return serial
1187 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001188 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001189 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001190 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001191
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001192 def gmtime_adj_notAfter(self, amount):
1193 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001194 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001195
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001196 :param amount: The number of seconds by which to adjust the timestamp.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001197 :type amount: :py:class:`int`
1198
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001199 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -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 notAfter = _lib.X509_get_notAfter(self._x509)
1205 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001206
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001207 def gmtime_adj_notBefore(self, amount):
1208 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001209 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001210
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001211 :param amount: The number of seconds by which to adjust the timestamp.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001212 :return: :py:const:`None`
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001213 """
1214 if not isinstance(amount, int):
1215 raise TypeError("amount must be an integer")
1216
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001217 notBefore = _lib.X509_get_notBefore(self._x509)
1218 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001219
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001220 def has_expired(self):
1221 """
1222 Check whether the certificate has expired.
1223
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001224 :return: :py:const:`True` if the certificate has expired,
1225 :py:const:`False` otherwise.
1226 :rtype: :py:class:`bool`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001227 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001228 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001229 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001230
Paul Kehrerfde45c92016-01-21 12:57:37 -06001231 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001232
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001233 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001234 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001235
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001236 def get_notBefore(self):
1237 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001238 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001240 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001241
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001242 YYYYMMDDhhmmssZ
1243 YYYYMMDDhhmmss+hhmm
1244 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001245
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001246 :return: A timestamp string, or :py:const:`None` if there is none.
1247 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001248 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001249 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001250
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001251 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001252 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001253
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001254 def set_notBefore(self, when):
1255 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001256 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001257
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001258 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001259
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001260 YYYYMMDDhhmmssZ
1261 YYYYMMDDhhmmss+hhmm
1262 YYYYMMDDhhmmss-hhmm
1263
1264 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001265 :type when: :py:class:`bytes`
1266
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001267 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001268 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001269 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001270
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001271 def get_notAfter(self):
1272 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001273 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001274
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001275 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001276
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001277 YYYYMMDDhhmmssZ
1278 YYYYMMDDhhmmss+hhmm
1279 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001280
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001281 :return: A timestamp string, or :py:const:`None` if there is none.
1282 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001283 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001284 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001285
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001286 def set_notAfter(self, when):
1287 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001288 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001289
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001290 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001291
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001292 YYYYMMDDhhmmssZ
1293 YYYYMMDDhhmmss+hhmm
1294 YYYYMMDDhhmmss-hhmm
1295
1296 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001297 :type when: :py:class:`bytes`
1298
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001299 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001300 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001301 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001302
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001303 def _get_name(self, which):
1304 name = X509Name.__new__(X509Name)
1305 name._name = which(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001306 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001307 # TODO: This is untested.
1308 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001309
1310 # The name is owned by the X509 structure. As long as the X509Name
1311 # Python object is alive, keep the X509 Python object alive.
1312 name._owner = self
1313
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001314 return name
1315
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001316 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001317 if not isinstance(name, X509Name):
1318 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001319 set_result = which(self._x509, name._name)
1320 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001321 # TODO: This is untested.
1322 _raise_current_error()
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001323
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001324 def get_issuer(self):
1325 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001326 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001327
Cory Benfielde6bcce82015-12-09 08:40:03 +00001328 This creates a new :class:`X509Name` that wraps the underlying issuer
1329 name field on the certificate. Modifying it will modify the underlying
1330 certificate, and will have the effect of modifying any other
1331 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001332
1333 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001334 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001335 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001336 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001337
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001338 def set_issuer(self, issuer):
1339 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001340 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001341
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001342 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001343 :type issuer: :py:class:`X509Name`
1344
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001345 :return: :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001346 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001347 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001348
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001349 def get_subject(self):
1350 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001351 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001352
Cory Benfielde6bcce82015-12-09 08:40:03 +00001353 This creates a new :class:`X509Name` that wraps the underlying subject
1354 name field on the certificate. Modifying it will modify the underlying
1355 certificate, and will have the effect of modifying any other
1356 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001357
1358 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001359 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001360 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001361 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001362
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001363 def set_subject(self, subject):
1364 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001365 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001366
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001367 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001368 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001369
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001370 :return: :py:const:`None`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001371 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001372 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001373
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001374 def get_extension_count(self):
1375 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001376 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001377
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001378 :return: The number of extensions.
1379 :rtype: :py:class:`int`
1380
1381 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001382 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001383 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001384
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001385 def add_extensions(self, extensions):
1386 """
1387 Add extensions to the certificate.
1388
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001389 :param extensions: The extensions to add.
1390 :type extensions: An iterable of :py:class:`X509Extension` objects.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001391 :return: :py:const:`None`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001392 """
1393 for ext in extensions:
1394 if not isinstance(ext, X509Extension):
1395 raise ValueError("One of the elements is not an X509Extension")
1396
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001397 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001398 if not add_result:
1399 _raise_current_error()
1400
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001401 def get_extension(self, index):
1402 """
1403 Get a specific extension of the certificate by index.
1404
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001405 Extensions on a certificate are kept in order. The index
1406 parameter selects which extension will be returned.
1407
1408 :param int index: The index of the extension to retrieve.
1409 :return: The extension at the specified index.
1410 :rtype: :py:class:`X509Extension`
1411 :raises IndexError: If the extension index was out of bounds.
1412
1413 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001414 """
1415 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001416 ext._extension = _lib.X509_get_ext(self._x509, index)
1417 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001418 raise IndexError("extension index out of bounds")
1419
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001420 extension = _lib.X509_EXTENSION_dup(ext._extension)
1421 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001422 return ext
1423
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001424
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001425X509Type = X509
1426
1427
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001428class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001429 """
1430 An X509 certificate store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001431 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001432
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001433 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001434 store = _lib.X509_STORE_new()
1435 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001436
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001437 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001438 """
1439 Adds the certificate :py:data:`cert` to this store.
1440
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +02001441 This is the Python equivalent of OpenSSL's ``X509_STORE_add_cert``.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001442
1443 :param X509 cert: The certificate to add to this store.
1444 :raises TypeError: If the certificate is not an :py:class:`X509`.
1445 :raises Error: If OpenSSL was unhappy with your certificate.
Laurens Van Houtven5ee60b32015-04-23 10:51:16 -07001446 :return: :py:data:`None` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001447 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001448 if not isinstance(cert, X509):
1449 raise TypeError()
1450
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 result = _lib.X509_STORE_add_cert(self._store, cert._x509)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001452 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001453 _raise_current_error()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001454
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001455
1456X509StoreType = X509Store
1457
1458
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001459class X509StoreContextError(Exception):
1460 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001461 An exception raised when an error occurred while verifying a certificate
1462 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001463
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001464 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001465 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001466 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001467
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001468 def __init__(self, message, certificate):
1469 super(X509StoreContextError, self).__init__(message)
1470 self.certificate = certificate
1471
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001472
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001473class X509StoreContext(object):
1474 """
1475 An X.509 store context.
1476
Jean-Paul Calderone13a81682015-01-18 15:49:15 -05001477 An :py:class:`X509StoreContext` is used to define some of the criteria for
1478 certificate verification. The information encapsulated in this object
1479 includes, but is not limited to, a set of trusted certificates,
1480 verification parameters, and revoked certificates.
1481
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001482 .. note::
1483
1484 Currently, one can only set the trusted certificates on an
1485 :py:class:`X509StoreContext`. Future versions of pyOpenSSL will expose
1486 verification parameters and certificate revocation lists.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001487
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001488 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1489 instance. It is dynamically allocated and automatically garbage
1490 collected.
1491
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001492 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001493
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001494 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001495
1496 :param X509Store store: The certificates which will be trusted for the
1497 purposes of any verifications.
1498
1499 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001500 """
1501
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001502 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001503 store_ctx = _lib.X509_STORE_CTX_new()
1504 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1505 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001506 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001507 # Make the store context available for use after instantiating this
1508 # class by initializing it now. Per testing, subsequent calls to
1509 # :py:meth:`_init` have no adverse affect.
1510 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001511
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001512 def _init(self):
1513 """
1514 Set up the store context for a subsequent verification operation.
1515 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001516 ret = _lib.X509_STORE_CTX_init(
1517 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1518 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001519 if ret <= 0:
1520 _raise_current_error()
1521
1522 def _cleanup(self):
1523 """
1524 Internally cleans up the store context.
1525
1526 The store context can then be reused with a new call to
Stephen Holsapple46a09252015-02-12 14:45:43 -08001527 :py:meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001528 """
1529 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1530
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001531 def _exception_from_context(self):
1532 """
1533 Convert an OpenSSL native context error failure into a Python
1534 exception.
1535
Alex Gaynor5945ea82015-09-05 14:59:06 -04001536 When a call to native OpenSSL X509_verify_cert fails, additional
1537 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001538 """
1539 errors = [
1540 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1541 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1542 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001543 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001544 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001545 # A context error should always be associated with a certificate, so we
1546 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001547 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001548 _cert = _lib.X509_dup(_x509)
1549 pycert = X509.__new__(X509)
1550 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001551 return X509StoreContextError(errors, pycert)
1552
Stephen Holsapple46a09252015-02-12 14:45:43 -08001553 def set_store(self, store):
1554 """
1555 Set the context's trust store.
1556
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001557 .. versionadded:: 0.15
1558
Stephen Holsapple46a09252015-02-12 14:45:43 -08001559 :param X509Store store: The certificates which will be trusted for the
1560 purposes of any *future* verifications.
1561 """
1562 self._store = store
1563
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001564 def verify_certificate(self):
1565 """
1566 Verify a certificate in a context.
1567
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001568 .. versionadded:: 0.15
1569
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001570 :param store_ctx: The :py:class:`X509StoreContext` to verify.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001571
Alex Gaynorca87ff62015-09-04 23:31:03 -04001572 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001573 certificate in the context. Sets ``certificate`` attribute to
1574 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001575 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001576 # Always re-initialize the store context in case
1577 # :py:meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001578 self._init()
1579 ret = _lib.X509_verify_cert(self._store_ctx)
1580 self._cleanup()
1581 if ret <= 0:
1582 raise self._exception_from_context()
1583
1584
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001585def load_certificate(type, buffer):
1586 """
1587 Load a certificate from a buffer
1588
1589 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1590
1591 :param buffer: The buffer the certificate is stored in
1592 :type buffer: :py:class:`bytes`
1593
1594 :return: The X509 object
1595 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001596 if isinstance(buffer, _text_type):
1597 buffer = buffer.encode("ascii")
1598
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001599 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001600
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001601 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001602 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001603 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001604 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001605 else:
1606 raise ValueError(
1607 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001609 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001610 _raise_current_error()
1611
1612 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001613 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001614 return cert
1615
1616
1617def dump_certificate(type, cert):
1618 """
1619 Dump a certificate to a buffer
1620
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001621 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1622 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001623 :param cert: The certificate to dump
1624 :return: The buffer with the dumped certificate in
1625 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001626 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001627
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001628 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001629 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001630 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001631 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001632 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001633 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001634 else:
1635 raise ValueError(
1636 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1637 "FILETYPE_TEXT")
1638
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001639 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001640 return _bio_to_string(bio)
1641
1642
Cory Benfield6492f7c2015-10-27 16:57:58 +09001643def dump_publickey(type, pkey):
1644 """
Cory Benfield11c10192015-10-27 17:23:03 +09001645 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001646
Cory Benfield9c590b92015-10-28 14:55:05 +09001647 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001648 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001649 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001650 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001651 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001652 """
1653 bio = _new_mem_buf()
1654 if type == FILETYPE_PEM:
1655 write_bio = _lib.PEM_write_bio_PUBKEY
1656 elif type == FILETYPE_ASN1:
1657 write_bio = _lib.i2d_PUBKEY_bio
1658 else:
1659 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1660
1661 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001662 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001663 _raise_current_error()
1664
1665 return _bio_to_string(bio)
1666
1667
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001668def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1669 """
1670 Dump a private key to a buffer
1671
Jean-Paul Calderonee66fde22013-04-03 08:35:08 -04001672 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1673 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001674 :param pkey: The PKey to dump
1675 :param cipher: (optional) if encrypted PEM format, the cipher to
1676 use
1677 :param passphrase: (optional) if encrypted PEM format, this can be either
1678 the passphrase to use, or a callback for providing the
1679 passphrase.
1680 :return: The buffer with the dumped key in
Maximilian Hils0de43752015-09-18 15:26:54 +02001681 :rtype: :py:data:`bytes`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001682 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001683 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001684
1685 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001686 if passphrase is None:
1687 raise TypeError(
1688 "if a value is given for cipher "
1689 "one must also be given for passphrase")
1690 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001691 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001692 raise ValueError("Invalid cipher name")
1693 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001695
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001696 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001697 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001698 result_code = _lib.PEM_write_bio_PrivateKey(
1699 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001700 helper.callback, helper.callback_args)
1701 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001702 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001703 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001704 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001705 rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)
1706 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001707 # TODO RSA_free(rsa)?
1708 else:
1709 raise ValueError(
1710 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1711 "FILETYPE_TEXT")
1712
1713 if result_code == 0:
1714 _raise_current_error()
1715
1716 return _bio_to_string(bio)
1717
1718
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001719class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001720 """
1721 A certificate revocation.
1722 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001723 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1724 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1725 # OCSP_crl_reason_str. We use the latter, just like the command line
1726 # program.
1727 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001728 b"unspecified",
1729 b"keyCompromise",
1730 b"CACompromise",
1731 b"affiliationChanged",
1732 b"superseded",
1733 b"cessationOfOperation",
1734 b"certificateHold",
1735 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001736 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001737
1738 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001739 revoked = _lib.X509_REVOKED_new()
1740 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001741
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001742 def set_serial(self, hex_str):
1743 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001744 Set the serial number.
1745
1746 The serial number is formatted as a hexadecimal number encoded in
1747 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001748
1749 :param hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001750 :type hex_str: :py:class:`bytes`
1751
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001752 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001753 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1755 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001756 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001757 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001758 if not bn_result:
1759 raise ValueError("bad hex string")
1760
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001761 asn1_serial = _ffi.gc(
1762 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1763 _lib.ASN1_INTEGER_free)
1764 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001765
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001766 def get_serial(self):
1767 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001768 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001769
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001770 The serial number is formatted as a hexadecimal number encoded in
1771 ASCII.
1772
1773 :return: The serial number.
1774 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001775 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001776 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001777
Alex Gaynor67903a62016-06-02 10:37:13 -07001778 asn1_int = _lib.X509_REVOKED_get0_serialNumber(self._revoked)
1779 _openssl_assert(asn1_int != _ffi.NULL)
1780 result = _lib.i2a_ASN1_INTEGER(bio, asn1_int)
1781 _openssl_assert(result >= 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001782 return _bio_to_string(bio)
1783
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001784 def _delete_reason(self):
Alex Gaynor67903a62016-06-02 10:37:13 -07001785 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1786 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001787 obj = _lib.X509_EXTENSION_get_object(ext)
1788 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001789 _lib.X509_EXTENSION_free(ext)
Alex Gaynor67903a62016-06-02 10:37:13 -07001790 _lib.X509_REVOKED_delete_ext(self._revoked, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001791 break
1792
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001793 def set_reason(self, reason):
1794 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001795 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001796
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001797 If :py:data:`reason` is :py:const:`None`, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001798
1799 :param reason: The reason string.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001800 :type reason: :py:class:`bytes` or :py:class:`NoneType`
1801
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001802 :return: :py:const:`None`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001803
1804 .. seealso::
1805
1806 :py:meth:`all_reasons`, which gives you a list of all supported
1807 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001808 """
1809 if reason is None:
1810 self._delete_reason()
1811 elif not isinstance(reason, bytes):
1812 raise TypeError("reason must be None or a byte string")
1813 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001814 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001815 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1816
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001817 new_reason_ext = _lib.ASN1_ENUMERATED_new()
1818 if new_reason_ext == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001819 # TODO: This is untested.
1820 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001822
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001823 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
1824 if set_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001825 # TODO: This is untested.
1826 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001827
1828 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001829 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1830 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001831
1832 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001833 # TODO: This is untested.
1834 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001835
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001836 def get_reason(self):
1837 """
Alex Gaynor80262fb2016-04-22 07:53:42 -04001838 Get the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001839
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001840 :return: The reason, or :py:const:`None` if there is none.
1841 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1842
1843 .. seealso::
1844
1845 :py:meth:`all_reasons`, which gives you a list of all supported
1846 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001848 for i in range(_lib.X509_REVOKED_get_ext_count(self._revoked)):
1849 ext = _lib.X509_REVOKED_get_ext(self._revoked, i)
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001850 obj = _lib.X509_EXTENSION_get_object(ext)
1851 if _lib.OBJ_obj2nid(obj) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001852 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001853
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001854 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001855 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001856 print_result = _lib.M_ASN1_OCTET_STRING_print(
Paul Kehrere8f91cc2016-03-09 21:26:29 -04001857 bio, _lib.X509_EXTENSION_get_data(ext)
Alex Gaynor5945ea82015-09-05 14:59:06 -04001858 )
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001859 if print_result == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001860 # TODO: This is untested.
1861 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001862
1863 return _bio_to_string(bio)
1864
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001865 def all_reasons(self):
1866 """
1867 Return a list of all the supported reason strings.
1868
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001869 This list is a copy; modifying it does not change the supported reason
1870 strings.
1871
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001872 :return: A list of reason strings.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001873 :rtype: :py:class:`list` of :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001874 """
1875 return self._crl_reasons[:]
1876
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001877 def set_rev_date(self, when):
1878 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001879 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001880
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001881 :param when: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1882 :type when: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001883 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001884 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001885 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1886 return _set_asn1_time(dt, when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001887
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001888 def get_rev_date(self):
1889 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001890 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001891
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001892 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1893 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001894 """
Alex Gaynor67903a62016-06-02 10:37:13 -07001895 dt = _lib.X509_REVOKED_get0_revocationDate(self._revoked)
1896 return _get_asn1_time(dt)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001897
1898
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001899class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001900 """
1901 A certificate revocation list.
1902 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001903
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001904 def __init__(self):
1905 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001906 Create a new empty certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001907 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001908 crl = _lib.X509_CRL_new()
1909 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001910
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001911 def get_revoked(self):
1912 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001913 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001914
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001915 These revocations will be provided by value, not by reference.
1916 That means it's okay to mutate them: it won't affect this CRL.
1917
1918 :return: The revocations in this CRL.
1919 :rtype: :py:class:`tuple` of :py:class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001920 """
1921 results = []
Alex Gaynor67903a62016-06-02 10:37:13 -07001922 revoked_stack = _lib.X509_CRL_get_REVOKED(self._crl)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001923 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1924 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Paul Kehrer2fe23b02016-03-09 22:02:15 -04001925 revoked_copy = _lib.Cryptography_X509_REVOKED_dup(revoked)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001926 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001927 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001928 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001929 if results:
1930 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001931
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001932 def add_revoked(self, revoked):
1933 """
1934 Add a revoked (by value not reference) to the CRL structure
1935
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001936 This revocation will be added by value, not by reference. That
1937 means it's okay to mutate it after adding: it won't affect
1938 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001939
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001940 :param revoked: The new revocation.
1941 :type revoked: :class:`Revoked`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001942
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001943 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001944 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001945 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001946 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001947 # TODO: This is untested.
1948 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001949
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001950 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001951 if add_result == 0:
1952 # TODO: This is untested.
1953 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001954
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001955 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001956 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001957 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001958 Export a CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001959
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001960 :param cert: The certificate used to sign the CRL.
1961 :type cert: :py:class:`X509`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001962
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001963 :param key: The key used to sign the CRL.
1964 :type key: :py:class:`PKey`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001965
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001966 :param type: The export format, either :py:data:`FILETYPE_PEM`,
1967 :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001968
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04001969 :param int days: The number of days until the next update of this CRL.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04001970
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001971 :param bytes digest: The name of the message digest to use (eg
1972 ``b"sha1"``).
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001973
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001974 :return: :py:data:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001975 """
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001976 if not isinstance(cert, X509):
1977 raise TypeError("cert must be an X509 instance")
1978 if not isinstance(key, PKey):
1979 raise TypeError("key must be a PKey instance")
1980 if not isinstance(type, int):
1981 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001982
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001983 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001984 _warn(
1985 "The default message digest (md5) is deprecated. "
1986 "Pass the name of a message digest explicitly.",
1987 category=DeprecationWarning,
1988 stacklevel=2,
1989 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001990 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001991
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001992 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04001993 if digest_obj == _ffi.NULL:
1994 raise ValueError("No such digest method")
1995
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001996 bio = _lib.BIO_new(_lib.BIO_s_mem())
1997 if bio == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001998 # TODO: This is untested.
1999 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002000
Alex Gaynora738ed52015-09-05 11:17:10 -04002001 # A scratch time object to give different values to different CRL
2002 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002003 sometime = _lib.ASN1_TIME_new()
2004 if sometime == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002005 # TODO: This is untested.
2006 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002007
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002008 _lib.X509_gmtime_adj(sometime, 0)
2009 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002010
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002011 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2012 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002013
Alex Gaynor5945ea82015-09-05 14:59:06 -04002014 _lib.X509_CRL_set_issuer_name(
2015 self._crl, _lib.X509_get_subject_name(cert._x509)
2016 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002017
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002018 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002019 if not sign_result:
2020 _raise_current_error()
2021
Dominic Chenf05b2122015-10-13 16:32:35 +00002022 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002023
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002024
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002025CRLType = CRL
2026
2027
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002028class PKCS7(object):
2029 def type_is_signed(self):
2030 """
2031 Check if this NID_pkcs7_signed object
2032
2033 :return: True if the PKCS7 is of type signed
2034 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002035 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002036 return True
2037 return False
2038
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002039 def type_is_enveloped(self):
2040 """
2041 Check if this NID_pkcs7_enveloped object
2042
2043 :returns: True if the PKCS7 is of type enveloped
2044 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002045 if _lib.PKCS7_type_is_enveloped(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_signedAndEnveloped(self):
2050 """
2051 Check if this NID_pkcs7_signedAndEnveloped object
2052
2053 :returns: True if the PKCS7 is of type signedAndEnveloped
2054 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002055 if _lib.PKCS7_type_is_signedAndEnveloped(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_data(self):
2060 """
2061 Check if this NID_pkcs7_data object
2062
2063 :return: True if the PKCS7 is of type data
2064 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002065 if _lib.PKCS7_type_is_data(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 get_type_name(self):
2070 """
2071 Returns the type name of the PKCS7 structure
2072
2073 :return: A string with the typename
2074 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002075 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2076 string_type = _lib.OBJ_nid2sn(nid)
2077 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002078
2079PKCS7Type = PKCS7
2080
2081
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002082class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002083 """
2084 A PKCS #12 archive.
2085 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002086
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002087 def __init__(self):
2088 self._pkey = None
2089 self._cert = None
2090 self._cacerts = None
2091 self._friendlyname = None
2092
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002093 def get_certificate(self):
2094 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002095 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002096
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002097 :return: The certificate, or :py:const:`None` if there is none.
2098 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002099 """
2100 return self._cert
2101
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002102 def set_certificate(self, cert):
2103 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002104 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002105
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002106 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002107 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002108
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002109 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002110 """
2111 if not isinstance(cert, X509):
2112 raise TypeError("cert must be an X509 instance")
2113 self._cert = cert
2114
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002115 def get_privatekey(self):
2116 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002117 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002118
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002119 :return: The private key, or :py:const:`None` if there is none.
2120 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002121 """
2122 return self._pkey
2123
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002124 def set_privatekey(self, pkey):
2125 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002126 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002127
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002128 :param pkey: The new private key, or :py:const:`None` to unset it.
2129 :type pkey: :py:class:`PKey` or :py:const:`None`
2130
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002131 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002132 """
2133 if not isinstance(pkey, PKey):
2134 raise TypeError("pkey must be a PKey instance")
2135 self._pkey = pkey
2136
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002137 def get_ca_certificates(self):
2138 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002139 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002140
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002141 :return: A tuple with the CA certificates in the chain, or
2142 :py:const:`None` if there are none.
2143 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002144 """
2145 if self._cacerts is not None:
2146 return tuple(self._cacerts)
2147
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002148 def set_ca_certificates(self, cacerts):
2149 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002150 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002151
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002152 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2153 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002154 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002155
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002156 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002157 """
2158 if cacerts is None:
2159 self._cacerts = None
2160 else:
2161 cacerts = list(cacerts)
2162 for cert in cacerts:
2163 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002164 raise TypeError(
2165 "iterable must only contain X509 instances"
2166 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002167 self._cacerts = cacerts
2168
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002169 def set_friendlyname(self, name):
2170 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002171 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002172
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002173 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002174 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002175
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002176 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002177 """
2178 if name is None:
2179 self._friendlyname = None
2180 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002181 raise TypeError(
2182 "name must be a byte string or None (not %r)" % (name,)
2183 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002184 self._friendlyname = name
2185
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002186 def get_friendlyname(self):
2187 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002188 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002189
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002190 :returns: The friendly name, or :py:const:`None` if there is none.
2191 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002192 """
2193 return self._friendlyname
2194
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002195 def export(self, passphrase=None, iter=2048, maciter=1):
2196 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002197 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002198
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002199 For more information, see the :c:func:`PKCS12_create` man page.
2200
2201 :param passphrase: The passphrase used to encrypt the structure. Unlike
2202 some other passphrase arguments, this *must* be a string, not a
2203 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002204 :type passphrase: :py:data:`bytes`
2205
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002206 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002207 :type iter: :py:data:`int`
2208
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002209 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002210 :type maciter: :py:data:`int`
2211
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002212 :return: The string representation of the PKCS #12 structure.
2213 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002214 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002215 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002216
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002218 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002219 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002220 cacerts = _lib.sk_X509_new_null()
2221 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002222 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002224
2225 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002226 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002227
2228 friendlyname = self._friendlyname
2229 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002230 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002231
2232 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002233 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002234 else:
2235 pkey = self._pkey._pkey
2236
2237 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002238 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002239 else:
2240 cert = self._cert._x509
2241
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002242 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002243 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002244 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2245 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002246 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002247 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002248 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002249 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002250
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002251 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002252 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002253 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002254
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002255
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002256PKCS12Type = PKCS12
2257
2258
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002259class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002260 """
2261 A Netscape SPKI object.
2262 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002263
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002264 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002265 spki = _lib.NETSCAPE_SPKI_new()
2266 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002267
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002268 def sign(self, pkey, digest):
2269 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002270 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002271
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002272 :param pkey: The private key to sign with.
2273 :type pkey: :py:class:`PKey`
2274
2275 :param digest: The message digest to use.
2276 :type digest: :py:class:`bytes`
2277
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002278 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002279 """
2280 if pkey._only_public:
2281 raise ValueError("Key has only public part")
2282
2283 if not pkey._initialized:
2284 raise ValueError("Key is uninitialized")
2285
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002286 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002287 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002288 raise ValueError("No such digest method")
2289
Alex Gaynor5945ea82015-09-05 14:59:06 -04002290 sign_result = _lib.NETSCAPE_SPKI_sign(
2291 self._spki, pkey._pkey, digest_obj
2292 )
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002293 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002294 # TODO: This is untested.
2295 _raise_current_error()
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002296
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002297 def verify(self, key):
2298 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002299 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002300
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002301 :param key: The public key that signature is supposedly from.
2302 :type pkey: :py:class:`PKey`
2303
2304 :return: :py:const:`True` if the signature is correct.
2305 :rtype: :py:class:`bool`
2306
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002307 :raises Error: If the signature is invalid, or there was a problem
2308 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002309 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002310 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002311 if answer <= 0:
2312 _raise_current_error()
2313 return True
2314
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002315 def b64_encode(self):
2316 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002317 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002318
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002319 :return: The base64 encoded string.
2320 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002321 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002322 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2323 result = _ffi.string(encoded)
Paul Kehrer0dcacf72016-03-17 19:25:39 -04002324 _lib.OPENSSL_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002325 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002326
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002327 def get_pubkey(self):
2328 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002329 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002330
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002331 :return: The public key.
2332 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002333 """
2334 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002335 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
2336 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002337 # TODO: This is untested.
2338 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002339 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002340 pkey._only_public = True
2341 return pkey
2342
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002343 def set_pubkey(self, pkey):
2344 """
2345 Set the public key of the certificate
2346
2347 :param pkey: The public key
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002348 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002349 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002350 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002351 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002352 # TODO: This is untested.
2353 _raise_current_error()
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002354
2355
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002356NetscapeSPKIType = NetscapeSPKI
2357
2358
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002359class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002360 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002361 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002362 raise ValueError(
2363 "only FILETYPE_PEM key format supports encryption"
2364 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002365 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002366 self._more_args = more_args
2367 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002368 self._problems = []
2369
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002370 @property
2371 def callback(self):
2372 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002373 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002374 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002375 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002376 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002377 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002378 else:
2379 raise TypeError("Last argument must be string or callable")
2380
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002381 @property
2382 def callback_args(self):
2383 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002384 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002385 elif isinstance(self._passphrase, bytes):
2386 return self._passphrase
2387 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002388 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002389 else:
2390 raise TypeError("Last argument must be string or callable")
2391
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002392 def raise_if_problem(self, exceptionType=Error):
2393 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002394 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002395 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002396 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002397 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002398 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002399 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002400
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002401 def _read_passphrase(self, buf, size, rwflag, userdata):
2402 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002403 if self._more_args:
2404 result = self._passphrase(size, rwflag, userdata)
2405 else:
2406 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002407 if not isinstance(result, bytes):
2408 raise ValueError("String expected")
2409 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002410 if self._truncate:
2411 result = result[:size]
2412 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002413 raise ValueError(
2414 "passphrase returned by callback is too long"
2415 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002416 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002417 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002418 return len(result)
2419 except Exception as e:
2420 self._problems.append(e)
2421 return 0
2422
2423
Cory Benfield6492f7c2015-10-27 16:57:58 +09002424def load_publickey(type, buffer):
2425 """
Cory Benfield11c10192015-10-27 17:23:03 +09002426 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002427
Cory Benfield9c590b92015-10-28 14:55:05 +09002428 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002429 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002430 :param buffer: The buffer the key is stored in.
2431 :type buffer: A Python string object, either unicode or bytestring.
2432 :return: The PKey object.
2433 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002434 """
2435 if isinstance(buffer, _text_type):
2436 buffer = buffer.encode("ascii")
2437
2438 bio = _new_mem_buf(buffer)
2439
2440 if type == FILETYPE_PEM:
2441 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2442 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2443 elif type == FILETYPE_ASN1:
2444 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2445 else:
2446 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2447
2448 if evp_pkey == _ffi.NULL:
2449 _raise_current_error()
2450
2451 pkey = PKey.__new__(PKey)
2452 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
2453 return pkey
2454
2455
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002456def load_privatekey(type, buffer, passphrase=None):
2457 """
2458 Load a private key from a buffer
2459
2460 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2461 :param buffer: The buffer the key is stored in
2462 :param passphrase: (optional) if encrypted PEM format, this can be
2463 either the passphrase to use, or a callback for
2464 providing the passphrase.
2465
2466 :return: The PKey object
2467 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002468 if isinstance(buffer, _text_type):
2469 buffer = buffer.encode("ascii")
2470
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002471 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002472
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002473 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002474 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002475 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2476 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002477 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002478 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002479 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002480 else:
2481 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2482
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002483 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002484 _raise_current_error()
2485
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002486 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002487 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002488 return pkey
2489
2490
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002491def dump_certificate_request(type, req):
2492 """
2493 Dump a certificate request to a buffer
2494
2495 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2496 :param req: The certificate request to dump
2497 :return: The buffer with the dumped certificate request in
2498 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002499 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002500
2501 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002502 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002503 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002504 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002505 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002506 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002507 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002508 raise ValueError(
2509 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2510 "FILETYPE_TEXT"
2511 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002512
2513 if result_code == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002514 # TODO: This is untested.
2515 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002516
2517 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002518
2519
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002520def load_certificate_request(type, buffer):
2521 """
2522 Load a certificate request from a buffer
2523
2524 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2525 :param buffer: The buffer the certificate request is stored in
2526 :return: The X509Req object
2527 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002528 if isinstance(buffer, _text_type):
2529 buffer = buffer.encode("ascii")
2530
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002531 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002532
2533 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002534 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002535 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002536 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002537 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002538 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002539
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002540 if req == _ffi.NULL:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002541 # TODO: This is untested.
2542 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002543
2544 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002545 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002546 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002547
2548
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002549def sign(pkey, data, digest):
2550 """
2551 Sign data with a digest
2552
2553 :param pkey: Pkey to sign with
2554 :param data: data to be signed
2555 :param digest: message digest to use
2556 :return: signature
2557 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002558 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002559
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002560 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002561 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002562 raise ValueError("No such digest method")
2563
Alex Gaynor67903a62016-06-02 10:37:13 -07002564 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002565 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002566
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002567 _lib.EVP_SignInit(md_ctx, digest_obj)
2568 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002569
Colleen Murphye09399b2016-03-01 17:40:49 -08002570 pkey_length = (PKey.bits(pkey) + 7) // 8
2571 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002572 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002573 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002574 md_ctx, signature_buffer, signature_length, pkey._pkey)
2575
2576 if final_result != 1:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002577 # TODO: This is untested.
2578 _raise_current_error()
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002579
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002580 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002581
2582
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002583def verify(cert, signature, data, digest):
2584 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002585 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002586
2587 :param cert: signing certificate (X509 object)
2588 :param signature: signature returned by sign function
2589 :param data: data to be verified
2590 :param digest: message digest to use
Alex Gaynor5945ea82015-09-05 14:59:06 -04002591 :return: :py:const:`None` if the signature is correct, raise exception
2592 otherwise
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002593 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002594 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002595
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002596 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002597 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002598 raise ValueError("No such digest method")
2599
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002600 pkey = _lib.X509_get_pubkey(cert._x509)
2601 if pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002602 # TODO: This is untested.
2603 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002604 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002605
Alex Gaynor67903a62016-06-02 10:37:13 -07002606 md_ctx = _lib.Cryptography_EVP_MD_CTX_new()
Alex Gaynor1f9d4de2016-06-02 11:01:52 -07002607 md_ctx = _ffi.gc(md_ctx, _lib.Cryptography_EVP_MD_CTX_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002609 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2610 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002611 verify_result = _lib.EVP_VerifyFinal(
2612 md_ctx, signature, len(signature), pkey
2613 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002614
2615 if verify_result != 1:
2616 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002617
2618
Dominic Chenf05b2122015-10-13 16:32:35 +00002619def dump_crl(type, crl):
2620 """
2621 Dump a certificate revocation list to a buffer.
2622
2623 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2624 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002625 :param CRL crl: The CRL to dump.
2626
Dominic Chenf05b2122015-10-13 16:32:35 +00002627 :return: The buffer with the CRL.
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002628 :rtype: :data:`bytes`
Dominic Chenf05b2122015-10-13 16:32:35 +00002629 """
2630 bio = _new_mem_buf()
2631
2632 if type == FILETYPE_PEM:
2633 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2634 elif type == FILETYPE_ASN1:
2635 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2636 elif type == FILETYPE_TEXT:
2637 ret = _lib.X509_CRL_print(bio, crl._crl)
2638 else:
2639 raise ValueError(
2640 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2641 "FILETYPE_TEXT")
2642
2643 assert ret == 1
2644 return _bio_to_string(bio)
2645
2646
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002647def load_crl(type, buffer):
2648 """
2649 Load a certificate revocation list from a buffer
2650
2651 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2652 :param buffer: The buffer the CRL is stored in
2653
2654 :return: The PKey object
2655 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002656 if isinstance(buffer, _text_type):
2657 buffer = buffer.encode("ascii")
2658
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002659 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002660
2661 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002662 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002663 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002664 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002665 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002666 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2667
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002668 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002669 _raise_current_error()
2670
2671 result = CRL.__new__(CRL)
2672 result._crl = crl
2673 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002674
2675
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002676def load_pkcs7_data(type, buffer):
2677 """
2678 Load pkcs7 data from a buffer
2679
2680 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2681 :param buffer: The buffer with the pkcs7 data.
2682 :return: The PKCS7 object
2683 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002684 if isinstance(buffer, _text_type):
2685 buffer = buffer.encode("ascii")
2686
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002687 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002688
2689 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002690 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002691 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002692 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002693 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002694 # TODO: This is untested.
2695 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002696 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2697
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002698 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002699 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002700
2701 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002702 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002703 return pypkcs7
2704
2705
Stephen Holsapple38482622014-04-05 20:29:34 -07002706def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002707 """
2708 Load a PKCS12 object from a buffer
2709
2710 :param buffer: The buffer the certificate is stored in
2711 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2712 :returns: The PKCS12 object
2713 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002714 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002715
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002716 if isinstance(buffer, _text_type):
2717 buffer = buffer.encode("ascii")
2718
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002719 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002720
Stephen Holsapple38482622014-04-05 20:29:34 -07002721 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2722 # password based encryption no password and a zero length password are two
2723 # different things, but OpenSSL implementation will try both to figure out
2724 # which one works.
2725 if not passphrase:
2726 passphrase = _ffi.NULL
2727
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002728 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2729 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002730 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002731 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002732
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002733 pkey = _ffi.new("EVP_PKEY**")
2734 cert = _ffi.new("X509**")
2735 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002736
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002737 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002738 if not parse_result:
2739 _raise_current_error()
2740
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002741 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002742
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002743 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2744 # queue for no particular reason. This error isn't interesting to anyone
2745 # outside this function. It's not even interesting to us. Get rid of it.
2746 try:
2747 _raise_current_error()
2748 except Error:
2749 pass
2750
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002751 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002752 pykey = None
2753 else:
2754 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002755 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002756
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002757 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002758 pycert = None
2759 friendlyname = None
2760 else:
2761 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002762 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002763
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002764 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002765 friendlyname_buffer = _lib.X509_alias_get0(
2766 cert[0], friendlyname_length
2767 )
2768 friendlyname = _ffi.buffer(
2769 friendlyname_buffer, friendlyname_length[0]
2770 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002771 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002772 friendlyname = None
2773
2774 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002775 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002776 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002777 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002778 pycacerts.append(pycacert)
2779 if not pycacerts:
2780 pycacerts = None
2781
2782 pkcs12 = PKCS12.__new__(PKCS12)
2783 pkcs12._pkey = pykey
2784 pkcs12._cert = pycert
2785 pkcs12._cacerts = pycacerts
2786 pkcs12._friendlyname = friendlyname
2787 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002788
2789
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002790# There are no direct unit tests for this initialization. It is tested
2791# indirectly since it is necessary for functions like dump_privatekey when
2792# using encryption.
2793#
2794# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2795# and some other similar tests may fail without this (though they may not if
2796# the Python runtime has already done some initialization of the underlying
2797# OpenSSL library (and is linked against the same one that cryptography is
2798# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002799_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002800
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002801# This is similar but exercised mainly by exception_from_error_queue. It calls
2802# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2803_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002804
2805
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002806# Set the default string mask to match OpenSSL upstream (since 2005) and
2807# RFC5280 recommendations.
2808_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')