pkcs7.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 email.base64mime
  6. import email.generator
  7. import email.message
  8. import email.policy
  9. import io
  10. import typing
  11. from collections.abc import Iterable
  12. from cryptography import utils, x509
  13. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  14. from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7
  15. from cryptography.hazmat.primitives import hashes, serialization
  16. from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
  17. from cryptography.hazmat.primitives.ciphers import (
  18. algorithms,
  19. )
  20. from cryptography.utils import _check_byteslike
  21. load_pem_pkcs7_certificates = rust_pkcs7.load_pem_pkcs7_certificates
  22. load_der_pkcs7_certificates = rust_pkcs7.load_der_pkcs7_certificates
  23. serialize_certificates = rust_pkcs7.serialize_certificates
  24. PKCS7HashTypes = typing.Union[
  25. hashes.SHA224,
  26. hashes.SHA256,
  27. hashes.SHA384,
  28. hashes.SHA512,
  29. ]
  30. PKCS7PrivateKeyTypes = typing.Union[
  31. rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey
  32. ]
  33. ContentEncryptionAlgorithm = typing.Union[
  34. typing.Type[algorithms.AES128], typing.Type[algorithms.AES256]
  35. ]
  36. class PKCS7Options(utils.Enum):
  37. Text = "Add text/plain MIME type"
  38. Binary = "Don't translate input data into canonical MIME format"
  39. DetachedSignature = "Don't embed data in the PKCS7 structure"
  40. NoCapabilities = "Don't embed SMIME capabilities"
  41. NoAttributes = "Don't embed authenticatedAttributes"
  42. NoCerts = "Don't embed signer certificate"
  43. class PKCS7SignatureBuilder:
  44. def __init__(
  45. self,
  46. data: utils.Buffer | None = None,
  47. signers: list[
  48. tuple[
  49. x509.Certificate,
  50. PKCS7PrivateKeyTypes,
  51. PKCS7HashTypes,
  52. padding.PSS | padding.PKCS1v15 | None,
  53. ]
  54. ] = [],
  55. additional_certs: list[x509.Certificate] = [],
  56. ):
  57. self._data = data
  58. self._signers = signers
  59. self._additional_certs = additional_certs
  60. def set_data(self, data: utils.Buffer) -> PKCS7SignatureBuilder:
  61. _check_byteslike("data", data)
  62. if self._data is not None:
  63. raise ValueError("data may only be set once")
  64. return PKCS7SignatureBuilder(data, self._signers)
  65. def add_signer(
  66. self,
  67. certificate: x509.Certificate,
  68. private_key: PKCS7PrivateKeyTypes,
  69. hash_algorithm: PKCS7HashTypes,
  70. *,
  71. rsa_padding: padding.PSS | padding.PKCS1v15 | None = None,
  72. ) -> PKCS7SignatureBuilder:
  73. if not isinstance(
  74. hash_algorithm,
  75. (
  76. hashes.SHA224,
  77. hashes.SHA256,
  78. hashes.SHA384,
  79. hashes.SHA512,
  80. ),
  81. ):
  82. raise TypeError(
  83. "hash_algorithm must be one of hashes.SHA224, "
  84. "SHA256, SHA384, or SHA512"
  85. )
  86. if not isinstance(certificate, x509.Certificate):
  87. raise TypeError("certificate must be a x509.Certificate")
  88. if not isinstance(
  89. private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)
  90. ):
  91. raise TypeError("Only RSA & EC keys are supported at this time.")
  92. if rsa_padding is not None:
  93. if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)):
  94. raise TypeError("Padding must be PSS or PKCS1v15")
  95. if not isinstance(private_key, rsa.RSAPrivateKey):
  96. raise TypeError("Padding is only supported for RSA keys")
  97. return PKCS7SignatureBuilder(
  98. self._data,
  99. [
  100. *self._signers,
  101. (certificate, private_key, hash_algorithm, rsa_padding),
  102. ],
  103. )
  104. def add_certificate(
  105. self, certificate: x509.Certificate
  106. ) -> PKCS7SignatureBuilder:
  107. if not isinstance(certificate, x509.Certificate):
  108. raise TypeError("certificate must be a x509.Certificate")
  109. return PKCS7SignatureBuilder(
  110. self._data, self._signers, [*self._additional_certs, certificate]
  111. )
  112. def sign(
  113. self,
  114. encoding: serialization.Encoding,
  115. options: Iterable[PKCS7Options],
  116. backend: typing.Any = None,
  117. ) -> bytes:
  118. if len(self._signers) == 0:
  119. raise ValueError("Must have at least one signer")
  120. if self._data is None:
  121. raise ValueError("You must add data to sign")
  122. options = list(options)
  123. if not all(isinstance(x, PKCS7Options) for x in options):
  124. raise ValueError("options must be from the PKCS7Options enum")
  125. if encoding not in (
  126. serialization.Encoding.PEM,
  127. serialization.Encoding.DER,
  128. serialization.Encoding.SMIME,
  129. ):
  130. raise ValueError(
  131. "Must be PEM, DER, or SMIME from the Encoding enum"
  132. )
  133. # Text is a meaningless option unless it is accompanied by
  134. # DetachedSignature
  135. if (
  136. PKCS7Options.Text in options
  137. and PKCS7Options.DetachedSignature not in options
  138. ):
  139. raise ValueError(
  140. "When passing the Text option you must also pass "
  141. "DetachedSignature"
  142. )
  143. if PKCS7Options.Text in options and encoding in (
  144. serialization.Encoding.DER,
  145. serialization.Encoding.PEM,
  146. ):
  147. raise ValueError(
  148. "The Text option is only available for SMIME serialization"
  149. )
  150. # No attributes implies no capabilities so we'll error if you try to
  151. # pass both.
  152. if (
  153. PKCS7Options.NoAttributes in options
  154. and PKCS7Options.NoCapabilities in options
  155. ):
  156. raise ValueError(
  157. "NoAttributes is a superset of NoCapabilities. Do not pass "
  158. "both values."
  159. )
  160. return rust_pkcs7.sign_and_serialize(self, encoding, options)
  161. class PKCS7EnvelopeBuilder:
  162. def __init__(
  163. self,
  164. *,
  165. _data: bytes | None = None,
  166. _recipients: list[x509.Certificate] | None = None,
  167. _content_encryption_algorithm: ContentEncryptionAlgorithm
  168. | None = None,
  169. ):
  170. from cryptography.hazmat.backends.openssl.backend import (
  171. backend as ossl,
  172. )
  173. if not ossl.rsa_encryption_supported(padding=padding.PKCS1v15()):
  174. raise UnsupportedAlgorithm(
  175. "RSA with PKCS1 v1.5 padding is not supported by this version"
  176. " of OpenSSL.",
  177. _Reasons.UNSUPPORTED_PADDING,
  178. )
  179. self._data = _data
  180. self._recipients = _recipients if _recipients is not None else []
  181. self._content_encryption_algorithm = _content_encryption_algorithm
  182. def set_data(self, data: bytes) -> PKCS7EnvelopeBuilder:
  183. _check_byteslike("data", data)
  184. if self._data is not None:
  185. raise ValueError("data may only be set once")
  186. return PKCS7EnvelopeBuilder(
  187. _data=data,
  188. _recipients=self._recipients,
  189. _content_encryption_algorithm=self._content_encryption_algorithm,
  190. )
  191. def add_recipient(
  192. self,
  193. certificate: x509.Certificate,
  194. ) -> PKCS7EnvelopeBuilder:
  195. if not isinstance(certificate, x509.Certificate):
  196. raise TypeError("certificate must be a x509.Certificate")
  197. if not isinstance(certificate.public_key(), rsa.RSAPublicKey):
  198. raise TypeError("Only RSA keys are supported at this time.")
  199. return PKCS7EnvelopeBuilder(
  200. _data=self._data,
  201. _recipients=[
  202. *self._recipients,
  203. certificate,
  204. ],
  205. _content_encryption_algorithm=self._content_encryption_algorithm,
  206. )
  207. def set_content_encryption_algorithm(
  208. self, content_encryption_algorithm: ContentEncryptionAlgorithm
  209. ) -> PKCS7EnvelopeBuilder:
  210. if self._content_encryption_algorithm is not None:
  211. raise ValueError("Content encryption algo may only be set once")
  212. if content_encryption_algorithm not in {
  213. algorithms.AES128,
  214. algorithms.AES256,
  215. }:
  216. raise TypeError("Only AES128 and AES256 are supported")
  217. return PKCS7EnvelopeBuilder(
  218. _data=self._data,
  219. _recipients=self._recipients,
  220. _content_encryption_algorithm=content_encryption_algorithm,
  221. )
  222. def encrypt(
  223. self,
  224. encoding: serialization.Encoding,
  225. options: Iterable[PKCS7Options],
  226. ) -> bytes:
  227. if len(self._recipients) == 0:
  228. raise ValueError("Must have at least one recipient")
  229. if self._data is None:
  230. raise ValueError("You must add data to encrypt")
  231. # The default content encryption algorithm is AES-128, which the S/MIME
  232. # v3.2 RFC specifies as MUST support (https://datatracker.ietf.org/doc/html/rfc5751#section-2.7)
  233. content_encryption_algorithm = (
  234. self._content_encryption_algorithm or algorithms.AES128
  235. )
  236. options = list(options)
  237. if not all(isinstance(x, PKCS7Options) for x in options):
  238. raise ValueError("options must be from the PKCS7Options enum")
  239. if encoding not in (
  240. serialization.Encoding.PEM,
  241. serialization.Encoding.DER,
  242. serialization.Encoding.SMIME,
  243. ):
  244. raise ValueError(
  245. "Must be PEM, DER, or SMIME from the Encoding enum"
  246. )
  247. # Only allow options that make sense for encryption
  248. if any(
  249. opt not in [PKCS7Options.Text, PKCS7Options.Binary]
  250. for opt in options
  251. ):
  252. raise ValueError(
  253. "Only the following options are supported for encryption: "
  254. "Text, Binary"
  255. )
  256. elif PKCS7Options.Text in options and PKCS7Options.Binary in options:
  257. # OpenSSL accepts both options at the same time, but ignores Text.
  258. # We fail defensively to avoid unexpected outputs.
  259. raise ValueError(
  260. "Cannot use Binary and Text options at the same time"
  261. )
  262. return rust_pkcs7.encrypt_and_serialize(
  263. self, content_encryption_algorithm, encoding, options
  264. )
  265. pkcs7_decrypt_der = rust_pkcs7.decrypt_der
  266. pkcs7_decrypt_pem = rust_pkcs7.decrypt_pem
  267. pkcs7_decrypt_smime = rust_pkcs7.decrypt_smime
  268. def _smime_signed_encode(
  269. data: bytes, signature: bytes, micalg: str, text_mode: bool
  270. ) -> bytes:
  271. # This function works pretty hard to replicate what OpenSSL does
  272. # precisely. For good and for ill.
  273. m = email.message.Message()
  274. m.add_header("MIME-Version", "1.0")
  275. m.add_header(
  276. "Content-Type",
  277. "multipart/signed",
  278. protocol="application/x-pkcs7-signature",
  279. micalg=micalg,
  280. )
  281. m.preamble = "This is an S/MIME signed message\n"
  282. msg_part = OpenSSLMimePart()
  283. msg_part.set_payload(data)
  284. if text_mode:
  285. msg_part.add_header("Content-Type", "text/plain")
  286. m.attach(msg_part)
  287. sig_part = email.message.MIMEPart()
  288. sig_part.add_header(
  289. "Content-Type", "application/x-pkcs7-signature", name="smime.p7s"
  290. )
  291. sig_part.add_header("Content-Transfer-Encoding", "base64")
  292. sig_part.add_header(
  293. "Content-Disposition", "attachment", filename="smime.p7s"
  294. )
  295. sig_part.set_payload(
  296. email.base64mime.body_encode(signature, maxlinelen=65)
  297. )
  298. del sig_part["MIME-Version"]
  299. m.attach(sig_part)
  300. fp = io.BytesIO()
  301. g = email.generator.BytesGenerator(
  302. fp,
  303. maxheaderlen=0,
  304. mangle_from_=False,
  305. policy=m.policy.clone(linesep="\r\n"),
  306. )
  307. g.flatten(m)
  308. return fp.getvalue()
  309. def _smime_enveloped_encode(data: bytes) -> bytes:
  310. m = email.message.Message()
  311. m.add_header("MIME-Version", "1.0")
  312. m.add_header("Content-Disposition", "attachment", filename="smime.p7m")
  313. m.add_header(
  314. "Content-Type",
  315. "application/pkcs7-mime",
  316. smime_type="enveloped-data",
  317. name="smime.p7m",
  318. )
  319. m.add_header("Content-Transfer-Encoding", "base64")
  320. m.set_payload(email.base64mime.body_encode(data, maxlinelen=65))
  321. return m.as_bytes(policy=m.policy.clone(linesep="\n", max_line_length=0))
  322. def _smime_enveloped_decode(data: bytes) -> bytes:
  323. m = email.message_from_bytes(data)
  324. if m.get_content_type() not in {
  325. "application/x-pkcs7-mime",
  326. "application/pkcs7-mime",
  327. }:
  328. raise ValueError("Not an S/MIME enveloped message")
  329. return bytes(m.get_payload(decode=True))
  330. def _smime_remove_text_headers(data: bytes) -> bytes:
  331. m = email.message_from_bytes(data)
  332. # Using get() instead of get_content_type() since it has None as default,
  333. # where the latter has "text/plain". Both methods are case-insensitive.
  334. content_type = m.get("content-type")
  335. if content_type is None:
  336. raise ValueError(
  337. "Decrypted MIME data has no 'Content-Type' header. "
  338. "Please remove the 'Text' option to parse it manually."
  339. )
  340. if "text/plain" not in content_type:
  341. raise ValueError(
  342. f"Decrypted MIME data content type is '{content_type}', not "
  343. "'text/plain'. Remove the 'Text' option to parse it manually."
  344. )
  345. return bytes(m.get_payload(decode=True))
  346. class OpenSSLMimePart(email.message.MIMEPart):
  347. # A MIMEPart subclass that replicates OpenSSL's behavior of not including
  348. # a newline if there are no headers.
  349. def _write_headers(self, generator) -> None:
  350. if list(self.raw_items()):
  351. generator._write_headers(self)