pkcs7.py 12 KB

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