blob: 46ba5a28dd561cb66601da41be491fe0e65e223e [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 Kehrer890cb7f2015-08-10 21:05:34 -05008import hashlib
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -05009import ipaddress
Paul Kehrer9f8069a2015-08-10 21:10:34 -050010from enum import Enum
Paul Kehrer890cb7f2015-08-10 21:05:34 -050011
12from pyasn1.codec.der import decoder
13from pyasn1.type import namedtype, univ
14
15import six
16
17from cryptography import utils
Predrag Gruevski38995392015-09-21 21:53:49 -040018from cryptography.hazmat.primitives import constant_time, serialization
Paul Kehreraa7a3222015-08-11 00:00:54 -050019from cryptography.x509.general_name import GeneralName, IPAddress, OtherName
Paul Kehrer9f8069a2015-08-10 21:10:34 -050020from cryptography.x509.name import Name
Paul Kehrer890cb7f2015-08-10 21:05:34 -050021from cryptography.x509.oid import (
Paul Kehrer012262c2015-08-10 23:42:57 -050022 AuthorityInformationAccessOID, ExtensionOID, ObjectIdentifier
Paul Kehrer890cb7f2015-08-10 21:05:34 -050023)
24
25
26class _SubjectPublicKeyInfo(univ.Sequence):
27 componentType = namedtype.NamedTypes(
28 namedtype.NamedType('algorithm', univ.Sequence()),
29 namedtype.NamedType('subjectPublicKey', univ.BitString())
30 )
31
32
33def _key_identifier_from_public_key(public_key):
34 # This is a very slow way to do this.
35 serialized = public_key.public_bytes(
36 serialization.Encoding.DER,
37 serialization.PublicFormat.SubjectPublicKeyInfo
38 )
39 spki, remaining = decoder.decode(
40 serialized, asn1Spec=_SubjectPublicKeyInfo()
41 )
42 assert not remaining
43 # the univ.BitString object is a tuple of bits. We need bytes and
44 # pyasn1 really doesn't want to give them to us. To get it we'll
45 # build an integer and convert that to bytes.
46 bits = 0
47 for bit in spki.getComponentByName("subjectPublicKey"):
48 bits = bits << 1 | bit
49
50 data = utils.int_to_bytes(bits)
51 return hashlib.sha1(data).digest()
52
53
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050054class DuplicateExtension(Exception):
55 def __init__(self, msg, oid):
56 super(DuplicateExtension, self).__init__(msg)
57 self.oid = oid
58
59
60class UnsupportedExtension(Exception):
61 def __init__(self, msg, oid):
62 super(UnsupportedExtension, self).__init__(msg)
63 self.oid = oid
64
65
66class ExtensionNotFound(Exception):
67 def __init__(self, msg, oid):
68 super(ExtensionNotFound, self).__init__(msg)
69 self.oid = oid
70
71
Paul Kehreraa7a3222015-08-11 00:00:54 -050072@six.add_metaclass(abc.ABCMeta)
73class ExtensionType(object):
74 @abc.abstractproperty
75 def oid(self):
76 """
77 Returns the oid associated with the given extension type.
78 """
79
80
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -050081class Extensions(object):
82 def __init__(self, extensions):
83 self._extensions = extensions
84
85 def get_extension_for_oid(self, oid):
86 for ext in self:
87 if ext.oid == oid:
88 return ext
89
90 raise ExtensionNotFound("No {0} extension was found".format(oid), oid)
91
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010092 def get_extension_for_class(self, extclass):
93 for ext in self:
Phoebe Queen754be602015-08-12 03:11:35 +010094 if isinstance(ext.value, extclass):
Phoebe Queen64cf4cd2015-08-12 02:28:43 +010095 return ext
96
Phoebe Queen2cc111a2015-08-12 04:14:22 +010097 raise ExtensionNotFound(
Phoebe Queenecae9812015-08-12 05:00:32 +010098 "No {0} extension was found".format(extclass), extclass.oid
Phoebe Queen2cc111a2015-08-12 04:14:22 +010099 )
Phoebe Queen64cf4cd2015-08-12 02:28:43 +0100100
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500101 def __iter__(self):
102 return iter(self._extensions)
103
104 def __len__(self):
105 return len(self._extensions)
106
Paul Kehrerafbe75b2015-10-20 08:08:43 -0500107 def __repr__(self):
108 return (
109 "<Extensions({0})>".format(self._extensions)
110 )
111
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500112
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500113@utils.register_interface(ExtensionType)
114class AuthorityKeyIdentifier(object):
115 oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER
116
117 def __init__(self, key_identifier, authority_cert_issuer,
118 authority_cert_serial_number):
119 if authority_cert_issuer or authority_cert_serial_number:
120 if not authority_cert_issuer or not authority_cert_serial_number:
121 raise ValueError(
122 "authority_cert_issuer and authority_cert_serial_number "
123 "must both be present or both None"
124 )
125
126 if not all(
127 isinstance(x, GeneralName) for x in authority_cert_issuer
128 ):
129 raise TypeError(
130 "authority_cert_issuer must be a list of GeneralName "
131 "objects"
132 )
133
134 if not isinstance(authority_cert_serial_number, six.integer_types):
135 raise TypeError(
136 "authority_cert_serial_number must be an integer"
137 )
138
139 self._key_identifier = key_identifier
140 self._authority_cert_issuer = authority_cert_issuer
141 self._authority_cert_serial_number = authority_cert_serial_number
142
143 @classmethod
144 def from_issuer_public_key(cls, public_key):
145 digest = _key_identifier_from_public_key(public_key)
146 return cls(
147 key_identifier=digest,
148 authority_cert_issuer=None,
149 authority_cert_serial_number=None
150 )
151
152 def __repr__(self):
153 return (
154 "<AuthorityKeyIdentifier(key_identifier={0.key_identifier!r}, "
155 "authority_cert_issuer={0.authority_cert_issuer}, "
156 "authority_cert_serial_number={0.authority_cert_serial_number}"
157 ")>".format(self)
158 )
159
160 def __eq__(self, other):
161 if not isinstance(other, AuthorityKeyIdentifier):
162 return NotImplemented
163
164 return (
165 self.key_identifier == other.key_identifier and
166 self.authority_cert_issuer == other.authority_cert_issuer and
167 self.authority_cert_serial_number ==
168 other.authority_cert_serial_number
169 )
170
171 def __ne__(self, other):
172 return not self == other
173
174 key_identifier = utils.read_only_property("_key_identifier")
175 authority_cert_issuer = utils.read_only_property("_authority_cert_issuer")
176 authority_cert_serial_number = utils.read_only_property(
177 "_authority_cert_serial_number"
178 )
179
180
181@utils.register_interface(ExtensionType)
182class SubjectKeyIdentifier(object):
183 oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER
184
185 def __init__(self, digest):
186 self._digest = digest
187
188 @classmethod
189 def from_public_key(cls, public_key):
190 return cls(_key_identifier_from_public_key(public_key))
191
192 digest = utils.read_only_property("_digest")
193
194 def __repr__(self):
195 return "<SubjectKeyIdentifier(digest={0!r})>".format(self.digest)
196
197 def __eq__(self, other):
198 if not isinstance(other, SubjectKeyIdentifier):
199 return NotImplemented
200
Predrag Gruevski57f3b3f2015-09-21 18:51:47 -0400201 return constant_time.bytes_eq(self.digest, other.digest)
Paul Kehrer890cb7f2015-08-10 21:05:34 -0500202
203 def __ne__(self, other):
204 return not self == other
Paul Kehrer9f8069a2015-08-10 21:10:34 -0500205
206
207@utils.register_interface(ExtensionType)
208class AuthorityInformationAccess(object):
209 oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS
210
211 def __init__(self, descriptions):
212 if not all(isinstance(x, AccessDescription) for x in descriptions):
213 raise TypeError(
214 "Every item in the descriptions list must be an "
215 "AccessDescription"
216 )
217
218 self._descriptions = descriptions
219
220 def __iter__(self):
221 return iter(self._descriptions)
222
223 def __len__(self):
224 return len(self._descriptions)
225
226 def __repr__(self):
227 return "<AuthorityInformationAccess({0})>".format(self._descriptions)
228
229 def __eq__(self, other):
230 if not isinstance(other, AuthorityInformationAccess):
231 return NotImplemented
232
233 return self._descriptions == other._descriptions
234
235 def __ne__(self, other):
236 return not self == other
237
238
239class AccessDescription(object):
240 def __init__(self, access_method, access_location):
241 if not (access_method == AuthorityInformationAccessOID.OCSP or
242 access_method == AuthorityInformationAccessOID.CA_ISSUERS):
243 raise ValueError(
244 "access_method must be OID_OCSP or OID_CA_ISSUERS"
245 )
246
247 if not isinstance(access_location, GeneralName):
248 raise TypeError("access_location must be a GeneralName")
249
250 self._access_method = access_method
251 self._access_location = access_location
252
253 def __repr__(self):
254 return (
255 "<AccessDescription(access_method={0.access_method}, access_locati"
256 "on={0.access_location})>".format(self)
257 )
258
259 def __eq__(self, other):
260 if not isinstance(other, AccessDescription):
261 return NotImplemented
262
263 return (
264 self.access_method == other.access_method and
265 self.access_location == other.access_location
266 )
267
268 def __ne__(self, other):
269 return not self == other
270
271 access_method = utils.read_only_property("_access_method")
272 access_location = utils.read_only_property("_access_location")
273
274
275@utils.register_interface(ExtensionType)
276class BasicConstraints(object):
277 oid = ExtensionOID.BASIC_CONSTRAINTS
278
279 def __init__(self, ca, path_length):
280 if not isinstance(ca, bool):
281 raise TypeError("ca must be a boolean value")
282
283 if path_length is not None and not ca:
284 raise ValueError("path_length must be None when ca is False")
285
286 if (
287 path_length is not None and
288 (not isinstance(path_length, six.integer_types) or path_length < 0)
289 ):
290 raise TypeError(
291 "path_length must be a non-negative integer or None"
292 )
293
294 self._ca = ca
295 self._path_length = path_length
296
297 ca = utils.read_only_property("_ca")
298 path_length = utils.read_only_property("_path_length")
299
300 def __repr__(self):
301 return ("<BasicConstraints(ca={0.ca}, "
302 "path_length={0.path_length})>").format(self)
303
304 def __eq__(self, other):
305 if not isinstance(other, BasicConstraints):
306 return NotImplemented
307
308 return self.ca == other.ca and self.path_length == other.path_length
309
310 def __ne__(self, other):
311 return not self == other
312
313
314@utils.register_interface(ExtensionType)
315class CRLDistributionPoints(object):
316 oid = ExtensionOID.CRL_DISTRIBUTION_POINTS
317
318 def __init__(self, distribution_points):
319 if not all(
320 isinstance(x, DistributionPoint) for x in distribution_points
321 ):
322 raise TypeError(
323 "distribution_points must be a list of DistributionPoint "
324 "objects"
325 )
326
327 self._distribution_points = distribution_points
328
329 def __iter__(self):
330 return iter(self._distribution_points)
331
332 def __len__(self):
333 return len(self._distribution_points)
334
335 def __repr__(self):
336 return "<CRLDistributionPoints({0})>".format(self._distribution_points)
337
338 def __eq__(self, other):
339 if not isinstance(other, CRLDistributionPoints):
340 return NotImplemented
341
342 return self._distribution_points == other._distribution_points
343
344 def __ne__(self, other):
345 return not self == other
346
347
348class DistributionPoint(object):
349 def __init__(self, full_name, relative_name, reasons, crl_issuer):
350 if full_name and relative_name:
351 raise ValueError(
352 "You cannot provide both full_name and relative_name, at "
353 "least one must be None."
354 )
355
356 if full_name and not all(
357 isinstance(x, GeneralName) for x in full_name
358 ):
359 raise TypeError(
360 "full_name must be a list of GeneralName objects"
361 )
362
363 if relative_name and not isinstance(relative_name, Name):
364 raise TypeError("relative_name must be a Name")
365
366 if crl_issuer and not all(
367 isinstance(x, GeneralName) for x in crl_issuer
368 ):
369 raise TypeError(
370 "crl_issuer must be None or a list of general names"
371 )
372
373 if reasons and (not isinstance(reasons, frozenset) or not all(
374 isinstance(x, ReasonFlags) for x in reasons
375 )):
376 raise TypeError("reasons must be None or frozenset of ReasonFlags")
377
378 if reasons and (
379 ReasonFlags.unspecified in reasons or
380 ReasonFlags.remove_from_crl in reasons
381 ):
382 raise ValueError(
383 "unspecified and remove_from_crl are not valid reasons in a "
384 "DistributionPoint"
385 )
386
387 if reasons and not crl_issuer and not (full_name or relative_name):
388 raise ValueError(
389 "You must supply crl_issuer, full_name, or relative_name when "
390 "reasons is not None"
391 )
392
393 self._full_name = full_name
394 self._relative_name = relative_name
395 self._reasons = reasons
396 self._crl_issuer = crl_issuer
397
398 def __repr__(self):
399 return (
400 "<DistributionPoint(full_name={0.full_name}, relative_name={0.rela"
401 "tive_name}, reasons={0.reasons}, crl_issuer={0.crl_is"
402 "suer})>".format(self)
403 )
404
405 def __eq__(self, other):
406 if not isinstance(other, DistributionPoint):
407 return NotImplemented
408
409 return (
410 self.full_name == other.full_name and
411 self.relative_name == other.relative_name and
412 self.reasons == other.reasons and
413 self.crl_issuer == other.crl_issuer
414 )
415
416 def __ne__(self, other):
417 return not self == other
418
419 full_name = utils.read_only_property("_full_name")
420 relative_name = utils.read_only_property("_relative_name")
421 reasons = utils.read_only_property("_reasons")
422 crl_issuer = utils.read_only_property("_crl_issuer")
423
424
425class ReasonFlags(Enum):
426 unspecified = "unspecified"
427 key_compromise = "keyCompromise"
428 ca_compromise = "cACompromise"
429 affiliation_changed = "affiliationChanged"
430 superseded = "superseded"
431 cessation_of_operation = "cessationOfOperation"
432 certificate_hold = "certificateHold"
433 privilege_withdrawn = "privilegeWithdrawn"
434 aa_compromise = "aACompromise"
435 remove_from_crl = "removeFromCRL"
Paul Kehrer012262c2015-08-10 23:42:57 -0500436
437
438@utils.register_interface(ExtensionType)
439class CertificatePolicies(object):
440 oid = ExtensionOID.CERTIFICATE_POLICIES
441
442 def __init__(self, policies):
443 if not all(isinstance(x, PolicyInformation) for x in policies):
444 raise TypeError(
445 "Every item in the policies list must be a "
446 "PolicyInformation"
447 )
448
449 self._policies = policies
450
451 def __iter__(self):
452 return iter(self._policies)
453
454 def __len__(self):
455 return len(self._policies)
456
457 def __repr__(self):
458 return "<CertificatePolicies({0})>".format(self._policies)
459
460 def __eq__(self, other):
461 if not isinstance(other, CertificatePolicies):
462 return NotImplemented
463
464 return self._policies == other._policies
465
466 def __ne__(self, other):
467 return not self == other
468
469
470class PolicyInformation(object):
471 def __init__(self, policy_identifier, policy_qualifiers):
472 if not isinstance(policy_identifier, ObjectIdentifier):
473 raise TypeError("policy_identifier must be an ObjectIdentifier")
474
475 self._policy_identifier = policy_identifier
476 if policy_qualifiers and not all(
477 isinstance(
478 x, (six.text_type, UserNotice)
479 ) for x in policy_qualifiers
480 ):
481 raise TypeError(
482 "policy_qualifiers must be a list of strings and/or UserNotice"
483 " objects or None"
484 )
485
486 self._policy_qualifiers = policy_qualifiers
487
488 def __repr__(self):
489 return (
490 "<PolicyInformation(policy_identifier={0.policy_identifier}, polic"
491 "y_qualifiers={0.policy_qualifiers})>".format(self)
492 )
493
494 def __eq__(self, other):
495 if not isinstance(other, PolicyInformation):
496 return NotImplemented
497
498 return (
499 self.policy_identifier == other.policy_identifier and
500 self.policy_qualifiers == other.policy_qualifiers
501 )
502
503 def __ne__(self, other):
504 return not self == other
505
506 policy_identifier = utils.read_only_property("_policy_identifier")
507 policy_qualifiers = utils.read_only_property("_policy_qualifiers")
508
509
510class UserNotice(object):
511 def __init__(self, notice_reference, explicit_text):
512 if notice_reference and not isinstance(
513 notice_reference, NoticeReference
514 ):
515 raise TypeError(
516 "notice_reference must be None or a NoticeReference"
517 )
518
519 self._notice_reference = notice_reference
520 self._explicit_text = explicit_text
521
522 def __repr__(self):
523 return (
524 "<UserNotice(notice_reference={0.notice_reference}, explicit_text="
525 "{0.explicit_text!r})>".format(self)
526 )
527
528 def __eq__(self, other):
529 if not isinstance(other, UserNotice):
530 return NotImplemented
531
532 return (
533 self.notice_reference == other.notice_reference and
534 self.explicit_text == other.explicit_text
535 )
536
537 def __ne__(self, other):
538 return not self == other
539
540 notice_reference = utils.read_only_property("_notice_reference")
541 explicit_text = utils.read_only_property("_explicit_text")
542
543
544class NoticeReference(object):
545 def __init__(self, organization, notice_numbers):
546 self._organization = organization
547 if not isinstance(notice_numbers, list) or not all(
548 isinstance(x, int) for x in notice_numbers
549 ):
550 raise TypeError(
551 "notice_numbers must be a list of integers"
552 )
553
554 self._notice_numbers = notice_numbers
555
556 def __repr__(self):
557 return (
558 "<NoticeReference(organization={0.organization!r}, notice_numbers="
559 "{0.notice_numbers})>".format(self)
560 )
561
562 def __eq__(self, other):
563 if not isinstance(other, NoticeReference):
564 return NotImplemented
565
566 return (
567 self.organization == other.organization and
568 self.notice_numbers == other.notice_numbers
569 )
570
571 def __ne__(self, other):
572 return not self == other
573
574 organization = utils.read_only_property("_organization")
575 notice_numbers = utils.read_only_property("_notice_numbers")
576
577
578@utils.register_interface(ExtensionType)
579class ExtendedKeyUsage(object):
580 oid = ExtensionOID.EXTENDED_KEY_USAGE
581
582 def __init__(self, usages):
583 if not all(isinstance(x, ObjectIdentifier) for x in usages):
584 raise TypeError(
585 "Every item in the usages list must be an ObjectIdentifier"
586 )
587
588 self._usages = usages
589
590 def __iter__(self):
591 return iter(self._usages)
592
593 def __len__(self):
594 return len(self._usages)
595
596 def __repr__(self):
597 return "<ExtendedKeyUsage({0})>".format(self._usages)
598
599 def __eq__(self, other):
600 if not isinstance(other, ExtendedKeyUsage):
601 return NotImplemented
602
603 return self._usages == other._usages
604
605 def __ne__(self, other):
606 return not self == other
607
608
609@utils.register_interface(ExtensionType)
610class OCSPNoCheck(object):
611 oid = ExtensionOID.OCSP_NO_CHECK
612
613
614@utils.register_interface(ExtensionType)
615class InhibitAnyPolicy(object):
616 oid = ExtensionOID.INHIBIT_ANY_POLICY
617
618 def __init__(self, skip_certs):
619 if not isinstance(skip_certs, six.integer_types):
620 raise TypeError("skip_certs must be an integer")
621
622 if skip_certs < 0:
623 raise ValueError("skip_certs must be a non-negative integer")
624
625 self._skip_certs = skip_certs
626
627 def __repr__(self):
628 return "<InhibitAnyPolicy(skip_certs={0.skip_certs})>".format(self)
629
630 def __eq__(self, other):
631 if not isinstance(other, InhibitAnyPolicy):
632 return NotImplemented
633
634 return self.skip_certs == other.skip_certs
635
636 def __ne__(self, other):
637 return not self == other
638
639 skip_certs = utils.read_only_property("_skip_certs")
Paul Kehrerfbeaf2a2015-08-10 23:52:10 -0500640
641
642@utils.register_interface(ExtensionType)
643class KeyUsage(object):
644 oid = ExtensionOID.KEY_USAGE
645
646 def __init__(self, digital_signature, content_commitment, key_encipherment,
647 data_encipherment, key_agreement, key_cert_sign, crl_sign,
648 encipher_only, decipher_only):
649 if not key_agreement and (encipher_only or decipher_only):
650 raise ValueError(
651 "encipher_only and decipher_only can only be true when "
652 "key_agreement is true"
653 )
654
655 self._digital_signature = digital_signature
656 self._content_commitment = content_commitment
657 self._key_encipherment = key_encipherment
658 self._data_encipherment = data_encipherment
659 self._key_agreement = key_agreement
660 self._key_cert_sign = key_cert_sign
661 self._crl_sign = crl_sign
662 self._encipher_only = encipher_only
663 self._decipher_only = decipher_only
664
665 digital_signature = utils.read_only_property("_digital_signature")
666 content_commitment = utils.read_only_property("_content_commitment")
667 key_encipherment = utils.read_only_property("_key_encipherment")
668 data_encipherment = utils.read_only_property("_data_encipherment")
669 key_agreement = utils.read_only_property("_key_agreement")
670 key_cert_sign = utils.read_only_property("_key_cert_sign")
671 crl_sign = utils.read_only_property("_crl_sign")
672
673 @property
674 def encipher_only(self):
675 if not self.key_agreement:
676 raise ValueError(
677 "encipher_only is undefined unless key_agreement is true"
678 )
679 else:
680 return self._encipher_only
681
682 @property
683 def decipher_only(self):
684 if not self.key_agreement:
685 raise ValueError(
686 "decipher_only is undefined unless key_agreement is true"
687 )
688 else:
689 return self._decipher_only
690
691 def __repr__(self):
692 try:
693 encipher_only = self.encipher_only
694 decipher_only = self.decipher_only
695 except ValueError:
696 encipher_only = None
697 decipher_only = None
698
699 return ("<KeyUsage(digital_signature={0.digital_signature}, "
700 "content_commitment={0.content_commitment}, "
701 "key_encipherment={0.key_encipherment}, "
702 "data_encipherment={0.data_encipherment}, "
703 "key_agreement={0.key_agreement}, "
704 "key_cert_sign={0.key_cert_sign}, crl_sign={0.crl_sign}, "
705 "encipher_only={1}, decipher_only={2})>").format(
706 self, encipher_only, decipher_only)
707
708 def __eq__(self, other):
709 if not isinstance(other, KeyUsage):
710 return NotImplemented
711
712 return (
713 self.digital_signature == other.digital_signature and
714 self.content_commitment == other.content_commitment and
715 self.key_encipherment == other.key_encipherment and
716 self.data_encipherment == other.data_encipherment and
717 self.key_agreement == other.key_agreement and
718 self.key_cert_sign == other.key_cert_sign and
719 self.crl_sign == other.crl_sign and
720 self._encipher_only == other._encipher_only and
721 self._decipher_only == other._decipher_only
722 )
723
724 def __ne__(self, other):
725 return not self == other
726
727
728@utils.register_interface(ExtensionType)
729class NameConstraints(object):
730 oid = ExtensionOID.NAME_CONSTRAINTS
731
732 def __init__(self, permitted_subtrees, excluded_subtrees):
733 if permitted_subtrees is not None:
734 if not all(
735 isinstance(x, GeneralName) for x in permitted_subtrees
736 ):
737 raise TypeError(
738 "permitted_subtrees must be a list of GeneralName objects "
739 "or None"
740 )
741
742 self._validate_ip_name(permitted_subtrees)
743
744 if excluded_subtrees is not None:
745 if not all(
746 isinstance(x, GeneralName) for x in excluded_subtrees
747 ):
748 raise TypeError(
749 "excluded_subtrees must be a list of GeneralName objects "
750 "or None"
751 )
752
753 self._validate_ip_name(excluded_subtrees)
754
755 if permitted_subtrees is None and excluded_subtrees is None:
756 raise ValueError(
757 "At least one of permitted_subtrees and excluded_subtrees "
758 "must not be None"
759 )
760
761 self._permitted_subtrees = permitted_subtrees
762 self._excluded_subtrees = excluded_subtrees
763
764 def __eq__(self, other):
765 if not isinstance(other, NameConstraints):
766 return NotImplemented
767
768 return (
769 self.excluded_subtrees == other.excluded_subtrees and
770 self.permitted_subtrees == other.permitted_subtrees
771 )
772
773 def __ne__(self, other):
774 return not self == other
775
776 def _validate_ip_name(self, tree):
777 if any(isinstance(name, IPAddress) and not isinstance(
778 name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
779 ) for name in tree):
780 raise TypeError(
781 "IPAddress name constraints must be an IPv4Network or"
782 " IPv6Network object"
783 )
784
785 def __repr__(self):
786 return (
787 u"<NameConstraints(permitted_subtrees={0.permitted_subtrees}, "
788 u"excluded_subtrees={0.excluded_subtrees})>".format(self)
789 )
790
791 permitted_subtrees = utils.read_only_property("_permitted_subtrees")
792 excluded_subtrees = utils.read_only_property("_excluded_subtrees")
Paul Kehreraa7a3222015-08-11 00:00:54 -0500793
794
795class Extension(object):
796 def __init__(self, oid, critical, value):
797 if not isinstance(oid, ObjectIdentifier):
798 raise TypeError(
799 "oid argument must be an ObjectIdentifier instance."
800 )
801
802 if not isinstance(critical, bool):
803 raise TypeError("critical must be a boolean value")
804
805 self._oid = oid
806 self._critical = critical
807 self._value = value
808
809 oid = utils.read_only_property("_oid")
810 critical = utils.read_only_property("_critical")
811 value = utils.read_only_property("_value")
812
813 def __repr__(self):
814 return ("<Extension(oid={0.oid}, critical={0.critical}, "
815 "value={0.value})>").format(self)
816
817 def __eq__(self, other):
818 if not isinstance(other, Extension):
819 return NotImplemented
820
821 return (
822 self.oid == other.oid and
823 self.critical == other.critical and
824 self.value == other.value
825 )
826
827 def __ne__(self, other):
828 return not self == other
829
830
831class GeneralNames(object):
832 def __init__(self, general_names):
833 if not all(isinstance(x, GeneralName) for x in general_names):
834 raise TypeError(
835 "Every item in the general_names list must be an "
836 "object conforming to the GeneralName interface"
837 )
838
839 self._general_names = general_names
840
841 def __iter__(self):
842 return iter(self._general_names)
843
844 def __len__(self):
845 return len(self._general_names)
846
847 def get_values_for_type(self, type):
848 # Return the value of each GeneralName, except for OtherName instances
849 # which we return directly because it has two important properties not
850 # just one value.
851 objs = (i for i in self if isinstance(i, type))
852 if type != OtherName:
853 objs = (i.value for i in objs)
854 return list(objs)
855
856 def __repr__(self):
857 return "<GeneralNames({0})>".format(self._general_names)
858
859 def __eq__(self, other):
860 if not isinstance(other, GeneralNames):
861 return NotImplemented
862
863 return self._general_names == other._general_names
864
865 def __ne__(self, other):
866 return not self == other
867
868
869@utils.register_interface(ExtensionType)
870class SubjectAlternativeName(object):
871 oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME
872
873 def __init__(self, general_names):
874 self._general_names = GeneralNames(general_names)
875
876 def __iter__(self):
877 return iter(self._general_names)
878
879 def __len__(self):
880 return len(self._general_names)
881
882 def get_values_for_type(self, type):
883 return self._general_names.get_values_for_type(type)
884
885 def __repr__(self):
886 return "<SubjectAlternativeName({0})>".format(self._general_names)
887
888 def __eq__(self, other):
889 if not isinstance(other, SubjectAlternativeName):
890 return NotImplemented
891
892 return self._general_names == other._general_names
893
894 def __ne__(self, other):
895 return not self == other
896
897
898@utils.register_interface(ExtensionType)
899class IssuerAlternativeName(object):
900 oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME
901
902 def __init__(self, general_names):
903 self._general_names = GeneralNames(general_names)
904
905 def __iter__(self):
906 return iter(self._general_names)
907
908 def __len__(self):
909 return len(self._general_names)
910
911 def get_values_for_type(self, type):
912 return self._general_names.get_values_for_type(type)
913
914 def __repr__(self):
915 return "<IssuerAlternativeName({0})>".format(self._general_names)
916
917 def __eq__(self, other):
918 if not isinstance(other, IssuerAlternativeName):
919 return NotImplemented
920
921 return self._general_names == other._general_names
922
923 def __ne__(self, other):
924 return not self == other