blob: 01378b38acddc689aa7352d839d638dc5e903516 [file] [log] [blame]
Paul Kehrer890cb7f2015-08-10 21:05:34 -05001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
4
5from __future__ import absolute_import, division, print_function
6
Paul Kehreraa7a3222015-08-11 00:00:54 -05007import abc
Paul Kehrer23c0bbc2015-12-25 22:35:19 -06008import datetime
Paul Kehrer890cb7f2015-08-10 21:05:34 -05009import hashlib
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050010import ipaddress
Paul Kehrer9f8069a2015-08-10 21:10:34 -050011from enum import Enum
Paul Kehrer890cb7f2015-08-10 21:05:34 -050012
Ofek Lev0e6a1292017-02-08 00:09:41 -050013from asn1crypto.keys import PublicKeyInfo
Paul Kehrer890cb7f2015-08-10 21:05:34 -050014
15import six
16
17from cryptography import utils
Predrag Gruevski38995392015-09-21 21:53:49 -040018from cryptography.hazmat.primitives import constant_time, serialization
Alex Gaynor01c70492016-03-27 17:00:59 -040019from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey
Alex Gaynorbeb25512016-03-27 16:39:49 -040020from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
Alex Gaynor6a0718f2017-06-04 13:36:58 -040021from cryptography.x509.certificate_transparency import (
22 SignedCertificateTimestamp
23)
Paul Kehreraa7a3222015-08-11 00:00:54 -050024from cryptography.x509.general_name import GeneralName, IPAddress, OtherName
Alex Gaynora783c572017-03-21 09:24:12 -040025from cryptography.x509.name import RelativeDistinguishedName
Paul Kehrer49bb7562015-12-25 16:17:40 -060026from cryptography.x509.oid import (
27 CRLEntryExtensionOID, ExtensionOID, ObjectIdentifier
28)
Paul Kehrer890cb7f2015-08-10 21:05:34 -050029
30
Paul Kehrer890cb7f2015-08-10 21:05:34 -050031def _key_identifier_from_public_key(public_key):
Alex Gaynorbeb25512016-03-27 16:39:49 -040032 if isinstance(public_key, RSAPublicKey):
33 data = public_key.public_bytes(
34 serialization.Encoding.DER,
35 serialization.PublicFormat.PKCS1,
36 )
Alex Gaynor01c70492016-03-27 17:00:59 -040037 elif isinstance(public_key, EllipticCurvePublicKey):
38 data = public_key.public_numbers().encode_point()
Alex Gaynorbeb25512016-03-27 16:39:49 -040039 else:
40 # This is a very slow way to do this.
41 serialized = public_key.public_bytes(
42 serialization.Encoding.DER,
43 serialization.PublicFormat.SubjectPublicKeyInfo
44 )
Paul Kehrer890cb7f2015-08-10 21:05:34 -050045
Ofek Lev0e6a1292017-02-08 00:09:41 -050046 data = six.binary_type(PublicKeyInfo.load(serialized)['public_key'])
Alex Gaynorbeb25512016-03-27 16:39:49 -040047
Paul Kehrer890cb7f2015-08-10 21:05:34 -050048 return hashlib.sha1(data).digest()
49
50
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050051class DuplicateExtension(Exception):
52 def __init__(self, msg, oid):
53 super(DuplicateExtension, self).__init__(msg)
54 self.oid = oid
55
56
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050057class ExtensionNotFound(Exception):
58 def __init__(self, msg, oid):
59 super(ExtensionNotFound, self).__init__(msg)
60 self.oid = oid
61
62
Paul Kehreraa7a3222015-08-11 00:00:54 -050063@six.add_metaclass(abc.ABCMeta)
64class ExtensionType(object):
65 @abc.abstractproperty
66 def oid(self):
67 """
68 Returns the oid associated with the given extension type.
69 """
70
71
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050072class Extensions(object):
73 def __init__(self, extensions):
74 self._extensions = extensions
75
76 def get_extension_for_oid(self, oid):
77 for ext in self:
78 if ext.oid == oid:
79 return ext
80
81 raise ExtensionNotFound("No {0} extension was found".format(oid), oid)
82
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010083 def get_extension_for_class(self, extclass):
Paul Kehrere69c5fe2015-12-30 21:03:26 -060084 if extclass is UnrecognizedExtension:
85 raise TypeError(
86 "UnrecognizedExtension can't be used with "
87 "get_extension_for_class because more than one instance of the"
88 " class may be present."
89 )
90
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010091 for ext in self:
Phoebe Queen754be602015-08-12 03:11:35 +010092 if isinstance(ext.value, extclass):
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010093 return ext
94
Phoebe Queen2cc111a2015-08-12 04:14:22 +010095 raise ExtensionNotFound(
Phoebe Queenecae9812015-08-12 05:00:32 +010096 "No {0} extension was found".format(extclass), extclass.oid
Phoebe Queen2cc111a2015-08-12 04:14:22 +010097 )
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010098
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050099 def __iter__(self):
100 return iter(self._extensions)
101
102 def __len__(self):
103 return len(self._extensions)
104
Paul Kehrer5b90c972015-12-26 00:52:58 -0600105 def __getitem__(self, idx):
106 return self._extensions[idx]
107
Paul Kehrerafbe75b2015-10-20 08:08:43 -0500108 def __repr__(self):
109 return (
110 "<Extensions({0})>".format(self._extensions)
111 )
112
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500113
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500114@utils.register_interface(ExtensionType)
Paul Kehrer3b95cd72015-12-22 21:40:20 -0600115class CRLNumber(object):
116 oid = ExtensionOID.CRL_NUMBER
117
118 def __init__(self, crl_number):
119 if not isinstance(crl_number, six.integer_types):
120 raise TypeError("crl_number must be an integer")
121
122 self._crl_number = crl_number
123
124 def __eq__(self, other):
125 if not isinstance(other, CRLNumber):
126 return NotImplemented
127
128 return self.crl_number == other.crl_number
129
130 def __ne__(self, other):
131 return not self == other
132
Alex Gaynorf9a77b62015-12-26 12:14:25 -0500133 def __hash__(self):
134 return hash(self.crl_number)
135
Paul Kehrer3b95cd72015-12-22 21:40:20 -0600136 def __repr__(self):
137 return "<CRLNumber({0})>".format(self.crl_number)
138
139 crl_number = utils.read_only_property("_crl_number")
140
141
142@utils.register_interface(ExtensionType)
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500143class AuthorityKeyIdentifier(object):
144 oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER
145
146 def __init__(self, key_identifier, authority_cert_issuer,
147 authority_cert_serial_number):
Paul Kehrer0d943bb2016-01-05 19:02:32 -0600148 if (authority_cert_issuer is None) != (
149 authority_cert_serial_number is None
150 ):
151 raise ValueError(
152 "authority_cert_issuer and authority_cert_serial_number "
153 "must both be present or both None"
154 )
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500155
Marti40f19992016-08-26 04:26:31 +0300156 if authority_cert_issuer is not None:
157 authority_cert_issuer = list(authority_cert_issuer)
158 if not all(
159 isinstance(x, GeneralName) for x in authority_cert_issuer
160 ):
161 raise TypeError(
162 "authority_cert_issuer must be a list of GeneralName "
163 "objects"
164 )
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500165
Paul Kehrer0d943bb2016-01-05 19:02:32 -0600166 if authority_cert_serial_number is not None and not isinstance(
167 authority_cert_serial_number, six.integer_types
168 ):
169 raise TypeError(
170 "authority_cert_serial_number must be an integer"
171 )
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500172
173 self._key_identifier = key_identifier
174 self._authority_cert_issuer = authority_cert_issuer
175 self._authority_cert_serial_number = authority_cert_serial_number
176
177 @classmethod
178 def from_issuer_public_key(cls, public_key):
179 digest = _key_identifier_from_public_key(public_key)
180 return cls(
181 key_identifier=digest,
182 authority_cert_issuer=None,
183 authority_cert_serial_number=None
184 )
185
Paul Kehrer61ff3562016-03-11 22:51:27 -0400186 @classmethod
187 def from_issuer_subject_key_identifier(cls, ski):
188 return cls(
189 key_identifier=ski.value.digest,
190 authority_cert_issuer=None,
191 authority_cert_serial_number=None
192 )
193
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500194 def __repr__(self):
195 return (
196 "<AuthorityKeyIdentifier(key_identifier={0.key_identifier!r}, "
197 "authority_cert_issuer={0.authority_cert_issuer}, "
198 "authority_cert_serial_number={0.authority_cert_serial_number}"
199 ")>".format(self)
200 )
201
202 def __eq__(self, other):
203 if not isinstance(other, AuthorityKeyIdentifier):
204 return NotImplemented
205
206 return (
207 self.key_identifier == other.key_identifier and
208 self.authority_cert_issuer == other.authority_cert_issuer and
209 self.authority_cert_serial_number ==
210 other.authority_cert_serial_number
211 )
212
213 def __ne__(self, other):
214 return not self == other
215
216 key_identifier = utils.read_only_property("_key_identifier")
217 authority_cert_issuer = utils.read_only_property("_authority_cert_issuer")
218 authority_cert_serial_number = utils.read_only_property(
219 "_authority_cert_serial_number"
220 )
221
222
223@utils.register_interface(ExtensionType)
224class SubjectKeyIdentifier(object):
225 oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER
226
227 def __init__(self, digest):
228 self._digest = digest
229
230 @classmethod
231 def from_public_key(cls, public_key):
232 return cls(_key_identifier_from_public_key(public_key))
233
234 digest = utils.read_only_property("_digest")
235
236 def __repr__(self):
237 return "<SubjectKeyIdentifier(digest={0!r})>".format(self.digest)
238
239 def __eq__(self, other):
240 if not isinstance(other, SubjectKeyIdentifier):
241 return NotImplemented
242
Predrag Gruevski57f3b3f2015-09-21 18:51:47 -0400243 return constant_time.bytes_eq(self.digest, other.digest)
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500244
245 def __ne__(self, other):
246 return not self == other
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500247
Alex Gaynor410fe352015-12-26 15:01:25 -0500248 def __hash__(self):
249 return hash(self.digest)
250
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500251
252@utils.register_interface(ExtensionType)
253class AuthorityInformationAccess(object):
254 oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS
255
256 def __init__(self, descriptions):
Marti40f19992016-08-26 04:26:31 +0300257 descriptions = list(descriptions)
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500258 if not all(isinstance(x, AccessDescription) for x in descriptions):
259 raise TypeError(
260 "Every item in the descriptions list must be an "
261 "AccessDescription"
262 )
263
264 self._descriptions = descriptions
265
266 def __iter__(self):
267 return iter(self._descriptions)
268
269 def __len__(self):
270 return len(self._descriptions)
271
272 def __repr__(self):
273 return "<AuthorityInformationAccess({0})>".format(self._descriptions)
274
275 def __eq__(self, other):
276 if not isinstance(other, AuthorityInformationAccess):
277 return NotImplemented
278
279 return self._descriptions == other._descriptions
280
281 def __ne__(self, other):
282 return not self == other
283
Paul Kehrerad4b3592015-12-27 17:27:40 -0600284 def __getitem__(self, idx):
285 return self._descriptions[idx]
286
Paul Kehrer54024492017-09-14 01:55:31 +0800287 def __hash__(self):
288 return hash(tuple(self._descriptions))
289
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500290
291class AccessDescription(object):
292 def __init__(self, access_method, access_location):
Nick Bastind06763d2015-12-12 18:32:59 -0800293 if not isinstance(access_method, ObjectIdentifier):
Nick Bastinbd079ae2015-12-13 05:15:44 -0800294 raise TypeError("access_method must be an ObjectIdentifier")
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500295
296 if not isinstance(access_location, GeneralName):
297 raise TypeError("access_location must be a GeneralName")
298
299 self._access_method = access_method
300 self._access_location = access_location
301
302 def __repr__(self):
303 return (
304 "<AccessDescription(access_method={0.access_method}, access_locati"
305 "on={0.access_location})>".format(self)
306 )
307
308 def __eq__(self, other):
309 if not isinstance(other, AccessDescription):
310 return NotImplemented
311
312 return (
313 self.access_method == other.access_method and
314 self.access_location == other.access_location
315 )
316
317 def __ne__(self, other):
318 return not self == other
319
Eeshan Gargd8e0d852016-01-31 16:46:22 -0330320 def __hash__(self):
321 return hash((self.access_method, self.access_location))
322
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500323 access_method = utils.read_only_property("_access_method")
324 access_location = utils.read_only_property("_access_location")
325
326
327@utils.register_interface(ExtensionType)
328class BasicConstraints(object):
329 oid = ExtensionOID.BASIC_CONSTRAINTS
330
331 def __init__(self, ca, path_length):
332 if not isinstance(ca, bool):
333 raise TypeError("ca must be a boolean value")
334
335 if path_length is not None and not ca:
336 raise ValueError("path_length must be None when ca is False")
337
338 if (
339 path_length is not None and
340 (not isinstance(path_length, six.integer_types) or path_length < 0)
341 ):
342 raise TypeError(
343 "path_length must be a non-negative integer or None"
344 )
345
346 self._ca = ca
347 self._path_length = path_length
348
349 ca = utils.read_only_property("_ca")
350 path_length = utils.read_only_property("_path_length")
351
352 def __repr__(self):
353 return ("<BasicConstraints(ca={0.ca}, "
354 "path_length={0.path_length})>").format(self)
355
356 def __eq__(self, other):
357 if not isinstance(other, BasicConstraints):
358 return NotImplemented
359
360 return self.ca == other.ca and self.path_length == other.path_length
361
362 def __ne__(self, other):
363 return not self == other
364
Paul Kehrer2eb69f62015-12-27 11:46:11 -0600365 def __hash__(self):
366 return hash((self.ca, self.path_length))
367
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500368
369@utils.register_interface(ExtensionType)
370class CRLDistributionPoints(object):
371 oid = ExtensionOID.CRL_DISTRIBUTION_POINTS
372
373 def __init__(self, distribution_points):
Marti40f19992016-08-26 04:26:31 +0300374 distribution_points = list(distribution_points)
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500375 if not all(
376 isinstance(x, DistributionPoint) for x in distribution_points
377 ):
378 raise TypeError(
379 "distribution_points must be a list of DistributionPoint "
380 "objects"
381 )
382
383 self._distribution_points = distribution_points
384
385 def __iter__(self):
386 return iter(self._distribution_points)
387
388 def __len__(self):
389 return len(self._distribution_points)
390
391 def __repr__(self):
392 return "<CRLDistributionPoints({0})>".format(self._distribution_points)
393
394 def __eq__(self, other):
395 if not isinstance(other, CRLDistributionPoints):
396 return NotImplemented
397
398 return self._distribution_points == other._distribution_points
399
400 def __ne__(self, other):
401 return not self == other
402
Paul Kehreree2e92d2015-12-27 17:29:37 -0600403 def __getitem__(self, idx):
404 return self._distribution_points[idx]
405
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500406
407class DistributionPoint(object):
408 def __init__(self, full_name, relative_name, reasons, crl_issuer):
409 if full_name and relative_name:
410 raise ValueError(
411 "You cannot provide both full_name and relative_name, at "
412 "least one must be None."
413 )
414
Marti40f19992016-08-26 04:26:31 +0300415 if full_name:
416 full_name = list(full_name)
417 if not all(isinstance(x, GeneralName) for x in full_name):
418 raise TypeError(
419 "full_name must be a list of GeneralName objects"
420 )
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500421
Fraser Tweedale02467dd2016-11-07 15:54:04 +1000422 if relative_name:
Alex Gaynora783c572017-03-21 09:24:12 -0400423 if not isinstance(relative_name, RelativeDistinguishedName):
Fraser Tweedale02467dd2016-11-07 15:54:04 +1000424 raise TypeError(
425 "relative_name must be a RelativeDistinguishedName"
426 )
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500427
Marti40f19992016-08-26 04:26:31 +0300428 if crl_issuer:
429 crl_issuer = list(crl_issuer)
430 if not all(isinstance(x, GeneralName) for x in crl_issuer):
431 raise TypeError(
432 "crl_issuer must be None or a list of general names"
433 )
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500434
435 if reasons and (not isinstance(reasons, frozenset) or not all(
436 isinstance(x, ReasonFlags) for x in reasons
437 )):
438 raise TypeError("reasons must be None or frozenset of ReasonFlags")
439
440 if reasons and (
441 ReasonFlags.unspecified in reasons or
442 ReasonFlags.remove_from_crl in reasons
443 ):
444 raise ValueError(
445 "unspecified and remove_from_crl are not valid reasons in a "
446 "DistributionPoint"
447 )
448
449 if reasons and not crl_issuer and not (full_name or relative_name):
450 raise ValueError(
451 "You must supply crl_issuer, full_name, or relative_name when "
452 "reasons is not None"
453 )
454
455 self._full_name = full_name
456 self._relative_name = relative_name
457 self._reasons = reasons
458 self._crl_issuer = crl_issuer
459
460 def __repr__(self):
461 return (
462 "<DistributionPoint(full_name={0.full_name}, relative_name={0.rela"
463 "tive_name}, reasons={0.reasons}, crl_issuer={0.crl_is"
464 "suer})>".format(self)
465 )
466
467 def __eq__(self, other):
468 if not isinstance(other, DistributionPoint):
469 return NotImplemented
470
471 return (
472 self.full_name == other.full_name and
473 self.relative_name == other.relative_name and
474 self.reasons == other.reasons and
475 self.crl_issuer == other.crl_issuer
476 )
477
478 def __ne__(self, other):
479 return not self == other
480
481 full_name = utils.read_only_property("_full_name")
482 relative_name = utils.read_only_property("_relative_name")
483 reasons = utils.read_only_property("_reasons")
484 crl_issuer = utils.read_only_property("_crl_issuer")
485
486
487class ReasonFlags(Enum):
488 unspecified = "unspecified"
489 key_compromise = "keyCompromise"
490 ca_compromise = "cACompromise"
491 affiliation_changed = "affiliationChanged"
492 superseded = "superseded"
493 cessation_of_operation = "cessationOfOperation"
494 certificate_hold = "certificateHold"
495 privilege_withdrawn = "privilegeWithdrawn"
496 aa_compromise = "aACompromise"
497 remove_from_crl = "removeFromCRL"
Paul Kehrer012262c2015-08-10 23:42:57 -0500498
499
500@utils.register_interface(ExtensionType)
Paul Kehrer7e8fe9d2015-05-18 09:53:47 -0700501class PolicyConstraints(object):
Paul Kehrer159b3b52016-02-26 08:27:22 -0600502 oid = ExtensionOID.POLICY_CONSTRAINTS
503
Paul Kehrer7e8fe9d2015-05-18 09:53:47 -0700504 def __init__(self, require_explicit_policy, inhibit_policy_mapping):
505 if require_explicit_policy is not None and not isinstance(
506 require_explicit_policy, six.integer_types
507 ):
508 raise TypeError(
509 "require_explicit_policy must be a non-negative integer or "
510 "None"
511 )
512
513 if inhibit_policy_mapping is not None and not isinstance(
514 inhibit_policy_mapping, six.integer_types
515 ):
516 raise TypeError(
517 "inhibit_policy_mapping must be a non-negative integer or None"
518 )
519
520 if inhibit_policy_mapping is None and require_explicit_policy is None:
521 raise ValueError(
522 "At least one of require_explicit_policy and "
523 "inhibit_policy_mapping must not be None"
524 )
525
526 self._require_explicit_policy = require_explicit_policy
527 self._inhibit_policy_mapping = inhibit_policy_mapping
528
529 def __repr__(self):
530 return (
531 u"<PolicyConstraints(require_explicit_policy={0.require_explicit"
532 u"_policy}, inhibit_policy_mapping={0.inhibit_policy_"
533 u"mapping})>".format(self)
534 )
535
536 def __eq__(self, other):
537 if not isinstance(other, PolicyConstraints):
538 return NotImplemented
539
540 return (
541 self.require_explicit_policy == other.require_explicit_policy and
542 self.inhibit_policy_mapping == other.inhibit_policy_mapping
543 )
544
545 def __ne__(self, other):
546 return not self == other
547
548 require_explicit_policy = utils.read_only_property(
549 "_require_explicit_policy"
550 )
551 inhibit_policy_mapping = utils.read_only_property(
552 "_inhibit_policy_mapping"
553 )
554
555
556@utils.register_interface(ExtensionType)
Paul Kehrer012262c2015-08-10 23:42:57 -0500557class CertificatePolicies(object):
558 oid = ExtensionOID.CERTIFICATE_POLICIES
559
560 def __init__(self, policies):
Marti40f19992016-08-26 04:26:31 +0300561 policies = list(policies)
Paul Kehrer012262c2015-08-10 23:42:57 -0500562 if not all(isinstance(x, PolicyInformation) for x in policies):
563 raise TypeError(
564 "Every item in the policies list must be a "
565 "PolicyInformation"
566 )
567
568 self._policies = policies
569
570 def __iter__(self):
571 return iter(self._policies)
572
573 def __len__(self):
574 return len(self._policies)
575
576 def __repr__(self):
577 return "<CertificatePolicies({0})>".format(self._policies)
578
579 def __eq__(self, other):
580 if not isinstance(other, CertificatePolicies):
581 return NotImplemented
582
583 return self._policies == other._policies
584
585 def __ne__(self, other):
586 return not self == other
587
Paul Kehrere8db7bd2015-12-27 17:32:57 -0600588 def __getitem__(self, idx):
589 return self._policies[idx]
590
Paul Kehrer012262c2015-08-10 23:42:57 -0500591
592class PolicyInformation(object):
593 def __init__(self, policy_identifier, policy_qualifiers):
594 if not isinstance(policy_identifier, ObjectIdentifier):
595 raise TypeError("policy_identifier must be an ObjectIdentifier")
596
597 self._policy_identifier = policy_identifier
Marti40f19992016-08-26 04:26:31 +0300598
599 if policy_qualifiers:
600 policy_qualifiers = list(policy_qualifiers)
601 if not all(
602 isinstance(x, (six.text_type, UserNotice))
603 for x in policy_qualifiers
604 ):
605 raise TypeError(
606 "policy_qualifiers must be a list of strings and/or "
607 "UserNotice objects or None"
608 )
Paul Kehrer012262c2015-08-10 23:42:57 -0500609
610 self._policy_qualifiers = policy_qualifiers
611
612 def __repr__(self):
613 return (
614 "<PolicyInformation(policy_identifier={0.policy_identifier}, polic"
615 "y_qualifiers={0.policy_qualifiers})>".format(self)
616 )
617
618 def __eq__(self, other):
619 if not isinstance(other, PolicyInformation):
620 return NotImplemented
621
622 return (
623 self.policy_identifier == other.policy_identifier and
624 self.policy_qualifiers == other.policy_qualifiers
625 )
626
627 def __ne__(self, other):
628 return not self == other
629
630 policy_identifier = utils.read_only_property("_policy_identifier")
631 policy_qualifiers = utils.read_only_property("_policy_qualifiers")
632
633
634class UserNotice(object):
635 def __init__(self, notice_reference, explicit_text):
636 if notice_reference and not isinstance(
637 notice_reference, NoticeReference
638 ):
639 raise TypeError(
640 "notice_reference must be None or a NoticeReference"
641 )
642
643 self._notice_reference = notice_reference
644 self._explicit_text = explicit_text
645
646 def __repr__(self):
647 return (
648 "<UserNotice(notice_reference={0.notice_reference}, explicit_text="
649 "{0.explicit_text!r})>".format(self)
650 )
651
652 def __eq__(self, other):
653 if not isinstance(other, UserNotice):
654 return NotImplemented
655
656 return (
657 self.notice_reference == other.notice_reference and
658 self.explicit_text == other.explicit_text
659 )
660
661 def __ne__(self, other):
662 return not self == other
663
664 notice_reference = utils.read_only_property("_notice_reference")
665 explicit_text = utils.read_only_property("_explicit_text")
666
667
668class NoticeReference(object):
669 def __init__(self, organization, notice_numbers):
670 self._organization = organization
Marti40f19992016-08-26 04:26:31 +0300671 notice_numbers = list(notice_numbers)
672 if not all(isinstance(x, int) for x in notice_numbers):
Paul Kehrer012262c2015-08-10 23:42:57 -0500673 raise TypeError(
674 "notice_numbers must be a list of integers"
675 )
676
677 self._notice_numbers = notice_numbers
678
679 def __repr__(self):
680 return (
681 "<NoticeReference(organization={0.organization!r}, notice_numbers="
682 "{0.notice_numbers})>".format(self)
683 )
684
685 def __eq__(self, other):
686 if not isinstance(other, NoticeReference):
687 return NotImplemented
688
689 return (
690 self.organization == other.organization and
691 self.notice_numbers == other.notice_numbers
692 )
693
694 def __ne__(self, other):
695 return not self == other
696
697 organization = utils.read_only_property("_organization")
698 notice_numbers = utils.read_only_property("_notice_numbers")
699
700
701@utils.register_interface(ExtensionType)
702class ExtendedKeyUsage(object):
703 oid = ExtensionOID.EXTENDED_KEY_USAGE
704
705 def __init__(self, usages):
Marti40f19992016-08-26 04:26:31 +0300706 usages = list(usages)
Paul Kehrer012262c2015-08-10 23:42:57 -0500707 if not all(isinstance(x, ObjectIdentifier) for x in usages):
708 raise TypeError(
709 "Every item in the usages list must be an ObjectIdentifier"
710 )
711
712 self._usages = usages
713
714 def __iter__(self):
715 return iter(self._usages)
716
717 def __len__(self):
718 return len(self._usages)
719
720 def __repr__(self):
721 return "<ExtendedKeyUsage({0})>".format(self._usages)
722
723 def __eq__(self, other):
724 if not isinstance(other, ExtendedKeyUsage):
725 return NotImplemented
726
727 return self._usages == other._usages
728
729 def __ne__(self, other):
730 return not self == other
731
732
733@utils.register_interface(ExtensionType)
734class OCSPNoCheck(object):
735 oid = ExtensionOID.OCSP_NO_CHECK
736
737
738@utils.register_interface(ExtensionType)
Paul Kehrer5d669662017-09-11 09:16:34 +0800739class TLSFeature(object):
740 oid = ExtensionOID.TLS_FEATURE
741
742 def __init__(self, features):
743 features = list(features)
744 if (
745 not all(isinstance(x, TLSFeatureType) for x in features) or
746 len(features) == 0
747 ):
748 raise TypeError(
749 "features must be a list of elements from the TLSFeatureType "
750 "enum"
751 )
752
753 self._features = features
754
755 def __iter__(self):
756 return iter(self._features)
757
758 def __len__(self):
759 return len(self._features)
760
761 def __repr__(self):
762 return "<TLSFeature(features={0._features})>".format(self)
763
764 def __eq__(self, other):
765 if not isinstance(other, TLSFeature):
766 return NotImplemented
767
768 return self._features == other._features
769
770 def __getitem__(self, idx):
771 return self._features[idx]
772
773 def __ne__(self, other):
774 return not self == other
775
776 def __hash__(self):
777 return hash(tuple(self._features))
778
779
780class TLSFeatureType(Enum):
781 # status_request is defined in RFC 6066 and is used for what is commonly
782 # called OCSP Must-Staple when present in the TLS Feature extension in an
783 # X.509 certificate.
784 status_request = 5
785 # status_request_v2 is defined in RFC 6961 and allows multiple OCSP
786 # responses to be provided. It is not currently in use by clients or
787 # servers.
788 status_request_v2 = 17
789
790
791_TLS_FEATURE_TYPE_TO_ENUM = dict((x.value, x) for x in TLSFeatureType)
792
793
794@utils.register_interface(ExtensionType)
Paul Kehrer012262c2015-08-10 23:42:57 -0500795class InhibitAnyPolicy(object):
796 oid = ExtensionOID.INHIBIT_ANY_POLICY
797
798 def __init__(self, skip_certs):
799 if not isinstance(skip_certs, six.integer_types):
800 raise TypeError("skip_certs must be an integer")
801
802 if skip_certs < 0:
803 raise ValueError("skip_certs must be a non-negative integer")
804
805 self._skip_certs = skip_certs
806
807 def __repr__(self):
808 return "<InhibitAnyPolicy(skip_certs={0.skip_certs})>".format(self)
809
810 def __eq__(self, other):
811 if not isinstance(other, InhibitAnyPolicy):
812 return NotImplemented
813
814 return self.skip_certs == other.skip_certs
815
816 def __ne__(self, other):
817 return not self == other
818
Eeshan Garg0a0293e2016-02-01 12:56:40 -0330819 def __hash__(self):
820 return hash(self.skip_certs)
821
Paul Kehrer012262c2015-08-10 23:42:57 -0500822 skip_certs = utils.read_only_property("_skip_certs")
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500823
824
825@utils.register_interface(ExtensionType)
826class KeyUsage(object):
827 oid = ExtensionOID.KEY_USAGE
828
829 def __init__(self, digital_signature, content_commitment, key_encipherment,
830 data_encipherment, key_agreement, key_cert_sign, crl_sign,
831 encipher_only, decipher_only):
832 if not key_agreement and (encipher_only or decipher_only):
833 raise ValueError(
834 "encipher_only and decipher_only can only be true when "
835 "key_agreement is true"
836 )
837
838 self._digital_signature = digital_signature
839 self._content_commitment = content_commitment
840 self._key_encipherment = key_encipherment
841 self._data_encipherment = data_encipherment
842 self._key_agreement = key_agreement
843 self._key_cert_sign = key_cert_sign
844 self._crl_sign = crl_sign
845 self._encipher_only = encipher_only
846 self._decipher_only = decipher_only
847
848 digital_signature = utils.read_only_property("_digital_signature")
849 content_commitment = utils.read_only_property("_content_commitment")
850 key_encipherment = utils.read_only_property("_key_encipherment")
851 data_encipherment = utils.read_only_property("_data_encipherment")
852 key_agreement = utils.read_only_property("_key_agreement")
853 key_cert_sign = utils.read_only_property("_key_cert_sign")
854 crl_sign = utils.read_only_property("_crl_sign")
855
856 @property
857 def encipher_only(self):
858 if not self.key_agreement:
859 raise ValueError(
860 "encipher_only is undefined unless key_agreement is true"
861 )
862 else:
863 return self._encipher_only
864
865 @property
866 def decipher_only(self):
867 if not self.key_agreement:
868 raise ValueError(
869 "decipher_only is undefined unless key_agreement is true"
870 )
871 else:
872 return self._decipher_only
873
874 def __repr__(self):
875 try:
876 encipher_only = self.encipher_only
877 decipher_only = self.decipher_only
878 except ValueError:
879 encipher_only = None
880 decipher_only = None
881
882 return ("<KeyUsage(digital_signature={0.digital_signature}, "
883 "content_commitment={0.content_commitment}, "
884 "key_encipherment={0.key_encipherment}, "
885 "data_encipherment={0.data_encipherment}, "
886 "key_agreement={0.key_agreement}, "
887 "key_cert_sign={0.key_cert_sign}, crl_sign={0.crl_sign}, "
888 "encipher_only={1}, decipher_only={2})>").format(
889 self, encipher_only, decipher_only)
890
891 def __eq__(self, other):
892 if not isinstance(other, KeyUsage):
893 return NotImplemented
894
895 return (
896 self.digital_signature == other.digital_signature and
897 self.content_commitment == other.content_commitment and
898 self.key_encipherment == other.key_encipherment and
899 self.data_encipherment == other.data_encipherment and
900 self.key_agreement == other.key_agreement and
901 self.key_cert_sign == other.key_cert_sign and
902 self.crl_sign == other.crl_sign and
903 self._encipher_only == other._encipher_only and
904 self._decipher_only == other._decipher_only
905 )
906
907 def __ne__(self, other):
908 return not self == other
909
910
911@utils.register_interface(ExtensionType)
912class NameConstraints(object):
913 oid = ExtensionOID.NAME_CONSTRAINTS
914
915 def __init__(self, permitted_subtrees, excluded_subtrees):
916 if permitted_subtrees is not None:
Marti40f19992016-08-26 04:26:31 +0300917 permitted_subtrees = list(permitted_subtrees)
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500918 if not all(
919 isinstance(x, GeneralName) for x in permitted_subtrees
920 ):
921 raise TypeError(
922 "permitted_subtrees must be a list of GeneralName objects "
923 "or None"
924 )
925
926 self._validate_ip_name(permitted_subtrees)
927
928 if excluded_subtrees is not None:
Marti40f19992016-08-26 04:26:31 +0300929 excluded_subtrees = list(excluded_subtrees)
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500930 if not all(
931 isinstance(x, GeneralName) for x in excluded_subtrees
932 ):
933 raise TypeError(
934 "excluded_subtrees must be a list of GeneralName objects "
935 "or None"
936 )
937
938 self._validate_ip_name(excluded_subtrees)
939
940 if permitted_subtrees is None and excluded_subtrees is None:
941 raise ValueError(
942 "At least one of permitted_subtrees and excluded_subtrees "
943 "must not be None"
944 )
945
946 self._permitted_subtrees = permitted_subtrees
947 self._excluded_subtrees = excluded_subtrees
948
949 def __eq__(self, other):
950 if not isinstance(other, NameConstraints):
951 return NotImplemented
952
953 return (
954 self.excluded_subtrees == other.excluded_subtrees and
955 self.permitted_subtrees == other.permitted_subtrees
956 )
957
958 def __ne__(self, other):
959 return not self == other
960
961 def _validate_ip_name(self, tree):
962 if any(isinstance(name, IPAddress) and not isinstance(
963 name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
964 ) for name in tree):
965 raise TypeError(
966 "IPAddress name constraints must be an IPv4Network or"
967 " IPv6Network object"
968 )
969
970 def __repr__(self):
971 return (
972 u"<NameConstraints(permitted_subtrees={0.permitted_subtrees}, "
973 u"excluded_subtrees={0.excluded_subtrees})>".format(self)
974 )
975
Paul Kehrerbdad0512017-09-14 04:24:20 +0800976 def __hash__(self):
977 if self.permitted_subtrees is not None:
978 ps = tuple(self.permitted_subtrees)
979 else:
980 ps = None
981
982 if self.excluded_subtrees is not None:
983 es = tuple(self.excluded_subtrees)
984 else:
985 es = None
986
987 return hash((ps, es))
988
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500989 permitted_subtrees = utils.read_only_property("_permitted_subtrees")
990 excluded_subtrees = utils.read_only_property("_excluded_subtrees")
Paul Kehreraa7a3222015-08-11 00:00:54 -0500991
992
993class Extension(object):
994 def __init__(self, oid, critical, value):
995 if not isinstance(oid, ObjectIdentifier):
996 raise TypeError(
997 "oid argument must be an ObjectIdentifier instance."
998 )
999
1000 if not isinstance(critical, bool):
1001 raise TypeError("critical must be a boolean value")
1002
1003 self._oid = oid
1004 self._critical = critical
1005 self._value = value
1006
1007 oid = utils.read_only_property("_oid")
1008 critical = utils.read_only_property("_critical")
1009 value = utils.read_only_property("_value")
1010
1011 def __repr__(self):
1012 return ("<Extension(oid={0.oid}, critical={0.critical}, "
1013 "value={0.value})>").format(self)
1014
1015 def __eq__(self, other):
1016 if not isinstance(other, Extension):
1017 return NotImplemented
1018
1019 return (
1020 self.oid == other.oid and
1021 self.critical == other.critical and
1022 self.value == other.value
1023 )
1024
1025 def __ne__(self, other):
1026 return not self == other
1027
1028
1029class GeneralNames(object):
1030 def __init__(self, general_names):
Marti40f19992016-08-26 04:26:31 +03001031 general_names = list(general_names)
Paul Kehreraa7a3222015-08-11 00:00:54 -05001032 if not all(isinstance(x, GeneralName) for x in general_names):
1033 raise TypeError(
1034 "Every item in the general_names list must be an "
1035 "object conforming to the GeneralName interface"
1036 )
1037
1038 self._general_names = general_names
1039
1040 def __iter__(self):
1041 return iter(self._general_names)
1042
1043 def __len__(self):
1044 return len(self._general_names)
1045
1046 def get_values_for_type(self, type):
1047 # Return the value of each GeneralName, except for OtherName instances
1048 # which we return directly because it has two important properties not
1049 # just one value.
1050 objs = (i for i in self if isinstance(i, type))
1051 if type != OtherName:
1052 objs = (i.value for i in objs)
1053 return list(objs)
1054
1055 def __repr__(self):
1056 return "<GeneralNames({0})>".format(self._general_names)
1057
1058 def __eq__(self, other):
1059 if not isinstance(other, GeneralNames):
1060 return NotImplemented
1061
1062 return self._general_names == other._general_names
1063
1064 def __ne__(self, other):
1065 return not self == other
1066
Paul Kehrer8adb5962015-12-26 14:46:58 -06001067 def __getitem__(self, idx):
1068 return self._general_names[idx]
1069
Paul Kehreraa7a3222015-08-11 00:00:54 -05001070
1071@utils.register_interface(ExtensionType)
1072class SubjectAlternativeName(object):
1073 oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME
1074
1075 def __init__(self, general_names):
1076 self._general_names = GeneralNames(general_names)
1077
1078 def __iter__(self):
1079 return iter(self._general_names)
1080
1081 def __len__(self):
1082 return len(self._general_names)
1083
1084 def get_values_for_type(self, type):
1085 return self._general_names.get_values_for_type(type)
1086
1087 def __repr__(self):
1088 return "<SubjectAlternativeName({0})>".format(self._general_names)
1089
1090 def __eq__(self, other):
1091 if not isinstance(other, SubjectAlternativeName):
1092 return NotImplemented
1093
1094 return self._general_names == other._general_names
1095
Paul Kehrer8adb5962015-12-26 14:46:58 -06001096 def __getitem__(self, idx):
1097 return self._general_names[idx]
1098
Paul Kehreraa7a3222015-08-11 00:00:54 -05001099 def __ne__(self, other):
1100 return not self == other
1101
1102
1103@utils.register_interface(ExtensionType)
1104class IssuerAlternativeName(object):
1105 oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME
1106
1107 def __init__(self, general_names):
1108 self._general_names = GeneralNames(general_names)
1109
1110 def __iter__(self):
1111 return iter(self._general_names)
1112
1113 def __len__(self):
1114 return len(self._general_names)
1115
1116 def get_values_for_type(self, type):
1117 return self._general_names.get_values_for_type(type)
1118
1119 def __repr__(self):
1120 return "<IssuerAlternativeName({0})>".format(self._general_names)
1121
1122 def __eq__(self, other):
1123 if not isinstance(other, IssuerAlternativeName):
1124 return NotImplemented
1125
1126 return self._general_names == other._general_names
1127
1128 def __ne__(self, other):
1129 return not self == other
Paul Kehrer49bb7562015-12-25 16:17:40 -06001130
Paul Kehrer5c999d32015-12-26 17:45:20 -06001131 def __getitem__(self, idx):
1132 return self._general_names[idx]
1133
Paul Kehrer49bb7562015-12-25 16:17:40 -06001134
1135@utils.register_interface(ExtensionType)
1136class CertificateIssuer(object):
1137 oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER
1138
1139 def __init__(self, general_names):
1140 self._general_names = GeneralNames(general_names)
1141
1142 def __iter__(self):
1143 return iter(self._general_names)
1144
1145 def __len__(self):
1146 return len(self._general_names)
1147
1148 def get_values_for_type(self, type):
1149 return self._general_names.get_values_for_type(type)
1150
1151 def __repr__(self):
1152 return "<CertificateIssuer({0})>".format(self._general_names)
1153
1154 def __eq__(self, other):
1155 if not isinstance(other, CertificateIssuer):
1156 return NotImplemented
1157
1158 return self._general_names == other._general_names
1159
1160 def __ne__(self, other):
1161 return not self == other
Paul Kehrer7058ece2015-12-25 22:28:29 -06001162
Paul Kehrer5c999d32015-12-26 17:45:20 -06001163 def __getitem__(self, idx):
1164 return self._general_names[idx]
1165
Paul Kehrer7058ece2015-12-25 22:28:29 -06001166
1167@utils.register_interface(ExtensionType)
1168class CRLReason(object):
1169 oid = CRLEntryExtensionOID.CRL_REASON
1170
1171 def __init__(self, reason):
1172 if not isinstance(reason, ReasonFlags):
1173 raise TypeError("reason must be an element from ReasonFlags")
1174
1175 self._reason = reason
1176
1177 def __repr__(self):
1178 return "<CRLReason(reason={0})>".format(self._reason)
1179
1180 def __eq__(self, other):
1181 if not isinstance(other, CRLReason):
1182 return NotImplemented
1183
1184 return self.reason == other.reason
1185
1186 def __ne__(self, other):
1187 return not self == other
1188
Alex Gaynor07d5cae2015-12-27 15:30:39 -05001189 def __hash__(self):
1190 return hash(self.reason)
1191
Paul Kehrer7058ece2015-12-25 22:28:29 -06001192 reason = utils.read_only_property("_reason")
Paul Kehrer23c0bbc2015-12-25 22:35:19 -06001193
1194
1195@utils.register_interface(ExtensionType)
1196class InvalidityDate(object):
1197 oid = CRLEntryExtensionOID.INVALIDITY_DATE
1198
1199 def __init__(self, invalidity_date):
1200 if not isinstance(invalidity_date, datetime.datetime):
1201 raise TypeError("invalidity_date must be a datetime.datetime")
1202
1203 self._invalidity_date = invalidity_date
1204
1205 def __repr__(self):
1206 return "<InvalidityDate(invalidity_date={0})>".format(
1207 self._invalidity_date
1208 )
1209
1210 def __eq__(self, other):
1211 if not isinstance(other, InvalidityDate):
1212 return NotImplemented
1213
1214 return self.invalidity_date == other.invalidity_date
1215
1216 def __ne__(self, other):
1217 return not self == other
1218
Paul Kehrer67cde762015-12-26 11:37:14 -06001219 def __hash__(self):
1220 return hash(self.invalidity_date)
1221
Paul Kehrer23c0bbc2015-12-25 22:35:19 -06001222 invalidity_date = utils.read_only_property("_invalidity_date")
Paul Kehrer14fd6972015-12-30 10:58:25 -06001223
1224
1225@utils.register_interface(ExtensionType)
Alex Gaynor6a0718f2017-06-04 13:36:58 -04001226class PrecertificateSignedCertificateTimestamps(object):
1227 oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS
1228
1229 def __init__(self, signed_certificate_timestamps):
1230 signed_certificate_timestamps = list(signed_certificate_timestamps)
1231 if not all(
1232 isinstance(sct, SignedCertificateTimestamp)
1233 for sct in signed_certificate_timestamps
1234 ):
1235 raise TypeError(
1236 "Every item in the signed_certificate_timestamps list must be "
1237 "a SignedCertificateTimestamp"
1238 )
1239 self._signed_certificate_timestamps = signed_certificate_timestamps
1240
1241 def __iter__(self):
1242 return iter(self._signed_certificate_timestamps)
1243
1244 def __len__(self):
1245 return len(self._signed_certificate_timestamps)
1246
1247 def __getitem__(self, idx):
1248 return self._signed_certificate_timestamps[idx]
1249
1250 def __repr__(self):
1251 return (
1252 "<PrecertificateSignedCertificateTimestamps({0})>".format(
1253 list(self)
1254 )
1255 )
1256
1257
1258@utils.register_interface(ExtensionType)
Paul Kehrer14fd6972015-12-30 10:58:25 -06001259class UnrecognizedExtension(object):
1260 def __init__(self, oid, value):
1261 if not isinstance(oid, ObjectIdentifier):
1262 raise TypeError("oid must be an ObjectIdentifier")
1263 self._oid = oid
1264 self._value = value
1265
1266 oid = utils.read_only_property("_oid")
1267 value = utils.read_only_property("_value")
1268
1269 def __repr__(self):
1270 return (
1271 "<UnrecognizedExtension(oid={0.oid}, value={0.value!r})>".format(
1272 self
1273 )
1274 )
1275
1276 def __eq__(self, other):
1277 if not isinstance(other, UnrecognizedExtension):
1278 return NotImplemented
1279
1280 return self.oid == other.oid and self.value == other.value
1281
1282 def __ne__(self, other):
1283 return not self == other
1284
1285 def __hash__(self):
1286 return hash((self.oid, self.value))