blob: 71fafab2208360e4a3bcd46ed64dffa2cda2aa2a [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,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -040021)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080022
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050023FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
24FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080025
26# TODO This was an API mistake. OpenSSL has no such constant.
27FILETYPE_TEXT = 2 ** 16 - 1
28
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050029TYPE_RSA = _lib.EVP_PKEY_RSA
30TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080031
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080032
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050033class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050034 """
35 An error occurred in an `OpenSSL.crypto` API.
36 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050037
38
39_raise_current_error = partial(_exception_from_error_queue, Error)
40
Stephen Holsapple0d9815f2014-08-27 19:36:53 -070041
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050042def _untested_error(where):
43 """
44 An OpenSSL API failed somehow. Additionally, the failure which was
45 encountered isn't one that's exercised by the test suite so future behavior
46 of pyOpenSSL is now somewhat less predictable.
47 """
48 raise RuntimeError("Unknown %s failure" % (where,))
49
50
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050051def _new_mem_buf(buffer=None):
52 """
53 Allocate a new OpenSSL memory BIO.
54
55 Arrange for the garbage collector to clean it up automatically.
56
57 :param buffer: None or some bytes to use to put into the BIO so that they
58 can be read out.
59 """
60 if buffer is None:
61 bio = _lib.BIO_new(_lib.BIO_s_mem())
62 free = _lib.BIO_free
63 else:
64 data = _ffi.new("char[]", buffer)
65 bio = _lib.BIO_new_mem_buf(data, len(buffer))
Alex Gaynor5945ea82015-09-05 14:59:06 -040066
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050067 # Keep the memory alive as long as the bio is alive!
68 def free(bio, ref=data):
69 return _lib.BIO_free(bio)
70
71 if bio == _ffi.NULL:
72 # TODO: This is untested.
73 _raise_current_error()
74
75 bio = _ffi.gc(bio, free)
76 return bio
77
78
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080079def _bio_to_string(bio):
80 """
81 Copy the contents of an OpenSSL BIO object into a Python byte string.
82 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050083 result_buffer = _ffi.new('char**')
84 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
85 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080086
87
Jean-Paul Calderone57122982013-02-21 08:47:05 -080088def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050089 """
90 The the time value of an ASN1 time object.
91
92 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
93 castable to that type) which will have its value set.
94 @param when: A string representation of the desired time value.
95
96 @raise TypeError: If C{when} is not a L{bytes} string.
97 @raise ValueError: If C{when} does not represent a time in the required
98 format.
99 @raise RuntimeError: If the time value cannot be set for some other
100 (unspecified) reason.
101 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800102 if not isinstance(when, bytes):
103 raise TypeError("when must be a byte string")
104
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500105 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
106 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800107 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500108 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
109 _lib.ASN1_STRING_set(dummy, when, len(when))
110 check_result = _lib.ASN1_GENERALIZEDTIME_check(
111 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800112 if not check_result:
113 raise ValueError("Invalid string")
114 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500115 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800116
117
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800118def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500119 """
120 Retrieve the time value of an ASN1 time object.
121
122 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
123 that type) from which the time value will be retrieved.
124
125 @return: The time value from C{timestamp} as a L{bytes} string in a certain
126 format. Or C{None} if the object contains no time value.
127 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
129 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800130 return None
Alex Gaynor5945ea82015-09-05 14:59:06 -0400131 elif (
132 _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
133 ):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500134 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800135 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500136 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
137 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
138 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500139 # This may happen:
140 # - if timestamp was not an ASN1_TIME
141 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
142 # - if a copy of the time data from timestamp cannot be made for
143 # the newly allocated ASN1_GENERALIZEDTIME
144 #
145 # These are difficult to test. cffi enforces the ASN1_TIME type.
146 # Memory allocation failures are a pain to trigger
147 # deterministically.
148 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800149 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500150 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800151 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500152 string_data = _lib.ASN1_STRING_data(string_timestamp)
153 string_result = _ffi.string(string_data)
154 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800155 return string_result
156
157
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800158class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200159 """
160 A class representing an DSA or RSA public key or key pair.
161 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800162 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800163 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800164
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800165 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500166 pkey = _lib.EVP_PKEY_new()
167 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800168 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800169
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800170 def generate_key(self, type, bits):
171 """
Laurens Van Houtven90c09142015-04-23 10:52:49 -0700172 Generate a key pair of the given type, with the given number of bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800173
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200174 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800175
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200176 :param type: The key type.
177 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
178 :param bits: The number of bits.
179 :type bits: :py:data:`int` ``>= 0``
180 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
181 of the appropriate type.
182 :raises ValueError: If the number of bits isn't an integer of
183 the appropriate size.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200184 :return: :py:const:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800185 """
186 if not isinstance(type, int):
187 raise TypeError("type must be an integer")
188
189 if not isinstance(bits, int):
190 raise TypeError("bits must be an integer")
191
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800192 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500193 exponent = _lib.BN_new()
194 exponent = _ffi.gc(exponent, _lib.BN_free)
195 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800196
197 if type == TYPE_RSA:
198 if bits <= 0:
199 raise ValueError("Invalid number of bits")
200
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500201 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800202
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500203 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500204 if result == 0:
205 # TODO: The test for this case is commented out. Different
206 # builds of OpenSSL appear to have different failure modes that
207 # make it hard to test. Visual inspection of the OpenSSL
208 # source reveals that a return value of 0 signals an error.
209 # Manual testing on a particular build of OpenSSL suggests that
210 # this is probably the appropriate way to handle those errors.
211 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800212
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500213 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800214 if not result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500215 # TODO: It appears as though this can fail if an engine is in
216 # use which does not support RSA.
217 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800218
219 elif type == TYPE_DSA:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500220 dsa = _lib.DSA_generate_parameters(
221 bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)
222 if dsa == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500223 # TODO: This is untested.
224 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500225 if not _lib.DSA_generate_key(dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500226 # TODO: This is untested.
227 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500228 if not _lib.EVP_PKEY_assign_DSA(self._pkey, dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500229 # TODO: This is untested.
230 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800231 else:
232 raise Error("No such key type")
233
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800234 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800235
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800236 def check(self):
237 """
238 Check the consistency of an RSA private key.
239
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200240 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
241
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800242 :return: True if key is consistent.
243 :raise Error: if the key is inconsistent.
244 :raise TypeError: if the key is of a type which cannot be checked.
245 Only RSA keys can currently be checked.
246 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800247 if self._only_public:
248 raise TypeError("public key only")
249
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100250 if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800251 raise TypeError("key type unsupported")
252
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500253 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
254 rsa = _ffi.gc(rsa, _lib.RSA_free)
255 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800256 if result:
257 return True
258 _raise_current_error()
259
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800260 def type(self):
261 """
262 Returns the type of the key
263
264 :return: The type of the key.
265 """
Hynek Schlawack2a91ba32016-01-31 14:18:54 +0100266 try:
267 # cryptography 1.2+
268 return _lib.Cryptography_EVP_PKEY_id(self._pkey)
269 except AttributeError:
270 # Older releases of cryptography.
271 return self._pkey.type
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800272
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800273 def bits(self):
274 """
275 Returns the number of bits of the key
276
277 :return: The number of bits of the key.
278 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500279 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800280PKeyType = PKey
281
282
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400283class _EllipticCurve(object):
284 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400285 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400286
287 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
288 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
289 instances each of which represents one curve supported by the system.
290 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400291 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400292 _curves = None
293
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400294 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400295 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400296 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400297 """
298 Implement cooperation with the right-hand side argument of ``!=``.
299
300 Python 3 seems to have dropped this cooperation in this very narrow
301 circumstance.
302 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400303 if isinstance(other, _EllipticCurve):
304 return super(_EllipticCurve, self).__ne__(other)
305 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400306
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400307 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400308 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400309 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400310 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400311
312 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400313
314 :return: A :py:type:`set` of ``cls`` instances giving the names of the
315 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400316 """
317 if lib.Cryptography_HAS_EC:
318 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
319 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
Alex Gaynor5945ea82015-09-05 14:59:06 -0400320 # The return value on this call should be num_curves again. We
321 # could check it to make sure but if it *isn't* then.. what could
322 # we do? Abort the whole process, I suppose...? -exarkun
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400323 lib.EC_get_builtin_curves(builtin_curves, num_curves)
324 return set(
325 cls.from_nid(lib, c.nid)
326 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400327 return set()
328
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400329 @classmethod
330 def _get_elliptic_curves(cls, lib):
331 """
332 Get, cache, and return the curves supported by OpenSSL.
333
334 :param lib: The OpenSSL library binding object.
335
336 :return: A :py:type:`set` of ``cls`` instances giving the names of the
337 elliptic curves the underlying library supports.
338 """
339 if cls._curves is None:
340 cls._curves = cls._load_elliptic_curves(lib)
341 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400342
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400343 @classmethod
344 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400345 """
346 Instantiate a new :py:class:`_EllipticCurve` associated with the given
347 OpenSSL NID.
348
349 :param lib: The OpenSSL library binding object.
350
351 :param nid: The OpenSSL NID the resulting curve object will represent.
352 This must be a curve NID (and not, for example, a hash NID) or
353 subsequent operations will fail in unpredictable ways.
354 :type nid: :py:class:`int`
355
356 :return: The curve object.
357 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400358 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
359
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400360 def __init__(self, lib, nid, name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400361 """
362 :param _lib: The :py:mod:`cryptography` binding instance used to
363 interface with OpenSSL.
364
365 :param _nid: The OpenSSL NID identifying the curve this object
366 represents.
367 :type _nid: :py:class:`int`
368
369 :param name: The OpenSSL short name identifying the curve this object
370 represents.
371 :type name: :py:class:`unicode`
372 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400373 self._lib = lib
374 self._nid = nid
375 self.name = name
376
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400377 def __repr__(self):
378 return "<Curve %r>" % (self.name,)
379
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400380 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400381 """
382 Create a new OpenSSL EC_KEY structure initialized to use this curve.
383
384 The structure is automatically garbage collected when the Python object
385 is garbage collected.
386 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400387 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
388 return _ffi.gc(key, _lib.EC_KEY_free)
389
390
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400391def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400392 """
393 Return a set of objects representing the elliptic curves supported in the
394 OpenSSL build in use.
395
396 The curve objects have a :py:class:`unicode` ``name`` attribute by which
397 they identify themselves.
398
399 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400400 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
401 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400402 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400403 return _EllipticCurve._get_elliptic_curves(_lib)
404
405
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400406def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400407 """
408 Return a single curve object selected by name.
409
410 See :py:func:`get_elliptic_curves` for information about curve objects.
411
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400412 :param name: The OpenSSL short name identifying the curve object to
413 retrieve.
414 :type name: :py:class:`unicode`
415
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400416 If the named curve is not supported then :py:class:`ValueError` is raised.
417 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400418 for curve in get_elliptic_curves():
419 if curve.name == name:
420 return curve
421 raise ValueError("unknown curve name", name)
422
423
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800424class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200425 """
426 An X.509 Distinguished Name.
427
428 :ivar countryName: The country of the entity.
429 :ivar C: Alias for :py:attr:`countryName`.
430
431 :ivar stateOrProvinceName: The state or province of the entity.
432 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
433
434 :ivar localityName: The locality of the entity.
435 :ivar L: Alias for :py:attr:`localityName`.
436
437 :ivar organizationName: The organization name of the entity.
438 :ivar O: Alias for :py:attr:`organizationName`.
439
440 :ivar organizationalUnitName: The organizational unit of the entity.
441 :ivar OU: Alias for :py:attr:`organizationalUnitName`
442
443 :ivar commonName: The common name of the entity.
444 :ivar CN: Alias for :py:attr:`commonName`.
445
446 :ivar emailAddress: The e-mail address of the entity.
447 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400448
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800449 def __init__(self, name):
450 """
451 Create a new X509Name, copying the given X509Name instance.
452
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200453 :param name: The name to copy.
454 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800455 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500456 name = _lib.X509_NAME_dup(name._name)
457 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800458
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800459 def __setattr__(self, name, value):
460 if name.startswith('_'):
461 return super(X509Name, self).__setattr__(name, value)
462
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800463 # Note: we really do not want str subclasses here, so we do not use
464 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800465 if type(name) is not str:
466 raise TypeError("attribute name must be string, not '%.200s'" % (
Alex Gaynora738ed52015-09-05 11:17:10 -0400467 type(value).__name__,))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800468
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500469 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500470 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800471 try:
472 _raise_current_error()
473 except Error:
474 pass
475 raise AttributeError("No such attribute")
476
477 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500478 for i in range(_lib.X509_NAME_entry_count(self._name)):
479 ent = _lib.X509_NAME_get_entry(self._name, i)
480 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
481 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800482 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500483 ent = _lib.X509_NAME_delete_entry(self._name, i)
484 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800485 break
486
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500487 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800488 value = value.encode('utf-8')
489
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500490 add_result = _lib.X509_NAME_add_entry_by_NID(
491 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800492 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500493 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800494
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800495 def __getattr__(self, name):
496 """
497 Find attribute. An X509Name object has the following attributes:
498 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
Alex Gaynor5945ea82015-09-05 14:59:06 -0400499 organization (alias O), organizationalUnit (alias OU), commonName
500 (alias CN) and more...
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800501 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500502 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500503 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800504 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
505 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
506 # push something onto the error queue. If we don't clean that up
507 # now, someone else will bump into it later and be quite confused.
508 # See lp#314814.
509 try:
510 _raise_current_error()
511 except Error:
512 pass
513 return super(X509Name, self).__getattr__(name)
514
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500515 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800516 if entry_index == -1:
517 return None
518
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500519 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
520 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800521
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500522 result_buffer = _ffi.new("unsigned char**")
523 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800524 if data_length < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500525 # TODO: This is untested.
526 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800527
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700528 try:
Alex Gaynor5945ea82015-09-05 14:59:06 -0400529 result = _ffi.buffer(
530 result_buffer[0], data_length
531 )[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700532 finally:
533 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500534 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800535 return result
536
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500537 def _cmp(op):
538 def f(self, other):
539 if not isinstance(other, X509Name):
540 return NotImplemented
541 result = _lib.X509_NAME_cmp(self._name, other._name)
542 return op(result, 0)
543 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800544
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500545 __eq__ = _cmp(__eq__)
546 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800547
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500548 __lt__ = _cmp(__lt__)
549 __le__ = _cmp(__le__)
550
551 __gt__ = _cmp(__gt__)
552 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800553
554 def __repr__(self):
555 """
556 String representation of an X509Name
557 """
Alex Gaynor962ac212015-09-04 08:06:42 -0400558 result_buffer = _ffi.new("char[]", 512)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500559 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800560 self._name, result_buffer, len(result_buffer))
561
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500562 if format_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500563 # TODO: This is untested.
564 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800565
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500566 return "<X509Name object '%s'>" % (
567 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800568
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800569 def hash(self):
570 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200571 Return an integer representation of the first four bytes of the
572 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800573
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200574 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
575
576 :return: The (integer) hash of this name.
577 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800578 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500579 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800580
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800581 def der(self):
582 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200583 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800584
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200585 :return: The DER encoded form of this name.
586 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800587 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500588 result_buffer = _ffi.new('unsigned char**')
589 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800590 if encode_result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500591 # TODO: This is untested.
592 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800593
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500594 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
595 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800596 return string_result
597
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800598 def get_components(self):
599 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200600 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800601
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200602 :return: The components of this name.
603 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800604 """
605 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500606 for i in range(_lib.X509_NAME_entry_count(self._name)):
607 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800608
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500609 fname = _lib.X509_NAME_ENTRY_get_object(ent)
610 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800611
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500612 nid = _lib.OBJ_obj2nid(fname)
613 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800614
615 result.append((
Alex Gaynora738ed52015-09-05 11:17:10 -0400616 _ffi.string(name),
617 _ffi.string(
618 _lib.ASN1_STRING_data(fval),
619 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800620
621 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200622
623
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800624X509NameType = X509Name
625
626
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800627class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200628 """
629 An X.509 v3 certificate extension.
630 """
Alex Gaynor5945ea82015-09-05 14:59:06 -0400631
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800632 def __init__(self, type_name, critical, value, subject=None, issuer=None):
633 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200634 Initializes an X509 extension.
635
Alex Gaynor6f719912015-09-20 09:21:29 -0400636 :param type_name: The name of the type of extension to create. See
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200637 http://openssl.org/docs/apps/x509v3_config.html#STANDARD_EXTENSIONS
Alex Gaynor6f719912015-09-20 09:21:29 -0400638 :type type_name: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800639
Alex Gaynor5945ea82015-09-05 14:59:06 -0400640 :param bool critical: A flag indicating whether this is a critical
641 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800642
643 :param value: The value of the extension.
Maximilian Hils0de43752015-09-18 15:26:54 +0200644 :type value: :py:data:`bytes`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800645
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200646 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800647 :type subject: :py:class:`X509`
648
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200649 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800650 :type issuer: :py:class:`X509`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800651 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500652 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800653
Alex Gaynor5945ea82015-09-05 14:59:06 -0400654 # A context is necessary for any extension which uses the r2i
655 # conversion method. That is, X509V3_EXT_nconf may segfault if passed
656 # a NULL ctx. Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500657 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800658
659 # We have no configuration database - but perhaps we should (some
660 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500661 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800662
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800663 # Initialize the subject and issuer, if appropriate. ctx is a local,
664 # and as far as I can tell none of the X509V3_* APIs invoked here steal
Alex Gaynora738ed52015-09-05 11:17:10 -0400665 # any references, so no need to mess with reference counts or
666 # duplicates.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800667 if issuer is not None:
668 if not isinstance(issuer, X509):
669 raise TypeError("issuer must be an X509 instance")
670 ctx.issuer_cert = issuer._x509
671 if subject is not None:
672 if not isinstance(subject, X509):
673 raise TypeError("subject must be an X509 instance")
674 ctx.subject_cert = subject._x509
675
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800676 if critical:
677 # There are other OpenSSL APIs which would let us pass in critical
678 # separately, but they're harder to use, and since value is already
679 # a pile of crappy junk smuggling a ton of utterly important
680 # structured data, what's the point of trying to avoid nasty stuff
Alex Gaynor5945ea82015-09-05 14:59:06 -0400681 # with strings? (However, X509V3_EXT_i2d in particular seems like
682 # it would be a better API to invoke. I do not know where to get
683 # the ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500684 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800685
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500686 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
687 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800688 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500689 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800690
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400691 @property
692 def _nid(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500693 return _lib.OBJ_obj2nid(self._extension.object)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400694
695 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500696 _lib.GEN_EMAIL: "email",
697 _lib.GEN_DNS: "DNS",
698 _lib.GEN_URI: "URI",
Alex Gaynora738ed52015-09-05 11:17:10 -0400699 }
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400700
701 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500702 method = _lib.X509V3_EXT_get(self._extension)
703 if method == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500704 # TODO: This is untested.
705 _raise_current_error()
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400706 payload = self._extension.value.data
707 length = self._extension.value.length
708
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500709 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400710 payloadptr[0] = payload
711
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500712 if method.it != _ffi.NULL:
713 ptr = _lib.ASN1_ITEM_ptr(method.it)
714 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
715 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400716 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400718 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500719 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400720
Paul Kehrerb7d79502015-05-04 07:43:51 -0500721 names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400722 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500723 for i in range(_lib.sk_GENERAL_NAME_num(names)):
724 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400725 try:
726 label = self._prefixes[name.type]
727 except KeyError:
728 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500729 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500730 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400731 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500732 value = _native(
733 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
734 parts.append(label + ":" + value)
735 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400736
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800737 def __str__(self):
738 """
739 :return: a nice text representation of the extension
740 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500741 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400742 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800743
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400744 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500745 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800746 if not print_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500747 # TODO: This is untested.
748 _raise_current_error()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800749
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500750 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800751
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800752 def get_critical(self):
753 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200754 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800755
756 :return: The critical field.
757 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500758 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800759
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800760 def get_short_name(self):
761 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200762 Returns the short type name of this X.509 extension.
763
764 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800765
766 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200767 :rtype: :py:data:`bytes`
768
769 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800770 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500771 obj = _lib.X509_EXTENSION_get_object(self._extension)
772 nid = _lib.OBJ_obj2nid(obj)
773 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800774
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800775 def get_data(self):
776 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200777 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800778
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200779 :return: The ASN.1 encoded data of this X509 extension.
780 :rtype: :py:data:`bytes`
781
782 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800783 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500784 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
785 string_result = _ffi.cast('ASN1_STRING*', octet_result)
786 char_result = _lib.ASN1_STRING_data(string_result)
787 result_length = _lib.ASN1_STRING_length(string_result)
788 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800789
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200790
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800791X509ExtensionType = X509Extension
792
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800793
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800794class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200795 """
796 An X.509 certificate signing requests.
797 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400798
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800799 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500800 req = _lib.X509_REQ_new()
801 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800802
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800803 def set_pubkey(self, pkey):
804 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200805 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800806
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200807 :param pkey: The public key to use.
808 :type pkey: :py:class:`PKey`
809
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200810 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800811 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500812 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800813 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500814 # TODO: This is untested.
815 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800816
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800817 def get_pubkey(self):
818 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200819 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800820
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200821 :return: The public key.
822 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800823 """
824 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500825 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
826 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500827 # TODO: This is untested.
828 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500829 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800830 pkey._only_public = True
831 return pkey
832
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800833 def set_version(self, version):
834 """
835 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
836 request.
837
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200838 :param int version: The version number.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200839 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800840 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500841 set_result = _lib.X509_REQ_set_version(self._req, version)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800842 if not set_result:
843 _raise_current_error()
844
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800845 def get_version(self):
846 """
847 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
848 request.
849
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200850 :return: The value of the version subfield.
851 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800852 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500853 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800854
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800855 def get_subject(self):
856 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200857 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800858
Cory Benfield881dc8d2015-12-09 08:25:14 +0000859 This creates a new :class:`X509Name` that wraps the underlying subject
860 name field on the certificate signing request. Modifying it will modify
861 the underlying signing request, and will have the effect of modifying
862 any other :class:`X509Name` that refers to this subject.
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200863
864 :return: The subject of this certificate signing request.
Cory Benfield881dc8d2015-12-09 08:25:14 +0000865 :rtype: :class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800866 """
867 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500868 name._name = _lib.X509_REQ_get_subject_name(self._req)
869 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500870 # TODO: This is untested.
871 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800872
873 # The name is owned by the X509Req structure. As long as the X509Name
874 # Python object is alive, keep the X509Req Python object alive.
875 name._owner = self
876
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800877 return name
878
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800879 def add_extensions(self, extensions):
880 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200881 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800882
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200883 :param extensions: The X.509 extensions to add.
884 :type extensions: iterable of :py:class:`X509Extension`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200885 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800886 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500887 stack = _lib.sk_X509_EXTENSION_new_null()
888 if stack == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500889 # TODO: This is untested.
890 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800891
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500892 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800893
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800894 for ext in extensions:
895 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800896 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800897
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800898 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500899 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800900
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500901 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800902 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500903 # TODO: This is untested.
904 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800905
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800906 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800907 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200908 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800909
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200910 :return: The X.509 extensions in this request.
911 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
912
913 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800914 """
915 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500916 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500917 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800918 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500919 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800920 exts.append(ext)
921 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800922
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800923 def sign(self, pkey, digest):
924 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -0700925 Sign the certificate signing request with this key and digest type.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800926
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200927 :param pkey: The key pair to sign with.
928 :type pkey: :py:class:`PKey`
929 :param digest: The name of the message digest to use for the signature,
930 e.g. :py:data:`b"sha1"`.
931 :type digest: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200932 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800933 """
934 if pkey._only_public:
935 raise ValueError("Key has only public part")
936
937 if not pkey._initialized:
938 raise ValueError("Key is uninitialized")
939
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500940 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500941 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800942 raise ValueError("No such digest method")
943
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500944 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800945 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500946 # TODO: This is untested.
947 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800948
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800949 def verify(self, pkey):
950 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200951 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800952
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200953 :param key: A public key.
954 :type key: :py:class:`PKey`
955 :return: :py:data:`True` if the signature is correct.
956 :rtype: :py:class:`bool`
957 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800958 problem verifying the signature.
959 """
960 if not isinstance(pkey, PKey):
961 raise TypeError("pkey must be a PKey instance")
962
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500963 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800964 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500965 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800966
967 return result
968
969
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800970X509ReqType = X509Req
971
972
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800973class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200974 """
975 An X.509 certificate.
976 """
Alex Gaynora738ed52015-09-05 11:17:10 -0400977
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800978 def __init__(self):
979 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500980 x509 = _lib.X509_new()
981 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800982
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800983 def set_version(self, version):
984 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200985 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800986
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200987 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800988 :type version: :py:class:`int`
989
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200990 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800991 """
992 if not isinstance(version, int):
993 raise TypeError("version must be an integer")
994
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500995 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800996
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800997 def get_version(self):
998 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200999 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001000
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001001 :return: The version number of the certificate.
1002 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001003 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001004 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001005
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001006 def get_pubkey(self):
1007 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001008 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001009
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001010 :return: The public key.
1011 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001012 """
1013 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001014 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1015 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001016 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001017 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001018 pkey._only_public = True
1019 return pkey
1020
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001021 def set_pubkey(self, pkey):
1022 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001023 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001024
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001025 :param pkey: The public key.
1026 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001027
Laurens Van Houtven33fcf122015-04-23 10:50:08 -07001028 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001029 """
1030 if not isinstance(pkey, PKey):
1031 raise TypeError("pkey must be a PKey instance")
1032
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001033 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001034 if not set_result:
1035 _raise_current_error()
1036
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001037 def sign(self, pkey, digest):
1038 """
Laurens Van Houtven6f2e4262015-04-23 10:48:32 -07001039 Sign the certificate with this key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001040
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001041 :param pkey: The key to sign with.
1042 :type pkey: :py:class:`PKey`
1043
1044 :param digest: The name of the message digest to use.
1045 :type digest: :py:class:`bytes`
1046
Laurens Van Houtvena367fe82015-04-23 10:49:12 -07001047 :return: :py:data:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001048 """
1049 if not isinstance(pkey, PKey):
1050 raise TypeError("pkey must be a PKey instance")
1051
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001052 if pkey._only_public:
1053 raise ValueError("Key only has public part")
1054
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001055 if not pkey._initialized:
1056 raise ValueError("Key is uninitialized")
1057
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001058 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001059 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001060 raise ValueError("No such digest method")
1061
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001062 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001063 if not sign_result:
1064 _raise_current_error()
1065
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001066 def get_signature_algorithm(self):
1067 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001068 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001069
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001070 :return: The name of the algorithm.
1071 :rtype: :py:class:`bytes`
1072
1073 :raises ValueError: If the signature algorithm is undefined.
1074
Laurens Van Houtven0dd87402015-04-23 10:47:18 -07001075 .. versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001076 """
1077 alg = self._x509.cert_info.signature.algorithm
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001078 nid = _lib.OBJ_obj2nid(alg)
1079 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001080 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001081 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001082
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001083 def digest(self, digest_name):
1084 """
1085 Return the digest of the X509 object.
1086
1087 :param digest_name: The name of the digest algorithm to use.
1088 :type digest_name: :py:class:`bytes`
1089
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001090 :return: The digest of the object, formatted as
1091 :py:const:`b":"`-delimited hex pairs.
1092 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001093 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001094 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001095 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001096 raise ValueError("No such digest method")
1097
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001098 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1099 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001100 result_length[0] = len(result_buffer)
1101
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001102 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001103 self._x509, digest, result_buffer, result_length)
1104
1105 if not digest_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001106 # TODO: This is untested.
1107 _raise_current_error()
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001108
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001109 return b":".join([
Alex Gaynora738ed52015-09-05 11:17:10 -04001110 b16encode(ch).upper() for ch
1111 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001112
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001113 def subject_name_hash(self):
1114 """
1115 Return the hash of the X509 subject.
1116
1117 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001118 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001119 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001120 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001121
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001122 def set_serial_number(self, serial):
1123 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001124 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001125
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001126 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001127 :type serial: :py:class:`int`
1128
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001129 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001130 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001131 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001132 raise TypeError("serial must be an integer")
1133
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001134 hex_serial = hex(serial)[2:]
1135 if not isinstance(hex_serial, bytes):
1136 hex_serial = hex_serial.encode('ascii')
1137
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001138 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001139
1140 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
Alex Gaynor5945ea82015-09-05 14:59:06 -04001141 # it. If bignum is still NULL after this call, then the return value
1142 # is actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001143 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001144
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001145 if bignum_serial[0] == _ffi.NULL:
1146 set_result = _lib.ASN1_INTEGER_set(
1147 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001148 if set_result:
1149 # TODO Not tested
1150 _raise_current_error()
1151 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001152 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1153 _lib.BN_free(bignum_serial[0])
1154 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001155 # TODO Not tested
1156 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001157 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1158 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001159 if not set_result:
1160 # TODO Not tested
1161 _raise_current_error()
1162
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001163 def get_serial_number(self):
1164 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001165 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001166
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001167 :return: The serial number.
1168 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001169 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001170 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1171 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001172 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001173 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001174 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001175 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001176 serial = int(hexstring_serial, 16)
1177 return serial
1178 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001179 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001180 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001182
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001183 def gmtime_adj_notAfter(self, amount):
1184 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001185 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001186
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001187 :param amount: The number of seconds by which to adjust the timestamp.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001188 :type amount: :py:class:`int`
1189
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001190 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001191 """
1192 if not isinstance(amount, int):
1193 raise TypeError("amount must be an integer")
1194
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001195 notAfter = _lib.X509_get_notAfter(self._x509)
1196 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001197
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001198 def gmtime_adj_notBefore(self, amount):
1199 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001200 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001201
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001202 :param amount: The number of seconds by which to adjust the timestamp.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001203 :return: :py:const:`None`
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001204 """
1205 if not isinstance(amount, int):
1206 raise TypeError("amount must be an integer")
1207
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001208 notBefore = _lib.X509_get_notBefore(self._x509)
1209 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001210
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001211 def has_expired(self):
1212 """
1213 Check whether the certificate has expired.
1214
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001215 :return: :py:const:`True` if the certificate has expired,
1216 :py:const:`False` otherwise.
1217 :rtype: :py:class:`bool`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001218 """
Paul Kehrer8d887e12015-10-24 09:09:55 -05001219 time_string = _native(self.get_notAfter())
Paul Kehrerfde45c92016-01-21 12:57:37 -06001220 not_after = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%SZ")
Paul Kehrer5d5d28d2015-10-21 18:55:22 -05001221
Paul Kehrerfde45c92016-01-21 12:57:37 -06001222 return not_after < datetime.datetime.utcnow()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001223
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001224 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001225 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001226
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001227 def get_notBefore(self):
1228 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001229 Get the timestamp at which the certificate starts being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001230
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001231 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001232
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001233 YYYYMMDDhhmmssZ
1234 YYYYMMDDhhmmss+hhmm
1235 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001236
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001237 :return: A timestamp string, or :py:const:`None` if there is none.
1238 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001239 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 return self._get_boundary_time(_lib.X509_get_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001241
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001242 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001243 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001244
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001245 def set_notBefore(self, when):
1246 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001247 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001248
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001249 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001250
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001251 YYYYMMDDhhmmssZ
1252 YYYYMMDDhhmmss+hhmm
1253 YYYYMMDDhhmmss-hhmm
1254
1255 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001256 :type when: :py:class:`bytes`
1257
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001258 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001259 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001260 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001261
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001262 def get_notAfter(self):
1263 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001264 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001265
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001266 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001267
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001268 YYYYMMDDhhmmssZ
1269 YYYYMMDDhhmmss+hhmm
1270 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001271
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001272 :return: A timestamp string, or :py:const:`None` if there is none.
1273 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001274 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001275 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001276
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001277 def set_notAfter(self, when):
1278 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001279 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001280
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001281 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001282
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001283 YYYYMMDDhhmmssZ
1284 YYYYMMDDhhmmss+hhmm
1285 YYYYMMDDhhmmss-hhmm
1286
1287 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001288 :type when: :py:class:`bytes`
1289
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001290 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001291 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001292 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001293
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001294 def _get_name(self, which):
1295 name = X509Name.__new__(X509Name)
1296 name._name = which(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001297 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001298 # TODO: This is untested.
1299 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001300
1301 # The name is owned by the X509 structure. As long as the X509Name
1302 # Python object is alive, keep the X509 Python object alive.
1303 name._owner = self
1304
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305 return name
1306
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001307 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001308 if not isinstance(name, X509Name):
1309 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001310 set_result = which(self._x509, name._name)
1311 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001312 # TODO: This is untested.
1313 _raise_current_error()
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001314
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001315 def get_issuer(self):
1316 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001317 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001318
Cory Benfielde6bcce82015-12-09 08:40:03 +00001319 This creates a new :class:`X509Name` that wraps the underlying issuer
1320 name field on the certificate. Modifying it will modify the underlying
1321 certificate, and will have the effect of modifying any other
1322 :class:`X509Name` that refers to this issuer.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001323
1324 :return: The issuer of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001325 :rtype: :class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001326 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001327 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001328
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001329 def set_issuer(self, issuer):
1330 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001331 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001332
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001333 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001334 :type issuer: :py:class:`X509Name`
1335
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001336 :return: :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001337 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001338 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001339
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001340 def get_subject(self):
1341 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001342 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001343
Cory Benfielde6bcce82015-12-09 08:40:03 +00001344 This creates a new :class:`X509Name` that wraps the underlying subject
1345 name field on the certificate. Modifying it will modify the underlying
1346 certificate, and will have the effect of modifying any other
1347 :class:`X509Name` that refers to this subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001348
1349 :return: The subject of this certificate.
Cory Benfielde6bcce82015-12-09 08:40:03 +00001350 :rtype: :class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001351 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001352 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001353
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001354 def set_subject(self, subject):
1355 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001356 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001357
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001358 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001359 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001360
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001361 :return: :py:const:`None`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001362 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001363 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001364
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001365 def get_extension_count(self):
1366 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001367 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001368
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001369 :return: The number of extensions.
1370 :rtype: :py:class:`int`
1371
1372 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001373 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001374 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001375
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001376 def add_extensions(self, extensions):
1377 """
1378 Add extensions to the certificate.
1379
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001380 :param extensions: The extensions to add.
1381 :type extensions: An iterable of :py:class:`X509Extension` objects.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001382 :return: :py:const:`None`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001383 """
1384 for ext in extensions:
1385 if not isinstance(ext, X509Extension):
1386 raise ValueError("One of the elements is not an X509Extension")
1387
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001388 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001389 if not add_result:
1390 _raise_current_error()
1391
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001392 def get_extension(self, index):
1393 """
1394 Get a specific extension of the certificate by index.
1395
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001396 Extensions on a certificate are kept in order. The index
1397 parameter selects which extension will be returned.
1398
1399 :param int index: The index of the extension to retrieve.
1400 :return: The extension at the specified index.
1401 :rtype: :py:class:`X509Extension`
1402 :raises IndexError: If the extension index was out of bounds.
1403
1404 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001405 """
1406 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001407 ext._extension = _lib.X509_get_ext(self._x509, index)
1408 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001409 raise IndexError("extension index out of bounds")
1410
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001411 extension = _lib.X509_EXTENSION_dup(ext._extension)
1412 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001413 return ext
1414
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001415
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001416X509Type = X509
1417
1418
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001419class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001420 """
1421 An X509 certificate store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001422 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001423
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001424 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001425 store = _lib.X509_STORE_new()
1426 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001427
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001428 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001429 """
1430 Adds the certificate :py:data:`cert` to this store.
1431
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +02001432 This is the Python equivalent of OpenSSL's ``X509_STORE_add_cert``.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001433
1434 :param X509 cert: The certificate to add to this store.
1435 :raises TypeError: If the certificate is not an :py:class:`X509`.
1436 :raises Error: If OpenSSL was unhappy with your certificate.
Laurens Van Houtven5ee60b32015-04-23 10:51:16 -07001437 :return: :py:data:`None` if the certificate was added successfully.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001438 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001439 if not isinstance(cert, X509):
1440 raise TypeError()
1441
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001442 result = _lib.X509_STORE_add_cert(self._store, cert._x509)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001443 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001444 _raise_current_error()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001445
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001446
1447X509StoreType = X509Store
1448
1449
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001450class X509StoreContextError(Exception):
1451 """
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001452 An exception raised when an error occurred while verifying a certificate
1453 using `OpenSSL.X509StoreContext.verify_certificate`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001454
Jean-Paul Calderonefeb17432015-03-15 15:49:45 -04001455 :ivar certificate: The certificate which caused verificate failure.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001456 :type certificate: :class:`X509`
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001457 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001458
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001459 def __init__(self, message, certificate):
1460 super(X509StoreContextError, self).__init__(message)
1461 self.certificate = certificate
1462
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001463
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001464class X509StoreContext(object):
1465 """
1466 An X.509 store context.
1467
Jean-Paul Calderone13a81682015-01-18 15:49:15 -05001468 An :py:class:`X509StoreContext` is used to define some of the criteria for
1469 certificate verification. The information encapsulated in this object
1470 includes, but is not limited to, a set of trusted certificates,
1471 verification parameters, and revoked certificates.
1472
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001473 .. note::
1474
1475 Currently, one can only set the trusted certificates on an
1476 :py:class:`X509StoreContext`. Future versions of pyOpenSSL will expose
1477 verification parameters and certificate revocation lists.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001478
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001479 :ivar _store_ctx: The underlying X509_STORE_CTX structure used by this
1480 instance. It is dynamically allocated and automatically garbage
1481 collected.
1482
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001483 :ivar _store: See the ``store`` ``__init__`` parameter.
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001484
Jean-Paul Calderone64b6b842015-03-15 16:08:02 -04001485 :ivar _cert: See the ``certificate`` ``__init__`` parameter.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001486
1487 :param X509Store store: The certificates which will be trusted for the
1488 purposes of any verifications.
1489
1490 :param X509 certificate: The certificate to be verified.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001491 """
1492
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001493 def __init__(self, store, certificate):
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001494 store_ctx = _lib.X509_STORE_CTX_new()
1495 self._store_ctx = _ffi.gc(store_ctx, _lib.X509_STORE_CTX_free)
1496 self._store = store
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001497 self._cert = certificate
Stephen Holsapple46a09252015-02-12 14:45:43 -08001498 # Make the store context available for use after instantiating this
1499 # class by initializing it now. Per testing, subsequent calls to
1500 # :py:meth:`_init` have no adverse affect.
1501 self._init()
Jean-Paul Calderoneb7b7fb92015-01-18 15:37:10 -05001502
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001503 def _init(self):
1504 """
1505 Set up the store context for a subsequent verification operation.
1506 """
Alex Gaynor5945ea82015-09-05 14:59:06 -04001507 ret = _lib.X509_STORE_CTX_init(
1508 self._store_ctx, self._store._store, self._cert._x509, _ffi.NULL
1509 )
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001510 if ret <= 0:
1511 _raise_current_error()
1512
1513 def _cleanup(self):
1514 """
1515 Internally cleans up the store context.
1516
1517 The store context can then be reused with a new call to
Stephen Holsapple46a09252015-02-12 14:45:43 -08001518 :py:meth:`_init`.
Stephen Holsapple0d9815f2014-08-27 19:36:53 -07001519 """
1520 _lib.X509_STORE_CTX_cleanup(self._store_ctx)
1521
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001522 def _exception_from_context(self):
1523 """
1524 Convert an OpenSSL native context error failure into a Python
1525 exception.
1526
Alex Gaynor5945ea82015-09-05 14:59:06 -04001527 When a call to native OpenSSL X509_verify_cert fails, additional
1528 information about the failure can be obtained from the store context.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001529 """
1530 errors = [
1531 _lib.X509_STORE_CTX_get_error(self._store_ctx),
1532 _lib.X509_STORE_CTX_get_error_depth(self._store_ctx),
1533 _native(_ffi.string(_lib.X509_verify_cert_error_string(
Alex Gaynor5945ea82015-09-05 14:59:06 -04001534 _lib.X509_STORE_CTX_get_error(self._store_ctx)))),
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001535 ]
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001536 # A context error should always be associated with a certificate, so we
1537 # expect this call to never return :class:`None`.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001538 _x509 = _lib.X509_STORE_CTX_get_current_cert(self._store_ctx)
Stephen Holsapple1f713eb2015-02-09 19:19:44 -08001539 _cert = _lib.X509_dup(_x509)
1540 pycert = X509.__new__(X509)
1541 pycert._x509 = _ffi.gc(_cert, _lib.X509_free)
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001542 return X509StoreContextError(errors, pycert)
1543
Stephen Holsapple46a09252015-02-12 14:45:43 -08001544 def set_store(self, store):
1545 """
1546 Set the context's trust store.
1547
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001548 .. versionadded:: 0.15
1549
Stephen Holsapple46a09252015-02-12 14:45:43 -08001550 :param X509Store store: The certificates which will be trusted for the
1551 purposes of any *future* verifications.
1552 """
1553 self._store = store
1554
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001555 def verify_certificate(self):
1556 """
1557 Verify a certificate in a context.
1558
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001559 .. versionadded:: 0.15
1560
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001561 :param store_ctx: The :py:class:`X509StoreContext` to verify.
Stephen Holsapple8ad4a192015-06-09 22:51:43 -07001562
Alex Gaynorca87ff62015-09-04 23:31:03 -04001563 :raises X509StoreContextError: If an error occurred when validating a
Alex Gaynor5945ea82015-09-05 14:59:06 -04001564 certificate in the context. Sets ``certificate`` attribute to
1565 indicate which certificate caused the error.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001566 """
Stephen Holsapple46a09252015-02-12 14:45:43 -08001567 # Always re-initialize the store context in case
1568 # :py:meth:`verify_certificate` is called multiple times.
Stephen Holsapple08ffaa62015-01-30 17:18:40 -08001569 self._init()
1570 ret = _lib.X509_verify_cert(self._store_ctx)
1571 self._cleanup()
1572 if ret <= 0:
1573 raise self._exception_from_context()
1574
1575
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001576def load_certificate(type, buffer):
1577 """
1578 Load a certificate from a buffer
1579
1580 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1581
1582 :param buffer: The buffer the certificate is stored in
1583 :type buffer: :py:class:`bytes`
1584
1585 :return: The X509 object
1586 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001587 if isinstance(buffer, _text_type):
1588 buffer = buffer.encode("ascii")
1589
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001590 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001591
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001592 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001593 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001594 elif type == FILETYPE_ASN1:
Alex Gaynor962ac212015-09-04 08:06:42 -04001595 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001596 else:
1597 raise ValueError(
1598 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001599
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001600 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001601 _raise_current_error()
1602
1603 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001604 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001605 return cert
1606
1607
1608def dump_certificate(type, cert):
1609 """
1610 Dump a certificate to a buffer
1611
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001612 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1613 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001614 :param cert: The certificate to dump
1615 :return: The buffer with the dumped certificate in
1616 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001617 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001618
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001619 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001620 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001621 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001622 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001623 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001624 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001625 else:
1626 raise ValueError(
1627 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1628 "FILETYPE_TEXT")
1629
Alex Gaynorc7a9eb52015-09-05 16:57:49 -04001630 assert result_code == 1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001631 return _bio_to_string(bio)
1632
1633
Cory Benfield6492f7c2015-10-27 16:57:58 +09001634def dump_publickey(type, pkey):
1635 """
Cory Benfield11c10192015-10-27 17:23:03 +09001636 Dump a public key to a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09001637
Cory Benfield9c590b92015-10-28 14:55:05 +09001638 :param type: The file type (one of :data:`FILETYPE_PEM` or
Cory Benfielde813cec2015-10-28 08:57:08 +09001639 :data:`FILETYPE_ASN1`).
Cory Benfield2b6bb802015-10-28 22:19:31 +09001640 :param PKey pkey: The public key to dump
Cory Benfield6492f7c2015-10-27 16:57:58 +09001641 :return: The buffer with the dumped key in it.
Cory Benfield11c10192015-10-27 17:23:03 +09001642 :rtype: bytes
Cory Benfield6492f7c2015-10-27 16:57:58 +09001643 """
1644 bio = _new_mem_buf()
1645 if type == FILETYPE_PEM:
1646 write_bio = _lib.PEM_write_bio_PUBKEY
1647 elif type == FILETYPE_ASN1:
1648 write_bio = _lib.i2d_PUBKEY_bio
1649 else:
1650 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
1651
1652 result_code = write_bio(bio, pkey._pkey)
Cory Benfield1e9c7ab2015-10-28 08:58:31 +09001653 if result_code != 1: # pragma: no cover
Cory Benfield6492f7c2015-10-27 16:57:58 +09001654 _raise_current_error()
1655
1656 return _bio_to_string(bio)
1657
1658
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001659def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1660 """
1661 Dump a private key to a buffer
1662
Jean-Paul Calderonee66fde22013-04-03 08:35:08 -04001663 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1664 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001665 :param pkey: The PKey to dump
1666 :param cipher: (optional) if encrypted PEM format, the cipher to
1667 use
1668 :param passphrase: (optional) if encrypted PEM format, this can be either
1669 the passphrase to use, or a callback for providing the
1670 passphrase.
1671 :return: The buffer with the dumped key in
Maximilian Hils0de43752015-09-18 15:26:54 +02001672 :rtype: :py:data:`bytes`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001673 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001674 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001675
1676 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001677 if passphrase is None:
1678 raise TypeError(
1679 "if a value is given for cipher "
1680 "one must also be given for passphrase")
1681 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001682 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001683 raise ValueError("Invalid cipher name")
1684 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001685 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001686
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001687 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001688 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001689 result_code = _lib.PEM_write_bio_PrivateKey(
1690 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001691 helper.callback, helper.callback_args)
1692 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001693 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001695 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001696 rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)
1697 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001698 # TODO RSA_free(rsa)?
1699 else:
1700 raise ValueError(
1701 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1702 "FILETYPE_TEXT")
1703
1704 if result_code == 0:
1705 _raise_current_error()
1706
1707 return _bio_to_string(bio)
1708
1709
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001710class Revoked(object):
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001711 """
1712 A certificate revocation.
1713 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001714 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1715 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1716 # OCSP_crl_reason_str. We use the latter, just like the command line
1717 # program.
1718 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001719 b"unspecified",
1720 b"keyCompromise",
1721 b"CACompromise",
1722 b"affiliationChanged",
1723 b"superseded",
1724 b"cessationOfOperation",
1725 b"certificateHold",
1726 # b"removeFromCRL",
Alex Gaynorca87ff62015-09-04 23:31:03 -04001727 ]
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001728
1729 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001730 revoked = _lib.X509_REVOKED_new()
1731 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001732
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001733 def set_serial(self, hex_str):
1734 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001735 Set the serial number.
1736
1737 The serial number is formatted as a hexadecimal number encoded in
1738 ASCII.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001739
1740 :param hex_str: The new serial number.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001741 :type hex_str: :py:class:`bytes`
1742
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001743 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001744 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001745 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1746 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001747 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001748 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001749 if not bn_result:
1750 raise ValueError("bad hex string")
1751
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001752 asn1_serial = _ffi.gc(
1753 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1754 _lib.ASN1_INTEGER_free)
1755 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001756
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001757 def get_serial(self):
1758 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001759 Get the serial number.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001760
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001761 The serial number is formatted as a hexadecimal number encoded in
1762 ASCII.
1763
1764 :return: The serial number.
1765 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001766 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001767 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001768
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001769 result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001770 if result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001771 # TODO: This is untested.
1772 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001773
1774 return _bio_to_string(bio)
1775
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001776 def _delete_reason(self):
1777 stack = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001778 for i in range(_lib.sk_X509_EXTENSION_num(stack)):
1779 ext = _lib.sk_X509_EXTENSION_value(stack, i)
1780 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
1781 _lib.X509_EXTENSION_free(ext)
1782 _lib.sk_X509_EXTENSION_delete(stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001783 break
1784
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001785 def set_reason(self, reason):
1786 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001787 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001788
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001789 If :py:data:`reason` is :py:const:`None`, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001790
1791 :param reason: The reason string.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001792 :type reason: :py:class:`bytes` or :py:class:`NoneType`
1793
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001794 :return: :py:const:`None`
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001795
1796 .. seealso::
1797
1798 :py:meth:`all_reasons`, which gives you a list of all supported
1799 reasons which you might pass to this method.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001800 """
1801 if reason is None:
1802 self._delete_reason()
1803 elif not isinstance(reason, bytes):
1804 raise TypeError("reason must be None or a byte string")
1805 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001806 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001807 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1808
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001809 new_reason_ext = _lib.ASN1_ENUMERATED_new()
1810 if new_reason_ext == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001811 # TODO: This is untested.
1812 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001813 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001814
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001815 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
1816 if set_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001817 # TODO: This is untested.
1818 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001819
1820 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1822 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001823
1824 if not add_result:
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
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001828 def get_reason(self):
1829 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001830 Set the reason of this revocation.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001831
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001832 :return: The reason, or :py:const:`None` if there is none.
1833 :rtype: :py:class:`bytes` or :py:class:`NoneType`
1834
1835 .. seealso::
1836
1837 :py:meth:`all_reasons`, which gives you a list of all supported
1838 reasons this method might return.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001839 """
1840 extensions = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001841 for i in range(_lib.sk_X509_EXTENSION_num(extensions)):
1842 ext = _lib.sk_X509_EXTENSION_value(extensions, i)
1843 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001844 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001845
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001846 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001847 if not print_result:
Alex Gaynor5945ea82015-09-05 14:59:06 -04001848 print_result = _lib.M_ASN1_OCTET_STRING_print(
1849 bio, ext.value
1850 )
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001851 if print_result == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001852 # TODO: This is untested.
1853 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001854
1855 return _bio_to_string(bio)
1856
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001857 def all_reasons(self):
1858 """
1859 Return a list of all the supported reason strings.
1860
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001861 This list is a copy; modifying it does not change the supported reason
1862 strings.
1863
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001864 :return: A list of reason strings.
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001865 :rtype: :py:class:`list` of :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001866 """
1867 return self._crl_reasons[:]
1868
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001869 def set_rev_date(self, when):
1870 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001871 Set the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001872
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001873 :param when: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1874 :type when: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001875 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001876 """
1877 return _set_asn1_time(self._revoked.revocationDate, when)
1878
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001879 def get_rev_date(self):
1880 """
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001881 Get the revocation timestamp.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001882
Laurens Van Houtvend92f55c2014-06-19 17:08:41 +02001883 :return: The timestamp of the revocation, as ASN.1 GENERALIZEDTIME.
1884 :rtype: :py:class:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001885 """
1886 return _get_asn1_time(self._revoked.revocationDate)
1887
1888
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001889class CRL(object):
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001890 """
1891 A certificate revocation list.
1892 """
Alex Gaynora738ed52015-09-05 11:17:10 -04001893
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001894 def __init__(self):
1895 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001896 Create a new empty certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001897 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001898 crl = _lib.X509_CRL_new()
1899 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001900
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001901 def get_revoked(self):
1902 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001903 Return the revocations in this certificate revocation list.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001904
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001905 These revocations will be provided by value, not by reference.
1906 That means it's okay to mutate them: it won't affect this CRL.
1907
1908 :return: The revocations in this CRL.
1909 :rtype: :py:class:`tuple` of :py:class:`Revocation`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001910 """
1911 results = []
1912 revoked_stack = self._crl.crl.revoked
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001913 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1914 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001915 revoked_copy = _X509_REVOKED_dup(revoked)
1916 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001917 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001918 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001919 if results:
1920 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001921
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001922 def add_revoked(self, revoked):
1923 """
1924 Add a revoked (by value not reference) to the CRL structure
1925
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001926 This revocation will be added by value, not by reference. That
1927 means it's okay to mutate it after adding: it won't affect
1928 this CRL.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001929
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001930 :param revoked: The new revocation.
1931 :type revoked: :class:`Revoked`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001932
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001933 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001934 """
Paul Kehrer8dddb1a2016-03-09 21:48:04 -04001935 copy = _lib.Cryptography_X509_REVOKED_dup(revoked._revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001936 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001937 # TODO: This is untested.
1938 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001939
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001940 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001941 if add_result == 0:
1942 # TODO: This is untested.
1943 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001944
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001945 def export(self, cert, key, type=FILETYPE_PEM, days=100,
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001946 digest=_UNSPECIFIED):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001947 """
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001948 Export a CRL as a string.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001949
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001950 :param cert: The certificate used to sign the CRL.
1951 :type cert: :py:class:`X509`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001952
Laurens Van Houtvencb32e852014-06-19 17:36:28 +02001953 :param key: The key used to sign the CRL.
1954 :type key: :py:class:`PKey`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001955
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001956 :param type: The export format, either :py:data:`FILETYPE_PEM`,
1957 :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001958
Jean-Paul Calderonedf514012015-04-13 21:45:18 -04001959 :param int days: The number of days until the next update of this CRL.
Bulat Gaifullin5f9eea42014-09-23 19:35:15 +04001960
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001961 :param bytes digest: The name of the message digest to use (eg
1962 ``b"sha1"``).
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001963
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001964 :return: :py:data:`bytes`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001965 """
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001966 if not isinstance(cert, X509):
1967 raise TypeError("cert must be an X509 instance")
1968 if not isinstance(key, PKey):
1969 raise TypeError("key must be a PKey instance")
1970 if not isinstance(type, int):
1971 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001972
Jean-Paul Calderone00f84eb2015-04-13 12:47:21 -04001973 if digest is _UNSPECIFIED:
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001974 _warn(
1975 "The default message digest (md5) is deprecated. "
1976 "Pass the name of a message digest explicitly.",
1977 category=DeprecationWarning,
1978 stacklevel=2,
1979 )
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001980 digest = b"md5"
Jean-Paul Calderone60432792015-04-13 12:26:07 -04001981
Jean-Paul Calderonecce22d02015-04-13 13:56:09 -04001982 digest_obj = _lib.EVP_get_digestbyname(digest)
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04001983 if digest_obj == _ffi.NULL:
1984 raise ValueError("No such digest method")
1985
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001986 bio = _lib.BIO_new(_lib.BIO_s_mem())
1987 if bio == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001988 # TODO: This is untested.
1989 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001990
Alex Gaynora738ed52015-09-05 11:17:10 -04001991 # A scratch time object to give different values to different CRL
1992 # fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001993 sometime = _lib.ASN1_TIME_new()
1994 if sometime == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001995 # TODO: This is untested.
1996 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001997
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001998 _lib.X509_gmtime_adj(sometime, 0)
1999 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002000
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002001 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
2002 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002003
Alex Gaynor5945ea82015-09-05 14:59:06 -04002004 _lib.X509_CRL_set_issuer_name(
2005 self._crl, _lib.X509_get_subject_name(cert._x509)
2006 )
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002007
Bulat Gaifullin2923dc02014-09-21 22:36:48 +04002008 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, digest_obj)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002009 if not sign_result:
2010 _raise_current_error()
2011
Dominic Chenf05b2122015-10-13 16:32:35 +00002012 return dump_crl(type, self)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002013
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08002014
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002015CRLType = CRL
2016
2017
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002018class PKCS7(object):
2019 def type_is_signed(self):
2020 """
2021 Check if this NID_pkcs7_signed object
2022
2023 :return: True if the PKCS7 is of type signed
2024 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002025 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002026 return True
2027 return False
2028
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002029 def type_is_enveloped(self):
2030 """
2031 Check if this NID_pkcs7_enveloped object
2032
2033 :returns: True if the PKCS7 is of type enveloped
2034 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002035 if _lib.PKCS7_type_is_enveloped(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_signedAndEnveloped(self):
2040 """
2041 Check if this NID_pkcs7_signedAndEnveloped object
2042
2043 :returns: True if the PKCS7 is of type signedAndEnveloped
2044 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002045 if _lib.PKCS7_type_is_signedAndEnveloped(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_data(self):
2050 """
2051 Check if this NID_pkcs7_data object
2052
2053 :return: True if the PKCS7 is of type data
2054 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002055 if _lib.PKCS7_type_is_data(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 get_type_name(self):
2060 """
2061 Returns the type name of the PKCS7 structure
2062
2063 :return: A string with the typename
2064 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002065 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
2066 string_type = _lib.OBJ_nid2sn(nid)
2067 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002068
2069PKCS7Type = PKCS7
2070
2071
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002072class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002073 """
2074 A PKCS #12 archive.
2075 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002076
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002077 def __init__(self):
2078 self._pkey = None
2079 self._cert = None
2080 self._cacerts = None
2081 self._friendlyname = None
2082
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002083 def get_certificate(self):
2084 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002085 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002086
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002087 :return: The certificate, or :py:const:`None` if there is none.
2088 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002089 """
2090 return self._cert
2091
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002092 def set_certificate(self, cert):
2093 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002094 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002095
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002096 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002097 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002098
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002099 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002100 """
2101 if not isinstance(cert, X509):
2102 raise TypeError("cert must be an X509 instance")
2103 self._cert = cert
2104
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002105 def get_privatekey(self):
2106 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002107 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002108
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002109 :return: The private key, or :py:const:`None` if there is none.
2110 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002111 """
2112 return self._pkey
2113
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002114 def set_privatekey(self, pkey):
2115 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002116 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002117
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002118 :param pkey: The new private key, or :py:const:`None` to unset it.
2119 :type pkey: :py:class:`PKey` or :py:const:`None`
2120
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002121 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002122 """
2123 if not isinstance(pkey, PKey):
2124 raise TypeError("pkey must be a PKey instance")
2125 self._pkey = pkey
2126
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002127 def get_ca_certificates(self):
2128 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002129 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002130
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002131 :return: A tuple with the CA certificates in the chain, or
2132 :py:const:`None` if there are none.
2133 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002134 """
2135 if self._cacerts is not None:
2136 return tuple(self._cacerts)
2137
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002138 def set_ca_certificates(self, cacerts):
2139 """
Alex Gaynor3b0ee972014-11-15 09:17:33 -08002140 Replace or set the CA certificates within the PKCS12 object.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002141
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002142 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2143 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002144 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002145
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002146 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002147 """
2148 if cacerts is None:
2149 self._cacerts = None
2150 else:
2151 cacerts = list(cacerts)
2152 for cert in cacerts:
2153 if not isinstance(cert, X509):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002154 raise TypeError(
2155 "iterable must only contain X509 instances"
2156 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002157 self._cacerts = cacerts
2158
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002159 def set_friendlyname(self, name):
2160 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002161 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002162
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002163 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002164 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002165
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002166 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002167 """
2168 if name is None:
2169 self._friendlyname = None
2170 elif not isinstance(name, bytes):
Alex Gaynor5945ea82015-09-05 14:59:06 -04002171 raise TypeError(
2172 "name must be a byte string or None (not %r)" % (name,)
2173 )
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002174 self._friendlyname = name
2175
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002176 def get_friendlyname(self):
2177 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002178 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002179
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002180 :returns: The friendly name, or :py:const:`None` if there is none.
2181 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002182 """
2183 return self._friendlyname
2184
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002185 def export(self, passphrase=None, iter=2048, maciter=1):
2186 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002187 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002188
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002189 For more information, see the :c:func:`PKCS12_create` man page.
2190
2191 :param passphrase: The passphrase used to encrypt the structure. Unlike
2192 some other passphrase arguments, this *must* be a string, not a
2193 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002194 :type passphrase: :py:data:`bytes`
2195
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002196 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002197 :type iter: :py:data:`int`
2198
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002199 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002200 :type maciter: :py:data:`int`
2201
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002202 :return: The string representation of the PKCS #12 structure.
2203 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002204 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002205 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002206
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002207 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002208 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002209 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002210 cacerts = _lib.sk_X509_new_null()
2211 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002212 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002213 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002214
2215 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002216 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002217
2218 friendlyname = self._friendlyname
2219 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002220 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002221
2222 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002223 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002224 else:
2225 pkey = self._pkey._pkey
2226
2227 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002228 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002229 else:
2230 cert = self._cert._x509
2231
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002232 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002233 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002234 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2235 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002236 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002237 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002238 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002239 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002240
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002241 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002242 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002243 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002244
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002245
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002246PKCS12Type = PKCS12
2247
2248
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002249class NetscapeSPKI(object):
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002250 """
2251 A Netscape SPKI object.
2252 """
Alex Gaynora738ed52015-09-05 11:17:10 -04002253
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002254 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002255 spki = _lib.NETSCAPE_SPKI_new()
2256 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002257
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002258 def sign(self, pkey, digest):
2259 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002260 Sign the certificate request with this key and digest type.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002261
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002262 :param pkey: The private key to sign with.
2263 :type pkey: :py:class:`PKey`
2264
2265 :param digest: The message digest to use.
2266 :type digest: :py:class:`bytes`
2267
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002268 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002269 """
2270 if pkey._only_public:
2271 raise ValueError("Key has only public part")
2272
2273 if not pkey._initialized:
2274 raise ValueError("Key is uninitialized")
2275
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002276 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002277 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002278 raise ValueError("No such digest method")
2279
Alex Gaynor5945ea82015-09-05 14:59:06 -04002280 sign_result = _lib.NETSCAPE_SPKI_sign(
2281 self._spki, pkey._pkey, digest_obj
2282 )
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002283 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002284 # TODO: This is untested.
2285 _raise_current_error()
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002286
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002287 def verify(self, key):
2288 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002289 Verifies a signature on a certificate request.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002290
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002291 :param key: The public key that signature is supposedly from.
2292 :type pkey: :py:class:`PKey`
2293
2294 :return: :py:const:`True` if the signature is correct.
2295 :rtype: :py:class:`bool`
2296
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002297 :raises Error: If the signature is invalid, or there was a problem
2298 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002299 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002300 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002301 if answer <= 0:
2302 _raise_current_error()
2303 return True
2304
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002305 def b64_encode(self):
2306 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002307 Generate a base64 encoded representation of this SPKI object.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002308
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002309 :return: The base64 encoded string.
2310 :rtype: :py:class:`bytes`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002311 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002312 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2313 result = _ffi.string(encoded)
2314 _lib.CRYPTO_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002315 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002316
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002317 def get_pubkey(self):
2318 """
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002319 Get the public key of this certificate.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002320
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002321 :return: The public key.
2322 :rtype: :py:class:`PKey`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002323 """
2324 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002325 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
2326 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002327 # TODO: This is untested.
2328 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002329 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002330 pkey._only_public = True
2331 return pkey
2332
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002333 def set_pubkey(self, pkey):
2334 """
2335 Set the public key of the certificate
2336
2337 :param pkey: The public key
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002338 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002339 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002340 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002341 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002342 # TODO: This is untested.
2343 _raise_current_error()
Laurens Van Houtven59152b52014-06-19 16:42:30 +02002344
2345
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002346NetscapeSPKIType = NetscapeSPKI
2347
2348
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002349class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002350 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002351 if type != FILETYPE_PEM and passphrase is not None:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002352 raise ValueError(
2353 "only FILETYPE_PEM key format supports encryption"
2354 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002355 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002356 self._more_args = more_args
2357 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002358 self._problems = []
2359
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002360 @property
2361 def callback(self):
2362 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002363 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002364 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002365 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002366 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002367 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002368 else:
2369 raise TypeError("Last argument must be string or callable")
2370
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002371 @property
2372 def callback_args(self):
2373 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002374 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002375 elif isinstance(self._passphrase, bytes):
2376 return self._passphrase
2377 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002378 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002379 else:
2380 raise TypeError("Last argument must be string or callable")
2381
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002382 def raise_if_problem(self, exceptionType=Error):
2383 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002384 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002385 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002386 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002387 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002388 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002389 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002390
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002391 def _read_passphrase(self, buf, size, rwflag, userdata):
2392 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002393 if self._more_args:
2394 result = self._passphrase(size, rwflag, userdata)
2395 else:
2396 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002397 if not isinstance(result, bytes):
2398 raise ValueError("String expected")
2399 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002400 if self._truncate:
2401 result = result[:size]
2402 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002403 raise ValueError(
2404 "passphrase returned by callback is too long"
2405 )
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002406 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002407 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002408 return len(result)
2409 except Exception as e:
2410 self._problems.append(e)
2411 return 0
2412
2413
Cory Benfield6492f7c2015-10-27 16:57:58 +09002414def load_publickey(type, buffer):
2415 """
Cory Benfield11c10192015-10-27 17:23:03 +09002416 Load a public key from a buffer.
Cory Benfield6492f7c2015-10-27 16:57:58 +09002417
Cory Benfield9c590b92015-10-28 14:55:05 +09002418 :param type: The file type (one of :data:`FILETYPE_PEM`,
Cory Benfielde813cec2015-10-28 08:57:08 +09002419 :data:`FILETYPE_ASN1`).
Cory Benfieldc9c30a22015-10-28 17:39:20 +09002420 :param buffer: The buffer the key is stored in.
2421 :type buffer: A Python string object, either unicode or bytestring.
2422 :return: The PKey object.
2423 :rtype: :class:`PKey`
Cory Benfield6492f7c2015-10-27 16:57:58 +09002424 """
2425 if isinstance(buffer, _text_type):
2426 buffer = buffer.encode("ascii")
2427
2428 bio = _new_mem_buf(buffer)
2429
2430 if type == FILETYPE_PEM:
2431 evp_pkey = _lib.PEM_read_bio_PUBKEY(
2432 bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
2433 elif type == FILETYPE_ASN1:
2434 evp_pkey = _lib.d2i_PUBKEY_bio(bio, _ffi.NULL)
2435 else:
2436 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2437
2438 if evp_pkey == _ffi.NULL:
2439 _raise_current_error()
2440
2441 pkey = PKey.__new__(PKey)
2442 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
2443 return pkey
2444
2445
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002446def load_privatekey(type, buffer, passphrase=None):
2447 """
2448 Load a private key from a buffer
2449
2450 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2451 :param buffer: The buffer the key is stored in
2452 :param passphrase: (optional) if encrypted PEM format, this can be
2453 either the passphrase to use, or a callback for
2454 providing the passphrase.
2455
2456 :return: The PKey object
2457 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002458 if isinstance(buffer, _text_type):
2459 buffer = buffer.encode("ascii")
2460
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002461 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002462
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002463 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002464 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002465 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2466 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002467 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002468 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002469 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002470 else:
2471 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2472
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002473 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002474 _raise_current_error()
2475
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002476 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002477 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002478 return pkey
2479
2480
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002481def dump_certificate_request(type, req):
2482 """
2483 Dump a certificate request to a buffer
2484
2485 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2486 :param req: The certificate request to dump
2487 :return: The buffer with the dumped certificate request in
2488 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002489 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002490
2491 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002492 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002493 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002494 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002495 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002496 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002497 else:
Alex Gaynor5945ea82015-09-05 14:59:06 -04002498 raise ValueError(
2499 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2500 "FILETYPE_TEXT"
2501 )
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002502
2503 if result_code == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002504 # TODO: This is untested.
2505 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002506
2507 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002508
2509
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002510def load_certificate_request(type, buffer):
2511 """
2512 Load a certificate request from a buffer
2513
2514 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2515 :param buffer: The buffer the certificate request is stored in
2516 :return: The X509Req object
2517 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002518 if isinstance(buffer, _text_type):
2519 buffer = buffer.encode("ascii")
2520
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002521 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002522
2523 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002524 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002525 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002526 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002527 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002528 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002529
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002530 if req == _ffi.NULL:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002531 # TODO: This is untested.
2532 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002533
2534 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002535 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002536 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002537
2538
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002539def sign(pkey, data, digest):
2540 """
2541 Sign data with a digest
2542
2543 :param pkey: Pkey to sign with
2544 :param data: data to be signed
2545 :param digest: message digest to use
2546 :return: signature
2547 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002548 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002549
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002550 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002551 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002552 raise ValueError("No such digest method")
2553
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002554 md_ctx = _ffi.new("EVP_MD_CTX*")
2555 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002556
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002557 _lib.EVP_SignInit(md_ctx, digest_obj)
2558 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002559
Colleen Murphye09399b2016-03-01 17:40:49 -08002560 pkey_length = (PKey.bits(pkey) + 7) // 8
2561 signature_buffer = _ffi.new("unsigned char[]", pkey_length)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002562 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002563 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002564 md_ctx, signature_buffer, signature_length, pkey._pkey)
2565
2566 if final_result != 1:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002567 # TODO: This is untested.
2568 _raise_current_error()
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002569
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002570 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002571
2572
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002573def verify(cert, signature, data, digest):
2574 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002575 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002576
2577 :param cert: signing certificate (X509 object)
2578 :param signature: signature returned by sign function
2579 :param data: data to be verified
2580 :param digest: message digest to use
Alex Gaynor5945ea82015-09-05 14:59:06 -04002581 :return: :py:const:`None` if the signature is correct, raise exception
2582 otherwise
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002583 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002584 data = _text_to_bytes_and_warn("data", data)
Abraham Martine82326c2015-02-04 10:18:10 +00002585
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002586 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002587 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002588 raise ValueError("No such digest method")
2589
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002590 pkey = _lib.X509_get_pubkey(cert._x509)
2591 if pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002592 # TODO: This is untested.
2593 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002594 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002595
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002596 md_ctx = _ffi.new("EVP_MD_CTX*")
2597 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002598
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002599 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2600 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
Alex Gaynor5945ea82015-09-05 14:59:06 -04002601 verify_result = _lib.EVP_VerifyFinal(
2602 md_ctx, signature, len(signature), pkey
2603 )
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002604
2605 if verify_result != 1:
2606 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002607
2608
Dominic Chenf05b2122015-10-13 16:32:35 +00002609def dump_crl(type, crl):
2610 """
2611 Dump a certificate revocation list to a buffer.
2612
2613 :param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
2614 ``FILETYPE_TEXT``).
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002615 :param CRL crl: The CRL to dump.
2616
Dominic Chenf05b2122015-10-13 16:32:35 +00002617 :return: The buffer with the CRL.
Hynek Schlawack0a3cd6d2015-10-21 16:39:22 +02002618 :rtype: :data:`bytes`
Dominic Chenf05b2122015-10-13 16:32:35 +00002619 """
2620 bio = _new_mem_buf()
2621
2622 if type == FILETYPE_PEM:
2623 ret = _lib.PEM_write_bio_X509_CRL(bio, crl._crl)
2624 elif type == FILETYPE_ASN1:
2625 ret = _lib.i2d_X509_CRL_bio(bio, crl._crl)
2626 elif type == FILETYPE_TEXT:
2627 ret = _lib.X509_CRL_print(bio, crl._crl)
2628 else:
2629 raise ValueError(
2630 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
2631 "FILETYPE_TEXT")
2632
2633 assert ret == 1
2634 return _bio_to_string(bio)
2635
2636
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002637def load_crl(type, buffer):
2638 """
2639 Load a certificate revocation list from a buffer
2640
2641 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2642 :param buffer: The buffer the CRL is stored in
2643
2644 :return: The PKey object
2645 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002646 if isinstance(buffer, _text_type):
2647 buffer = buffer.encode("ascii")
2648
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002649 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002650
2651 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002652 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002653 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002654 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002655 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002656 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2657
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002658 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002659 _raise_current_error()
2660
2661 result = CRL.__new__(CRL)
2662 result._crl = crl
2663 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002664
2665
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002666def load_pkcs7_data(type, buffer):
2667 """
2668 Load pkcs7 data from a buffer
2669
2670 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2671 :param buffer: The buffer with the pkcs7 data.
2672 :return: The PKCS7 object
2673 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002674 if isinstance(buffer, _text_type):
2675 buffer = buffer.encode("ascii")
2676
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002677 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002678
2679 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002680 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002681 elif type == FILETYPE_ASN1:
Alex Gaynor77acc362014-08-13 14:46:15 -07002682 pkcs7 = _lib.d2i_PKCS7_bio(bio, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002683 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002684 # TODO: This is untested.
2685 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002686 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2687
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002688 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002689 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002690
2691 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002692 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002693 return pypkcs7
2694
2695
Stephen Holsapple38482622014-04-05 20:29:34 -07002696def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002697 """
2698 Load a PKCS12 object from a buffer
2699
2700 :param buffer: The buffer the certificate is stored in
2701 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2702 :returns: The PKCS12 object
2703 """
Jean-Paul Calderone39a8d592015-04-13 20:49:50 -04002704 passphrase = _text_to_bytes_and_warn("passphrase", passphrase)
Abraham Martine82326c2015-02-04 10:18:10 +00002705
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002706 if isinstance(buffer, _text_type):
2707 buffer = buffer.encode("ascii")
2708
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002709 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002710
Stephen Holsapple38482622014-04-05 20:29:34 -07002711 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2712 # password based encryption no password and a zero length password are two
2713 # different things, but OpenSSL implementation will try both to figure out
2714 # which one works.
2715 if not passphrase:
2716 passphrase = _ffi.NULL
2717
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002718 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2719 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002720 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002721 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002722
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002723 pkey = _ffi.new("EVP_PKEY**")
2724 cert = _ffi.new("X509**")
2725 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002726
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002727 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002728 if not parse_result:
2729 _raise_current_error()
2730
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002731 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002732
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002733 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2734 # queue for no particular reason. This error isn't interesting to anyone
2735 # outside this function. It's not even interesting to us. Get rid of it.
2736 try:
2737 _raise_current_error()
2738 except Error:
2739 pass
2740
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002741 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002742 pykey = None
2743 else:
2744 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002745 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002746
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002747 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002748 pycert = None
2749 friendlyname = None
2750 else:
2751 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002752 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002753
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002754 friendlyname_length = _ffi.new("int*")
Alex Gaynor5945ea82015-09-05 14:59:06 -04002755 friendlyname_buffer = _lib.X509_alias_get0(
2756 cert[0], friendlyname_length
2757 )
2758 friendlyname = _ffi.buffer(
2759 friendlyname_buffer, friendlyname_length[0]
2760 )[:]
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002761 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002762 friendlyname = None
2763
2764 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002765 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002766 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002767 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002768 pycacerts.append(pycacert)
2769 if not pycacerts:
2770 pycacerts = None
2771
2772 pkcs12 = PKCS12.__new__(PKCS12)
2773 pkcs12._pkey = pykey
2774 pkcs12._cert = pycert
2775 pkcs12._cacerts = pycacerts
2776 pkcs12._friendlyname = friendlyname
2777 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002778
2779
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002780# There are no direct unit tests for this initialization. It is tested
2781# indirectly since it is necessary for functions like dump_privatekey when
2782# using encryption.
2783#
2784# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2785# and some other similar tests may fail without this (though they may not if
2786# the Python runtime has already done some initialization of the underlying
2787# OpenSSL library (and is linked against the same one that cryptography is
2788# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002789_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002790
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002791# This is similar but exercised mainly by exception_from_error_queue. It calls
2792# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2793_lib.SSL_load_error_strings()
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002794
2795
D.S. Ljungmark349e1362014-05-31 18:40:38 +02002796# Set the default string mask to match OpenSSL upstream (since 2005) and
2797# RFC5280 recommendations.
2798_lib.ASN1_STRING_set_default_mask_asc(b'utf8only')