Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

extensions.py 67KB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  1. # 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. from __future__ import annotations
  5. import abc
  6. import datetime
  7. import hashlib
  8. import ipaddress
  9. import typing
  10. from cryptography import utils
  11. from cryptography.hazmat.bindings._rust import asn1
  12. from cryptography.hazmat.bindings._rust import x509 as rust_x509
  13. from cryptography.hazmat.primitives import constant_time, serialization
  14. from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey
  15. from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
  16. from cryptography.hazmat.primitives.asymmetric.types import (
  17. CertificateIssuerPublicKeyTypes,
  18. CertificatePublicKeyTypes,
  19. )
  20. from cryptography.x509.certificate_transparency import (
  21. SignedCertificateTimestamp,
  22. )
  23. from cryptography.x509.general_name import (
  24. DirectoryName,
  25. DNSName,
  26. GeneralName,
  27. IPAddress,
  28. OtherName,
  29. RegisteredID,
  30. RFC822Name,
  31. UniformResourceIdentifier,
  32. _IPAddressTypes,
  33. )
  34. from cryptography.x509.name import Name, RelativeDistinguishedName
  35. from cryptography.x509.oid import (
  36. CRLEntryExtensionOID,
  37. ExtensionOID,
  38. ObjectIdentifier,
  39. OCSPExtensionOID,
  40. )
  41. ExtensionTypeVar = typing.TypeVar(
  42. "ExtensionTypeVar", bound="ExtensionType", covariant=True
  43. )
  44. def _key_identifier_from_public_key(
  45. public_key: CertificatePublicKeyTypes,
  46. ) -> bytes:
  47. if isinstance(public_key, RSAPublicKey):
  48. data = public_key.public_bytes(
  49. serialization.Encoding.DER,
  50. serialization.PublicFormat.PKCS1,
  51. )
  52. elif isinstance(public_key, EllipticCurvePublicKey):
  53. data = public_key.public_bytes(
  54. serialization.Encoding.X962,
  55. serialization.PublicFormat.UncompressedPoint,
  56. )
  57. else:
  58. # This is a very slow way to do this.
  59. serialized = public_key.public_bytes(
  60. serialization.Encoding.DER,
  61. serialization.PublicFormat.SubjectPublicKeyInfo,
  62. )
  63. data = asn1.parse_spki_for_data(serialized)
  64. return hashlib.sha1(data).digest()
  65. def _make_sequence_methods(field_name: str):
  66. def len_method(self) -> int:
  67. return len(getattr(self, field_name))
  68. def iter_method(self):
  69. return iter(getattr(self, field_name))
  70. def getitem_method(self, idx):
  71. return getattr(self, field_name)[idx]
  72. return len_method, iter_method, getitem_method
  73. class DuplicateExtension(Exception):
  74. def __init__(self, msg: str, oid: ObjectIdentifier) -> None:
  75. super().__init__(msg)
  76. self.oid = oid
  77. class ExtensionNotFound(Exception):
  78. def __init__(self, msg: str, oid: ObjectIdentifier) -> None:
  79. super().__init__(msg)
  80. self.oid = oid
  81. class ExtensionType(metaclass=abc.ABCMeta):
  82. oid: typing.ClassVar[ObjectIdentifier]
  83. def public_bytes(self) -> bytes:
  84. """
  85. Serializes the extension type to DER.
  86. """
  87. raise NotImplementedError(
  88. "public_bytes is not implemented for extension type {!r}".format(
  89. self
  90. )
  91. )
  92. class Extensions:
  93. def __init__(
  94. self, extensions: typing.Iterable[Extension[ExtensionType]]
  95. ) -> None:
  96. self._extensions = list(extensions)
  97. def get_extension_for_oid(
  98. self, oid: ObjectIdentifier
  99. ) -> Extension[ExtensionType]:
  100. for ext in self:
  101. if ext.oid == oid:
  102. return ext
  103. raise ExtensionNotFound(f"No {oid} extension was found", oid)
  104. def get_extension_for_class(
  105. self, extclass: typing.Type[ExtensionTypeVar]
  106. ) -> Extension[ExtensionTypeVar]:
  107. if extclass is UnrecognizedExtension:
  108. raise TypeError(
  109. "UnrecognizedExtension can't be used with "
  110. "get_extension_for_class because more than one instance of the"
  111. " class may be present."
  112. )
  113. for ext in self:
  114. if isinstance(ext.value, extclass):
  115. return ext
  116. raise ExtensionNotFound(
  117. f"No {extclass} extension was found", extclass.oid
  118. )
  119. __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions")
  120. def __repr__(self) -> str:
  121. return f"<Extensions({self._extensions})>"
  122. class CRLNumber(ExtensionType):
  123. oid = ExtensionOID.CRL_NUMBER
  124. def __init__(self, crl_number: int) -> None:
  125. if not isinstance(crl_number, int):
  126. raise TypeError("crl_number must be an integer")
  127. self._crl_number = crl_number
  128. def __eq__(self, other: object) -> bool:
  129. if not isinstance(other, CRLNumber):
  130. return NotImplemented
  131. return self.crl_number == other.crl_number
  132. def __hash__(self) -> int:
  133. return hash(self.crl_number)
  134. def __repr__(self) -> str:
  135. return f"<CRLNumber({self.crl_number})>"
  136. @property
  137. def crl_number(self) -> int:
  138. return self._crl_number
  139. def public_bytes(self) -> bytes:
  140. return rust_x509.encode_extension_value(self)
  141. class AuthorityKeyIdentifier(ExtensionType):
  142. oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER
  143. def __init__(
  144. self,
  145. key_identifier: typing.Optional[bytes],
  146. authority_cert_issuer: typing.Optional[typing.Iterable[GeneralName]],
  147. authority_cert_serial_number: typing.Optional[int],
  148. ) -> None:
  149. if (authority_cert_issuer is None) != (
  150. authority_cert_serial_number is None
  151. ):
  152. raise ValueError(
  153. "authority_cert_issuer and authority_cert_serial_number "
  154. "must both be present or both None"
  155. )
  156. 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. )
  165. if authority_cert_serial_number is not None and not isinstance(
  166. authority_cert_serial_number, int
  167. ):
  168. raise TypeError("authority_cert_serial_number must be an integer")
  169. self._key_identifier = key_identifier
  170. self._authority_cert_issuer = authority_cert_issuer
  171. self._authority_cert_serial_number = authority_cert_serial_number
  172. # This takes a subset of CertificatePublicKeyTypes because an issuer
  173. # cannot have an X25519/X448 key. This introduces some unfortunate
  174. # asymmetry that requires typing users to explicitly
  175. # narrow their type, but we should make this accurate and not just
  176. # convenient.
  177. @classmethod
  178. def from_issuer_public_key(
  179. cls, public_key: CertificateIssuerPublicKeyTypes
  180. ) -> AuthorityKeyIdentifier:
  181. digest = _key_identifier_from_public_key(public_key)
  182. return cls(
  183. key_identifier=digest,
  184. authority_cert_issuer=None,
  185. authority_cert_serial_number=None,
  186. )
  187. @classmethod
  188. def from_issuer_subject_key_identifier(
  189. cls, ski: SubjectKeyIdentifier
  190. ) -> AuthorityKeyIdentifier:
  191. return cls(
  192. key_identifier=ski.digest,
  193. authority_cert_issuer=None,
  194. authority_cert_serial_number=None,
  195. )
  196. def __repr__(self) -> str:
  197. return (
  198. "<AuthorityKeyIdentifier(key_identifier={0.key_identifier!r}, "
  199. "authority_cert_issuer={0.authority_cert_issuer}, "
  200. "authority_cert_serial_number={0.authority_cert_serial_number}"
  201. ")>".format(self)
  202. )
  203. def __eq__(self, other: object) -> bool:
  204. if not isinstance(other, AuthorityKeyIdentifier):
  205. return NotImplemented
  206. return (
  207. self.key_identifier == other.key_identifier
  208. and self.authority_cert_issuer == other.authority_cert_issuer
  209. and self.authority_cert_serial_number
  210. == other.authority_cert_serial_number
  211. )
  212. def __hash__(self) -> int:
  213. if self.authority_cert_issuer is None:
  214. aci = None
  215. else:
  216. aci = tuple(self.authority_cert_issuer)
  217. return hash(
  218. (self.key_identifier, aci, self.authority_cert_serial_number)
  219. )
  220. @property
  221. def key_identifier(self) -> typing.Optional[bytes]:
  222. return self._key_identifier
  223. @property
  224. def authority_cert_issuer(
  225. self,
  226. ) -> typing.Optional[typing.List[GeneralName]]:
  227. return self._authority_cert_issuer
  228. @property
  229. def authority_cert_serial_number(self) -> typing.Optional[int]:
  230. return self._authority_cert_serial_number
  231. def public_bytes(self) -> bytes:
  232. return rust_x509.encode_extension_value(self)
  233. class SubjectKeyIdentifier(ExtensionType):
  234. oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER
  235. def __init__(self, digest: bytes) -> None:
  236. self._digest = digest
  237. @classmethod
  238. def from_public_key(
  239. cls, public_key: CertificatePublicKeyTypes
  240. ) -> SubjectKeyIdentifier:
  241. return cls(_key_identifier_from_public_key(public_key))
  242. @property
  243. def digest(self) -> bytes:
  244. return self._digest
  245. @property
  246. def key_identifier(self) -> bytes:
  247. return self._digest
  248. def __repr__(self) -> str:
  249. return f"<SubjectKeyIdentifier(digest={self.digest!r})>"
  250. def __eq__(self, other: object) -> bool:
  251. if not isinstance(other, SubjectKeyIdentifier):
  252. return NotImplemented
  253. return constant_time.bytes_eq(self.digest, other.digest)
  254. def __hash__(self) -> int:
  255. return hash(self.digest)
  256. def public_bytes(self) -> bytes:
  257. return rust_x509.encode_extension_value(self)
  258. class AuthorityInformationAccess(ExtensionType):
  259. oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS
  260. def __init__(
  261. self, descriptions: typing.Iterable[AccessDescription]
  262. ) -> None:
  263. descriptions = list(descriptions)
  264. if not all(isinstance(x, AccessDescription) for x in descriptions):
  265. raise TypeError(
  266. "Every item in the descriptions list must be an "
  267. "AccessDescription"
  268. )
  269. self._descriptions = descriptions
  270. __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions")
  271. def __repr__(self) -> str:
  272. return f"<AuthorityInformationAccess({self._descriptions})>"
  273. def __eq__(self, other: object) -> bool:
  274. if not isinstance(other, AuthorityInformationAccess):
  275. return NotImplemented
  276. return self._descriptions == other._descriptions
  277. def __hash__(self) -> int:
  278. return hash(tuple(self._descriptions))
  279. def public_bytes(self) -> bytes:
  280. return rust_x509.encode_extension_value(self)
  281. class SubjectInformationAccess(ExtensionType):
  282. oid = ExtensionOID.SUBJECT_INFORMATION_ACCESS
  283. def __init__(
  284. self, descriptions: typing.Iterable[AccessDescription]
  285. ) -> None:
  286. descriptions = list(descriptions)
  287. if not all(isinstance(x, AccessDescription) for x in descriptions):
  288. raise TypeError(
  289. "Every item in the descriptions list must be an "
  290. "AccessDescription"
  291. )
  292. self._descriptions = descriptions
  293. __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions")
  294. def __repr__(self) -> str:
  295. return f"<SubjectInformationAccess({self._descriptions})>"
  296. def __eq__(self, other: object) -> bool:
  297. if not isinstance(other, SubjectInformationAccess):
  298. return NotImplemented
  299. return self._descriptions == other._descriptions
  300. def __hash__(self) -> int:
  301. return hash(tuple(self._descriptions))
  302. def public_bytes(self) -> bytes:
  303. return rust_x509.encode_extension_value(self)
  304. class AccessDescription:
  305. def __init__(
  306. self, access_method: ObjectIdentifier, access_location: GeneralName
  307. ) -> None:
  308. if not isinstance(access_method, ObjectIdentifier):
  309. raise TypeError("access_method must be an ObjectIdentifier")
  310. if not isinstance(access_location, GeneralName):
  311. raise TypeError("access_location must be a GeneralName")
  312. self._access_method = access_method
  313. self._access_location = access_location
  314. def __repr__(self) -> str:
  315. return (
  316. "<AccessDescription(access_method={0.access_method}, access_locati"
  317. "on={0.access_location})>".format(self)
  318. )
  319. def __eq__(self, other: object) -> bool:
  320. if not isinstance(other, AccessDescription):
  321. return NotImplemented
  322. return (
  323. self.access_method == other.access_method
  324. and self.access_location == other.access_location
  325. )
  326. def __hash__(self) -> int:
  327. return hash((self.access_method, self.access_location))
  328. @property
  329. def access_method(self) -> ObjectIdentifier:
  330. return self._access_method
  331. @property
  332. def access_location(self) -> GeneralName:
  333. return self._access_location
  334. class BasicConstraints(ExtensionType):
  335. oid = ExtensionOID.BASIC_CONSTRAINTS
  336. def __init__(self, ca: bool, path_length: typing.Optional[int]) -> None:
  337. if not isinstance(ca, bool):
  338. raise TypeError("ca must be a boolean value")
  339. if path_length is not None and not ca:
  340. raise ValueError("path_length must be None when ca is False")
  341. if path_length is not None and (
  342. not isinstance(path_length, int) or path_length < 0
  343. ):
  344. raise TypeError(
  345. "path_length must be a non-negative integer or None"
  346. )
  347. self._ca = ca
  348. self._path_length = path_length
  349. @property
  350. def ca(self) -> bool:
  351. return self._ca
  352. @property
  353. def path_length(self) -> typing.Optional[int]:
  354. return self._path_length
  355. def __repr__(self) -> str:
  356. return (
  357. "<BasicConstraints(ca={0.ca}, " "path_length={0.path_length})>"
  358. ).format(self)
  359. def __eq__(self, other: object) -> bool:
  360. if not isinstance(other, BasicConstraints):
  361. return NotImplemented
  362. return self.ca == other.ca and self.path_length == other.path_length
  363. def __hash__(self) -> int:
  364. return hash((self.ca, self.path_length))
  365. def public_bytes(self) -> bytes:
  366. return rust_x509.encode_extension_value(self)
  367. class DeltaCRLIndicator(ExtensionType):
  368. oid = ExtensionOID.DELTA_CRL_INDICATOR
  369. def __init__(self, crl_number: int) -> None:
  370. if not isinstance(crl_number, int):
  371. raise TypeError("crl_number must be an integer")
  372. self._crl_number = crl_number
  373. @property
  374. def crl_number(self) -> int:
  375. return self._crl_number
  376. def __eq__(self, other: object) -> bool:
  377. if not isinstance(other, DeltaCRLIndicator):
  378. return NotImplemented
  379. return self.crl_number == other.crl_number
  380. def __hash__(self) -> int:
  381. return hash(self.crl_number)
  382. def __repr__(self) -> str:
  383. return f"<DeltaCRLIndicator(crl_number={self.crl_number})>"
  384. def public_bytes(self) -> bytes:
  385. return rust_x509.encode_extension_value(self)
  386. class CRLDistributionPoints(ExtensionType):
  387. oid = ExtensionOID.CRL_DISTRIBUTION_POINTS
  388. def __init__(
  389. self, distribution_points: typing.Iterable[DistributionPoint]
  390. ) -> None:
  391. distribution_points = list(distribution_points)
  392. if not all(
  393. isinstance(x, DistributionPoint) for x in distribution_points
  394. ):
  395. raise TypeError(
  396. "distribution_points must be a list of DistributionPoint "
  397. "objects"
  398. )
  399. self._distribution_points = distribution_points
  400. __len__, __iter__, __getitem__ = _make_sequence_methods(
  401. "_distribution_points"
  402. )
  403. def __repr__(self) -> str:
  404. return f"<CRLDistributionPoints({self._distribution_points})>"
  405. def __eq__(self, other: object) -> bool:
  406. if not isinstance(other, CRLDistributionPoints):
  407. return NotImplemented
  408. return self._distribution_points == other._distribution_points
  409. def __hash__(self) -> int:
  410. return hash(tuple(self._distribution_points))
  411. def public_bytes(self) -> bytes:
  412. return rust_x509.encode_extension_value(self)
  413. class FreshestCRL(ExtensionType):
  414. oid = ExtensionOID.FRESHEST_CRL
  415. def __init__(
  416. self, distribution_points: typing.Iterable[DistributionPoint]
  417. ) -> None:
  418. distribution_points = list(distribution_points)
  419. if not all(
  420. isinstance(x, DistributionPoint) for x in distribution_points
  421. ):
  422. raise TypeError(
  423. "distribution_points must be a list of DistributionPoint "
  424. "objects"
  425. )
  426. self._distribution_points = distribution_points
  427. __len__, __iter__, __getitem__ = _make_sequence_methods(
  428. "_distribution_points"
  429. )
  430. def __repr__(self) -> str:
  431. return f"<FreshestCRL({self._distribution_points})>"
  432. def __eq__(self, other: object) -> bool:
  433. if not isinstance(other, FreshestCRL):
  434. return NotImplemented
  435. return self._distribution_points == other._distribution_points
  436. def __hash__(self) -> int:
  437. return hash(tuple(self._distribution_points))
  438. def public_bytes(self) -> bytes:
  439. return rust_x509.encode_extension_value(self)
  440. class DistributionPoint:
  441. def __init__(
  442. self,
  443. full_name: typing.Optional[typing.Iterable[GeneralName]],
  444. relative_name: typing.Optional[RelativeDistinguishedName],
  445. reasons: typing.Optional[typing.FrozenSet[ReasonFlags]],
  446. crl_issuer: typing.Optional[typing.Iterable[GeneralName]],
  447. ) -> None:
  448. if full_name and relative_name:
  449. raise ValueError(
  450. "You cannot provide both full_name and relative_name, at "
  451. "least one must be None."
  452. )
  453. if not full_name and not relative_name and not crl_issuer:
  454. raise ValueError(
  455. "Either full_name, relative_name or crl_issuer must be "
  456. "provided."
  457. )
  458. if full_name is not None:
  459. full_name = list(full_name)
  460. if not all(isinstance(x, GeneralName) for x in full_name):
  461. raise TypeError(
  462. "full_name must be a list of GeneralName objects"
  463. )
  464. if relative_name:
  465. if not isinstance(relative_name, RelativeDistinguishedName):
  466. raise TypeError(
  467. "relative_name must be a RelativeDistinguishedName"
  468. )
  469. if crl_issuer is not None:
  470. crl_issuer = list(crl_issuer)
  471. if not all(isinstance(x, GeneralName) for x in crl_issuer):
  472. raise TypeError(
  473. "crl_issuer must be None or a list of general names"
  474. )
  475. if reasons and (
  476. not isinstance(reasons, frozenset)
  477. or not all(isinstance(x, ReasonFlags) for x in reasons)
  478. ):
  479. raise TypeError("reasons must be None or frozenset of ReasonFlags")
  480. if reasons and (
  481. ReasonFlags.unspecified in reasons
  482. or ReasonFlags.remove_from_crl in reasons
  483. ):
  484. raise ValueError(
  485. "unspecified and remove_from_crl are not valid reasons in a "
  486. "DistributionPoint"
  487. )
  488. self._full_name = full_name
  489. self._relative_name = relative_name
  490. self._reasons = reasons
  491. self._crl_issuer = crl_issuer
  492. def __repr__(self) -> str:
  493. return (
  494. "<DistributionPoint(full_name={0.full_name}, relative_name={0.rela"
  495. "tive_name}, reasons={0.reasons}, "
  496. "crl_issuer={0.crl_issuer})>".format(self)
  497. )
  498. def __eq__(self, other: object) -> bool:
  499. if not isinstance(other, DistributionPoint):
  500. return NotImplemented
  501. return (
  502. self.full_name == other.full_name
  503. and self.relative_name == other.relative_name
  504. and self.reasons == other.reasons
  505. and self.crl_issuer == other.crl_issuer
  506. )
  507. def __hash__(self) -> int:
  508. if self.full_name is not None:
  509. fn: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple(
  510. self.full_name
  511. )
  512. else:
  513. fn = None
  514. if self.crl_issuer is not None:
  515. crl_issuer: typing.Optional[
  516. typing.Tuple[GeneralName, ...]
  517. ] = tuple(self.crl_issuer)
  518. else:
  519. crl_issuer = None
  520. return hash((fn, self.relative_name, self.reasons, crl_issuer))
  521. @property
  522. def full_name(self) -> typing.Optional[typing.List[GeneralName]]:
  523. return self._full_name
  524. @property
  525. def relative_name(self) -> typing.Optional[RelativeDistinguishedName]:
  526. return self._relative_name
  527. @property
  528. def reasons(self) -> typing.Optional[typing.FrozenSet[ReasonFlags]]:
  529. return self._reasons
  530. @property
  531. def crl_issuer(self) -> typing.Optional[typing.List[GeneralName]]:
  532. return self._crl_issuer
  533. class ReasonFlags(utils.Enum):
  534. unspecified = "unspecified"
  535. key_compromise = "keyCompromise"
  536. ca_compromise = "cACompromise"
  537. affiliation_changed = "affiliationChanged"
  538. superseded = "superseded"
  539. cessation_of_operation = "cessationOfOperation"
  540. certificate_hold = "certificateHold"
  541. privilege_withdrawn = "privilegeWithdrawn"
  542. aa_compromise = "aACompromise"
  543. remove_from_crl = "removeFromCRL"
  544. # These are distribution point bit string mappings. Not to be confused with
  545. # CRLReason reason flags bit string mappings.
  546. # ReasonFlags ::= BIT STRING {
  547. # unused (0),
  548. # keyCompromise (1),
  549. # cACompromise (2),
  550. # affiliationChanged (3),
  551. # superseded (4),
  552. # cessationOfOperation (5),
  553. # certificateHold (6),
  554. # privilegeWithdrawn (7),
  555. # aACompromise (8) }
  556. _REASON_BIT_MAPPING = {
  557. 1: ReasonFlags.key_compromise,
  558. 2: ReasonFlags.ca_compromise,
  559. 3: ReasonFlags.affiliation_changed,
  560. 4: ReasonFlags.superseded,
  561. 5: ReasonFlags.cessation_of_operation,
  562. 6: ReasonFlags.certificate_hold,
  563. 7: ReasonFlags.privilege_withdrawn,
  564. 8: ReasonFlags.aa_compromise,
  565. }
  566. _CRLREASONFLAGS = {
  567. ReasonFlags.key_compromise: 1,
  568. ReasonFlags.ca_compromise: 2,
  569. ReasonFlags.affiliation_changed: 3,
  570. ReasonFlags.superseded: 4,
  571. ReasonFlags.cessation_of_operation: 5,
  572. ReasonFlags.certificate_hold: 6,
  573. ReasonFlags.privilege_withdrawn: 7,
  574. ReasonFlags.aa_compromise: 8,
  575. }
  576. class PolicyConstraints(ExtensionType):
  577. oid = ExtensionOID.POLICY_CONSTRAINTS
  578. def __init__(
  579. self,
  580. require_explicit_policy: typing.Optional[int],
  581. inhibit_policy_mapping: typing.Optional[int],
  582. ) -> None:
  583. if require_explicit_policy is not None and not isinstance(
  584. require_explicit_policy, int
  585. ):
  586. raise TypeError(
  587. "require_explicit_policy must be a non-negative integer or "
  588. "None"
  589. )
  590. if inhibit_policy_mapping is not None and not isinstance(
  591. inhibit_policy_mapping, int
  592. ):
  593. raise TypeError(
  594. "inhibit_policy_mapping must be a non-negative integer or None"
  595. )
  596. if inhibit_policy_mapping is None and require_explicit_policy is None:
  597. raise ValueError(
  598. "At least one of require_explicit_policy and "
  599. "inhibit_policy_mapping must not be None"
  600. )
  601. self._require_explicit_policy = require_explicit_policy
  602. self._inhibit_policy_mapping = inhibit_policy_mapping
  603. def __repr__(self) -> str:
  604. return (
  605. "<PolicyConstraints(require_explicit_policy={0.require_explicit"
  606. "_policy}, inhibit_policy_mapping={0.inhibit_policy_"
  607. "mapping})>".format(self)
  608. )
  609. def __eq__(self, other: object) -> bool:
  610. if not isinstance(other, PolicyConstraints):
  611. return NotImplemented
  612. return (
  613. self.require_explicit_policy == other.require_explicit_policy
  614. and self.inhibit_policy_mapping == other.inhibit_policy_mapping
  615. )
  616. def __hash__(self) -> int:
  617. return hash(
  618. (self.require_explicit_policy, self.inhibit_policy_mapping)
  619. )
  620. @property
  621. def require_explicit_policy(self) -> typing.Optional[int]:
  622. return self._require_explicit_policy
  623. @property
  624. def inhibit_policy_mapping(self) -> typing.Optional[int]:
  625. return self._inhibit_policy_mapping
  626. def public_bytes(self) -> bytes:
  627. return rust_x509.encode_extension_value(self)
  628. class CertificatePolicies(ExtensionType):
  629. oid = ExtensionOID.CERTIFICATE_POLICIES
  630. def __init__(self, policies: typing.Iterable[PolicyInformation]) -> None:
  631. policies = list(policies)
  632. if not all(isinstance(x, PolicyInformation) for x in policies):
  633. raise TypeError(
  634. "Every item in the policies list must be a "
  635. "PolicyInformation"
  636. )
  637. self._policies = policies
  638. __len__, __iter__, __getitem__ = _make_sequence_methods("_policies")
  639. def __repr__(self) -> str:
  640. return f"<CertificatePolicies({self._policies})>"
  641. def __eq__(self, other: object) -> bool:
  642. if not isinstance(other, CertificatePolicies):
  643. return NotImplemented
  644. return self._policies == other._policies
  645. def __hash__(self) -> int:
  646. return hash(tuple(self._policies))
  647. def public_bytes(self) -> bytes:
  648. return rust_x509.encode_extension_value(self)
  649. class PolicyInformation:
  650. def __init__(
  651. self,
  652. policy_identifier: ObjectIdentifier,
  653. policy_qualifiers: typing.Optional[
  654. typing.Iterable[typing.Union[str, UserNotice]]
  655. ],
  656. ) -> None:
  657. if not isinstance(policy_identifier, ObjectIdentifier):
  658. raise TypeError("policy_identifier must be an ObjectIdentifier")
  659. self._policy_identifier = policy_identifier
  660. if policy_qualifiers is not None:
  661. policy_qualifiers = list(policy_qualifiers)
  662. if not all(
  663. isinstance(x, (str, UserNotice)) for x in policy_qualifiers
  664. ):
  665. raise TypeError(
  666. "policy_qualifiers must be a list of strings and/or "
  667. "UserNotice objects or None"
  668. )
  669. self._policy_qualifiers = policy_qualifiers
  670. def __repr__(self) -> str:
  671. return (
  672. "<PolicyInformation(policy_identifier={0.policy_identifier}, polic"
  673. "y_qualifiers={0.policy_qualifiers})>".format(self)
  674. )
  675. def __eq__(self, other: object) -> bool:
  676. if not isinstance(other, PolicyInformation):
  677. return NotImplemented
  678. return (
  679. self.policy_identifier == other.policy_identifier
  680. and self.policy_qualifiers == other.policy_qualifiers
  681. )
  682. def __hash__(self) -> int:
  683. if self.policy_qualifiers is not None:
  684. pq: typing.Optional[
  685. typing.Tuple[typing.Union[str, UserNotice], ...]
  686. ] = tuple(self.policy_qualifiers)
  687. else:
  688. pq = None
  689. return hash((self.policy_identifier, pq))
  690. @property
  691. def policy_identifier(self) -> ObjectIdentifier:
  692. return self._policy_identifier
  693. @property
  694. def policy_qualifiers(
  695. self,
  696. ) -> typing.Optional[typing.List[typing.Union[str, UserNotice]]]:
  697. return self._policy_qualifiers
  698. class UserNotice:
  699. def __init__(
  700. self,
  701. notice_reference: typing.Optional[NoticeReference],
  702. explicit_text: typing.Optional[str],
  703. ) -> None:
  704. if notice_reference and not isinstance(
  705. notice_reference, NoticeReference
  706. ):
  707. raise TypeError(
  708. "notice_reference must be None or a NoticeReference"
  709. )
  710. self._notice_reference = notice_reference
  711. self._explicit_text = explicit_text
  712. def __repr__(self) -> str:
  713. return (
  714. "<UserNotice(notice_reference={0.notice_reference}, explicit_text="
  715. "{0.explicit_text!r})>".format(self)
  716. )
  717. def __eq__(self, other: object) -> bool:
  718. if not isinstance(other, UserNotice):
  719. return NotImplemented
  720. return (
  721. self.notice_reference == other.notice_reference
  722. and self.explicit_text == other.explicit_text
  723. )
  724. def __hash__(self) -> int:
  725. return hash((self.notice_reference, self.explicit_text))
  726. @property
  727. def notice_reference(self) -> typing.Optional[NoticeReference]:
  728. return self._notice_reference
  729. @property
  730. def explicit_text(self) -> typing.Optional[str]:
  731. return self._explicit_text
  732. class NoticeReference:
  733. def __init__(
  734. self,
  735. organization: typing.Optional[str],
  736. notice_numbers: typing.Iterable[int],
  737. ) -> None:
  738. self._organization = organization
  739. notice_numbers = list(notice_numbers)
  740. if not all(isinstance(x, int) for x in notice_numbers):
  741. raise TypeError("notice_numbers must be a list of integers")
  742. self._notice_numbers = notice_numbers
  743. def __repr__(self) -> str:
  744. return (
  745. "<NoticeReference(organization={0.organization!r}, notice_numbers="
  746. "{0.notice_numbers})>".format(self)
  747. )
  748. def __eq__(self, other: object) -> bool:
  749. if not isinstance(other, NoticeReference):
  750. return NotImplemented
  751. return (
  752. self.organization == other.organization
  753. and self.notice_numbers == other.notice_numbers
  754. )
  755. def __hash__(self) -> int:
  756. return hash((self.organization, tuple(self.notice_numbers)))
  757. @property
  758. def organization(self) -> typing.Optional[str]:
  759. return self._organization
  760. @property
  761. def notice_numbers(self) -> typing.List[int]:
  762. return self._notice_numbers
  763. class ExtendedKeyUsage(ExtensionType):
  764. oid = ExtensionOID.EXTENDED_KEY_USAGE
  765. def __init__(self, usages: typing.Iterable[ObjectIdentifier]) -> None:
  766. usages = list(usages)
  767. if not all(isinstance(x, ObjectIdentifier) for x in usages):
  768. raise TypeError(
  769. "Every item in the usages list must be an ObjectIdentifier"
  770. )
  771. self._usages = usages
  772. __len__, __iter__, __getitem__ = _make_sequence_methods("_usages")
  773. def __repr__(self) -> str:
  774. return f"<ExtendedKeyUsage({self._usages})>"
  775. def __eq__(self, other: object) -> bool:
  776. if not isinstance(other, ExtendedKeyUsage):
  777. return NotImplemented
  778. return self._usages == other._usages
  779. def __hash__(self) -> int:
  780. return hash(tuple(self._usages))
  781. def public_bytes(self) -> bytes:
  782. return rust_x509.encode_extension_value(self)
  783. class OCSPNoCheck(ExtensionType):
  784. oid = ExtensionOID.OCSP_NO_CHECK
  785. def __eq__(self, other: object) -> bool:
  786. if not isinstance(other, OCSPNoCheck):
  787. return NotImplemented
  788. return True
  789. def __hash__(self) -> int:
  790. return hash(OCSPNoCheck)
  791. def __repr__(self) -> str:
  792. return "<OCSPNoCheck()>"
  793. def public_bytes(self) -> bytes:
  794. return rust_x509.encode_extension_value(self)
  795. class PrecertPoison(ExtensionType):
  796. oid = ExtensionOID.PRECERT_POISON
  797. def __eq__(self, other: object) -> bool:
  798. if not isinstance(other, PrecertPoison):
  799. return NotImplemented
  800. return True
  801. def __hash__(self) -> int:
  802. return hash(PrecertPoison)
  803. def __repr__(self) -> str:
  804. return "<PrecertPoison()>"
  805. def public_bytes(self) -> bytes:
  806. return rust_x509.encode_extension_value(self)
  807. class TLSFeature(ExtensionType):
  808. oid = ExtensionOID.TLS_FEATURE
  809. def __init__(self, features: typing.Iterable[TLSFeatureType]) -> None:
  810. features = list(features)
  811. if (
  812. not all(isinstance(x, TLSFeatureType) for x in features)
  813. or len(features) == 0
  814. ):
  815. raise TypeError(
  816. "features must be a list of elements from the TLSFeatureType "
  817. "enum"
  818. )
  819. self._features = features
  820. __len__, __iter__, __getitem__ = _make_sequence_methods("_features")
  821. def __repr__(self) -> str:
  822. return f"<TLSFeature(features={self._features})>"
  823. def __eq__(self, other: object) -> bool:
  824. if not isinstance(other, TLSFeature):
  825. return NotImplemented
  826. return self._features == other._features
  827. def __hash__(self) -> int:
  828. return hash(tuple(self._features))
  829. def public_bytes(self) -> bytes:
  830. return rust_x509.encode_extension_value(self)
  831. class TLSFeatureType(utils.Enum):
  832. # status_request is defined in RFC 6066 and is used for what is commonly
  833. # called OCSP Must-Staple when present in the TLS Feature extension in an
  834. # X.509 certificate.
  835. status_request = 5
  836. # status_request_v2 is defined in RFC 6961 and allows multiple OCSP
  837. # responses to be provided. It is not currently in use by clients or
  838. # servers.
  839. status_request_v2 = 17
  840. _TLS_FEATURE_TYPE_TO_ENUM = {x.value: x for x in TLSFeatureType}
  841. class InhibitAnyPolicy(ExtensionType):
  842. oid = ExtensionOID.INHIBIT_ANY_POLICY
  843. def __init__(self, skip_certs: int) -> None:
  844. if not isinstance(skip_certs, int):
  845. raise TypeError("skip_certs must be an integer")
  846. if skip_certs < 0:
  847. raise ValueError("skip_certs must be a non-negative integer")
  848. self._skip_certs = skip_certs
  849. def __repr__(self) -> str:
  850. return f"<InhibitAnyPolicy(skip_certs={self.skip_certs})>"
  851. def __eq__(self, other: object) -> bool:
  852. if not isinstance(other, InhibitAnyPolicy):
  853. return NotImplemented
  854. return self.skip_certs == other.skip_certs
  855. def __hash__(self) -> int:
  856. return hash(self.skip_certs)
  857. @property
  858. def skip_certs(self) -> int:
  859. return self._skip_certs
  860. def public_bytes(self) -> bytes:
  861. return rust_x509.encode_extension_value(self)
  862. class KeyUsage(ExtensionType):
  863. oid = ExtensionOID.KEY_USAGE
  864. def __init__(
  865. self,
  866. digital_signature: bool,
  867. content_commitment: bool,
  868. key_encipherment: bool,
  869. data_encipherment: bool,
  870. key_agreement: bool,
  871. key_cert_sign: bool,
  872. crl_sign: bool,
  873. encipher_only: bool,
  874. decipher_only: bool,
  875. ) -> None:
  876. if not key_agreement and (encipher_only or decipher_only):
  877. raise ValueError(
  878. "encipher_only and decipher_only can only be true when "
  879. "key_agreement is true"
  880. )
  881. self._digital_signature = digital_signature
  882. self._content_commitment = content_commitment
  883. self._key_encipherment = key_encipherment
  884. self._data_encipherment = data_encipherment
  885. self._key_agreement = key_agreement
  886. self._key_cert_sign = key_cert_sign
  887. self._crl_sign = crl_sign
  888. self._encipher_only = encipher_only
  889. self._decipher_only = decipher_only
  890. @property
  891. def digital_signature(self) -> bool:
  892. return self._digital_signature
  893. @property
  894. def content_commitment(self) -> bool:
  895. return self._content_commitment
  896. @property
  897. def key_encipherment(self) -> bool:
  898. return self._key_encipherment
  899. @property
  900. def data_encipherment(self) -> bool:
  901. return self._data_encipherment
  902. @property
  903. def key_agreement(self) -> bool:
  904. return self._key_agreement
  905. @property
  906. def key_cert_sign(self) -> bool:
  907. return self._key_cert_sign
  908. @property
  909. def crl_sign(self) -> bool:
  910. return self._crl_sign
  911. @property
  912. def encipher_only(self) -> bool:
  913. if not self.key_agreement:
  914. raise ValueError(
  915. "encipher_only is undefined unless key_agreement is true"
  916. )
  917. else:
  918. return self._encipher_only
  919. @property
  920. def decipher_only(self) -> bool:
  921. if not self.key_agreement:
  922. raise ValueError(
  923. "decipher_only is undefined unless key_agreement is true"
  924. )
  925. else:
  926. return self._decipher_only
  927. def __repr__(self) -> str:
  928. try:
  929. encipher_only = self.encipher_only
  930. decipher_only = self.decipher_only
  931. except ValueError:
  932. # Users found None confusing because even though encipher/decipher
  933. # have no meaning unless key_agreement is true, to construct an
  934. # instance of the class you still need to pass False.
  935. encipher_only = False
  936. decipher_only = False
  937. return (
  938. "<KeyUsage(digital_signature={0.digital_signature}, "
  939. "content_commitment={0.content_commitment}, "
  940. "key_encipherment={0.key_encipherment}, "
  941. "data_encipherment={0.data_encipherment}, "
  942. "key_agreement={0.key_agreement}, "
  943. "key_cert_sign={0.key_cert_sign}, crl_sign={0.crl_sign}, "
  944. "encipher_only={1}, decipher_only={2})>"
  945. ).format(self, encipher_only, decipher_only)
  946. def __eq__(self, other: object) -> bool:
  947. if not isinstance(other, KeyUsage):
  948. return NotImplemented
  949. return (
  950. self.digital_signature == other.digital_signature
  951. and self.content_commitment == other.content_commitment
  952. and self.key_encipherment == other.key_encipherment
  953. and self.data_encipherment == other.data_encipherment
  954. and self.key_agreement == other.key_agreement
  955. and self.key_cert_sign == other.key_cert_sign
  956. and self.crl_sign == other.crl_sign
  957. and self._encipher_only == other._encipher_only
  958. and self._decipher_only == other._decipher_only
  959. )
  960. def __hash__(self) -> int:
  961. return hash(
  962. (
  963. self.digital_signature,
  964. self.content_commitment,
  965. self.key_encipherment,
  966. self.data_encipherment,
  967. self.key_agreement,
  968. self.key_cert_sign,
  969. self.crl_sign,
  970. self._encipher_only,
  971. self._decipher_only,
  972. )
  973. )
  974. def public_bytes(self) -> bytes:
  975. return rust_x509.encode_extension_value(self)
  976. class NameConstraints(ExtensionType):
  977. oid = ExtensionOID.NAME_CONSTRAINTS
  978. def __init__(
  979. self,
  980. permitted_subtrees: typing.Optional[typing.Iterable[GeneralName]],
  981. excluded_subtrees: typing.Optional[typing.Iterable[GeneralName]],
  982. ) -> None:
  983. if permitted_subtrees is not None:
  984. permitted_subtrees = list(permitted_subtrees)
  985. if not permitted_subtrees:
  986. raise ValueError(
  987. "permitted_subtrees must be a non-empty list or None"
  988. )
  989. if not all(isinstance(x, GeneralName) for x in permitted_subtrees):
  990. raise TypeError(
  991. "permitted_subtrees must be a list of GeneralName objects "
  992. "or None"
  993. )
  994. self._validate_tree(permitted_subtrees)
  995. if excluded_subtrees is not None:
  996. excluded_subtrees = list(excluded_subtrees)
  997. if not excluded_subtrees:
  998. raise ValueError(
  999. "excluded_subtrees must be a non-empty list or None"
  1000. )
  1001. if not all(isinstance(x, GeneralName) for x in excluded_subtrees):
  1002. raise TypeError(
  1003. "excluded_subtrees must be a list of GeneralName objects "
  1004. "or None"
  1005. )
  1006. self._validate_tree(excluded_subtrees)
  1007. if permitted_subtrees is None and excluded_subtrees is None:
  1008. raise ValueError(
  1009. "At least one of permitted_subtrees and excluded_subtrees "
  1010. "must not be None"
  1011. )
  1012. self._permitted_subtrees = permitted_subtrees
  1013. self._excluded_subtrees = excluded_subtrees
  1014. def __eq__(self, other: object) -> bool:
  1015. if not isinstance(other, NameConstraints):
  1016. return NotImplemented
  1017. return (
  1018. self.excluded_subtrees == other.excluded_subtrees
  1019. and self.permitted_subtrees == other.permitted_subtrees
  1020. )
  1021. def _validate_tree(self, tree: typing.Iterable[GeneralName]) -> None:
  1022. self._validate_ip_name(tree)
  1023. self._validate_dns_name(tree)
  1024. def _validate_ip_name(self, tree: typing.Iterable[GeneralName]) -> None:
  1025. if any(
  1026. isinstance(name, IPAddress)
  1027. and not isinstance(
  1028. name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network)
  1029. )
  1030. for name in tree
  1031. ):
  1032. raise TypeError(
  1033. "IPAddress name constraints must be an IPv4Network or"
  1034. " IPv6Network object"
  1035. )
  1036. def _validate_dns_name(self, tree: typing.Iterable[GeneralName]) -> None:
  1037. if any(
  1038. isinstance(name, DNSName) and "*" in name.value for name in tree
  1039. ):
  1040. raise ValueError(
  1041. "DNSName name constraints must not contain the '*' wildcard"
  1042. " character"
  1043. )
  1044. def __repr__(self) -> str:
  1045. return (
  1046. "<NameConstraints(permitted_subtrees={0.permitted_subtrees}, "
  1047. "excluded_subtrees={0.excluded_subtrees})>".format(self)
  1048. )
  1049. def __hash__(self) -> int:
  1050. if self.permitted_subtrees is not None:
  1051. ps: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple(
  1052. self.permitted_subtrees
  1053. )
  1054. else:
  1055. ps = None
  1056. if self.excluded_subtrees is not None:
  1057. es: typing.Optional[typing.Tuple[GeneralName, ...]] = tuple(
  1058. self.excluded_subtrees
  1059. )
  1060. else:
  1061. es = None
  1062. return hash((ps, es))
  1063. @property
  1064. def permitted_subtrees(
  1065. self,
  1066. ) -> typing.Optional[typing.List[GeneralName]]:
  1067. return self._permitted_subtrees
  1068. @property
  1069. def excluded_subtrees(
  1070. self,
  1071. ) -> typing.Optional[typing.List[GeneralName]]:
  1072. return self._excluded_subtrees
  1073. def public_bytes(self) -> bytes:
  1074. return rust_x509.encode_extension_value(self)
  1075. class Extension(typing.Generic[ExtensionTypeVar]):
  1076. def __init__(
  1077. self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar
  1078. ) -> None:
  1079. if not isinstance(oid, ObjectIdentifier):
  1080. raise TypeError(
  1081. "oid argument must be an ObjectIdentifier instance."
  1082. )
  1083. if not isinstance(critical, bool):
  1084. raise TypeError("critical must be a boolean value")
  1085. self._oid = oid
  1086. self._critical = critical
  1087. self._value = value
  1088. @property
  1089. def oid(self) -> ObjectIdentifier:
  1090. return self._oid
  1091. @property
  1092. def critical(self) -> bool:
  1093. return self._critical
  1094. @property
  1095. def value(self) -> ExtensionTypeVar:
  1096. return self._value
  1097. def __repr__(self) -> str:
  1098. return (
  1099. "<Extension(oid={0.oid}, critical={0.critical}, "
  1100. "value={0.value})>"
  1101. ).format(self)
  1102. def __eq__(self, other: object) -> bool:
  1103. if not isinstance(other, Extension):
  1104. return NotImplemented
  1105. return (
  1106. self.oid == other.oid
  1107. and self.critical == other.critical
  1108. and self.value == other.value
  1109. )
  1110. def __hash__(self) -> int:
  1111. return hash((self.oid, self.critical, self.value))
  1112. class GeneralNames:
  1113. def __init__(self, general_names: typing.Iterable[GeneralName]) -> None:
  1114. general_names = list(general_names)
  1115. if not all(isinstance(x, GeneralName) for x in general_names):
  1116. raise TypeError(
  1117. "Every item in the general_names list must be an "
  1118. "object conforming to the GeneralName interface"
  1119. )
  1120. self._general_names = general_names
  1121. __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names")
  1122. @typing.overload
  1123. def get_values_for_type(
  1124. self,
  1125. type: typing.Union[
  1126. typing.Type[DNSName],
  1127. typing.Type[UniformResourceIdentifier],
  1128. typing.Type[RFC822Name],
  1129. ],
  1130. ) -> typing.List[str]:
  1131. ...
  1132. @typing.overload
  1133. def get_values_for_type(
  1134. self,
  1135. type: typing.Type[DirectoryName],
  1136. ) -> typing.List[Name]:
  1137. ...
  1138. @typing.overload
  1139. def get_values_for_type(
  1140. self,
  1141. type: typing.Type[RegisteredID],
  1142. ) -> typing.List[ObjectIdentifier]:
  1143. ...
  1144. @typing.overload
  1145. def get_values_for_type(
  1146. self, type: typing.Type[IPAddress]
  1147. ) -> typing.List[_IPAddressTypes]:
  1148. ...
  1149. @typing.overload
  1150. def get_values_for_type(
  1151. self, type: typing.Type[OtherName]
  1152. ) -> typing.List[OtherName]:
  1153. ...
  1154. def get_values_for_type(
  1155. self,
  1156. type: typing.Union[
  1157. typing.Type[DNSName],
  1158. typing.Type[DirectoryName],
  1159. typing.Type[IPAddress],
  1160. typing.Type[OtherName],
  1161. typing.Type[RFC822Name],
  1162. typing.Type[RegisteredID],
  1163. typing.Type[UniformResourceIdentifier],
  1164. ],
  1165. ) -> typing.Union[
  1166. typing.List[_IPAddressTypes],
  1167. typing.List[str],
  1168. typing.List[OtherName],
  1169. typing.List[Name],
  1170. typing.List[ObjectIdentifier],
  1171. ]:
  1172. # Return the value of each GeneralName, except for OtherName instances
  1173. # which we return directly because it has two important properties not
  1174. # just one value.
  1175. objs = (i for i in self if isinstance(i, type))
  1176. if type != OtherName:
  1177. return [i.value for i in objs]
  1178. return list(objs)
  1179. def __repr__(self) -> str:
  1180. return f"<GeneralNames({self._general_names})>"
  1181. def __eq__(self, other: object) -> bool:
  1182. if not isinstance(other, GeneralNames):
  1183. return NotImplemented
  1184. return self._general_names == other._general_names
  1185. def __hash__(self) -> int:
  1186. return hash(tuple(self._general_names))
  1187. class SubjectAlternativeName(ExtensionType):
  1188. oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME
  1189. def __init__(self, general_names: typing.Iterable[GeneralName]) -> None:
  1190. self._general_names = GeneralNames(general_names)
  1191. __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names")
  1192. @typing.overload
  1193. def get_values_for_type(
  1194. self,
  1195. type: typing.Union[
  1196. typing.Type[DNSName],
  1197. typing.Type[UniformResourceIdentifier],
  1198. typing.Type[RFC822Name],
  1199. ],
  1200. ) -> typing.List[str]:
  1201. ...
  1202. @typing.overload
  1203. def get_values_for_type(
  1204. self,
  1205. type: typing.Type[DirectoryName],
  1206. ) -> typing.List[Name]:
  1207. ...
  1208. @typing.overload
  1209. def get_values_for_type(
  1210. self,
  1211. type: typing.Type[RegisteredID],
  1212. ) -> typing.List[ObjectIdentifier]:
  1213. ...
  1214. @typing.overload
  1215. def get_values_for_type(
  1216. self, type: typing.Type[IPAddress]
  1217. ) -> typing.List[_IPAddressTypes]:
  1218. ...
  1219. @typing.overload
  1220. def get_values_for_type(
  1221. self, type: typing.Type[OtherName]
  1222. ) -> typing.List[OtherName]:
  1223. ...
  1224. def get_values_for_type(
  1225. self,
  1226. type: typing.Union[
  1227. typing.Type[DNSName],
  1228. typing.Type[DirectoryName],
  1229. typing.Type[IPAddress],
  1230. typing.Type[OtherName],
  1231. typing.Type[RFC822Name],
  1232. typing.Type[RegisteredID],
  1233. typing.Type[UniformResourceIdentifier],
  1234. ],
  1235. ) -> typing.Union[
  1236. typing.List[_IPAddressTypes],
  1237. typing.List[str],
  1238. typing.List[OtherName],
  1239. typing.List[Name],
  1240. typing.List[ObjectIdentifier],
  1241. ]:
  1242. return self._general_names.get_values_for_type(type)
  1243. def __repr__(self) -> str:
  1244. return f"<SubjectAlternativeName({self._general_names})>"
  1245. def __eq__(self, other: object) -> bool:
  1246. if not isinstance(other, SubjectAlternativeName):
  1247. return NotImplemented
  1248. return self._general_names == other._general_names
  1249. def __hash__(self) -> int:
  1250. return hash(self._general_names)
  1251. def public_bytes(self) -> bytes:
  1252. return rust_x509.encode_extension_value(self)
  1253. class IssuerAlternativeName(ExtensionType):
  1254. oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME
  1255. def __init__(self, general_names: typing.Iterable[GeneralName]) -> None:
  1256. self._general_names = GeneralNames(general_names)
  1257. __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names")
  1258. @typing.overload
  1259. def get_values_for_type(
  1260. self,
  1261. type: typing.Union[
  1262. typing.Type[DNSName],
  1263. typing.Type[UniformResourceIdentifier],
  1264. typing.Type[RFC822Name],
  1265. ],
  1266. ) -> typing.List[str]:
  1267. ...
  1268. @typing.overload
  1269. def get_values_for_type(
  1270. self,
  1271. type: typing.Type[DirectoryName],
  1272. ) -> typing.List[Name]:
  1273. ...
  1274. @typing.overload
  1275. def get_values_for_type(
  1276. self,
  1277. type: typing.Type[RegisteredID],
  1278. ) -> typing.List[ObjectIdentifier]:
  1279. ...
  1280. @typing.overload
  1281. def get_values_for_type(
  1282. self, type: typing.Type[IPAddress]
  1283. ) -> typing.List[_IPAddressTypes]:
  1284. ...
  1285. @typing.overload
  1286. def get_values_for_type(
  1287. self, type: typing.Type[OtherName]
  1288. ) -> typing.List[OtherName]:
  1289. ...
  1290. def get_values_for_type(
  1291. self,
  1292. type: typing.Union[
  1293. typing.Type[DNSName],
  1294. typing.Type[DirectoryName],
  1295. typing.Type[IPAddress],
  1296. typing.Type[OtherName],
  1297. typing.Type[RFC822Name],
  1298. typing.Type[RegisteredID],
  1299. typing.Type[UniformResourceIdentifier],
  1300. ],
  1301. ) -> typing.Union[
  1302. typing.List[_IPAddressTypes],
  1303. typing.List[str],
  1304. typing.List[OtherName],
  1305. typing.List[Name],
  1306. typing.List[ObjectIdentifier],
  1307. ]:
  1308. return self._general_names.get_values_for_type(type)
  1309. def __repr__(self) -> str:
  1310. return f"<IssuerAlternativeName({self._general_names})>"
  1311. def __eq__(self, other: object) -> bool:
  1312. if not isinstance(other, IssuerAlternativeName):
  1313. return NotImplemented
  1314. return self._general_names == other._general_names
  1315. def __hash__(self) -> int:
  1316. return hash(self._general_names)
  1317. def public_bytes(self) -> bytes:
  1318. return rust_x509.encode_extension_value(self)
  1319. class CertificateIssuer(ExtensionType):
  1320. oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER
  1321. def __init__(self, general_names: typing.Iterable[GeneralName]) -> None:
  1322. self._general_names = GeneralNames(general_names)
  1323. __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names")
  1324. @typing.overload
  1325. def get_values_for_type(
  1326. self,
  1327. type: typing.Union[
  1328. typing.Type[DNSName],
  1329. typing.Type[UniformResourceIdentifier],
  1330. typing.Type[RFC822Name],
  1331. ],
  1332. ) -> typing.List[str]:
  1333. ...
  1334. @typing.overload
  1335. def get_values_for_type(
  1336. self,
  1337. type: typing.Type[DirectoryName],
  1338. ) -> typing.List[Name]:
  1339. ...
  1340. @typing.overload
  1341. def get_values_for_type(
  1342. self,
  1343. type: typing.Type[RegisteredID],
  1344. ) -> typing.List[ObjectIdentifier]:
  1345. ...
  1346. @typing.overload
  1347. def get_values_for_type(
  1348. self, type: typing.Type[IPAddress]
  1349. ) -> typing.List[_IPAddressTypes]:
  1350. ...
  1351. @typing.overload
  1352. def get_values_for_type(
  1353. self, type: typing.Type[OtherName]
  1354. ) -> typing.List[OtherName]:
  1355. ...
  1356. def get_values_for_type(
  1357. self,
  1358. type: typing.Union[
  1359. typing.Type[DNSName],
  1360. typing.Type[DirectoryName],
  1361. typing.Type[IPAddress],
  1362. typing.Type[OtherName],
  1363. typing.Type[RFC822Name],
  1364. typing.Type[RegisteredID],
  1365. typing.Type[UniformResourceIdentifier],
  1366. ],
  1367. ) -> typing.Union[
  1368. typing.List[_IPAddressTypes],
  1369. typing.List[str],
  1370. typing.List[OtherName],
  1371. typing.List[Name],
  1372. typing.List[ObjectIdentifier],
  1373. ]:
  1374. return self._general_names.get_values_for_type(type)
  1375. def __repr__(self) -> str:
  1376. return f"<CertificateIssuer({self._general_names})>"
  1377. def __eq__(self, other: object) -> bool:
  1378. if not isinstance(other, CertificateIssuer):
  1379. return NotImplemented
  1380. return self._general_names == other._general_names
  1381. def __hash__(self) -> int:
  1382. return hash(self._general_names)
  1383. def public_bytes(self) -> bytes:
  1384. return rust_x509.encode_extension_value(self)
  1385. class CRLReason(ExtensionType):
  1386. oid = CRLEntryExtensionOID.CRL_REASON
  1387. def __init__(self, reason: ReasonFlags) -> None:
  1388. if not isinstance(reason, ReasonFlags):
  1389. raise TypeError("reason must be an element from ReasonFlags")
  1390. self._reason = reason
  1391. def __repr__(self) -> str:
  1392. return f"<CRLReason(reason={self._reason})>"
  1393. def __eq__(self, other: object) -> bool:
  1394. if not isinstance(other, CRLReason):
  1395. return NotImplemented
  1396. return self.reason == other.reason
  1397. def __hash__(self) -> int:
  1398. return hash(self.reason)
  1399. @property
  1400. def reason(self) -> ReasonFlags:
  1401. return self._reason
  1402. def public_bytes(self) -> bytes:
  1403. return rust_x509.encode_extension_value(self)
  1404. class InvalidityDate(ExtensionType):
  1405. oid = CRLEntryExtensionOID.INVALIDITY_DATE
  1406. def __init__(self, invalidity_date: datetime.datetime) -> None:
  1407. if not isinstance(invalidity_date, datetime.datetime):
  1408. raise TypeError("invalidity_date must be a datetime.datetime")
  1409. self._invalidity_date = invalidity_date
  1410. def __repr__(self) -> str:
  1411. return "<InvalidityDate(invalidity_date={})>".format(
  1412. self._invalidity_date
  1413. )
  1414. def __eq__(self, other: object) -> bool:
  1415. if not isinstance(other, InvalidityDate):
  1416. return NotImplemented
  1417. return self.invalidity_date == other.invalidity_date
  1418. def __hash__(self) -> int:
  1419. return hash(self.invalidity_date)
  1420. @property
  1421. def invalidity_date(self) -> datetime.datetime:
  1422. return self._invalidity_date
  1423. def public_bytes(self) -> bytes:
  1424. return rust_x509.encode_extension_value(self)
  1425. class PrecertificateSignedCertificateTimestamps(ExtensionType):
  1426. oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS
  1427. def __init__(
  1428. self,
  1429. signed_certificate_timestamps: typing.Iterable[
  1430. SignedCertificateTimestamp
  1431. ],
  1432. ) -> None:
  1433. signed_certificate_timestamps = list(signed_certificate_timestamps)
  1434. if not all(
  1435. isinstance(sct, SignedCertificateTimestamp)
  1436. for sct in signed_certificate_timestamps
  1437. ):
  1438. raise TypeError(
  1439. "Every item in the signed_certificate_timestamps list must be "
  1440. "a SignedCertificateTimestamp"
  1441. )
  1442. self._signed_certificate_timestamps = signed_certificate_timestamps
  1443. __len__, __iter__, __getitem__ = _make_sequence_methods(
  1444. "_signed_certificate_timestamps"
  1445. )
  1446. def __repr__(self) -> str:
  1447. return "<PrecertificateSignedCertificateTimestamps({})>".format(
  1448. list(self)
  1449. )
  1450. def __hash__(self) -> int:
  1451. return hash(tuple(self._signed_certificate_timestamps))
  1452. def __eq__(self, other: object) -> bool:
  1453. if not isinstance(other, PrecertificateSignedCertificateTimestamps):
  1454. return NotImplemented
  1455. return (
  1456. self._signed_certificate_timestamps
  1457. == other._signed_certificate_timestamps
  1458. )
  1459. def public_bytes(self) -> bytes:
  1460. return rust_x509.encode_extension_value(self)
  1461. class SignedCertificateTimestamps(ExtensionType):
  1462. oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS
  1463. def __init__(
  1464. self,
  1465. signed_certificate_timestamps: typing.Iterable[
  1466. SignedCertificateTimestamp
  1467. ],
  1468. ) -> None:
  1469. signed_certificate_timestamps = list(signed_certificate_timestamps)
  1470. if not all(
  1471. isinstance(sct, SignedCertificateTimestamp)
  1472. for sct in signed_certificate_timestamps
  1473. ):
  1474. raise TypeError(
  1475. "Every item in the signed_certificate_timestamps list must be "
  1476. "a SignedCertificateTimestamp"
  1477. )
  1478. self._signed_certificate_timestamps = signed_certificate_timestamps
  1479. __len__, __iter__, __getitem__ = _make_sequence_methods(
  1480. "_signed_certificate_timestamps"
  1481. )
  1482. def __repr__(self) -> str:
  1483. return f"<SignedCertificateTimestamps({list(self)})>"
  1484. def __hash__(self) -> int:
  1485. return hash(tuple(self._signed_certificate_timestamps))
  1486. def __eq__(self, other: object) -> bool:
  1487. if not isinstance(other, SignedCertificateTimestamps):
  1488. return NotImplemented
  1489. return (
  1490. self._signed_certificate_timestamps
  1491. == other._signed_certificate_timestamps
  1492. )
  1493. def public_bytes(self) -> bytes:
  1494. return rust_x509.encode_extension_value(self)
  1495. class OCSPNonce(ExtensionType):
  1496. oid = OCSPExtensionOID.NONCE
  1497. def __init__(self, nonce: bytes) -> None:
  1498. if not isinstance(nonce, bytes):
  1499. raise TypeError("nonce must be bytes")
  1500. self._nonce = nonce
  1501. def __eq__(self, other: object) -> bool:
  1502. if not isinstance(other, OCSPNonce):
  1503. return NotImplemented
  1504. return self.nonce == other.nonce
  1505. def __hash__(self) -> int:
  1506. return hash(self.nonce)
  1507. def __repr__(self) -> str:
  1508. return f"<OCSPNonce(nonce={self.nonce!r})>"
  1509. @property
  1510. def nonce(self) -> bytes:
  1511. return self._nonce
  1512. def public_bytes(self) -> bytes:
  1513. return rust_x509.encode_extension_value(self)
  1514. class OCSPAcceptableResponses(ExtensionType):
  1515. oid = OCSPExtensionOID.ACCEPTABLE_RESPONSES
  1516. def __init__(self, responses: typing.Iterable[ObjectIdentifier]) -> None:
  1517. responses = list(responses)
  1518. if any(not isinstance(r, ObjectIdentifier) for r in responses):
  1519. raise TypeError("All responses must be ObjectIdentifiers")
  1520. self._responses = responses
  1521. def __eq__(self, other: object) -> bool:
  1522. if not isinstance(other, OCSPAcceptableResponses):
  1523. return NotImplemented
  1524. return self._responses == other._responses
  1525. def __hash__(self) -> int:
  1526. return hash(tuple(self._responses))
  1527. def __repr__(self) -> str:
  1528. return f"<OCSPAcceptableResponses(responses={self._responses})>"
  1529. def __iter__(self) -> typing.Iterator[ObjectIdentifier]:
  1530. return iter(self._responses)
  1531. def public_bytes(self) -> bytes:
  1532. return rust_x509.encode_extension_value(self)
  1533. class IssuingDistributionPoint(ExtensionType):
  1534. oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT
  1535. def __init__(
  1536. self,
  1537. full_name: typing.Optional[typing.Iterable[GeneralName]],
  1538. relative_name: typing.Optional[RelativeDistinguishedName],
  1539. only_contains_user_certs: bool,
  1540. only_contains_ca_certs: bool,
  1541. only_some_reasons: typing.Optional[typing.FrozenSet[ReasonFlags]],
  1542. indirect_crl: bool,
  1543. only_contains_attribute_certs: bool,
  1544. ) -> None:
  1545. if full_name is not None:
  1546. full_name = list(full_name)
  1547. if only_some_reasons and (
  1548. not isinstance(only_some_reasons, frozenset)
  1549. or not all(isinstance(x, ReasonFlags) for x in only_some_reasons)
  1550. ):
  1551. raise TypeError(
  1552. "only_some_reasons must be None or frozenset of ReasonFlags"
  1553. )
  1554. if only_some_reasons and (
  1555. ReasonFlags.unspecified in only_some_reasons
  1556. or ReasonFlags.remove_from_crl in only_some_reasons
  1557. ):
  1558. raise ValueError(
  1559. "unspecified and remove_from_crl are not valid reasons in an "
  1560. "IssuingDistributionPoint"
  1561. )
  1562. if not (
  1563. isinstance(only_contains_user_certs, bool)
  1564. and isinstance(only_contains_ca_certs, bool)
  1565. and isinstance(indirect_crl, bool)
  1566. and isinstance(only_contains_attribute_certs, bool)
  1567. ):
  1568. raise TypeError(
  1569. "only_contains_user_certs, only_contains_ca_certs, "
  1570. "indirect_crl and only_contains_attribute_certs "
  1571. "must all be boolean."
  1572. )
  1573. crl_constraints = [
  1574. only_contains_user_certs,
  1575. only_contains_ca_certs,
  1576. indirect_crl,
  1577. only_contains_attribute_certs,
  1578. ]
  1579. if len([x for x in crl_constraints if x]) > 1:
  1580. raise ValueError(
  1581. "Only one of the following can be set to True: "
  1582. "only_contains_user_certs, only_contains_ca_certs, "
  1583. "indirect_crl, only_contains_attribute_certs"
  1584. )
  1585. if not any(
  1586. [
  1587. only_contains_user_certs,
  1588. only_contains_ca_certs,
  1589. indirect_crl,
  1590. only_contains_attribute_certs,
  1591. full_name,
  1592. relative_name,
  1593. only_some_reasons,
  1594. ]
  1595. ):
  1596. raise ValueError(
  1597. "Cannot create empty extension: "
  1598. "if only_contains_user_certs, only_contains_ca_certs, "
  1599. "indirect_crl, and only_contains_attribute_certs are all False"
  1600. ", then either full_name, relative_name, or only_some_reasons "
  1601. "must have a value."
  1602. )
  1603. self._only_contains_user_certs = only_contains_user_certs
  1604. self._only_contains_ca_certs = only_contains_ca_certs
  1605. self._indirect_crl = indirect_crl
  1606. self._only_contains_attribute_certs = only_contains_attribute_certs
  1607. self._only_some_reasons = only_some_reasons
  1608. self._full_name = full_name
  1609. self._relative_name = relative_name
  1610. def __repr__(self) -> str:
  1611. return (
  1612. "<IssuingDistributionPoint(full_name={0.full_name}, "
  1613. "relative_name={0.relative_name}, "
  1614. "only_contains_user_certs={0.only_contains_user_certs}, "
  1615. "only_contains_ca_certs={0.only_contains_ca_certs}, "
  1616. "only_some_reasons={0.only_some_reasons}, "
  1617. "indirect_crl={0.indirect_crl}, "
  1618. "only_contains_attribute_certs="
  1619. "{0.only_contains_attribute_certs})>".format(self)
  1620. )
  1621. def __eq__(self, other: object) -> bool:
  1622. if not isinstance(other, IssuingDistributionPoint):
  1623. return NotImplemented
  1624. return (
  1625. self.full_name == other.full_name
  1626. and self.relative_name == other.relative_name
  1627. and self.only_contains_user_certs == other.only_contains_user_certs
  1628. and self.only_contains_ca_certs == other.only_contains_ca_certs
  1629. and self.only_some_reasons == other.only_some_reasons
  1630. and self.indirect_crl == other.indirect_crl
  1631. and self.only_contains_attribute_certs
  1632. == other.only_contains_attribute_certs
  1633. )
  1634. def __hash__(self) -> int:
  1635. return hash(
  1636. (
  1637. self.full_name,
  1638. self.relative_name,
  1639. self.only_contains_user_certs,
  1640. self.only_contains_ca_certs,
  1641. self.only_some_reasons,
  1642. self.indirect_crl,
  1643. self.only_contains_attribute_certs,
  1644. )
  1645. )
  1646. @property
  1647. def full_name(self) -> typing.Optional[typing.List[GeneralName]]:
  1648. return self._full_name
  1649. @property
  1650. def relative_name(self) -> typing.Optional[RelativeDistinguishedName]:
  1651. return self._relative_name
  1652. @property
  1653. def only_contains_user_certs(self) -> bool:
  1654. return self._only_contains_user_certs
  1655. @property
  1656. def only_contains_ca_certs(self) -> bool:
  1657. return self._only_contains_ca_certs
  1658. @property
  1659. def only_some_reasons(
  1660. self,
  1661. ) -> typing.Optional[typing.FrozenSet[ReasonFlags]]:
  1662. return self._only_some_reasons
  1663. @property
  1664. def indirect_crl(self) -> bool:
  1665. return self._indirect_crl
  1666. @property
  1667. def only_contains_attribute_certs(self) -> bool:
  1668. return self._only_contains_attribute_certs
  1669. def public_bytes(self) -> bytes:
  1670. return rust_x509.encode_extension_value(self)
  1671. class MSCertificateTemplate(ExtensionType):
  1672. oid = ExtensionOID.MS_CERTIFICATE_TEMPLATE
  1673. def __init__(
  1674. self,
  1675. template_id: ObjectIdentifier,
  1676. major_version: typing.Optional[int],
  1677. minor_version: typing.Optional[int],
  1678. ) -> None:
  1679. if not isinstance(template_id, ObjectIdentifier):
  1680. raise TypeError("oid must be an ObjectIdentifier")
  1681. self._template_id = template_id
  1682. if (
  1683. major_version is not None and not isinstance(major_version, int)
  1684. ) or (
  1685. minor_version is not None and not isinstance(minor_version, int)
  1686. ):
  1687. raise TypeError(
  1688. "major_version and minor_version must be integers or None"
  1689. )
  1690. self._major_version = major_version
  1691. self._minor_version = minor_version
  1692. @property
  1693. def template_id(self) -> ObjectIdentifier:
  1694. return self._template_id
  1695. @property
  1696. def major_version(self) -> typing.Optional[int]:
  1697. return self._major_version
  1698. @property
  1699. def minor_version(self) -> typing.Optional[int]:
  1700. return self._minor_version
  1701. def __repr__(self) -> str:
  1702. return (
  1703. f"<MSCertificateTemplate(template_id={self.template_id}, "
  1704. f"major_version={self.major_version}, "
  1705. f"minor_version={self.minor_version})>"
  1706. )
  1707. def __eq__(self, other: object) -> bool:
  1708. if not isinstance(other, MSCertificateTemplate):
  1709. return NotImplemented
  1710. return (
  1711. self.template_id == other.template_id
  1712. and self.major_version == other.major_version
  1713. and self.minor_version == other.minor_version
  1714. )
  1715. def __hash__(self) -> int:
  1716. return hash((self.template_id, self.major_version, self.minor_version))
  1717. def public_bytes(self) -> bytes:
  1718. return rust_x509.encode_extension_value(self)
  1719. class UnrecognizedExtension(ExtensionType):
  1720. def __init__(self, oid: ObjectIdentifier, value: bytes) -> None:
  1721. if not isinstance(oid, ObjectIdentifier):
  1722. raise TypeError("oid must be an ObjectIdentifier")
  1723. self._oid = oid
  1724. self._value = value
  1725. @property
  1726. def oid(self) -> ObjectIdentifier: # type: ignore[override]
  1727. return self._oid
  1728. @property
  1729. def value(self) -> bytes:
  1730. return self._value
  1731. def __repr__(self) -> str:
  1732. return (
  1733. "<UnrecognizedExtension(oid={0.oid}, "
  1734. "value={0.value!r})>".format(self)
  1735. )
  1736. def __eq__(self, other: object) -> bool:
  1737. if not isinstance(other, UnrecognizedExtension):
  1738. return NotImplemented
  1739. return self.oid == other.oid and self.value == other.value
  1740. def __hash__(self) -> int:
  1741. return hash((self.oid, self.value))
  1742. def public_bytes(self) -> bytes:
  1743. return self.value