ocsp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. import abc
  5. import datetime
  6. import typing
  7. from enum import Enum
  8. from cryptography import x509
  9. from cryptography.hazmat.primitives import hashes, serialization
  10. from cryptography.x509.base import (
  11. _EARLIEST_UTC_TIME,
  12. _PRIVATE_KEY_TYPES,
  13. _convert_to_naive_utc_time,
  14. _reject_duplicate_extension,
  15. )
  16. _OIDS_TO_HASH = {
  17. "1.3.14.3.2.26": hashes.SHA1(),
  18. "2.16.840.1.101.3.4.2.4": hashes.SHA224(),
  19. "2.16.840.1.101.3.4.2.1": hashes.SHA256(),
  20. "2.16.840.1.101.3.4.2.2": hashes.SHA384(),
  21. "2.16.840.1.101.3.4.2.3": hashes.SHA512(),
  22. }
  23. class OCSPResponderEncoding(Enum):
  24. HASH = "By Hash"
  25. NAME = "By Name"
  26. class OCSPResponseStatus(Enum):
  27. SUCCESSFUL = 0
  28. MALFORMED_REQUEST = 1
  29. INTERNAL_ERROR = 2
  30. TRY_LATER = 3
  31. SIG_REQUIRED = 5
  32. UNAUTHORIZED = 6
  33. _RESPONSE_STATUS_TO_ENUM = {x.value: x for x in OCSPResponseStatus}
  34. _ALLOWED_HASHES = (
  35. hashes.SHA1,
  36. hashes.SHA224,
  37. hashes.SHA256,
  38. hashes.SHA384,
  39. hashes.SHA512,
  40. )
  41. def _verify_algorithm(algorithm):
  42. if not isinstance(algorithm, _ALLOWED_HASHES):
  43. raise ValueError(
  44. "Algorithm must be SHA1, SHA224, SHA256, SHA384, or SHA512"
  45. )
  46. class OCSPCertStatus(Enum):
  47. GOOD = 0
  48. REVOKED = 1
  49. UNKNOWN = 2
  50. _CERT_STATUS_TO_ENUM = {x.value: x for x in OCSPCertStatus}
  51. class _SingleResponse(object):
  52. def __init__(
  53. self,
  54. cert,
  55. issuer,
  56. algorithm,
  57. cert_status,
  58. this_update,
  59. next_update,
  60. revocation_time,
  61. revocation_reason,
  62. ):
  63. if not isinstance(cert, x509.Certificate) or not isinstance(
  64. issuer, x509.Certificate
  65. ):
  66. raise TypeError("cert and issuer must be a Certificate")
  67. _verify_algorithm(algorithm)
  68. if not isinstance(this_update, datetime.datetime):
  69. raise TypeError("this_update must be a datetime object")
  70. if next_update is not None and not isinstance(
  71. next_update, datetime.datetime
  72. ):
  73. raise TypeError("next_update must be a datetime object or None")
  74. self._cert = cert
  75. self._issuer = issuer
  76. self._algorithm = algorithm
  77. self._this_update = this_update
  78. self._next_update = next_update
  79. if not isinstance(cert_status, OCSPCertStatus):
  80. raise TypeError(
  81. "cert_status must be an item from the OCSPCertStatus enum"
  82. )
  83. if cert_status is not OCSPCertStatus.REVOKED:
  84. if revocation_time is not None:
  85. raise ValueError(
  86. "revocation_time can only be provided if the certificate "
  87. "is revoked"
  88. )
  89. if revocation_reason is not None:
  90. raise ValueError(
  91. "revocation_reason can only be provided if the certificate"
  92. " is revoked"
  93. )
  94. else:
  95. if not isinstance(revocation_time, datetime.datetime):
  96. raise TypeError("revocation_time must be a datetime object")
  97. revocation_time = _convert_to_naive_utc_time(revocation_time)
  98. if revocation_time < _EARLIEST_UTC_TIME:
  99. raise ValueError(
  100. "The revocation_time must be on or after"
  101. " 1950 January 1."
  102. )
  103. if revocation_reason is not None and not isinstance(
  104. revocation_reason, x509.ReasonFlags
  105. ):
  106. raise TypeError(
  107. "revocation_reason must be an item from the ReasonFlags "
  108. "enum or None"
  109. )
  110. self._cert_status = cert_status
  111. self._revocation_time = revocation_time
  112. self._revocation_reason = revocation_reason
  113. class OCSPRequest(metaclass=abc.ABCMeta):
  114. @abc.abstractproperty
  115. def issuer_key_hash(self) -> bytes:
  116. """
  117. The hash of the issuer public key
  118. """
  119. @abc.abstractproperty
  120. def issuer_name_hash(self) -> bytes:
  121. """
  122. The hash of the issuer name
  123. """
  124. @abc.abstractproperty
  125. def hash_algorithm(self) -> hashes.HashAlgorithm:
  126. """
  127. The hash algorithm used in the issuer name and key hashes
  128. """
  129. @abc.abstractproperty
  130. def serial_number(self) -> int:
  131. """
  132. The serial number of the cert whose status is being checked
  133. """
  134. @abc.abstractmethod
  135. def public_bytes(self, encoding: serialization.Encoding) -> bytes:
  136. """
  137. Serializes the request to DER
  138. """
  139. @abc.abstractproperty
  140. def extensions(self) -> x509.Extensions:
  141. """
  142. The list of request extensions. Not single request extensions.
  143. """
  144. class OCSPResponse(metaclass=abc.ABCMeta):
  145. @abc.abstractproperty
  146. def response_status(self) -> OCSPResponseStatus:
  147. """
  148. The status of the response. This is a value from the OCSPResponseStatus
  149. enumeration
  150. """
  151. @abc.abstractproperty
  152. def signature_algorithm_oid(self) -> x509.ObjectIdentifier:
  153. """
  154. The ObjectIdentifier of the signature algorithm
  155. """
  156. @abc.abstractproperty
  157. def signature_hash_algorithm(
  158. self,
  159. ) -> typing.Optional[hashes.HashAlgorithm]:
  160. """
  161. Returns a HashAlgorithm corresponding to the type of the digest signed
  162. """
  163. @abc.abstractproperty
  164. def signature(self) -> bytes:
  165. """
  166. The signature bytes
  167. """
  168. @abc.abstractproperty
  169. def tbs_response_bytes(self) -> bytes:
  170. """
  171. The tbsResponseData bytes
  172. """
  173. @abc.abstractproperty
  174. def certificates(self) -> typing.List[x509.Certificate]:
  175. """
  176. A list of certificates used to help build a chain to verify the OCSP
  177. response. This situation occurs when the OCSP responder uses a delegate
  178. certificate.
  179. """
  180. @abc.abstractproperty
  181. def responder_key_hash(self) -> typing.Optional[bytes]:
  182. """
  183. The responder's key hash or None
  184. """
  185. @abc.abstractproperty
  186. def responder_name(self) -> typing.Optional[x509.Name]:
  187. """
  188. The responder's Name or None
  189. """
  190. @abc.abstractproperty
  191. def produced_at(self) -> datetime.datetime:
  192. """
  193. The time the response was produced
  194. """
  195. @abc.abstractproperty
  196. def certificate_status(self) -> OCSPCertStatus:
  197. """
  198. The status of the certificate (an element from the OCSPCertStatus enum)
  199. """
  200. @abc.abstractproperty
  201. def revocation_time(self) -> typing.Optional[datetime.datetime]:
  202. """
  203. The date of when the certificate was revoked or None if not
  204. revoked.
  205. """
  206. @abc.abstractproperty
  207. def revocation_reason(self) -> typing.Optional[x509.ReasonFlags]:
  208. """
  209. The reason the certificate was revoked or None if not specified or
  210. not revoked.
  211. """
  212. @abc.abstractproperty
  213. def this_update(self) -> datetime.datetime:
  214. """
  215. The most recent time at which the status being indicated is known by
  216. the responder to have been correct
  217. """
  218. @abc.abstractproperty
  219. def next_update(self) -> typing.Optional[datetime.datetime]:
  220. """
  221. The time when newer information will be available
  222. """
  223. @abc.abstractproperty
  224. def issuer_key_hash(self) -> bytes:
  225. """
  226. The hash of the issuer public key
  227. """
  228. @abc.abstractproperty
  229. def issuer_name_hash(self) -> bytes:
  230. """
  231. The hash of the issuer name
  232. """
  233. @abc.abstractproperty
  234. def hash_algorithm(self) -> hashes.HashAlgorithm:
  235. """
  236. The hash algorithm used in the issuer name and key hashes
  237. """
  238. @abc.abstractproperty
  239. def serial_number(self) -> int:
  240. """
  241. The serial number of the cert whose status is being checked
  242. """
  243. @abc.abstractproperty
  244. def extensions(self) -> x509.Extensions:
  245. """
  246. The list of response extensions. Not single response extensions.
  247. """
  248. @abc.abstractproperty
  249. def single_extensions(self) -> x509.Extensions:
  250. """
  251. The list of single response extensions. Not response extensions.
  252. """
  253. @abc.abstractmethod
  254. def public_bytes(self, encoding: serialization.Encoding) -> bytes:
  255. """
  256. Serializes the response to DER
  257. """
  258. class OCSPRequestBuilder(object):
  259. def __init__(self, request=None, extensions=[]):
  260. self._request = request
  261. self._extensions = extensions
  262. def add_certificate(
  263. self,
  264. cert: x509.Certificate,
  265. issuer: x509.Certificate,
  266. algorithm: hashes.HashAlgorithm,
  267. ) -> "OCSPRequestBuilder":
  268. if self._request is not None:
  269. raise ValueError("Only one certificate can be added to a request")
  270. _verify_algorithm(algorithm)
  271. if not isinstance(cert, x509.Certificate) or not isinstance(
  272. issuer, x509.Certificate
  273. ):
  274. raise TypeError("cert and issuer must be a Certificate")
  275. return OCSPRequestBuilder((cert, issuer, algorithm), self._extensions)
  276. def add_extension(
  277. self, extval: x509.ExtensionType, critical: bool
  278. ) -> "OCSPRequestBuilder":
  279. if not isinstance(extval, x509.ExtensionType):
  280. raise TypeError("extension must be an ExtensionType")
  281. extension = x509.Extension(extval.oid, critical, extval)
  282. _reject_duplicate_extension(extension, self._extensions)
  283. return OCSPRequestBuilder(
  284. self._request, self._extensions + [extension]
  285. )
  286. def build(self) -> OCSPRequest:
  287. from cryptography.hazmat.backends.openssl.backend import backend
  288. if self._request is None:
  289. raise ValueError("You must add a certificate before building")
  290. return backend.create_ocsp_request(self)
  291. class OCSPResponseBuilder(object):
  292. def __init__(
  293. self, response=None, responder_id=None, certs=None, extensions=[]
  294. ):
  295. self._response = response
  296. self._responder_id = responder_id
  297. self._certs = certs
  298. self._extensions = extensions
  299. def add_response(
  300. self,
  301. cert: x509.Certificate,
  302. issuer: x509.Certificate,
  303. algorithm: hashes.HashAlgorithm,
  304. cert_status: OCSPCertStatus,
  305. this_update: datetime.datetime,
  306. next_update: typing.Optional[datetime.datetime],
  307. revocation_time: typing.Optional[datetime.datetime],
  308. revocation_reason: typing.Optional[x509.ReasonFlags],
  309. ) -> "OCSPResponseBuilder":
  310. if self._response is not None:
  311. raise ValueError("Only one response per OCSPResponse.")
  312. singleresp = _SingleResponse(
  313. cert,
  314. issuer,
  315. algorithm,
  316. cert_status,
  317. this_update,
  318. next_update,
  319. revocation_time,
  320. revocation_reason,
  321. )
  322. return OCSPResponseBuilder(
  323. singleresp,
  324. self._responder_id,
  325. self._certs,
  326. self._extensions,
  327. )
  328. def responder_id(
  329. self, encoding: OCSPResponderEncoding, responder_cert: x509.Certificate
  330. ) -> "OCSPResponseBuilder":
  331. if self._responder_id is not None:
  332. raise ValueError("responder_id can only be set once")
  333. if not isinstance(responder_cert, x509.Certificate):
  334. raise TypeError("responder_cert must be a Certificate")
  335. if not isinstance(encoding, OCSPResponderEncoding):
  336. raise TypeError(
  337. "encoding must be an element from OCSPResponderEncoding"
  338. )
  339. return OCSPResponseBuilder(
  340. self._response,
  341. (responder_cert, encoding),
  342. self._certs,
  343. self._extensions,
  344. )
  345. def certificates(
  346. self, certs: typing.Iterable[x509.Certificate]
  347. ) -> "OCSPResponseBuilder":
  348. if self._certs is not None:
  349. raise ValueError("certificates may only be set once")
  350. certs = list(certs)
  351. if len(certs) == 0:
  352. raise ValueError("certs must not be an empty list")
  353. if not all(isinstance(x, x509.Certificate) for x in certs):
  354. raise TypeError("certs must be a list of Certificates")
  355. return OCSPResponseBuilder(
  356. self._response,
  357. self._responder_id,
  358. certs,
  359. self._extensions,
  360. )
  361. def add_extension(
  362. self, extval: x509.ExtensionType, critical: bool
  363. ) -> "OCSPResponseBuilder":
  364. if not isinstance(extval, x509.ExtensionType):
  365. raise TypeError("extension must be an ExtensionType")
  366. extension = x509.Extension(extval.oid, critical, extval)
  367. _reject_duplicate_extension(extension, self._extensions)
  368. return OCSPResponseBuilder(
  369. self._response,
  370. self._responder_id,
  371. self._certs,
  372. self._extensions + [extension],
  373. )
  374. def sign(
  375. self,
  376. private_key: _PRIVATE_KEY_TYPES,
  377. algorithm: typing.Optional[hashes.HashAlgorithm],
  378. ) -> OCSPResponse:
  379. from cryptography.hazmat.backends.openssl.backend import backend
  380. if self._response is None:
  381. raise ValueError("You must add a response before signing")
  382. if self._responder_id is None:
  383. raise ValueError("You must add a responder_id before signing")
  384. return backend.create_ocsp_response(
  385. OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm
  386. )
  387. @classmethod
  388. def build_unsuccessful(
  389. cls, response_status: OCSPResponseStatus
  390. ) -> OCSPResponse:
  391. from cryptography.hazmat.backends.openssl.backend import backend
  392. if not isinstance(response_status, OCSPResponseStatus):
  393. raise TypeError(
  394. "response_status must be an item from OCSPResponseStatus"
  395. )
  396. if response_status is OCSPResponseStatus.SUCCESSFUL:
  397. raise ValueError("response_status cannot be SUCCESSFUL")
  398. return backend.create_ocsp_response(response_status, None, None, None)
  399. def load_der_ocsp_request(data: bytes) -> OCSPRequest:
  400. from cryptography.hazmat.backends.openssl.backend import backend
  401. return backend.load_der_ocsp_request(data)
  402. def load_der_ocsp_response(data: bytes) -> OCSPResponse:
  403. from cryptography.hazmat.backends.openssl.backend import backend
  404. return backend.load_der_ocsp_response(data)