blob: 6b92ca5779fee176414ed28574d803d7f392adb5 [file] [log] [blame]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001from time import time
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002from base64 import b16encode
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05003from functools import partial
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05004from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
5
6from six import (
7 integer_types as _integer_types,
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -04008 text_type as _text_type,
9 PY3 as _PY3)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080010
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050011from OpenSSL._util import (
12 ffi as _ffi,
13 lib as _lib,
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -050014 exception_from_error_queue as _exception_from_error_queue,
15 byte_string as _byte_string,
16 native as _native)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080017
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050018FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
19FILETYPE_ASN1 = _lib.SSL_FILETYPE_ASN1
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080020
21# TODO This was an API mistake. OpenSSL has no such constant.
22FILETYPE_TEXT = 2 ** 16 - 1
23
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050024TYPE_RSA = _lib.EVP_PKEY_RSA
25TYPE_DSA = _lib.EVP_PKEY_DSA
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -080026
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080027
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050028class Error(Exception):
Jean-Paul Calderone511cde02013-12-29 10:31:13 -050029 """
30 An error occurred in an `OpenSSL.crypto` API.
31 """
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050032
33
34_raise_current_error = partial(_exception_from_error_queue, Error)
35
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -050036def _untested_error(where):
37 """
38 An OpenSSL API failed somehow. Additionally, the failure which was
39 encountered isn't one that's exercised by the test suite so future behavior
40 of pyOpenSSL is now somewhat less predictable.
41 """
42 raise RuntimeError("Unknown %s failure" % (where,))
43
44
45
46def _new_mem_buf(buffer=None):
47 """
48 Allocate a new OpenSSL memory BIO.
49
50 Arrange for the garbage collector to clean it up automatically.
51
52 :param buffer: None or some bytes to use to put into the BIO so that they
53 can be read out.
54 """
55 if buffer is None:
56 bio = _lib.BIO_new(_lib.BIO_s_mem())
57 free = _lib.BIO_free
58 else:
59 data = _ffi.new("char[]", buffer)
60 bio = _lib.BIO_new_mem_buf(data, len(buffer))
61 # Keep the memory alive as long as the bio is alive!
62 def free(bio, ref=data):
63 return _lib.BIO_free(bio)
64
65 if bio == _ffi.NULL:
66 # TODO: This is untested.
67 _raise_current_error()
68
69 bio = _ffi.gc(bio, free)
70 return bio
71
72
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -050073
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080074def _bio_to_string(bio):
75 """
76 Copy the contents of an OpenSSL BIO object into a Python byte string.
77 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -050078 result_buffer = _ffi.new('char**')
79 buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
80 return _ffi.buffer(result_buffer[0], buffer_length)[:]
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -080081
82
83
Jean-Paul Calderone57122982013-02-21 08:47:05 -080084def _set_asn1_time(boundary, when):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -050085 """
86 The the time value of an ASN1 time object.
87
88 @param boundary: An ASN1_GENERALIZEDTIME pointer (or an object safely
89 castable to that type) which will have its value set.
90 @param when: A string representation of the desired time value.
91
92 @raise TypeError: If C{when} is not a L{bytes} string.
93 @raise ValueError: If C{when} does not represent a time in the required
94 format.
95 @raise RuntimeError: If the time value cannot be set for some other
96 (unspecified) reason.
97 """
Jean-Paul Calderone57122982013-02-21 08:47:05 -080098 if not isinstance(when, bytes):
99 raise TypeError("when must be a byte string")
100
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500101 set_result = _lib.ASN1_GENERALIZEDTIME_set_string(
102 _ffi.cast('ASN1_GENERALIZEDTIME*', boundary), when)
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800103 if set_result == 0:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500104 dummy = _ffi.gc(_lib.ASN1_STRING_new(), _lib.ASN1_STRING_free)
105 _lib.ASN1_STRING_set(dummy, when, len(when))
106 check_result = _lib.ASN1_GENERALIZEDTIME_check(
107 _ffi.cast('ASN1_GENERALIZEDTIME*', dummy))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800108 if not check_result:
109 raise ValueError("Invalid string")
110 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500111 _untested_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800112
113
114
115def _get_asn1_time(timestamp):
Jean-Paul Calderonee728e872013-12-29 10:37:15 -0500116 """
117 Retrieve the time value of an ASN1 time object.
118
119 @param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
120 that type) from which the time value will be retrieved.
121
122 @return: The time value from C{timestamp} as a L{bytes} string in a certain
123 format. Or C{None} if the object contains no time value.
124 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500125 string_timestamp = _ffi.cast('ASN1_STRING*', timestamp)
126 if _lib.ASN1_STRING_length(string_timestamp) == 0:
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800127 return None
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500128 elif _lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME:
129 return _ffi.string(_lib.ASN1_STRING_data(string_timestamp))
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800130 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500131 generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
132 _lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
133 if generalized_timestamp[0] == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500134 # This may happen:
135 # - if timestamp was not an ASN1_TIME
136 # - if allocating memory for the ASN1_GENERALIZEDTIME failed
137 # - if a copy of the time data from timestamp cannot be made for
138 # the newly allocated ASN1_GENERALIZEDTIME
139 #
140 # These are difficult to test. cffi enforces the ASN1_TIME type.
141 # Memory allocation failures are a pain to trigger
142 # deterministically.
143 _untested_error("ASN1_TIME_to_generalizedtime")
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800144 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500145 string_timestamp = _ffi.cast(
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800146 "ASN1_STRING*", generalized_timestamp[0])
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500147 string_data = _lib.ASN1_STRING_data(string_timestamp)
148 string_result = _ffi.string(string_data)
149 _lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
Jean-Paul Calderone57122982013-02-21 08:47:05 -0800150 return string_result
151
152
153
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800154class PKey(object):
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200155 """
156 A class representing an DSA or RSA public key or key pair.
157 """
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800158 _only_public = False
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800159 _initialized = True
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -0800160
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800161 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500162 pkey = _lib.EVP_PKEY_new()
163 self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800164 self._initialized = False
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800165
166
167 def generate_key(self, type, bits):
168 """
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200169 Generate a key pair of the given type, with the given number of a bits.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800170
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200171 This generates a key "into" the this object.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800172
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200173 :param type: The key type.
174 :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
175 :param bits: The number of bits.
176 :type bits: :py:data:`int` ``>= 0``
177 :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
178 of the appropriate type.
179 :raises ValueError: If the number of bits isn't an integer of
180 the appropriate size.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200181 :return: :py:const:`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800182 """
183 if not isinstance(type, int):
184 raise TypeError("type must be an integer")
185
186 if not isinstance(bits, int):
187 raise TypeError("bits must be an integer")
188
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800189 # TODO Check error return
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500190 exponent = _lib.BN_new()
191 exponent = _ffi.gc(exponent, _lib.BN_free)
192 _lib.BN_set_word(exponent, _lib.RSA_F4)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800193
194 if type == TYPE_RSA:
195 if bits <= 0:
196 raise ValueError("Invalid number of bits")
197
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500198 rsa = _lib.RSA_new()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800199
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500200 result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500201 if result == 0:
202 # TODO: The test for this case is commented out. Different
203 # builds of OpenSSL appear to have different failure modes that
204 # make it hard to test. Visual inspection of the OpenSSL
205 # source reveals that a return value of 0 signals an error.
206 # Manual testing on a particular build of OpenSSL suggests that
207 # this is probably the appropriate way to handle those errors.
208 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800209
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500210 result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800211 if not result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500212 # TODO: It appears as though this can fail if an engine is in
213 # use which does not support RSA.
214 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800215
216 elif type == TYPE_DSA:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500217 dsa = _lib.DSA_generate_parameters(
218 bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL)
219 if dsa == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500220 # TODO: This is untested.
221 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500222 if not _lib.DSA_generate_key(dsa):
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.EVP_PKEY_assign_DSA(self._pkey, dsa):
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500226 # TODO: This is untested.
227 _raise_current_error()
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -0800228 else:
229 raise Error("No such key type")
230
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -0800231 self._initialized = True
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800232
233
234 def check(self):
235 """
236 Check the consistency of an RSA private key.
237
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +0200238 This is the Python equivalent of OpenSSL's ``RSA_check_key``.
239
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800240 :return: True if key is consistent.
241 :raise Error: if the key is inconsistent.
242 :raise TypeError: if the key is of a type which cannot be checked.
243 Only RSA keys can currently be checked.
244 """
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800245 if self._only_public:
246 raise TypeError("public key only")
247
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500248 if _lib.EVP_PKEY_type(self._pkey.type) != _lib.EVP_PKEY_RSA:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800249 raise TypeError("key type unsupported")
250
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500251 rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
252 rsa = _ffi.gc(rsa, _lib.RSA_free)
253 result = _lib.RSA_check_key(rsa)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800254 if result:
255 return True
256 _raise_current_error()
257
258
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800259 def type(self):
260 """
261 Returns the type of the key
262
263 :return: The type of the key.
264 """
265 return self._pkey.type
266
267
268 def bits(self):
269 """
270 Returns the number of bits of the key
271
272 :return: The number of bits of the key.
273 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500274 return _lib.EVP_PKEY_bits(self._pkey)
Jean-Paul Calderonec86fcaf2013-02-20 12:38:33 -0800275PKeyType = PKey
276
277
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800278
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400279class _EllipticCurve(object):
280 """
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400281 A representation of a supported elliptic curve.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400282
283 @cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
284 Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
285 instances each of which represents one curve supported by the system.
286 @type _curves: :py:type:`NoneType` or :py:type:`set`
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400287 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400288 _curves = None
289
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400290 if _PY3:
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400291 # This only necessary on Python 3. Morever, it is broken on Python 2.
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400292 def __ne__(self, other):
Jean-Paul Calderonea5381052014-05-01 09:32:46 -0400293 """
294 Implement cooperation with the right-hand side argument of ``!=``.
295
296 Python 3 seems to have dropped this cooperation in this very narrow
297 circumstance.
298 """
Jean-Paul Calderonef22abcd2014-05-01 09:31:19 -0400299 if isinstance(other, _EllipticCurve):
300 return super(_EllipticCurve, self).__ne__(other)
301 return NotImplemented
Jean-Paul Calderone40da72d2014-05-01 09:25:17 -0400302
303
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400304 @classmethod
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400305 def _load_elliptic_curves(cls, lib):
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400306 """
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400307 Get the curves supported by OpenSSL.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400308
309 :param lib: The OpenSSL library binding object.
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400310
311 :return: A :py:type:`set` of ``cls`` instances giving the names of the
312 elliptic curves the underlying library supports.
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400313 """
314 if lib.Cryptography_HAS_EC:
315 num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
316 builtin_curves = _ffi.new('EC_builtin_curve[]', num_curves)
317 # The return value on this call should be num_curves again. We could
318 # check it to make sure but if it *isn't* then.. what could we do?
319 # Abort the whole process, I suppose...? -exarkun
320 lib.EC_get_builtin_curves(builtin_curves, num_curves)
321 return set(
322 cls.from_nid(lib, c.nid)
323 for c in builtin_curves)
Jean-Paul Calderone73945e32014-04-30 18:18:01 -0400324 return set()
325
326
327 @classmethod
328 def _get_elliptic_curves(cls, lib):
329 """
330 Get, cache, and return the curves supported by OpenSSL.
331
332 :param lib: The OpenSSL library binding object.
333
334 :return: A :py:type:`set` of ``cls`` instances giving the names of the
335 elliptic curves the underlying library supports.
336 """
337 if cls._curves is None:
338 cls._curves = cls._load_elliptic_curves(lib)
339 return cls._curves
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400340
341
342 @classmethod
343 def from_nid(cls, lib, nid):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400344 """
345 Instantiate a new :py:class:`_EllipticCurve` associated with the given
346 OpenSSL NID.
347
348 :param lib: The OpenSSL library binding object.
349
350 :param nid: The OpenSSL NID the resulting curve object will represent.
351 This must be a curve NID (and not, for example, a hash NID) or
352 subsequent operations will fail in unpredictable ways.
353 :type nid: :py:class:`int`
354
355 :return: The curve object.
356 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400357 return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
358
359
360 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
377
378 def __repr__(self):
379 return "<Curve %r>" % (self.name,)
380
381
382 def _to_EC_KEY(self):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400383 """
384 Create a new OpenSSL EC_KEY structure initialized to use this curve.
385
386 The structure is automatically garbage collected when the Python object
387 is garbage collected.
388 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400389 key = self._lib.EC_KEY_new_by_curve_name(self._nid)
390 return _ffi.gc(key, _lib.EC_KEY_free)
391
392
393
394def get_elliptic_curves():
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400395 """
396 Return a set of objects representing the elliptic curves supported in the
397 OpenSSL build in use.
398
399 The curve objects have a :py:class:`unicode` ``name`` attribute by which
400 they identify themselves.
401
402 The curve objects are useful as values for the argument accepted by
Jean-Paul Calderone3b04e352014-04-19 09:29:10 -0400403 :py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
404 used for ECDHE key exchange.
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400405 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400406 return _EllipticCurve._get_elliptic_curves(_lib)
407
408
409
410def get_elliptic_curve(name):
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400411 """
412 Return a single curve object selected by name.
413
414 See :py:func:`get_elliptic_curves` for information about curve objects.
415
Jean-Paul Calderoned5839e22014-04-19 09:26:44 -0400416 :param name: The OpenSSL short name identifying the curve object to
417 retrieve.
418 :type name: :py:class:`unicode`
419
Jean-Paul Calderoneaaf516d2014-04-19 09:10:45 -0400420 If the named curve is not supported then :py:class:`ValueError` is raised.
421 """
Jean-Paul Calderonec09fd582014-04-18 22:00:10 -0400422 for curve in get_elliptic_curves():
423 if curve.name == name:
424 return curve
425 raise ValueError("unknown curve name", name)
426
427
428
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800429class X509Name(object):
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200430 """
431 An X.509 Distinguished Name.
432
433 :ivar countryName: The country of the entity.
434 :ivar C: Alias for :py:attr:`countryName`.
435
436 :ivar stateOrProvinceName: The state or province of the entity.
437 :ivar ST: Alias for :py:attr:`stateOrProvinceName`.
438
439 :ivar localityName: The locality of the entity.
440 :ivar L: Alias for :py:attr:`localityName`.
441
442 :ivar organizationName: The organization name of the entity.
443 :ivar O: Alias for :py:attr:`organizationName`.
444
445 :ivar organizationalUnitName: The organizational unit of the entity.
446 :ivar OU: Alias for :py:attr:`organizationalUnitName`
447
448 :ivar commonName: The common name of the entity.
449 :ivar CN: Alias for :py:attr:`commonName`.
450
451 :ivar emailAddress: The e-mail address of the entity.
452 """
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800453 def __init__(self, name):
454 """
455 Create a new X509Name, copying the given X509Name instance.
456
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200457 :param name: The name to copy.
458 :type name: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800459 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500460 name = _lib.X509_NAME_dup(name._name)
461 self._name = _ffi.gc(name, _lib.X509_NAME_free)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800462
463
464 def __setattr__(self, name, value):
465 if name.startswith('_'):
466 return super(X509Name, self).__setattr__(name, value)
467
Jean-Paul Calderoneff363be2013-03-03 10:21:23 -0800468 # Note: we really do not want str subclasses here, so we do not use
469 # isinstance.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800470 if type(name) is not str:
471 raise TypeError("attribute name must be string, not '%.200s'" % (
472 type(value).__name__,))
473
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500474 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500475 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800476 try:
477 _raise_current_error()
478 except Error:
479 pass
480 raise AttributeError("No such attribute")
481
482 # If there's an old entry for this NID, remove it
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500483 for i in range(_lib.X509_NAME_entry_count(self._name)):
484 ent = _lib.X509_NAME_get_entry(self._name, i)
485 ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
486 ent_nid = _lib.OBJ_obj2nid(ent_obj)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800487 if nid == ent_nid:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500488 ent = _lib.X509_NAME_delete_entry(self._name, i)
489 _lib.X509_NAME_ENTRY_free(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800490 break
491
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500492 if isinstance(value, _text_type):
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800493 value = value.encode('utf-8')
494
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500495 add_result = _lib.X509_NAME_add_entry_by_NID(
496 self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800497 if not add_result:
Jean-Paul Calderone5300d6a2013-12-29 16:36:50 -0500498 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800499
500
501 def __getattr__(self, name):
502 """
503 Find attribute. An X509Name object has the following attributes:
504 countryName (alias C), stateOrProvince (alias ST), locality (alias L),
505 organization (alias O), organizationalUnit (alias OU), commonName (alias
506 CN) and more...
507 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500508 nid = _lib.OBJ_txt2nid(_byte_string(name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500509 if nid == _lib.NID_undef:
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800510 # This is a bit weird. OBJ_txt2nid indicated failure, but it seems
511 # a lower level function, a2d_ASN1_OBJECT, also feels the need to
512 # push something onto the error queue. If we don't clean that up
513 # now, someone else will bump into it later and be quite confused.
514 # See lp#314814.
515 try:
516 _raise_current_error()
517 except Error:
518 pass
519 return super(X509Name, self).__getattr__(name)
520
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500521 entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800522 if entry_index == -1:
523 return None
524
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500525 entry = _lib.X509_NAME_get_entry(self._name, entry_index)
526 data = _lib.X509_NAME_ENTRY_get_data(entry)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800527
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500528 result_buffer = _ffi.new("unsigned char**")
529 data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800530 if data_length < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500531 # TODO: This is untested.
532 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800533
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700534 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500535 result = _ffi.buffer(result_buffer[0], data_length)[:].decode('utf-8')
Jean-Paul Calderoned899af02013-03-19 22:10:37 -0700536 finally:
537 # XXX untested
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500538 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800539 return result
540
541
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500542 def _cmp(op):
543 def f(self, other):
544 if not isinstance(other, X509Name):
545 return NotImplemented
546 result = _lib.X509_NAME_cmp(self._name, other._name)
547 return op(result, 0)
548 return f
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800549
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500550 __eq__ = _cmp(__eq__)
551 __ne__ = _cmp(__ne__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800552
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500553 __lt__ = _cmp(__lt__)
554 __le__ = _cmp(__le__)
555
556 __gt__ = _cmp(__gt__)
557 __ge__ = _cmp(__ge__)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800558
559 def __repr__(self):
560 """
561 String representation of an X509Name
562 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500563 result_buffer = _ffi.new("char[]", 512);
564 format_result = _lib.X509_NAME_oneline(
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800565 self._name, result_buffer, len(result_buffer))
566
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500567 if format_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500568 # TODO: This is untested.
569 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800570
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500571 return "<X509Name object '%s'>" % (
572 _native(_ffi.string(result_buffer)),)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800573
574
575 def hash(self):
576 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200577 Return an integer representation of the first four bytes of the
578 MD5 digest of the DER representation of the name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800579
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200580 This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
581
582 :return: The (integer) hash of this name.
583 :rtype: :py:class:`int`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800584 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500585 return _lib.X509_NAME_hash(self._name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800586
587
588 def der(self):
589 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200590 Return the DER encoding of this name.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800591
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200592 :return: The DER encoded form of this name.
593 :rtype: :py:class:`bytes`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800594 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500595 result_buffer = _ffi.new('unsigned char**')
596 encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800597 if encode_result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500598 # TODO: This is untested.
599 _raise_current_error()
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800600
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500601 string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
602 _lib.OPENSSL_free(result_buffer[0])
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800603 return string_result
604
605
606 def get_components(self):
607 """
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200608 Returns the components of this name, as a sequence of 2-tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800609
Laurens Van Houtven196195b2014-06-17 17:06:34 +0200610 :return: The components of this name.
611 :rtype: :py:class:`list` of ``name, value`` tuples.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800612 """
613 result = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500614 for i in range(_lib.X509_NAME_entry_count(self._name)):
615 ent = _lib.X509_NAME_get_entry(self._name, i)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500617 fname = _lib.X509_NAME_ENTRY_get_object(ent)
618 fval = _lib.X509_NAME_ENTRY_get_data(ent)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800619
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500620 nid = _lib.OBJ_obj2nid(fname)
621 name = _lib.OBJ_nid2sn(nid)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800622
623 result.append((
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500624 _ffi.string(name),
625 _ffi.string(
626 _lib.ASN1_STRING_data(fval),
627 _lib.ASN1_STRING_length(fval))))
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800628
629 return result
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200630
631
632
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800633X509NameType = X509Name
634
635
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200636
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800637class X509Extension(object):
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200638 """
639 An X.509 v3 certificate extension.
640 """
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800641 def __init__(self, type_name, critical, value, subject=None, issuer=None):
642 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200643 Initializes an X509 extension.
644
645 :param typename: The name of the type of extension to create. See
646 http://openssl.org/docs/apps/x509v3_config.html#STANDARD_EXTENSIONS
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800647 :type typename: :py:data:`str`
648
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200649 :param bool critical: A flag indicating whether this is a critical extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800650
651 :param value: The value of the extension.
652 :type value: :py:data:`str`
653
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200654 :param subject: Optional X509 certificate to use as subject.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800655 :type subject: :py:class:`X509`
656
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200657 :param issuer: Optional X509 certificate to use as issuer.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800658 :type issuer: :py:class:`X509`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800659 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500660 ctx = _ffi.new("X509V3_CTX*")
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800661
662 # A context is necessary for any extension which uses the r2i conversion
663 # method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx.
664 # Start off by initializing most of the fields to NULL.
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500665 _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800666
667 # We have no configuration database - but perhaps we should (some
668 # extensions may require it).
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500669 _lib.X509V3_set_ctx_nodb(ctx)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800670
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800671 # Initialize the subject and issuer, if appropriate. ctx is a local,
672 # and as far as I can tell none of the X509V3_* APIs invoked here steal
673 # any references, so no need to mess with reference counts or duplicates.
674 if issuer is not None:
675 if not isinstance(issuer, X509):
676 raise TypeError("issuer must be an X509 instance")
677 ctx.issuer_cert = issuer._x509
678 if subject is not None:
679 if not isinstance(subject, X509):
680 raise TypeError("subject must be an X509 instance")
681 ctx.subject_cert = subject._x509
682
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800683 if critical:
684 # There are other OpenSSL APIs which would let us pass in critical
685 # separately, but they're harder to use, and since value is already
686 # a pile of crappy junk smuggling a ton of utterly important
687 # structured data, what's the point of trying to avoid nasty stuff
688 # with strings? (However, X509V3_EXT_i2d in particular seems like it
689 # would be a better API to invoke. I do not know where to get the
690 # ext_struc it desires for its last parameter, though.)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500691 value = b"critical," + value
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800692
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500693 extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
694 if extension == _ffi.NULL:
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800695 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500696 self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800697
698
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400699 @property
700 def _nid(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500701 return _lib.OBJ_obj2nid(self._extension.object)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400702
703 _prefixes = {
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500704 _lib.GEN_EMAIL: "email",
705 _lib.GEN_DNS: "DNS",
706 _lib.GEN_URI: "URI",
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400707 }
708
709 def _subjectAltNameString(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500710 method = _lib.X509V3_EXT_get(self._extension)
711 if method == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500712 # TODO: This is untested.
713 _raise_current_error()
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400714 payload = self._extension.value.data
715 length = self._extension.value.length
716
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500717 payloadptr = _ffi.new("unsigned char**")
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400718 payloadptr[0] = payload
719
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500720 if method.it != _ffi.NULL:
721 ptr = _lib.ASN1_ITEM_ptr(method.it)
722 data = _lib.ASN1_item_d2i(_ffi.NULL, payloadptr, length, ptr)
723 names = _ffi.cast("GENERAL_NAMES*", data)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400724 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500725 names = _ffi.cast(
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400726 "GENERAL_NAMES*",
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500727 method.d2i(_ffi.NULL, payloadptr, length))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400728
729 parts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500730 for i in range(_lib.sk_GENERAL_NAME_num(names)):
731 name = _lib.sk_GENERAL_NAME_value(names, i)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400732 try:
733 label = self._prefixes[name.type]
734 except KeyError:
735 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500736 _lib.GENERAL_NAME_print(bio, name)
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500737 parts.append(_native(_bio_to_string(bio)))
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400738 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500739 value = _native(
740 _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[:])
741 parts.append(label + ":" + value)
742 return ", ".join(parts)
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400743
744
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800745 def __str__(self):
746 """
747 :return: a nice text representation of the extension
748 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500749 if _lib.NID_subject_alt_name == self._nid:
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400750 return self._subjectAltNameString()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800751
Jean-Paul Calderoneed0c57b2013-10-06 08:31:40 -0400752 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500753 print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800754 if not print_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500755 # TODO: This is untested.
756 _raise_current_error()
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800757
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500758 return _native(_bio_to_string(bio))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800759
760
761 def get_critical(self):
762 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200763 Returns the critical field of this X.509 extension.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800764
765 :return: The critical field.
766 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500767 return _lib.X509_EXTENSION_get_critical(self._extension)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800768
769
770 def get_short_name(self):
771 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200772 Returns the short type name of this X.509 extension.
773
774 The result is a byte string such as :py:const:`b"basicConstraints"`.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800775
776 :return: The short type name.
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200777 :rtype: :py:data:`bytes`
778
779 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800780 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500781 obj = _lib.X509_EXTENSION_get_object(self._extension)
782 nid = _lib.OBJ_obj2nid(obj)
783 return _ffi.string(_lib.OBJ_nid2sn(nid))
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -0800784
785
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800786 def get_data(self):
787 """
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200788 Returns the data of the X509 extension, encoded as ASN.1.
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800789
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200790 :return: The ASN.1 encoded data of this X509 extension.
791 :rtype: :py:data:`bytes`
792
793 .. versionadded:: 0.12
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800794 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500795 octet_result = _lib.X509_EXTENSION_get_data(self._extension)
796 string_result = _ffi.cast('ASN1_STRING*', octet_result)
797 char_result = _lib.ASN1_STRING_data(string_result)
798 result_length = _lib.ASN1_STRING_length(string_result)
799 return _ffi.buffer(char_result, result_length)[:]
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800800
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200801
802
Jean-Paul Calderoned418a9c2013-02-20 16:24:55 -0800803X509ExtensionType = X509Extension
804
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -0800805
Laurens Van Houtven2650de52014-06-18 13:47:47 +0200806
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800807class X509Req(object):
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200808 """
809 An X.509 certificate signing requests.
810 """
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800811 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500812 req = _lib.X509_REQ_new()
813 self._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800814
815
816 def set_pubkey(self, pkey):
817 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200818 Set the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800819
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200820 :param pkey: The public key to use.
821 :type pkey: :py:class:`PKey`
822
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200823 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800824 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500825 set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800826 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500827 # TODO: This is untested.
828 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800829
830
831 def get_pubkey(self):
832 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200833 Get the public key of the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800834
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200835 :return: The public key.
836 :rtype: :py:class:`PKey`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800837 """
838 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500839 pkey._pkey = _lib.X509_REQ_get_pubkey(self._req)
840 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500841 # TODO: This is untested.
842 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500843 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800844 pkey._only_public = True
845 return pkey
846
847
848 def set_version(self, version):
849 """
850 Set the version subfield (RFC 2459, section 4.1.2.1) of the certificate
851 request.
852
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200853 :param int version: The version number.
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200854 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800855 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500856 set_result = _lib.X509_REQ_set_version(self._req, version)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800857 if not set_result:
858 _raise_current_error()
859
860
861 def get_version(self):
862 """
863 Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate
864 request.
865
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200866 :return: The value of the version subfield.
867 :rtype: :py:class:`int`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800868 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500869 return _lib.X509_REQ_get_version(self._req)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800870
871
872 def get_subject(self):
873 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200874 Return the subject of this certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800875
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200876 This creates a new :py:class:`X509Name`: modifying it does not affect
877 this request.
878
879 :return: The subject of this certificate signing request.
880 :rtype: :py:class:`X509Name`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800881 """
882 name = X509Name.__new__(X509Name)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500883 name._name = _lib.X509_REQ_get_subject_name(self._req)
884 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500885 # TODO: This is untested.
886 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800887
888 # The name is owned by the X509Req structure. As long as the X509Name
889 # Python object is alive, keep the X509Req Python object alive.
890 name._owner = self
891
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800892 return name
893
894
895 def add_extensions(self, extensions):
896 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200897 Add extensions to the certificate signing request.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800898
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200899 :param extensions: The X.509 extensions to add.
900 :type extensions: iterable of :py:class:`X509Extension`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200901 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800902 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500903 stack = _lib.sk_X509_EXTENSION_new_null()
904 if stack == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500905 # TODO: This is untested.
906 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800907
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500908 stack = _ffi.gc(stack, _lib.sk_X509_EXTENSION_free)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -0800909
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800910 for ext in extensions:
911 if not isinstance(ext, X509Extension):
Jean-Paul Calderonec2154b72013-02-20 14:29:37 -0800912 raise ValueError("One of the elements is not an X509Extension")
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800913
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -0800914 # TODO push can fail (here and elsewhere)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500915 _lib.sk_X509_EXTENSION_push(stack, ext._extension)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800916
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500917 add_result = _lib.X509_REQ_add_extensions(self._req, stack)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800918 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500919 # TODO: This is untested.
920 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800921
922
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800923 def get_extensions(self):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800924 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200925 Get X.509 extensions in the certificate signing request.
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800926
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200927 :return: The X.509 extensions in this request.
928 :rtype: :py:class:`list` of :py:class:`X509Extension` objects.
929
930 .. versionadded:: 0.15
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800931 """
932 exts = []
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500933 native_exts_obj = _lib.X509_REQ_get_extensions(self._req)
Jean-Paul Calderoneb7a79b42014-03-02 08:06:47 -0500934 for i in range(_lib.sk_X509_EXTENSION_num(native_exts_obj)):
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800935 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone9479d732014-03-02 08:04:54 -0500936 ext._extension = _lib.sk_X509_EXTENSION_value(native_exts_obj, i)
Stephen Holsapple7fbdf642014-03-01 20:05:47 -0800937 exts.append(ext)
938 return exts
Stephen Holsappleadfd39d2014-01-28 17:58:31 -0800939
940
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800941 def sign(self, pkey, digest):
942 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200943 Sign the certificate signing request using the supplied key and digest.
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800944
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200945 :param pkey: The key pair to sign with.
946 :type pkey: :py:class:`PKey`
947 :param digest: The name of the message digest to use for the signature,
948 e.g. :py:data:`b"sha1"`.
949 :type digest: :py:class:`bytes`
Laurens Van Houtvena7904582014-06-19 12:33:04 +0200950 :return: :py:const:`None`
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800951 """
952 if pkey._only_public:
953 raise ValueError("Key has only public part")
954
955 if not pkey._initialized:
956 raise ValueError("Key is uninitialized")
957
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -0500958 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500959 if digest_obj == _ffi.NULL:
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800960 raise ValueError("No such digest method")
961
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500962 sign_result = _lib.X509_REQ_sign(self._req, pkey._pkey, digest_obj)
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800963 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -0500964 # TODO: This is untested.
965 _raise_current_error()
Jean-Paul Calderone4328d472013-02-20 14:28:46 -0800966
967
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800968 def verify(self, pkey):
969 """
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200970 Verifies the signature on this certificate signing request.
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800971
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200972 :param key: A public key.
973 :type key: :py:class:`PKey`
974 :return: :py:data:`True` if the signature is correct.
975 :rtype: :py:class:`bool`
976 :raises Error: If the signature is invalid or there is a
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800977 problem verifying the signature.
978 """
979 if not isinstance(pkey, PKey):
980 raise TypeError("pkey must be a PKey instance")
981
Jean-Paul Calderone6037d072013-12-28 18:04:00 -0500982 result = _lib.X509_REQ_verify(self._req, pkey._pkey)
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800983 if result <= 0:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -0500984 _raise_current_error()
Jean-Paul Calderone5565f0f2013-03-06 11:10:20 -0800985
986 return result
987
988
Laurens Van Houtven3e83d242014-06-18 14:29:47 +0200989
Jean-Paul Calderone066f0572013-02-20 13:43:44 -0800990X509ReqType = X509Req
991
992
993
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800994class X509(object):
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +0200995 """
996 An X.509 certificate.
997 """
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -0800998 def __init__(self):
999 # TODO Allocation failure? And why not __new__ instead of __init__?
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001000 x509 = _lib.X509_new()
1001 self._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001002
1003
1004 def set_version(self, version):
1005 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001006 Set the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001007
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001008 :param version: The version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001009 :type version: :py:class:`int`
1010
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001011 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001012 """
1013 if not isinstance(version, int):
1014 raise TypeError("version must be an integer")
1015
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001016 _lib.X509_set_version(self._x509, version)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001017
1018
1019 def get_version(self):
1020 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001021 Return the version number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001022
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001023 :return: The version number of the certificate.
1024 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001025 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001026 return _lib.X509_get_version(self._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001027
1028
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001029 def get_pubkey(self):
1030 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001031 Get the public key of the certificate.
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001032
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001033 :return: The public key.
1034 :rtype: :py:class:`PKey`
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001035 """
1036 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001037 pkey._pkey = _lib.X509_get_pubkey(self._x509)
1038 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001039 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001040 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001041 pkey._only_public = True
1042 return pkey
1043
1044
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001045 def set_pubkey(self, pkey):
1046 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001047 Set the public key of the certificate.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001048
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001049 :param pkey: The public key.
1050 :type pkey: :py:class:`PKey`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001051
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001052 :return: :py:data`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001053 """
1054 if not isinstance(pkey, PKey):
1055 raise TypeError("pkey must be a PKey instance")
1056
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001057 set_result = _lib.X509_set_pubkey(self._x509, pkey._pkey)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001058 if not set_result:
1059 _raise_current_error()
1060
1061
1062 def sign(self, pkey, digest):
1063 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001064 Sign the certificate using the supplied key and digest type.
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001065
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001066 :param pkey: The key to sign with.
1067 :type pkey: :py:class:`PKey`
1068
1069 :param digest: The name of the message digest to use.
1070 :type digest: :py:class:`bytes`
1071
1072 :return: :py:data`None`
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001073 """
1074 if not isinstance(pkey, PKey):
1075 raise TypeError("pkey must be a PKey instance")
1076
Jean-Paul Calderoneedafced2013-02-19 11:48:38 -08001077 if pkey._only_public:
1078 raise ValueError("Key only has public part")
1079
Jean-Paul Calderone09e3bdc2013-02-19 12:15:28 -08001080 if not pkey._initialized:
1081 raise ValueError("Key is uninitialized")
1082
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001083 evp_md = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001084 if evp_md == _ffi.NULL:
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001085 raise ValueError("No such digest method")
1086
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001087 sign_result = _lib.X509_sign(self._x509, pkey._pkey, evp_md)
Jean-Paul Calderone3e29ccf2013-02-19 11:32:46 -08001088 if not sign_result:
1089 _raise_current_error()
1090
1091
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001092 def get_signature_algorithm(self):
1093 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001094 Return the signature algorithm used in the certificate.
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001095
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001096 :return: The name of the algorithm.
1097 :rtype: :py:class:`bytes`
1098
1099 :raises ValueError: If the signature algorithm is undefined.
1100
1101 ..versionadded:: 0.13
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001102 """
1103 alg = self._x509.cert_info.signature.algorithm
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001104 nid = _lib.OBJ_obj2nid(alg)
1105 if nid == _lib.NID_undef:
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001106 raise ValueError("Undefined signature algorithm")
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001107 return _ffi.string(_lib.OBJ_nid2ln(nid))
Jean-Paul Calderonee4aa3fa2013-02-19 12:12:53 -08001108
1109
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001110 def digest(self, digest_name):
1111 """
1112 Return the digest of the X509 object.
1113
1114 :param digest_name: The name of the digest algorithm to use.
1115 :type digest_name: :py:class:`bytes`
1116
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001117 :return: The digest of the object, formatted as
1118 :py:const:`b":"`-delimited hex pairs.
1119 :rtype: :py:class:`bytes`
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001120 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001121 digest = _lib.EVP_get_digestbyname(_byte_string(digest_name))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001122 if digest == _ffi.NULL:
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001123 raise ValueError("No such digest method")
1124
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001125 result_buffer = _ffi.new("char[]", _lib.EVP_MAX_MD_SIZE)
1126 result_length = _ffi.new("unsigned int[]", 1)
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001127 result_length[0] = len(result_buffer)
1128
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001129 digest_result = _lib.X509_digest(
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001130 self._x509, digest, result_buffer, result_length)
1131
1132 if not digest_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001133 # TODO: This is untested.
1134 _raise_current_error()
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001135
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001136 return b":".join([
1137 b16encode(ch).upper() for ch
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001138 in _ffi.buffer(result_buffer, result_length[0])])
Jean-Paul Calderoneb4078722013-02-19 12:01:55 -08001139
1140
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001141 def subject_name_hash(self):
1142 """
1143 Return the hash of the X509 subject.
1144
1145 :return: The hash of the subject.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001146 :rtype: :py:class:`bytes`
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001147 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001148 return _lib.X509_subject_name_hash(self._x509)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001149
1150
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001151 def set_serial_number(self, serial):
1152 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001153 Set the serial number of the certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001154
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001155 :param serial: The new serial number.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001156 :type serial: :py:class:`int`
1157
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001158 :return: :py:data`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001159 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001160 if not isinstance(serial, _integer_types):
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001161 raise TypeError("serial must be an integer")
1162
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001163 hex_serial = hex(serial)[2:]
1164 if not isinstance(hex_serial, bytes):
1165 hex_serial = hex_serial.encode('ascii')
1166
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001167 bignum_serial = _ffi.new("BIGNUM**")
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001168
1169 # BN_hex2bn stores the result in &bignum. Unless it doesn't feel like
1170 # it. If bignum is still NULL after this call, then the return value is
1171 # actually the result. I hope. -exarkun
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001172 small_serial = _lib.BN_hex2bn(bignum_serial, hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001173
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001174 if bignum_serial[0] == _ffi.NULL:
1175 set_result = _lib.ASN1_INTEGER_set(
1176 _lib.X509_get_serialNumber(self._x509), small_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001177 if set_result:
1178 # TODO Not tested
1179 _raise_current_error()
1180 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001181 asn1_serial = _lib.BN_to_ASN1_INTEGER(bignum_serial[0], _ffi.NULL)
1182 _lib.BN_free(bignum_serial[0])
1183 if asn1_serial == _ffi.NULL:
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001184 # TODO Not tested
1185 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001186 asn1_serial = _ffi.gc(asn1_serial, _lib.ASN1_INTEGER_free)
1187 set_result = _lib.X509_set_serialNumber(self._x509, asn1_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001188 if not set_result:
1189 # TODO Not tested
1190 _raise_current_error()
1191
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001192
1193 def get_serial_number(self):
1194 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001195 Return the serial number of this certificate.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001196
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001197 :return: The serial number.
1198 :rtype: :py:class:`int`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001199 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001200 asn1_serial = _lib.X509_get_serialNumber(self._x509)
1201 bignum_serial = _lib.ASN1_INTEGER_to_BN(asn1_serial, _ffi.NULL)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001202 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001203 hex_serial = _lib.BN_bn2hex(bignum_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001204 try:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001205 hexstring_serial = _ffi.string(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001206 serial = int(hexstring_serial, 16)
1207 return serial
1208 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001209 _lib.OPENSSL_free(hex_serial)
Jean-Paul Calderone78133852013-02-19 10:41:46 -08001210 finally:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001211 _lib.BN_free(bignum_serial)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001212
1213
1214 def gmtime_adj_notAfter(self, amount):
1215 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001216 Adjust the time stamp on which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001217
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001218 :param amount: The number of seconds by which to adjust the timestamp.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001219 :type amount: :py:class:`int`
1220
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001221 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001222 """
1223 if not isinstance(amount, int):
1224 raise TypeError("amount must be an integer")
1225
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001226 notAfter = _lib.X509_get_notAfter(self._x509)
1227 _lib.X509_gmtime_adj(notAfter, amount)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001228
1229
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001230 def gmtime_adj_notBefore(self, amount):
1231 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001232 Adjust the timestamp on which the certificate starts being valid.
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001233
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001234 :param amount: The number of seconds by which to adjust the timestamp.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001235 :return: :py:const:`None`
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001236 """
1237 if not isinstance(amount, int):
1238 raise TypeError("amount must be an integer")
1239
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001240 notBefore = _lib.X509_get_notBefore(self._x509)
1241 _lib.X509_gmtime_adj(notBefore, amount)
Jean-Paul Calderone662afe52013-02-20 08:41:11 -08001242
1243
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001244 def has_expired(self):
1245 """
1246 Check whether the certificate has expired.
1247
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001248 :return: :py:const:`True` if the certificate has expired,
1249 :py:const:`False` otherwise.
1250 :rtype: :py:class:`bool`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001251 """
1252 now = int(time())
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001253 notAfter = _lib.X509_get_notAfter(self._x509)
1254 return _lib.ASN1_UTCTIME_cmp_time_t(
1255 _ffi.cast('ASN1_UTCTIME*', notAfter), now) < 0
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001256
1257
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001258 def _get_boundary_time(self, which):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001259 return _get_asn1_time(which(self._x509))
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001260
1261
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001262 def get_notBefore(self):
1263 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001264 Get the timestamp at which the certificate starts 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_notBefore)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001276
1277
1278 def _set_boundary_time(self, which, when):
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001279 return _set_asn1_time(which(self._x509), when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001280
1281
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001282 def set_notBefore(self, when):
1283 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001284 Set the timestamp at which the certificate starts being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001285
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001286 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001287
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001288 YYYYMMDDhhmmssZ
1289 YYYYMMDDhhmmss+hhmm
1290 YYYYMMDDhhmmss-hhmm
1291
1292 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001293 :type when: :py:class:`bytes`
1294
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001295 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001296 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001297 return self._set_boundary_time(_lib.X509_get_notBefore, when)
Jean-Paul Calderoned7d81272013-02-19 13:16:03 -08001298
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001299
1300 def get_notAfter(self):
1301 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001302 Get the timestamp at which the certificate stops being valid.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001303
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001304 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001305
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001306 YYYYMMDDhhmmssZ
1307 YYYYMMDDhhmmss+hhmm
1308 YYYYMMDDhhmmss-hhmm
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001309
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001310 :return: A timestamp string, or :py:const:`None` if there is none.
1311 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001312 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001313 return self._get_boundary_time(_lib.X509_get_notAfter)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001314
1315
1316 def set_notAfter(self, when):
1317 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001318 Set the timestamp at which the certificate stops being valid.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001319
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001320 The timestamp is formatted as an ASN.1 GENERALIZEDTIME::
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001321
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001322 YYYYMMDDhhmmssZ
1323 YYYYMMDDhhmmss+hhmm
1324 YYYYMMDDhhmmss-hhmm
1325
1326 :param when: A timestamp string.
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001327 :type when: :py:class:`bytes`
1328
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001329 :return: :py:const:`None`
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001330 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001331 return self._set_boundary_time(_lib.X509_get_notAfter, when)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001332
1333
1334 def _get_name(self, which):
1335 name = X509Name.__new__(X509Name)
1336 name._name = which(self._x509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001337 if name._name == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001338 # TODO: This is untested.
1339 _raise_current_error()
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001340
1341 # The name is owned by the X509 structure. As long as the X509Name
1342 # Python object is alive, keep the X509 Python object alive.
1343 name._owner = self
1344
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001345 return name
1346
1347
1348 def _set_name(self, which, name):
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001349 if not isinstance(name, X509Name):
1350 raise TypeError("name must be an X509Name")
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001351 set_result = which(self._x509, name._name)
1352 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001353 # TODO: This is untested.
1354 _raise_current_error()
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001355
1356
1357 def get_issuer(self):
1358 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001359 Return the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001360
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001361 This creates a new :py:class:`X509Name`: modifying it does not affect
1362 this certificate.
1363
1364 :return: The issuer of this certificate.
1365 :rtype: :py:class:`X509Name`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001366 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001367 return self._get_name(_lib.X509_get_issuer_name)
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001368
1369
1370 def set_issuer(self, issuer):
1371 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001372 Set the issuer of this certificate.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001373
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001374 :param issuer: The issuer.
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001375 :type issuer: :py:class:`X509Name`
1376
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001377 :return: :py:const:`None`
Jean-Paul Calderonec2bd4e92013-02-20 08:12:36 -08001378 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001379 return self._set_name(_lib.X509_set_issuer_name, issuer)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001380
1381
1382 def get_subject(self):
1383 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001384 Return the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001385
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001386 This creates a new :py:class:`X509Name`: modifying it does not affect
1387 this certificate.
1388
1389 :return: The subject of this certificate.
1390 :rtype: :py:class:`X509Name`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001391 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001392 return self._get_name(_lib.X509_get_subject_name)
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001393
1394
1395 def set_subject(self, subject):
1396 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001397 Set the subject of this certificate.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001398
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001399 :param subject: The subject.
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001400 :type subject: :py:class:`X509Name`
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001401
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001402 :return: :py:const:`None`
Jean-Paul Calderonea9de1952013-02-19 16:58:42 -08001403 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001404 return self._set_name(_lib.X509_set_subject_name, subject)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001405
1406
1407 def get_extension_count(self):
1408 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001409 Get the number of extensions on this certificate.
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001410
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001411 :return: The number of extensions.
1412 :rtype: :py:class:`int`
1413
1414 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001415 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001416 return _lib.X509_get_ext_count(self._x509)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001417
1418
1419 def add_extensions(self, extensions):
1420 """
1421 Add extensions to the certificate.
1422
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001423 :param extensions: The extensions to add.
1424 :type extensions: An iterable of :py:class:`X509Extension` objects.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001425 :return: :py:const:`None`
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001426 """
1427 for ext in extensions:
1428 if not isinstance(ext, X509Extension):
1429 raise ValueError("One of the elements is not an X509Extension")
1430
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001431 add_result = _lib.X509_add_ext(self._x509, ext._extension, -1)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001432 if not add_result:
1433 _raise_current_error()
1434
1435
1436 def get_extension(self, index):
1437 """
1438 Get a specific extension of the certificate by index.
1439
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02001440 Extensions on a certificate are kept in order. The index
1441 parameter selects which extension will be returned.
1442
1443 :param int index: The index of the extension to retrieve.
1444 :return: The extension at the specified index.
1445 :rtype: :py:class:`X509Extension`
1446 :raises IndexError: If the extension index was out of bounds.
1447
1448 .. versionadded:: 0.12
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001449 """
1450 ext = X509Extension.__new__(X509Extension)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001451 ext._extension = _lib.X509_get_ext(self._x509, index)
1452 if ext._extension == _ffi.NULL:
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001453 raise IndexError("extension index out of bounds")
1454
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001455 extension = _lib.X509_EXTENSION_dup(ext._extension)
1456 ext._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
Jean-Paul Calderone83d22eb2013-02-20 12:19:43 -08001457 return ext
1458
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001459
1460
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001461X509Type = X509
1462
1463
1464
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001465class X509Store(object):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001466 """
1467 An X509 certificate store.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001468 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001469 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001470 store = _lib.X509_STORE_new()
1471 self._store = _ffi.gc(store, _lib.X509_STORE_free)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001472
1473
1474 def add_cert(self, cert):
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001475 """
1476 Adds the certificate :py:data:`cert` to this store.
1477
Laurens Van Houtven6e7dd432014-06-17 16:10:57 +02001478 This is the Python equivalent of OpenSSL's ``X509_STORE_add_cert``.
Laurens Van Houtvenef5c83d2014-06-17 15:32:27 +02001479
1480 :param X509 cert: The certificate to add to this store.
1481 :raises TypeError: If the certificate is not an :py:class:`X509`.
1482 :raises Error: If OpenSSL was unhappy with your certificate.
1483 :return: py:data:`None` if the certificate was added successfully.
1484 """
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001485 if not isinstance(cert, X509):
1486 raise TypeError()
1487
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001488 result = _lib.X509_STORE_add_cert(self._store, cert._x509)
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001489 if not result:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05001490 _raise_current_error()
Jean-Paul Calderonee6f32b82013-03-06 10:27:57 -08001491
Jean-Paul Calderonea63714c2013-03-05 17:02:26 -08001492
1493X509StoreType = X509Store
1494
1495
1496
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001497def load_certificate(type, buffer):
1498 """
1499 Load a certificate from a buffer
1500
1501 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
1502
1503 :param buffer: The buffer the certificate is stored in
1504 :type buffer: :py:class:`bytes`
1505
1506 :return: The X509 object
1507 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05001508 if isinstance(buffer, _text_type):
1509 buffer = buffer.encode("ascii")
1510
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001511 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001512
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001513 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001514 x509 = _lib.PEM_read_bio_X509(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001515 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001516 x509 = _lib.d2i_X509_bio(bio, _ffi.NULL);
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08001517 else:
1518 raise ValueError(
1519 "type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001520
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001521 if x509 == _ffi.NULL:
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001522 _raise_current_error()
1523
1524 cert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001525 cert._x509 = _ffi.gc(x509, _lib.X509_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001526 return cert
1527
1528
1529def dump_certificate(type, cert):
1530 """
1531 Dump a certificate to a buffer
1532
Jean-Paul Calderonea12e7d22013-04-03 08:17:34 -04001533 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1534 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001535 :param cert: The certificate to dump
1536 :return: The buffer with the dumped certificate in
1537 """
Jean-Paul Calderone0c73aff2013-03-02 07:45:12 -08001538 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001539
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001540 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001541 result_code = _lib.PEM_write_bio_X509(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001542 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001543 result_code = _lib.i2d_X509_bio(bio, cert._x509)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001544 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001545 result_code = _lib.X509_print_ex(bio, cert._x509, 0, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001546 else:
1547 raise ValueError(
1548 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1549 "FILETYPE_TEXT")
1550
1551 return _bio_to_string(bio)
1552
1553
1554
1555def dump_privatekey(type, pkey, cipher=None, passphrase=None):
1556 """
1557 Dump a private key to a buffer
1558
Jean-Paul Calderonee66fde22013-04-03 08:35:08 -04001559 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or
1560 FILETYPE_TEXT)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001561 :param pkey: The PKey to dump
1562 :param cipher: (optional) if encrypted PEM format, the cipher to
1563 use
1564 :param passphrase: (optional) if encrypted PEM format, this can be either
1565 the passphrase to use, or a callback for providing the
1566 passphrase.
1567 :return: The buffer with the dumped key in
1568 :rtype: :py:data:`str`
1569 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08001570 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001571
1572 if cipher is not None:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001573 if passphrase is None:
1574 raise TypeError(
1575 "if a value is given for cipher "
1576 "one must also be given for passphrase")
1577 cipher_obj = _lib.EVP_get_cipherbyname(_byte_string(cipher))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001578 if cipher_obj == _ffi.NULL:
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08001579 raise ValueError("Invalid cipher name")
1580 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001581 cipher_obj = _ffi.NULL
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001582
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001583 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001584 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001585 result_code = _lib.PEM_write_bio_PrivateKey(
1586 bio, pkey._pkey, cipher_obj, _ffi.NULL, 0,
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08001587 helper.callback, helper.callback_args)
1588 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001589 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001590 result_code = _lib.i2d_PrivateKey_bio(bio, pkey._pkey)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001591 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001592 rsa = _lib.EVP_PKEY_get1_RSA(pkey._pkey)
1593 result_code = _lib.RSA_print(bio, rsa, 0)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08001594 # TODO RSA_free(rsa)?
1595 else:
1596 raise ValueError(
1597 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or "
1598 "FILETYPE_TEXT")
1599
1600 if result_code == 0:
1601 _raise_current_error()
1602
1603 return _bio_to_string(bio)
1604
1605
1606
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001607def _X509_REVOKED_dup(original):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001608 copy = _lib.X509_REVOKED_new()
1609 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001610 # TODO: This is untested.
1611 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001612
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001613 if original.serialNumber != _ffi.NULL:
Jonathan Giannuzzib5b93222014-03-20 15:54:29 +01001614 _lib.ASN1_INTEGER_free(copy.serialNumber)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001615 copy.serialNumber = _lib.ASN1_INTEGER_dup(original.serialNumber)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001616
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001617 if original.revocationDate != _ffi.NULL:
Jonathan Giannuzzib5b93222014-03-20 15:54:29 +01001618 _lib.ASN1_TIME_free(copy.revocationDate)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001619 copy.revocationDate = _lib.M_ASN1_TIME_dup(original.revocationDate)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001620
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001621 if original.extensions != _ffi.NULL:
1622 extension_stack = _lib.sk_X509_EXTENSION_new_null()
1623 for i in range(_lib.sk_X509_EXTENSION_num(original.extensions)):
1624 original_ext = _lib.sk_X509_EXTENSION_value(original.extensions, i)
1625 copy_ext = _lib.X509_EXTENSION_dup(original_ext)
1626 _lib.sk_X509_EXTENSION_push(extension_stack, copy_ext)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001627 copy.extensions = extension_stack
1628
1629 copy.sequence = original.sequence
1630 return copy
1631
1632
1633
1634class Revoked(object):
1635 # http://www.openssl.org/docs/apps/x509v3_config.html#CRL_distribution_points_
1636 # which differs from crl_reasons of crypto/x509v3/v3_enum.c that matches
1637 # OCSP_crl_reason_str. We use the latter, just like the command line
1638 # program.
1639 _crl_reasons = [
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001640 b"unspecified",
1641 b"keyCompromise",
1642 b"CACompromise",
1643 b"affiliationChanged",
1644 b"superseded",
1645 b"cessationOfOperation",
1646 b"certificateHold",
1647 # b"removeFromCRL",
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001648 ]
1649
1650 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001651 revoked = _lib.X509_REVOKED_new()
1652 self._revoked = _ffi.gc(revoked, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001653
1654
1655 def set_serial(self, hex_str):
1656 """
1657 Set the serial number of a revoked Revoked structure
1658
1659 :param hex_str: The new serial number.
1660 :type hex_str: :py:data:`str`
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001661 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001662 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001663 bignum_serial = _ffi.gc(_lib.BN_new(), _lib.BN_free)
1664 bignum_ptr = _ffi.new("BIGNUM**")
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001665 bignum_ptr[0] = bignum_serial
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001666 bn_result = _lib.BN_hex2bn(bignum_ptr, hex_str)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001667 if not bn_result:
1668 raise ValueError("bad hex string")
1669
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001670 asn1_serial = _ffi.gc(
1671 _lib.BN_to_ASN1_INTEGER(bignum_serial, _ffi.NULL),
1672 _lib.ASN1_INTEGER_free)
1673 _lib.X509_REVOKED_set_serialNumber(self._revoked, asn1_serial)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001674
1675
1676 def get_serial(self):
1677 """
1678 Return the serial number of a Revoked structure
1679
1680 :return: The serial number as a string
1681 """
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001682 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001683
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001684 result = _lib.i2a_ASN1_INTEGER(bio, self._revoked.serialNumber)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001685 if result < 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001686 # TODO: This is untested.
1687 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001688
1689 return _bio_to_string(bio)
1690
1691
1692 def _delete_reason(self):
1693 stack = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001694 for i in range(_lib.sk_X509_EXTENSION_num(stack)):
1695 ext = _lib.sk_X509_EXTENSION_value(stack, i)
1696 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
1697 _lib.X509_EXTENSION_free(ext)
1698 _lib.sk_X509_EXTENSION_delete(stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001699 break
1700
1701
1702 def set_reason(self, reason):
1703 """
1704 Set the reason of a Revoked object.
1705
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001706 If :py:data:`reason` is :py:const:`None`, delete the reason instead.
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001707
1708 :param reason: The reason string.
1709 :type reason: :py:class:`str` or :py:class:`NoneType`
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001710 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001711 """
1712 if reason is None:
1713 self._delete_reason()
1714 elif not isinstance(reason, bytes):
1715 raise TypeError("reason must be None or a byte string")
1716 else:
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05001717 reason = reason.lower().replace(b' ', b'')
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001718 reason_code = [r.lower() for r in self._crl_reasons].index(reason)
1719
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001720 new_reason_ext = _lib.ASN1_ENUMERATED_new()
1721 if new_reason_ext == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001722 # TODO: This is untested.
1723 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001724 new_reason_ext = _ffi.gc(new_reason_ext, _lib.ASN1_ENUMERATED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001725
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001726 set_result = _lib.ASN1_ENUMERATED_set(new_reason_ext, reason_code)
1727 if set_result == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001728 # TODO: This is untested.
1729 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001730
1731 self._delete_reason()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001732 add_result = _lib.X509_REVOKED_add1_ext_i2d(
1733 self._revoked, _lib.NID_crl_reason, new_reason_ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001734
1735 if not add_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001736 # TODO: This is untested.
1737 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001738
1739
1740 def get_reason(self):
1741 """
1742 Return the reason of a Revoked object.
1743
1744 :return: The reason as a string
1745 """
1746 extensions = self._revoked.extensions
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001747 for i in range(_lib.sk_X509_EXTENSION_num(extensions)):
1748 ext = _lib.sk_X509_EXTENSION_value(extensions, i)
1749 if _lib.OBJ_obj2nid(ext.object) == _lib.NID_crl_reason:
Jean-Paul Calderonefd371362013-03-01 20:53:58 -08001750 bio = _new_mem_buf()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001751
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001752 print_result = _lib.X509V3_EXT_print(bio, ext, 0, 0)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001753 if not print_result:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001754 print_result = _lib.M_ASN1_OCTET_STRING_print(bio, ext.value)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001755 if print_result == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001756 # TODO: This is untested.
1757 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001758
1759 return _bio_to_string(bio)
1760
1761
1762 def all_reasons(self):
1763 """
1764 Return a list of all the supported reason strings.
1765
1766 :return: A list of reason strings.
1767 """
1768 return self._crl_reasons[:]
1769
1770
1771 def set_rev_date(self, when):
1772 """
1773 Set the revocation timestamp
1774
1775 :param when: A string giving the timestamp, in the format:
1776
1777 YYYYMMDDhhmmssZ
1778 YYYYMMDDhhmmss+hhmm
1779 YYYYMMDDhhmmss-hhmm
1780
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001781 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001782 """
1783 return _set_asn1_time(self._revoked.revocationDate, when)
1784
1785
1786 def get_rev_date(self):
1787 """
1788 Retrieve the revocation date
1789
1790 :return: A string giving the timestamp, in the format:
1791
1792 YYYYMMDDhhmmssZ
1793 YYYYMMDDhhmmss+hhmm
1794 YYYYMMDDhhmmss-hhmm
1795 """
1796 return _get_asn1_time(self._revoked.revocationDate)
1797
1798
1799
1800class CRL(object):
1801 def __init__(self):
1802 """
1803 Create a new empty CRL object.
1804 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001805 crl = _lib.X509_CRL_new()
1806 self._crl = _ffi.gc(crl, _lib.X509_CRL_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001807
1808
1809 def get_revoked(self):
1810 """
1811 Return revoked portion of the CRL structure (by value not reference).
1812
1813 :return: A tuple of Revoked objects.
1814 """
1815 results = []
1816 revoked_stack = self._crl.crl.revoked
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001817 for i in range(_lib.sk_X509_REVOKED_num(revoked_stack)):
1818 revoked = _lib.sk_X509_REVOKED_value(revoked_stack, i)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001819 revoked_copy = _X509_REVOKED_dup(revoked)
1820 pyrev = Revoked.__new__(Revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001821 pyrev._revoked = _ffi.gc(revoked_copy, _lib.X509_REVOKED_free)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001822 results.append(pyrev)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001823 if results:
1824 return tuple(results)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001825
1826
1827 def add_revoked(self, revoked):
1828 """
1829 Add a revoked (by value not reference) to the CRL structure
1830
1831 :param revoked: The new revoked.
1832 :type revoked: :class:`X509`
1833
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001834 :return: :py:const:`None`
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001835 """
1836 copy = _X509_REVOKED_dup(revoked._revoked)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001837 if copy == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001838 # TODO: This is untested.
1839 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001840
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001841 add_result = _lib.X509_CRL_add0_revoked(self._crl, copy)
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001842 if add_result == 0:
1843 # TODO: This is untested.
1844 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001845
1846
1847 def export(self, cert, key, type=FILETYPE_PEM, days=100):
1848 """
1849 export a CRL as a string
1850
1851 :param cert: Used to sign CRL.
1852 :type cert: :class:`X509`
1853
1854 :param key: Used to sign CRL.
1855 :type key: :class:`PKey`
1856
1857 :param type: The export format, either :py:data:`FILETYPE_PEM`, :py:data:`FILETYPE_ASN1`, or :py:data:`FILETYPE_TEXT`.
1858
1859 :param days: The number of days until the next update of this CRL.
1860 :type days: :py:data:`int`
1861
1862 :return: :py:data:`str`
1863 """
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001864 if not isinstance(cert, X509):
1865 raise TypeError("cert must be an X509 instance")
1866 if not isinstance(key, PKey):
1867 raise TypeError("key must be a PKey instance")
1868 if not isinstance(type, int):
1869 raise TypeError("type must be an integer")
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001870
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001871 bio = _lib.BIO_new(_lib.BIO_s_mem())
1872 if bio == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001873 # TODO: This is untested.
1874 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001875
1876 # A scratch time object to give different values to different CRL fields
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001877 sometime = _lib.ASN1_TIME_new()
1878 if sometime == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001879 # TODO: This is untested.
1880 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001881
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001882 _lib.X509_gmtime_adj(sometime, 0)
1883 _lib.X509_CRL_set_lastUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001884
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001885 _lib.X509_gmtime_adj(sometime, days * 24 * 60 * 60)
1886 _lib.X509_CRL_set_nextUpdate(self._crl, sometime)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001887
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001888 _lib.X509_CRL_set_issuer_name(self._crl, _lib.X509_get_subject_name(cert._x509))
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001889
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001890 sign_result = _lib.X509_CRL_sign(self._crl, key._pkey, _lib.EVP_md5())
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001891 if not sign_result:
1892 _raise_current_error()
1893
1894 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001895 ret = _lib.PEM_write_bio_X509_CRL(bio, self._crl)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001896 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001897 ret = _lib.i2d_X509_CRL_bio(bio, self._crl)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001898 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001899 ret = _lib.X509_CRL_print(bio, self._crl)
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001900 else:
1901 raise ValueError(
1902 "type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")
1903
1904 if not ret:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05001905 # TODO: This is untested.
1906 _raise_current_error()
Jean-Paul Calderone85b74eb2013-02-21 09:15:01 -08001907
1908 return _bio_to_string(bio)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08001909CRLType = CRL
1910
1911
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08001912
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001913class PKCS7(object):
1914 def type_is_signed(self):
1915 """
1916 Check if this NID_pkcs7_signed object
1917
1918 :return: True if the PKCS7 is of type signed
1919 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001920 if _lib.PKCS7_type_is_signed(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001921 return True
1922 return False
1923
1924
1925 def type_is_enveloped(self):
1926 """
1927 Check if this NID_pkcs7_enveloped object
1928
1929 :returns: True if the PKCS7 is of type enveloped
1930 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001931 if _lib.PKCS7_type_is_enveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001932 return True
1933 return False
1934
1935
1936 def type_is_signedAndEnveloped(self):
1937 """
1938 Check if this NID_pkcs7_signedAndEnveloped object
1939
1940 :returns: True if the PKCS7 is of type signedAndEnveloped
1941 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001942 if _lib.PKCS7_type_is_signedAndEnveloped(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001943 return True
1944 return False
1945
1946
1947 def type_is_data(self):
1948 """
1949 Check if this NID_pkcs7_data object
1950
1951 :return: True if the PKCS7 is of type data
1952 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001953 if _lib.PKCS7_type_is_data(self._pkcs7):
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001954 return True
1955 return False
1956
1957
1958 def get_type_name(self):
1959 """
1960 Returns the type name of the PKCS7 structure
1961
1962 :return: A string with the typename
1963 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05001964 nid = _lib.OBJ_obj2nid(self._pkcs7.type)
1965 string_type = _lib.OBJ_nid2sn(nid)
1966 return _ffi.string(string_type)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08001967
1968PKCS7Type = PKCS7
1969
1970
1971
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08001972class PKCS12(object):
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001973 """
1974 A PKCS #12 archive.
1975 """
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08001976 def __init__(self):
1977 self._pkey = None
1978 self._cert = None
1979 self._cacerts = None
1980 self._friendlyname = None
1981
1982
1983 def get_certificate(self):
1984 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001985 Get the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08001986
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001987 :return: The certificate, or :py:const:`None` if there is none.
1988 :rtype: :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08001989 """
1990 return self._cert
1991
1992
1993 def set_certificate(self, cert):
1994 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001995 Set the certificate in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08001996
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001997 :param cert: The new certificate, or :py:const:`None` to unset it.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02001998 :type cert: :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02001999
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002000 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002001 """
2002 if not isinstance(cert, X509):
2003 raise TypeError("cert must be an X509 instance")
2004 self._cert = cert
2005
2006
2007 def get_privatekey(self):
2008 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002009 Get the private key in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002010
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002011 :return: The private key, or :py:const:`None` if there is none.
2012 :rtype: :py:class:`PKey`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002013 """
2014 return self._pkey
2015
2016
2017 def set_privatekey(self, pkey):
2018 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002019 Set the certificate portion of the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002020
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002021 :param pkey: The new private key, or :py:const:`None` to unset it.
2022 :type pkey: :py:class:`PKey` or :py:const:`None`
2023
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002024 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002025 """
2026 if not isinstance(pkey, PKey):
2027 raise TypeError("pkey must be a PKey instance")
2028 self._pkey = pkey
2029
2030
2031 def get_ca_certificates(self):
2032 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002033 Get the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002034
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002035 :return: A tuple with the CA certificates in the chain, or
2036 :py:const:`None` if there are none.
2037 :rtype: :py:class:`tuple` of :py:class:`X509` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002038 """
2039 if self._cacerts is not None:
2040 return tuple(self._cacerts)
2041
2042
2043 def set_ca_certificates(self, cacerts):
2044 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002045 Set the CA certificates in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002046
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002047 :param cacerts: The new CA certificates, or :py:const:`None` to unset
2048 them.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002049 :type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002050
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002051 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002052 """
2053 if cacerts is None:
2054 self._cacerts = None
2055 else:
2056 cacerts = list(cacerts)
2057 for cert in cacerts:
2058 if not isinstance(cert, X509):
2059 raise TypeError("iterable must only contain X509 instances")
2060 self._cacerts = cacerts
2061
2062
2063 def set_friendlyname(self, name):
2064 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002065 Set the friendly name in the PKCS #12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002066
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002067 :param name: The new friendly name, or :py:const:`None` to unset.
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002068 :type name: :py:class:`bytes` or :py:const:`None`
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002069
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002070 :return: :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002071 """
2072 if name is None:
2073 self._friendlyname = None
2074 elif not isinstance(name, bytes):
2075 raise TypeError("name must be a byte string or None (not %r)" % (name,))
2076 self._friendlyname = name
2077
2078
2079 def get_friendlyname(self):
2080 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002081 Get the friendly name in the PKCS# 12 structure.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002082
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002083 :returns: The friendly name, or :py:const:`None` if there is none.
2084 :rtype: :py:class:`bytes` or :py:const:`None`
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002085 """
2086 return self._friendlyname
2087
2088
2089 def export(self, passphrase=None, iter=2048, maciter=1):
2090 """
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002091 Dump a PKCS12 object as a string.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002092
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002093 For more information, see the :c:func:`PKCS12_create` man page.
2094
2095 :param passphrase: The passphrase used to encrypt the structure. Unlike
2096 some other passphrase arguments, this *must* be a string, not a
2097 callback.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002098 :type passphrase: :py:data:`bytes`
2099
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002100 :param iter: Number of times to repeat the encryption step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002101 :type iter: :py:data:`int`
2102
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002103 :param maciter: Number of times to repeat the MAC step.
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002104 :type maciter: :py:data:`int`
2105
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002106 :return: The string representation of the PKCS #12 structure.
2107 :rtype:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002108 """
2109 if self._cacerts is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002110 cacerts = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002111 else:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002112 cacerts = _lib.sk_X509_new_null()
2113 cacerts = _ffi.gc(cacerts, _lib.sk_X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002114 for cert in self._cacerts:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002115 _lib.sk_X509_push(cacerts, cert._x509)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002116
2117 if passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002118 passphrase = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002119
2120 friendlyname = self._friendlyname
2121 if friendlyname is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002122 friendlyname = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002123
2124 if self._pkey is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002125 pkey = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002126 else:
2127 pkey = self._pkey._pkey
2128
2129 if self._cert is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002130 cert = _ffi.NULL
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002131 else:
2132 cert = self._cert._x509
2133
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002134 pkcs12 = _lib.PKCS12_create(
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002135 passphrase, friendlyname, pkey, cert, cacerts,
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002136 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
2137 _lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002138 iter, maciter, 0)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002139 if pkcs12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002140 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002141 pkcs12 = _ffi.gc(pkcs12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002142
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002143 bio = _new_mem_buf()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002144 _lib.i2d_PKCS12_bio(bio, pkcs12)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002145 return _bio_to_string(bio)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002146
Laurens Van Houtvenbb503a32014-06-19 12:28:08 +02002147
2148
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002149PKCS12Type = PKCS12
2150
2151
2152
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002153class NetscapeSPKI(object):
2154 def __init__(self):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002155 spki = _lib.NETSCAPE_SPKI_new()
2156 self._spki = _ffi.gc(spki, _lib.NETSCAPE_SPKI_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002157
2158
2159 def sign(self, pkey, digest):
2160 """
2161 Sign the certificate request using the supplied key and digest
2162
2163 :param pkey: The key to sign with
2164 :param digest: The message digest to use
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002165 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002166 """
2167 if pkey._only_public:
2168 raise ValueError("Key has only public part")
2169
2170 if not pkey._initialized:
2171 raise ValueError("Key is uninitialized")
2172
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002173 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002174 if digest_obj == _ffi.NULL:
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002175 raise ValueError("No such digest method")
2176
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002177 sign_result = _lib.NETSCAPE_SPKI_sign(self._spki, pkey._pkey, digest_obj)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002178 if not sign_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002179 # TODO: This is untested.
2180 _raise_current_error()
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002181
2182
2183 def verify(self, key):
2184 """
2185 Verifies a certificate request using the supplied public key
2186
2187 :param key: a public key
2188 :return: True if the signature is correct.
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002189 :raises Error: If the signature is invalid, or there was a problem
2190 verifying the signature.
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002191 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002192 answer = _lib.NETSCAPE_SPKI_verify(self._spki, key._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002193 if answer <= 0:
2194 _raise_current_error()
2195 return True
2196
2197
2198 def b64_encode(self):
2199 """
2200 Generate a base64 encoded string from an SPKI
2201
2202 :return: The base64 encoded string
2203 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002204 encoded = _lib.NETSCAPE_SPKI_b64_encode(self._spki)
2205 result = _ffi.string(encoded)
2206 _lib.CRYPTO_free(encoded)
Jean-Paul Calderone2c2e21d2013-03-02 16:50:35 -08002207 return result
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002208
2209
2210 def get_pubkey(self):
2211 """
2212 Get the public key of the certificate
2213
2214 :return: The public key
2215 """
2216 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002217 pkey._pkey = _lib.NETSCAPE_SPKI_get_pubkey(self._spki)
2218 if pkey._pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002219 # TODO: This is untested.
2220 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002221 pkey._pkey = _ffi.gc(pkey._pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002222 pkey._only_public = True
2223 return pkey
2224
2225
2226 def set_pubkey(self, pkey):
2227 """
2228 Set the public key of the certificate
2229
2230 :param pkey: The public key
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002231 :return: :py:const:`None`
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002232 """
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002233 set_result = _lib.NETSCAPE_SPKI_set_pubkey(self._spki, pkey._pkey)
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002234 if not set_result:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002235 # TODO: This is untested.
2236 _raise_current_error()
Jean-Paul Calderone3b89f472013-02-21 09:32:25 -08002237NetscapeSPKIType = NetscapeSPKI
2238
2239
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002240class _PassphraseHelper(object):
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002241 def __init__(self, type, passphrase, more_args=False, truncate=False):
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002242 if type != FILETYPE_PEM and passphrase is not None:
2243 raise ValueError("only FILETYPE_PEM key format supports encryption")
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002244 self._passphrase = passphrase
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002245 self._more_args = more_args
2246 self._truncate = truncate
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002247 self._problems = []
2248
2249
2250 @property
2251 def callback(self):
2252 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002253 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002254 elif isinstance(self._passphrase, bytes):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002255 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002256 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002257 return _ffi.callback("pem_password_cb", self._read_passphrase)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002258 else:
2259 raise TypeError("Last argument must be string or callable")
2260
2261
2262 @property
2263 def callback_args(self):
2264 if self._passphrase is None:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002265 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002266 elif isinstance(self._passphrase, bytes):
2267 return self._passphrase
2268 elif callable(self._passphrase):
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002269 return _ffi.NULL
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002270 else:
2271 raise TypeError("Last argument must be string or callable")
2272
2273
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002274 def raise_if_problem(self, exceptionType=Error):
2275 try:
Jean-Paul Calderonec86bb7d2013-12-29 10:25:59 -05002276 _exception_from_error_queue(exceptionType)
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002277 except exceptionType as e:
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002278 from_queue = e
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002279 if self._problems:
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002280 raise self._problems[0]
Jean-Paul Calderone9b4115f2014-01-10 14:06:04 -05002281 return from_queue
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002282
2283
2284 def _read_passphrase(self, buf, size, rwflag, userdata):
2285 try:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002286 if self._more_args:
2287 result = self._passphrase(size, rwflag, userdata)
2288 else:
2289 result = self._passphrase(rwflag)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002290 if not isinstance(result, bytes):
2291 raise ValueError("String expected")
2292 if len(result) > size:
Jean-Paul Calderone8a1bea52013-03-05 07:57:57 -08002293 if self._truncate:
2294 result = result[:size]
2295 else:
2296 raise ValueError("passphrase returned by callback is too long")
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002297 for i in range(len(result)):
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002298 buf[i] = result[i:i + 1]
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002299 return len(result)
2300 except Exception as e:
2301 self._problems.append(e)
2302 return 0
2303
2304
2305
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002306def load_privatekey(type, buffer, passphrase=None):
2307 """
2308 Load a private key from a buffer
2309
2310 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2311 :param buffer: The buffer the key is stored in
2312 :param passphrase: (optional) if encrypted PEM format, this can be
2313 either the passphrase to use, or a callback for
2314 providing the passphrase.
2315
2316 :return: The PKey object
2317 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002318 if isinstance(buffer, _text_type):
2319 buffer = buffer.encode("ascii")
2320
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002321 bio = _new_mem_buf(buffer)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002322
Jean-Paul Calderone23478b32013-02-20 13:31:38 -08002323 helper = _PassphraseHelper(type, passphrase)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002324 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002325 evp_pkey = _lib.PEM_read_bio_PrivateKey(
2326 bio, _ffi.NULL, helper.callback, helper.callback_args)
Jean-Paul Calderonee41f05c2013-02-20 13:28:16 -08002327 helper.raise_if_problem()
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002328 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002329 evp_pkey = _lib.d2i_PrivateKey_bio(bio, _ffi.NULL)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002330 else:
2331 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2332
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002333 if evp_pkey == _ffi.NULL:
Jean-Paul Calderone31393aa2013-02-20 13:22:21 -08002334 _raise_current_error()
2335
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002336 pkey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002337 pkey._pkey = _ffi.gc(evp_pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002338 return pkey
2339
2340
2341
2342def dump_certificate_request(type, req):
2343 """
2344 Dump a certificate request to a buffer
2345
2346 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2347 :param req: The certificate request to dump
2348 :return: The buffer with the dumped certificate request in
2349 """
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002350 bio = _new_mem_buf()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002351
2352 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002353 result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002354 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002355 result_code = _lib.i2d_X509_REQ_bio(bio, req._req)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002356 elif type == FILETYPE_TEXT:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002357 result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002358 else:
Jean-Paul Calderonec9a395f2013-02-20 16:59:21 -08002359 raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002360
2361 if result_code == 0:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002362 # TODO: This is untested.
2363 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002364
2365 return _bio_to_string(bio)
Jean-Paul Calderoneabfbab62013-02-09 21:25:02 -08002366
2367
2368
2369def load_certificate_request(type, buffer):
2370 """
2371 Load a certificate request from a buffer
2372
2373 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2374 :param buffer: The buffer the certificate request is stored in
2375 :return: The X509Req object
2376 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002377 if isinstance(buffer, _text_type):
2378 buffer = buffer.encode("ascii")
2379
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002380 bio = _new_mem_buf(buffer)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002381
2382 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002383 req = _lib.PEM_read_bio_X509_REQ(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002384 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002385 req = _lib.d2i_X509_REQ_bio(bio, _ffi.NULL)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002386 else:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002387 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002388
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002389 if req == _ffi.NULL:
Jean-Paul Calderone4a68b402013-12-29 16:54:58 -05002390 # TODO: This is untested.
2391 _raise_current_error()
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002392
2393 x509req = X509Req.__new__(X509Req)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002394 x509req._req = _ffi.gc(req, _lib.X509_REQ_free)
Jean-Paul Calderone066f0572013-02-20 13:43:44 -08002395 return x509req
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002396
2397
2398
2399def sign(pkey, data, digest):
2400 """
2401 Sign data with a digest
2402
2403 :param pkey: Pkey to sign with
2404 :param data: data to be signed
2405 :param digest: message digest to use
2406 :return: signature
2407 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002408 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002409 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002410 raise ValueError("No such digest method")
2411
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002412 md_ctx = _ffi.new("EVP_MD_CTX*")
2413 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002414
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002415 _lib.EVP_SignInit(md_ctx, digest_obj)
2416 _lib.EVP_SignUpdate(md_ctx, data, len(data))
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002417
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002418 signature_buffer = _ffi.new("unsigned char[]", 512)
2419 signature_length = _ffi.new("unsigned int*")
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002420 signature_length[0] = len(signature_buffer)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002421 final_result = _lib.EVP_SignFinal(
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002422 md_ctx, signature_buffer, signature_length, pkey._pkey)
2423
2424 if final_result != 1:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002425 # TODO: This is untested.
2426 _raise_current_error()
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002427
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002428 return _ffi.buffer(signature_buffer, signature_length[0])[:]
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002429
2430
2431
2432def verify(cert, signature, data, digest):
2433 """
Laurens Van Houtvenc3baa7b2014-06-18 22:06:56 +02002434 Verify a signature.
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002435
2436 :param cert: signing certificate (X509 object)
2437 :param signature: signature returned by sign function
2438 :param data: data to be verified
2439 :param digest: message digest to use
Laurens Van Houtvena7904582014-06-19 12:33:04 +02002440 :return: :py:const:`None` if the signature is correct, raise exception otherwise
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002441 """
Jean-Paul Calderone4f0467a2014-01-11 11:58:41 -05002442 digest_obj = _lib.EVP_get_digestbyname(_byte_string(digest))
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002443 if digest_obj == _ffi.NULL:
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002444 raise ValueError("No such digest method")
2445
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002446 pkey = _lib.X509_get_pubkey(cert._x509)
2447 if pkey == _ffi.NULL:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002448 # TODO: This is untested.
2449 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002450 pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002451
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002452 md_ctx = _ffi.new("EVP_MD_CTX*")
2453 md_ctx = _ffi.gc(md_ctx, _lib.EVP_MD_CTX_cleanup)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002454
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002455 _lib.EVP_VerifyInit(md_ctx, digest_obj)
2456 _lib.EVP_VerifyUpdate(md_ctx, data, len(data))
2457 verify_result = _lib.EVP_VerifyFinal(md_ctx, signature, len(signature), pkey)
Jean-Paul Calderone8cf4f802013-02-20 16:45:02 -08002458
2459 if verify_result != 1:
2460 _raise_current_error()
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002461
2462
2463
2464def load_crl(type, buffer):
2465 """
2466 Load a certificate revocation list from a buffer
2467
2468 :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1)
2469 :param buffer: The buffer the CRL is stored in
2470
2471 :return: The PKey object
2472 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002473 if isinstance(buffer, _text_type):
2474 buffer = buffer.encode("ascii")
2475
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002476 bio = _new_mem_buf(buffer)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002477
2478 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002479 crl = _lib.PEM_read_bio_X509_CRL(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002480 elif type == FILETYPE_ASN1:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002481 crl = _lib.d2i_X509_CRL_bio(bio, _ffi.NULL)
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002482 else:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002483 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2484
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002485 if crl == _ffi.NULL:
Jean-Paul Calderone57122982013-02-21 08:47:05 -08002486 _raise_current_error()
2487
2488 result = CRL.__new__(CRL)
2489 result._crl = crl
2490 return result
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002491
2492
2493
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002494def load_pkcs7_data(type, buffer):
2495 """
2496 Load pkcs7 data from a buffer
2497
2498 :param type: The file type (one of FILETYPE_PEM or FILETYPE_ASN1)
2499 :param buffer: The buffer with the pkcs7 data.
2500 :return: The PKCS7 object
2501 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002502 if isinstance(buffer, _text_type):
2503 buffer = buffer.encode("ascii")
2504
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002505 bio = _new_mem_buf(buffer)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002506
2507 if type == FILETYPE_PEM:
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002508 pkcs7 = _lib.PEM_read_bio_PKCS7(bio, _ffi.NULL, _ffi.NULL, _ffi.NULL)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002509 elif type == FILETYPE_ASN1:
2510 pass
2511 else:
Jean-Paul Calderonedba578b2013-12-29 17:00:04 -05002512 # TODO: This is untested.
2513 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002514 raise ValueError("type argument must be FILETYPE_PEM or FILETYPE_ASN1")
2515
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002516 if pkcs7 == _ffi.NULL:
Jean-Paul Calderoneb0f64712013-03-03 10:15:39 -08002517 _raise_current_error()
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002518
2519 pypkcs7 = PKCS7.__new__(PKCS7)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002520 pypkcs7._pkcs7 = _ffi.gc(pkcs7, _lib.PKCS7_free)
Jean-Paul Calderone4e8be1c2013-02-21 18:31:12 -08002521 return pypkcs7
2522
2523
2524
Stephen Holsapple38482622014-04-05 20:29:34 -07002525def load_pkcs12(buffer, passphrase=None):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002526 """
2527 Load a PKCS12 object from a buffer
2528
2529 :param buffer: The buffer the certificate is stored in
2530 :param passphrase: (Optional) The password to decrypt the PKCS12 lump
2531 :returns: The PKCS12 object
2532 """
Jean-Paul Calderone6922a862014-01-18 10:38:28 -05002533 if isinstance(buffer, _text_type):
2534 buffer = buffer.encode("ascii")
2535
Jean-Paul Calderonef6745b32013-03-01 15:08:46 -08002536 bio = _new_mem_buf(buffer)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002537
Stephen Holsapple38482622014-04-05 20:29:34 -07002538 # Use null passphrase if passphrase is None or empty string. With PKCS#12
2539 # password based encryption no password and a zero length password are two
2540 # different things, but OpenSSL implementation will try both to figure out
2541 # which one works.
2542 if not passphrase:
2543 passphrase = _ffi.NULL
2544
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002545 p12 = _lib.d2i_PKCS12_bio(bio, _ffi.NULL)
2546 if p12 == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002547 _raise_current_error()
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002548 p12 = _ffi.gc(p12, _lib.PKCS12_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002549
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002550 pkey = _ffi.new("EVP_PKEY**")
2551 cert = _ffi.new("X509**")
2552 cacerts = _ffi.new("Cryptography_STACK_OF_X509**")
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002553
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002554 parse_result = _lib.PKCS12_parse(p12, passphrase, pkey, cert, cacerts)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002555 if not parse_result:
2556 _raise_current_error()
2557
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002558 cacerts = _ffi.gc(cacerts[0], _lib.sk_X509_free)
Jean-Paul Calderoneef9a3dc2013-03-02 16:33:32 -08002559
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002560 # openssl 1.0.0 sometimes leaves an X509_check_private_key error in the
2561 # queue for no particular reason. This error isn't interesting to anyone
2562 # outside this function. It's not even interesting to us. Get rid of it.
2563 try:
2564 _raise_current_error()
2565 except Error:
2566 pass
2567
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002568 if pkey[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002569 pykey = None
2570 else:
2571 pykey = PKey.__new__(PKey)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002572 pykey._pkey = _ffi.gc(pkey[0], _lib.EVP_PKEY_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002573
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002574 if cert[0] == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002575 pycert = None
2576 friendlyname = None
2577 else:
2578 pycert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002579 pycert._x509 = _ffi.gc(cert[0], _lib.X509_free)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002580
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002581 friendlyname_length = _ffi.new("int*")
2582 friendlyname_buffer = _lib.X509_alias_get0(cert[0], friendlyname_length)
2583 friendlyname = _ffi.buffer(friendlyname_buffer, friendlyname_length[0])[:]
2584 if friendlyname_buffer == _ffi.NULL:
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002585 friendlyname = None
2586
2587 pycacerts = []
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002588 for i in range(_lib.sk_X509_num(cacerts)):
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002589 pycacert = X509.__new__(X509)
Jean-Paul Calderone6037d072013-12-28 18:04:00 -05002590 pycacert._x509 = _lib.sk_X509_value(cacerts, i)
Jean-Paul Calderonee5912ce2013-02-21 10:49:35 -08002591 pycacerts.append(pycacert)
2592 if not pycacerts:
2593 pycacerts = None
2594
2595 pkcs12 = PKCS12.__new__(PKCS12)
2596 pkcs12._pkey = pykey
2597 pkcs12._cert = pycert
2598 pkcs12._cacerts = pycacerts
2599 pkcs12._friendlyname = friendlyname
2600 return pkcs12
Jean-Paul Calderone6bb40892014-01-01 12:21:34 -05002601
2602
2603def _initialize_openssl_threads(get_ident, Lock):
2604 import _ssl
2605 return
2606
2607 locks = list(Lock() for n in range(_lib.CRYPTO_num_locks()))
2608
2609 def locking_function(mode, index, filename, line):
2610 if mode & _lib.CRYPTO_LOCK:
2611 locks[index].acquire()
2612 else:
2613 locks[index].release()
2614
2615 _lib.CRYPTO_set_id_callback(
2616 _ffi.callback("unsigned long (*)(void)", get_ident))
2617
2618 _lib.CRYPTO_set_locking_callback(
2619 _ffi.callback(
2620 "void (*)(int, int, const char*, int)", locking_function))
2621
2622
2623try:
2624 from thread import get_ident
2625 from threading import Lock
2626except ImportError:
2627 pass
2628else:
2629 _initialize_openssl_threads(get_ident, Lock)
2630 del get_ident, Lock
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002631
Jean-Paul Calderoneb64e2a22014-01-11 08:06:35 -05002632# There are no direct unit tests for this initialization. It is tested
2633# indirectly since it is necessary for functions like dump_privatekey when
2634# using encryption.
2635#
2636# Thus OpenSSL.test.test_crypto.FunctionTests.test_dump_privatekey_passphrase
2637# and some other similar tests may fail without this (though they may not if
2638# the Python runtime has already done some initialization of the underlying
2639# OpenSSL library (and is linked against the same one that cryptography is
2640# using)).
Jean-Paul Calderonee324fd62014-01-11 08:00:33 -05002641_lib.OpenSSL_add_all_algorithms()
Jean-Paul Calderone11ed8e82014-01-18 10:21:50 -05002642
Jean-Paul Calderonefab157b2014-01-18 11:21:38 -05002643# This is similar but exercised mainly by exception_from_error_queue. It calls
2644# both ERR_load_crypto_strings() and ERR_load_SSL_strings().
2645_lib.SSL_load_error_strings()