extensions.py 66 KB

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