mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
Merge pull request #1455 from storytold/pr-mailcraft-smime
feat: add craft-smime (S/MIME CMS/X.509/PKCS#12)
This commit is contained in:
1 parent
0c144b7d98
commit
0f5b23b4de
26 files changed
+5265
-14
No files matched your search
@@ -6,6 +6,7 @@ author, source and license. Library code and original assets are under the repos
|
||||
|
||||
| File | Author | Source | License |
|
||||
|---|---|---|---|
|
||||
| `crates/smime/testdata/` | MailCraft contributors; RFC 9216 example certificates | [MailCraft at 240d1d42](https://github.com/UCS-Care-Group/mailcraft/tree/240d1d42fe394cf3274402b180663ba9b43ca180/crates/smime/testdata), restored unmodified; provenance in the directory README | MIT OR Apache-2.0 (source repository) |
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files |
|
||||
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
|
||||
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
|
||||
|
||||
Generated
+228
-14
@@ -301,6 +301,45 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
|
||||
dependencies = [
|
||||
"asn1-rs-derive",
|
||||
"asn1-rs-impl",
|
||||
"displaydoc",
|
||||
"nom 7.1.3",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-derive"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "asn1-rs-impl"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-broadcast"
|
||||
version = "0.7.2"
|
||||
@@ -564,6 +603,9 @@ name = "bit-vec"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
@@ -1093,7 +1135,7 @@ dependencies = [
|
||||
"crmf",
|
||||
"der 0.7.10",
|
||||
"spki 0.7.3",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1105,7 +1147,19 @@ dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der 0.7.10",
|
||||
"spki 0.7.3",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cms"
|
||||
version = "0.3.0-rc.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d089eddc8a5c984d82fcf1427367a6fa0d019d5af04b6e3197e86c8989533b8d"
|
||||
dependencies = [
|
||||
"const-oid 0.10.3",
|
||||
"der 0.8.3",
|
||||
"spki 0.8.1",
|
||||
"x509-cert 0.3.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2541,6 +2595,37 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-smime"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes 0.9.4",
|
||||
"base64 0.23.1",
|
||||
"cbc",
|
||||
"cms 0.3.0-rc.2",
|
||||
"const-oid 0.10.3",
|
||||
"craft-ber",
|
||||
"der 0.8.3",
|
||||
"des 0.9.0",
|
||||
"hmac 0.13.0",
|
||||
"p256 0.14.0",
|
||||
"p384 0.14.0",
|
||||
"pbkdf2",
|
||||
"pkcs1 0.8.0",
|
||||
"pkcs12",
|
||||
"proptest",
|
||||
"rcgen",
|
||||
"ring",
|
||||
"rsa 0.10.0-rc.18",
|
||||
"serde",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"spki 0.8.1",
|
||||
"thiserror 2.0.21",
|
||||
"x509-cert 0.3.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-stencilcraft-document"
|
||||
version = "0.1.0"
|
||||
@@ -2905,10 +2990,10 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92"
|
||||
dependencies = [
|
||||
"cms",
|
||||
"cms 0.2.3",
|
||||
"der 0.7.10",
|
||||
"spki 0.7.3",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3132,6 +3217,12 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||
|
||||
[[package]]
|
||||
name = "data-url"
|
||||
version = "0.3.2"
|
||||
@@ -3154,7 +3245,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"der_derive 0.7.3",
|
||||
"flagset",
|
||||
"pem-rfc7468 0.7.0",
|
||||
"zeroize",
|
||||
@@ -3167,10 +3258,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
|
||||
dependencies = [
|
||||
"const-oid 0.10.3",
|
||||
"der_derive 0.8.0",
|
||||
"flagset",
|
||||
"pem-rfc7468 1.0.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der-parser"
|
||||
version = "10.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"displaydoc",
|
||||
"nom 7.1.3",
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.7.3"
|
||||
@@ -3182,6 +3289,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der_derive"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.9"
|
||||
@@ -6646,6 +6764,15 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oid-registry"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -7135,6 +7262,21 @@ dependencies = [
|
||||
"spki 0.8.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs12"
|
||||
version = "0.2.0-rc.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca"
|
||||
dependencies = [
|
||||
"cms 0.3.0-rc.2",
|
||||
"const-oid 0.10.3",
|
||||
"der 0.8.3",
|
||||
"digest 0.11.3",
|
||||
"spki 0.8.1",
|
||||
"x509-cert 0.3.0",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
@@ -7764,6 +7906,19 @@ dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rcgen"
|
||||
version = "0.14.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"time",
|
||||
"x509-parser",
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
@@ -8131,6 +8286,15 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusticata-macros"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
|
||||
dependencies = [
|
||||
"nom 7.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.44"
|
||||
@@ -8661,7 +8825,7 @@ dependencies = [
|
||||
"spki 0.7.3",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8710,7 +8874,7 @@ dependencies = [
|
||||
"sigstore-crypto",
|
||||
"sigstore-types",
|
||||
"thiserror 2.0.21",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8723,7 +8887,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"cms 0.2.3",
|
||||
"const-oid 0.9.6",
|
||||
"der 0.7.10",
|
||||
"hex",
|
||||
@@ -8735,7 +8899,7 @@ dependencies = [
|
||||
"sigstore-types",
|
||||
"thiserror 2.0.21",
|
||||
"tracing",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
"x509-tsp",
|
||||
]
|
||||
|
||||
@@ -8762,7 +8926,7 @@ checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cms",
|
||||
"cms 0.2.3",
|
||||
"const-oid 0.9.6",
|
||||
"hex",
|
||||
"pem",
|
||||
@@ -8781,7 +8945,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"tls_codec",
|
||||
"tracing",
|
||||
"x509-cert",
|
||||
"x509-cert 0.2.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9332,6 +9496,17 @@ dependencies = [
|
||||
"futures-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.14.0"
|
||||
@@ -11337,6 +11512,35 @@ dependencies = [
|
||||
"tls_codec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-cert"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b"
|
||||
dependencies = [
|
||||
"const-oid 0.10.3",
|
||||
"der 0.8.3",
|
||||
"spki 0.8.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
|
||||
dependencies = [
|
||||
"asn1-rs",
|
||||
"data-encoding",
|
||||
"der-parser",
|
||||
"lazy_static",
|
||||
"nom 7.1.3",
|
||||
"oid-registry",
|
||||
"ring",
|
||||
"rusticata-macros",
|
||||
"thiserror 2.0.21",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "x509-tsp"
|
||||
version = "0.1.0"
|
||||
@@ -11344,7 +11548,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1"
|
||||
dependencies = [
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"cms 0.2.3",
|
||||
"der 0.7.10",
|
||||
]
|
||||
|
||||
@@ -11407,6 +11611,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
|
||||
|
||||
[[package]]
|
||||
name = "yasna"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
|
||||
dependencies = [
|
||||
"bit-vec 0.9.1",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yeslogic-fontconfig-sys"
|
||||
version = "6.0.1"
|
||||
@@ -11438,7 +11652,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11549,7 +11763,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
"synstructure",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -11,6 +11,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/craft-libs"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-smime = { path = "crates/smime" }
|
||||
craft-ber = { path = "crates/ber" }
|
||||
craft-proto = { path = "crates/proto" }
|
||||
acadrust = "=0.6.6"
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
[package]
|
||||
name = "craft-smime"
|
||||
description = "S/MIME (RFC 8551): Digital signatures checked from CMS (RFC 5652) and X.509 (RFC 5280), no I/O"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-ber = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
base64 = "0.23"
|
||||
# RustCrypto: CMS, X.509, DER, SPKI, OID, RSA, P256, P384, SHA2.
|
||||
cms = { version = "=0.3.0-rc.2", default-features = false }
|
||||
x509-cert = { version = "0.3", default-features = false }
|
||||
der = { version = "0.8", default-features = false, features = ["alloc", "oid"] }
|
||||
spki = { version = "0.8", default-features = false, features = ["alloc"] }
|
||||
const-oid = { version = "0.10", default-features = false, features = ["db"] }
|
||||
# Match craft-pkcs7's RSA pin; parse PKCS #1 separately to avoid incompatible RC encoding APIs.
|
||||
rsa = { version = "=0.10.0-rc.18", default-features = false }
|
||||
pkcs1 = { version = "0.8", default-features = false, features = ["alloc"] }
|
||||
p256 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] }
|
||||
p384 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] }
|
||||
sha2 = { version = "0.11", default-features = false, features = ["oid"] }
|
||||
# PKCS #12 file handling (RFC 7292 Appendix B): PBES2, triple-DES key derivation.
|
||||
pkcs12 = { version = "=0.2.0-rc.0", default-features = false, features = ["kdf"] }
|
||||
pbkdf2 = { version = "0.13", default-features = false, features = ["hmac"] }
|
||||
hmac = { version = "0.13", default-features = false }
|
||||
sha1 = { version = "0.11", default-features = false }
|
||||
aes = { version = "0.9", default-features = false }
|
||||
des = { version = "0.9", default-features = false }
|
||||
cbc = { version = "0.2", default-features = false, features = ["block-padding"] }
|
||||
zeroize = { version = "1", default-features = false, features = ["alloc"] }
|
||||
# Error handling.
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring"] }
|
||||
ring = "0.17"
|
||||
@@ -0,0 +1,283 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! The algorithms a Digital signature or a certificate is checked with (RFC 8551 §2, RFC 5754,
|
||||
//! RFC 4055, RFC 5480): SHA-2 digests, RSA (PKCS #1 v1.5 and PSS, 2048 bits or more) and ECDSA
|
||||
//! on P-256 and P-384. MD5, SHA-1 and shorter RSA keys are no longer safe and are refused as
|
||||
//! such; anything else is unknown. The primitives are RustCrypto's; this only names them.
|
||||
|
||||
use const_oid::ObjectIdentifier;
|
||||
use der::{Decode, Encode};
|
||||
use sha2::Digest;
|
||||
use spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned};
|
||||
|
||||
/// Why a signature didn't check out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Fault {
|
||||
/// It doesn't match: what it covers was changed, or another key made it.
|
||||
Invalid,
|
||||
/// It uses an algorithm that's no longer safe (MD5, SHA-1, RSA under 2048 bits).
|
||||
Weak,
|
||||
/// It uses an algorithm that isn't known here.
|
||||
Unknown,
|
||||
/// The key or the signature can't be read, or they are of different kinds: nothing can be
|
||||
/// said of what it covers.
|
||||
Malformed,
|
||||
}
|
||||
|
||||
/// The least RSA modulus, in bits, that is safe enough (RFC 8551 §6).
|
||||
pub const MIN_RSA_BITS: usize = 2048;
|
||||
/// The largest RSA modulus checked, in bits: a longer key takes too long to be worth it.
|
||||
pub const MAX_RSA_BITS: usize = 8192;
|
||||
|
||||
const fn oid(s: &str) -> ObjectIdentifier {
|
||||
ObjectIdentifier::new_unwrap(s)
|
||||
}
|
||||
|
||||
// Digests.
|
||||
const MD5: ObjectIdentifier = oid("1.2.840.113549.2.5");
|
||||
const SHA1: ObjectIdentifier = oid("1.3.14.3.2.26");
|
||||
const SHA224: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.4");
|
||||
const SHA256: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.1");
|
||||
const SHA384: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.2");
|
||||
const SHA512: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.3");
|
||||
|
||||
// RSA.
|
||||
const RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.1");
|
||||
const MD2_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.2");
|
||||
const MD5_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.4");
|
||||
const SHA1_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.5");
|
||||
const PSS: ObjectIdentifier = oid("1.2.840.113549.1.1.10");
|
||||
const SHA256_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.11");
|
||||
const SHA384_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.12");
|
||||
const SHA512_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.13");
|
||||
const SHA224_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.14");
|
||||
const MGF1: ObjectIdentifier = oid("1.2.840.113549.1.1.8");
|
||||
|
||||
/// The bits of an RSA modulus written big-endian.
|
||||
fn modulus_bits(modulus: &[u8]) -> usize {
|
||||
let mut significant = modulus.iter().skip_while(|b| **b == 0);
|
||||
let top = significant.next().copied().unwrap_or(0);
|
||||
significant.count().saturating_mul(8).saturating_add(8usize.saturating_sub(top.leading_zeros() as usize))
|
||||
}
|
||||
|
||||
/// What kind of key `key` is: RSA of so many bits, ECDSA on P-256 or P-384, or another.
|
||||
pub(crate) fn key_kind(key: &SubjectPublicKeyInfoOwned) -> crate::pkcs12::KeyKind {
|
||||
use crate::pkcs12::KeyKind;
|
||||
if key.algorithm.oid == RSA {
|
||||
return key
|
||||
.subject_public_key
|
||||
.as_bytes()
|
||||
.and_then(|b| pkcs1::RsaPublicKey::<der::asn1::UintRef<'_>>::from_der(b).ok())
|
||||
.map_or(KeyKind::Other, |k| KeyKind::Rsa { bits: modulus_bits(k.modulus.as_bytes()) });
|
||||
}
|
||||
if key.algorithm.oid == EC_KEY {
|
||||
return match key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::<ObjectIdentifier>().ok()) {
|
||||
Some(P256) => KeyKind::P256,
|
||||
Some(P384) => KeyKind::P384,
|
||||
_ => KeyKind::Other,
|
||||
};
|
||||
}
|
||||
KeyKind::Other
|
||||
}
|
||||
|
||||
/// What kind of private key a PKCS #8 `PrivateKeyInfo` holds, from its own algorithm identifier
|
||||
/// (`algorithm`; for EC, its named `curve`, from the identifier's parameters or the key's own)
|
||||
/// and, for RSA, its `modulus` (big-endian): never from a certificate that came with it.
|
||||
pub(crate) fn private_key_kind(algorithm: ObjectIdentifier, curve: Option<ObjectIdentifier>, modulus: Option<&[u8]>) -> crate::pkcs12::KeyKind {
|
||||
use crate::pkcs12::KeyKind;
|
||||
match (algorithm, curve, modulus) {
|
||||
(RSA, _, Some(modulus)) => KeyKind::Rsa { bits: modulus_bits(modulus) },
|
||||
(EC_KEY, Some(P256), _) => KeyKind::P256,
|
||||
(EC_KEY, Some(P384), _) => KeyKind::P384,
|
||||
_ => KeyKind::Other,
|
||||
}
|
||||
}
|
||||
|
||||
// ECDSA.
|
||||
const EC_KEY: ObjectIdentifier = oid("1.2.840.10045.2.1");
|
||||
const SHA1_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.1");
|
||||
const SHA224_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.1");
|
||||
const SHA256_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.2");
|
||||
const SHA384_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.3");
|
||||
const SHA512_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.4");
|
||||
const P256: ObjectIdentifier = oid("1.2.840.10045.3.1.7");
|
||||
const P384: ObjectIdentifier = oid("1.3.132.0.34");
|
||||
|
||||
/// A digest algorithm that is safe to rely on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Hash {
|
||||
Sha224,
|
||||
Sha256,
|
||||
Sha384,
|
||||
Sha512,
|
||||
}
|
||||
|
||||
impl Hash {
|
||||
/// The digest a CMS `digestAlgorithm` names.
|
||||
pub fn of(algorithm: &AlgorithmIdentifierOwned) -> Result<Hash, Fault> {
|
||||
Hash::by_oid(algorithm.oid)
|
||||
}
|
||||
|
||||
fn by_oid(oid: ObjectIdentifier) -> Result<Hash, Fault> {
|
||||
match oid {
|
||||
SHA224 => Ok(Hash::Sha224),
|
||||
SHA256 => Ok(Hash::Sha256),
|
||||
SHA384 => Ok(Hash::Sha384),
|
||||
SHA512 => Ok(Hash::Sha512),
|
||||
MD5 | SHA1 => Err(Fault::Weak),
|
||||
_ => Err(Fault::Unknown),
|
||||
}
|
||||
}
|
||||
|
||||
/// The digest of `data`.
|
||||
pub fn digest(self, data: &[u8]) -> Vec<u8> {
|
||||
match self {
|
||||
Hash::Sha224 => sha2::Sha224::digest(data).to_vec(),
|
||||
Hash::Sha256 => sha2::Sha256::digest(data).to_vec(),
|
||||
Hash::Sha384 => sha2::Sha384::digest(data).to_vec(),
|
||||
Hash::Sha512 => sha2::Sha512::digest(data).to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a signature is made.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Scheme {
|
||||
Pkcs1(Hash),
|
||||
Pss(Hash, usize),
|
||||
Ecdsa(Hash),
|
||||
}
|
||||
|
||||
/// The scheme `algorithm` names; `digest` is the CMS signer's digest algorithm, for the names
|
||||
/// that leave the hash to it (`rsaEncryption`, `id-ecPublicKey`), `None` for a certificate.
|
||||
fn scheme(algorithm: &AlgorithmIdentifierOwned, digest: Option<Hash>) -> Result<Scheme, Fault> {
|
||||
match algorithm.oid {
|
||||
RSA => digest.map(Scheme::Pkcs1).ok_or(Fault::Unknown),
|
||||
SHA224_RSA => Ok(Scheme::Pkcs1(Hash::Sha224)),
|
||||
SHA256_RSA => Ok(Scheme::Pkcs1(Hash::Sha256)),
|
||||
SHA384_RSA => Ok(Scheme::Pkcs1(Hash::Sha384)),
|
||||
SHA512_RSA => Ok(Scheme::Pkcs1(Hash::Sha512)),
|
||||
MD2_RSA | MD5_RSA | SHA1_RSA | SHA1_ECDSA => Err(Fault::Weak),
|
||||
PSS => pss(algorithm),
|
||||
EC_KEY => digest.map(Scheme::Ecdsa).ok_or(Fault::Unknown),
|
||||
SHA224_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha224)),
|
||||
SHA256_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha256)),
|
||||
SHA384_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha384)),
|
||||
SHA512_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha512)),
|
||||
_ => Err(Fault::Unknown),
|
||||
}
|
||||
}
|
||||
|
||||
/// RSASSA-PSS with its parameters (RFC 4055 §3.1): the hash, MGF1 with the same hash, and the
|
||||
/// salt's length. Their defaults are SHA-1, which is no longer safe.
|
||||
fn pss(algorithm: &AlgorithmIdentifierOwned) -> Result<Scheme, Fault> {
|
||||
let params = algorithm.parameters.as_ref().ok_or(Fault::Weak)?;
|
||||
let der = params.to_der().map_err(|_| Fault::Unknown)?;
|
||||
let params = pkcs1::RsaPssParams::<der::Any>::from_der(&der).map_err(|_| Fault::Unknown)?;
|
||||
let hash = Hash::by_oid(params.hash.oid)?;
|
||||
if params.mask_gen.oid != MGF1 {
|
||||
return Err(Fault::Unknown);
|
||||
}
|
||||
let mgf_hash = params.mask_gen.parameters.as_ref().map(|p| p.oid).ok_or(Fault::Weak)?;
|
||||
if Hash::by_oid(mgf_hash)? != hash {
|
||||
return Err(Fault::Unknown);
|
||||
}
|
||||
Ok(Scheme::Pss(hash, usize::from(params.salt_len)))
|
||||
}
|
||||
|
||||
/// Check `signature` over `data` with the key `key`, by `algorithm` (and `digest`, for a CMS
|
||||
/// signer: see [`scheme`]).
|
||||
pub fn verify(
|
||||
key: &SubjectPublicKeyInfoOwned,
|
||||
algorithm: &AlgorithmIdentifierOwned,
|
||||
digest: Option<Hash>,
|
||||
data: &[u8],
|
||||
signature: &[u8],
|
||||
) -> Result<(), Fault> {
|
||||
verify_hashed(key, algorithm, digest, &mut |hash| hash.digest(data), signature)
|
||||
}
|
||||
|
||||
/// [`verify`], with what was signed given by its digest: `hashed` gives it by each algorithm
|
||||
/// (so that a long content is hashed once per algorithm however many keys are tried).
|
||||
pub fn verify_hashed(
|
||||
key: &SubjectPublicKeyInfoOwned,
|
||||
algorithm: &AlgorithmIdentifierOwned,
|
||||
digest: Option<Hash>,
|
||||
hashed: &mut dyn FnMut(Hash) -> Vec<u8>,
|
||||
signature: &[u8],
|
||||
) -> Result<(), Fault> {
|
||||
// RFC 4055 3.3: an id-RSASSA-PSS SPKI restricts schemes and parameters.
|
||||
// Those restrictions are not implemented here; do not treat it as rsaEncryption.
|
||||
if key.algorithm.oid == PSS {
|
||||
return Err(Fault::Unknown);
|
||||
}
|
||||
let scheme = scheme(algorithm, digest)?;
|
||||
match scheme {
|
||||
Scheme::Pkcs1(hash) | Scheme::Pss(hash, _) => {
|
||||
if key.algorithm.oid != RSA {
|
||||
return Err(Fault::Malformed);
|
||||
}
|
||||
let public = rsa_key(key)?;
|
||||
let hashed = hashed(hash);
|
||||
let checked = match scheme {
|
||||
Scheme::Pss(_, salt) => match hash {
|
||||
Hash::Sha224 => public.verify(rsa::pss::Pss::<sha2::Sha224>::new_with_salt(salt), &hashed, signature),
|
||||
Hash::Sha256 => public.verify(rsa::pss::Pss::<sha2::Sha256>::new_with_salt(salt), &hashed, signature),
|
||||
Hash::Sha384 => public.verify(rsa::pss::Pss::<sha2::Sha384>::new_with_salt(salt), &hashed, signature),
|
||||
Hash::Sha512 => public.verify(rsa::pss::Pss::<sha2::Sha512>::new_with_salt(salt), &hashed, signature),
|
||||
},
|
||||
_ => {
|
||||
let padding = match hash {
|
||||
Hash::Sha224 => rsa::Pkcs1v15Sign::new::<sha2::Sha224>(),
|
||||
Hash::Sha256 => rsa::Pkcs1v15Sign::new::<sha2::Sha256>(),
|
||||
Hash::Sha384 => rsa::Pkcs1v15Sign::new::<sha2::Sha384>(),
|
||||
Hash::Sha512 => rsa::Pkcs1v15Sign::new::<sha2::Sha512>(),
|
||||
};
|
||||
public.verify(padding, &hashed, signature)
|
||||
}
|
||||
};
|
||||
checked.map_err(|_| Fault::Invalid)
|
||||
}
|
||||
Scheme::Ecdsa(hash) => {
|
||||
if key.algorithm.oid != EC_KEY {
|
||||
return Err(Fault::Malformed);
|
||||
}
|
||||
let curve = key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::<ObjectIdentifier>().ok()).ok_or(Fault::Unknown)?;
|
||||
let point = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?;
|
||||
let hashed = hashed(hash);
|
||||
use p256::ecdsa::signature::hazmat::PrehashVerifier;
|
||||
match curve {
|
||||
P256 => {
|
||||
let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?;
|
||||
let sig = p256::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?;
|
||||
key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid)
|
||||
}
|
||||
P384 => {
|
||||
let key = p384::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?;
|
||||
let sig = p384::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?;
|
||||
key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid)
|
||||
}
|
||||
_ => Err(Fault::Unknown),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The RSA key of `key`: [`Fault::Weak`] under [`MIN_RSA_BITS`], [`Fault::Unknown`] past what
|
||||
/// the library takes (8192 bits) or when it can't be read.
|
||||
fn rsa_key(key: &SubjectPublicKeyInfoOwned) -> Result<rsa::RsaPublicKey, Fault> {
|
||||
let bits = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?;
|
||||
let pkcs1 = pkcs1::RsaPublicKey::<der::asn1::UintRef<'_>>::from_der(bits).map_err(|_| Fault::Unknown)?;
|
||||
let bits = modulus_bits(pkcs1.modulus.as_bytes());
|
||||
if bits < MIN_RSA_BITS {
|
||||
return Err(Fault::Weak);
|
||||
}
|
||||
if bits > MAX_RSA_BITS {
|
||||
return Err(Fault::Unknown);
|
||||
}
|
||||
rsa::RsaPublicKey::new(
|
||||
rsa::BoxedUint::from_be_slice_vartime(pkcs1.modulus.as_bytes()),
|
||||
rsa::BoxedUint::from_be_slice_vartime(pkcs1.public_exponent.as_bytes()),
|
||||
)
|
||||
.map_err(|_| Fault::Unknown)
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! An X.509 certificate (RFC 5280) as a Digital signature is checked with: its bytes, what it
|
||||
//! says, and the few questions asked of it (who it names, for what, until when, who signed it).
|
||||
|
||||
use crate::Timestamp;
|
||||
use crate::digital_signature::{MAX_SIGNER_ADDRESSES, signer_text};
|
||||
use const_oid::ObjectIdentifier;
|
||||
use der::{Decode, Encode};
|
||||
use x509_cert::Certificate;
|
||||
use x509_cert::ext::pkix::constraints::name::GeneralSubtrees;
|
||||
use x509_cert::ext::pkix::name::GeneralName;
|
||||
use x509_cert::ext::pkix::{
|
||||
AuthorityKeyIdentifier, BasicConstraints, CertificatePolicies, ExtendedKeyUsage, KeyUsage, NameConstraints, SubjectAltName, SubjectKeyIdentifier,
|
||||
};
|
||||
|
||||
use crate::algorithms::{self, Fault};
|
||||
use craft_ber as ber;
|
||||
|
||||
/// The largest certificate read.
|
||||
pub const MAX_CERT_BYTES: usize = 64 * 1024;
|
||||
|
||||
const EMAIL_PROTECTION: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4");
|
||||
const ANY_EXTENDED_KEY_USAGE: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.37.0");
|
||||
const EMAIL_ADDRESS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1");
|
||||
|
||||
/// The extensions whose meaning is known here (RFC 5280 §4.2): a certificate with any other
|
||||
/// marked critical is refused (§6.1.4 (o)). Certificate policies are taken as any policy (no
|
||||
/// policy is asked for, §6.1.1 (c)); the identifiers say nothing to check.
|
||||
const KNOWN: [ObjectIdentifier; 8] = [
|
||||
ObjectIdentifier::new_unwrap("2.5.29.14"), // subject key identifier
|
||||
ObjectIdentifier::new_unwrap("2.5.29.15"), // key usage
|
||||
ObjectIdentifier::new_unwrap("2.5.29.17"), // subject alternative name
|
||||
ObjectIdentifier::new_unwrap("2.5.29.19"), // basic constraints
|
||||
ObjectIdentifier::new_unwrap("2.5.29.30"), // name constraints
|
||||
ObjectIdentifier::new_unwrap("2.5.29.32"), // certificate policies
|
||||
ObjectIdentifier::new_unwrap("2.5.29.35"), // authority key identifier
|
||||
ObjectIdentifier::new_unwrap("2.5.29.37"), // extended key usage
|
||||
];
|
||||
|
||||
/// The name constraints a certification authority puts on what it vouches for (RFC 5280
|
||||
/// §4.2.1.10), for the two kinds of name a mail certificate has: mail addresses and directory
|
||||
/// names. The other kinds name nothing that is checked here.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Constraints {
|
||||
pub permitted_mail: Option<Vec<String>>,
|
||||
pub excluded_mail: Vec<String>,
|
||||
pub permitted_dirs: Option<Vec<Vec<Vec<u8>>>>,
|
||||
pub excluded_dirs: Vec<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
/// A directory identity represented as ordered DER relative names.
|
||||
pub type DirectoryName = Vec<Vec<u8>>;
|
||||
|
||||
/// A certificate: its DER, the body its issuer signed, and what it says.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Cert {
|
||||
der: Vec<u8>,
|
||||
/// Where the to-be-signed body is in `der`.
|
||||
tbs: std::ops::Range<usize>,
|
||||
parsed: Certificate,
|
||||
subject: Vec<u8>,
|
||||
issuer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PartialEq for Cert {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.der == other.der
|
||||
}
|
||||
}
|
||||
|
||||
impl Cert {
|
||||
/// The certificate `der` is, when it is one.
|
||||
pub fn from_der(der: &[u8]) -> Option<Cert> {
|
||||
if der.len() > MAX_CERT_BYTES {
|
||||
return None;
|
||||
}
|
||||
let (outer, rest) = ber::read(der)?;
|
||||
if !rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (tbs, _) = ber::read(outer.value)?;
|
||||
let start = outer.whole.len().checked_sub(outer.value.len())?;
|
||||
let end = start.checked_add(tbs.whole.len())?;
|
||||
let parsed = Certificate::from_der(der).ok()?;
|
||||
// RFC 5280 4.1.1.2: the outer and signed algorithm identifiers must agree.
|
||||
if parsed.signature_algorithm() != parsed.tbs_certificate().signature() {
|
||||
return None;
|
||||
}
|
||||
// A recognized extension that cannot be decoded is not an absent extension.
|
||||
// In particular, never fall back to the subject identity after a malformed SAN.
|
||||
let tbs = parsed.tbs_certificate();
|
||||
if tbs.get_extension::<SubjectAltName>().is_err()
|
||||
|| tbs.get_extension::<SubjectKeyIdentifier>().is_err()
|
||||
|| tbs.get_extension::<AuthorityKeyIdentifier>().is_err()
|
||||
|| tbs.get_extension::<KeyUsage>().is_err()
|
||||
|| tbs.get_extension::<ExtendedKeyUsage>().is_err()
|
||||
|| tbs.get_extension::<BasicConstraints>().is_err()
|
||||
|| tbs.get_extension::<NameConstraints>().is_err()
|
||||
|| tbs.get_extension::<CertificatePolicies>().is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let subject = parsed.tbs_certificate().subject().to_der().ok()?;
|
||||
let issuer = parsed.tbs_certificate().issuer().to_der().ok()?;
|
||||
Some(Cert { der: der.to_vec(), tbs: start..end, parsed, subject, issuer })
|
||||
}
|
||||
|
||||
pub fn der(&self) -> &[u8] {
|
||||
&self.der
|
||||
}
|
||||
|
||||
fn tbs(&self) -> &[u8] {
|
||||
self.der.get(self.tbs.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn subject(&self) -> &[u8] {
|
||||
&self.subject
|
||||
}
|
||||
|
||||
pub fn issuer(&self) -> &[u8] {
|
||||
&self.issuer
|
||||
}
|
||||
|
||||
/// The serial number's bytes.
|
||||
pub fn serial(&self) -> &[u8] {
|
||||
self.parsed.tbs_certificate().serial_number().as_bytes()
|
||||
}
|
||||
|
||||
/// The subject key identifier, when it has one.
|
||||
pub fn key_id(&self) -> Option<Vec<u8>> {
|
||||
let (_, ski) = self.parsed.tbs_certificate().get_extension::<SubjectKeyIdentifier>().ok()??;
|
||||
Some(ski.0.as_bytes().to_vec())
|
||||
}
|
||||
|
||||
pub fn public_key(&self) -> &spki::SubjectPublicKeyInfoOwned {
|
||||
self.parsed.tbs_certificate().subject_public_key_info()
|
||||
}
|
||||
|
||||
/// Its SHA-256 fingerprint: upper-case hexadecimal pairs with colons between.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
algorithms::Hash::Sha256.digest(&self.der).iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(":")
|
||||
}
|
||||
|
||||
/// From and until when it is valid, in seconds since 1970.
|
||||
pub fn validity(&self) -> (Timestamp, Timestamp) {
|
||||
let v = self.parsed.tbs_certificate().validity();
|
||||
let secs = |t: &x509_cert::time::Time| Timestamp::try_from(t.to_unix_duration().as_secs()).unwrap_or(Timestamp::MAX);
|
||||
(secs(&v.not_before), secs(&v.not_after))
|
||||
}
|
||||
|
||||
/// Whether it is valid at `now`.
|
||||
pub fn valid_at(&self, now: Timestamp) -> bool {
|
||||
let (from, until) = self.validity();
|
||||
from <= now && now <= until
|
||||
}
|
||||
|
||||
/// The name it is for: its common name, else its whole name.
|
||||
pub fn name(&self) -> String {
|
||||
name_of(self.parsed.tbs_certificate().subject())
|
||||
}
|
||||
|
||||
/// The name of who issued it.
|
||||
pub fn issuer_name(&self) -> String {
|
||||
name_of(self.parsed.tbs_certificate().issuer())
|
||||
}
|
||||
|
||||
/// The mail addresses it is for: its subject alternative names of that kind, and an
|
||||
/// `emailAddress` in its subject (RFC 8551 §3.1), at most [`MAX_SIGNER_ADDRESSES`].
|
||||
pub fn addresses(&self) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>() {
|
||||
for name in san.0.iter() {
|
||||
if let GeneralName::Rfc822Name(a) = name {
|
||||
out.push(signer_text(a.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for atv in self.parsed.tbs_certificate().subject().iter() {
|
||||
if atv.oid == EMAIL_ADDRESS
|
||||
&& let Ok(a) = atv.value.decode_as::<der::asn1::Ia5String>()
|
||||
{
|
||||
out.push(signer_text(a.as_str()));
|
||||
}
|
||||
}
|
||||
out.retain(|a| !a.is_empty());
|
||||
out.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
|
||||
out.truncate(MAX_SIGNER_ADDRESSES);
|
||||
out
|
||||
}
|
||||
|
||||
/// The mail addresses it names, exactly as written (its alternative names of that kind and
|
||||
/// the `emailAddress` in its subject), all of them: for comparing
|
||||
/// and for name constraints, never for showing. The certificate byte cap bounds this list; display truncation
|
||||
/// must not hide names from certification-authority constraints.
|
||||
pub fn raw_addresses(&self) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>() {
|
||||
out.extend(san.0.iter().filter_map(|n| match n {
|
||||
GeneralName::Rfc822Name(a) => Some(a.as_str().to_string()),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
out.extend(
|
||||
self.parsed
|
||||
.tbs_certificate()
|
||||
.subject()
|
||||
.iter()
|
||||
.filter(|atv| atv.oid == EMAIL_ADDRESS)
|
||||
.filter_map(|atv| atv.value.decode_as::<der::asn1::Ia5String>().ok())
|
||||
.map(|a| a.as_str().to_string()),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether it is for `address`: one of its addresses as written is that address, letter case
|
||||
/// aside in plain ASCII (RFC 5280 §4.2.1.6, §7.5). An address with a space, a control or any
|
||||
/// character past ASCII on either side never is.
|
||||
pub fn is_for(&self, address: &str) -> bool {
|
||||
printable(address) && self.raw_addresses().iter().any(|a| printable(a) && a.eq_ignore_ascii_case(address))
|
||||
}
|
||||
|
||||
/// The address of its it is for `address` by ([`Cert::is_for`]), as it shows it.
|
||||
pub fn address_for(&self, address: &str) -> Option<String> {
|
||||
printable(address).then(|| self.raw_addresses().into_iter().find(|a| printable(a) && a.eq_ignore_ascii_case(address))).flatten()
|
||||
}
|
||||
|
||||
/// Whether it carries an extension marked critical that isn't known here.
|
||||
pub fn unknown_critical(&self) -> bool {
|
||||
self.parsed.tbs_certificate().extensions().is_some_and(|exts| exts.iter().any(|e| e.critical && !KNOWN.contains(&e.extn_id)))
|
||||
}
|
||||
|
||||
/// Its path length constraint, when its basic constraints give one (unreadable: none
|
||||
/// allowed below it).
|
||||
pub fn path_len(&self) -> Option<u8> {
|
||||
match self.parsed.tbs_certificate().get_extension::<BasicConstraints>() {
|
||||
Ok(Some((_, bc))) => bc.path_len_constraint,
|
||||
Ok(None) => None,
|
||||
Err(_) => Some(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether, as a certification authority on a path, its extended key usage (when it has
|
||||
/// one) lets it vouch for mail: email protection, or any use.
|
||||
pub fn may_vouch_for_mail(&self) -> bool {
|
||||
match self.parsed.tbs_certificate().get_extension::<ExtendedKeyUsage>() {
|
||||
Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE),
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it is a certification authority's by any sign (basic constraints say so, or its
|
||||
/// key usage lets it sign certificates): never a mail signer's.
|
||||
pub fn is_authority(&self) -> bool {
|
||||
let tbs = self.parsed.tbs_certificate();
|
||||
let ca = matches!(tbs.get_extension::<BasicConstraints>(), Ok(Some((_, bc))) if bc.ca);
|
||||
let signs = matches!(tbs.get_extension::<KeyUsage>(), Ok(Some((_, ku))) if ku.key_cert_sign());
|
||||
ca || signs
|
||||
}
|
||||
|
||||
/// The name constraints it puts on what it vouches for; `Err` when they can't be read or use
|
||||
/// what RFC 5280 says mustn't be (a minimum or a maximum).
|
||||
pub fn constraints(&self) -> Result<Option<Constraints>, ()> {
|
||||
let Some((_, nc)) = self.parsed.tbs_certificate().get_extension::<NameConstraints>().map_err(|_| ())? else { return Ok(None) };
|
||||
let mut c = Constraints::default();
|
||||
if let Some(permitted) = &nc.permitted_subtrees {
|
||||
let (mail, dirs) = subtrees(permitted)?;
|
||||
c.permitted_mail = mail;
|
||||
c.permitted_dirs = dirs;
|
||||
}
|
||||
if let Some(excluded) = &nc.excluded_subtrees {
|
||||
let (mail, dirs) = subtrees(excluded)?;
|
||||
c.excluded_mail = mail.unwrap_or_default();
|
||||
c.excluded_dirs = dirs.unwrap_or_default();
|
||||
}
|
||||
Ok(Some(c))
|
||||
}
|
||||
|
||||
/// Every directory identity: the nonempty subject and every directoryName SAN.
|
||||
pub fn directory_names(&self) -> Option<Vec<DirectoryName>> {
|
||||
let rdns = |name: &x509_cert::name::Name| name.iter_rdn().map(|r| r.to_der().ok()).collect::<Option<Vec<_>>>();
|
||||
let mut names = Vec::new();
|
||||
let subject = rdns(self.parsed.tbs_certificate().subject())?;
|
||||
if !subject.is_empty() {
|
||||
names.push(subject);
|
||||
}
|
||||
if let Some((_, san)) = self.parsed.tbs_certificate().get_extension::<SubjectAltName>().ok()? {
|
||||
for name in &san.0 {
|
||||
if let GeneralName::DirectoryName(name) = name {
|
||||
names.push(rdns(name)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(names)
|
||||
}
|
||||
|
||||
/// Whether it may be a certification authority's: basic constraints say so, and its key
|
||||
/// usage, when it has one, lets it sign certificates.
|
||||
pub fn is_ca(&self) -> bool {
|
||||
let tbs = self.parsed.tbs_certificate();
|
||||
let ca = matches!(tbs.get_extension::<BasicConstraints>(), Ok(Some((_, bc))) if bc.ca);
|
||||
let signs = match tbs.get_extension::<KeyUsage>() {
|
||||
Ok(Some((_, ku))) => ku.key_cert_sign(),
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
ca && signs
|
||||
}
|
||||
|
||||
/// Whether it is for signing mail (RFC 8551 §4.4): its key usage, when it has one, allows a
|
||||
/// Digital signature or non-repudiation, and its extended key usage, when it has one, names
|
||||
/// email protection (or any use).
|
||||
pub fn for_email(&self) -> bool {
|
||||
let tbs = self.parsed.tbs_certificate();
|
||||
let usage = match tbs.get_extension::<KeyUsage>() {
|
||||
Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation(),
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
let extended = match tbs.get_extension::<ExtendedKeyUsage>() {
|
||||
Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE),
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
usage && extended
|
||||
}
|
||||
|
||||
/// Whether it is for mail at all, to sign it or to encrypt it (RFC 8551 §4.4): its key usage,
|
||||
/// when it has one, allows a Digital signature, non-repudiation, key encipherment or key
|
||||
/// agreement, and its extended key usage, when it has one, names email protection (or any
|
||||
/// use). What a Public key imported for an address must be.
|
||||
pub fn for_mail(&self) -> bool {
|
||||
let tbs = self.parsed.tbs_certificate();
|
||||
let usage = match tbs.get_extension::<KeyUsage>() {
|
||||
Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation() || ku.key_encipherment() || ku.key_agreement(),
|
||||
Ok(None) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
usage && self.may_vouch_for_mail()
|
||||
}
|
||||
|
||||
/// Whether it names itself as its issuer.
|
||||
pub fn self_issued(&self) -> bool {
|
||||
self.subject == self.issuer
|
||||
}
|
||||
|
||||
/// Whether `issuer`'s key made its signature.
|
||||
pub fn signed_by(&self, issuer: &Cert) -> Result<(), Fault> {
|
||||
let signature = self.parsed.signature().as_bytes().ok_or(Fault::Invalid)?;
|
||||
algorithms::verify(issuer.public_key(), self.parsed.signature_algorithm(), None, self.tbs(), signature)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `address` has only the printable ASCII an address is compared in (and something).
|
||||
pub(crate) fn printable(address: &str) -> bool {
|
||||
!address.is_empty() && address.bytes().all(|b| (0x21..=0x7e).contains(&b))
|
||||
}
|
||||
|
||||
/// The mail and directory names of `subtrees` (`None` of a kind: none of that kind given).
|
||||
type Subtrees = (Option<Vec<String>>, Option<Vec<Vec<Vec<u8>>>>);
|
||||
|
||||
fn subtrees(subtrees: &GeneralSubtrees) -> Result<Subtrees, ()> {
|
||||
let (mut mail, mut dirs): Subtrees = (None, None);
|
||||
for s in subtrees.iter().take(64) {
|
||||
if s.minimum != 0 || s.maximum.is_some() {
|
||||
return Err(());
|
||||
}
|
||||
match &s.base {
|
||||
GeneralName::Rfc822Name(a) => mail.get_or_insert_with(Vec::new).push(a.as_str().to_string()),
|
||||
GeneralName::DirectoryName(n) => dirs.get_or_insert_with(Vec::new).push(n.iter_rdn().filter_map(|r| r.to_der().ok()).collect()),
|
||||
// RFC 5280 4.2.1.10: constraints cannot be treated as processed when
|
||||
// this validator does not implement their name form. Fail closed.
|
||||
_ => return Err(()),
|
||||
}
|
||||
}
|
||||
if subtrees.len() > 64 {
|
||||
return Err(());
|
||||
}
|
||||
Ok((mail, dirs))
|
||||
}
|
||||
|
||||
/// Whether the mail address `address` is within the constraint `base` (RFC 5280 §4.2.1.10): a
|
||||
/// whole address, every address at one host, or (with a leading dot) every address at any host
|
||||
/// under a domain. Letter case aside.
|
||||
pub fn mail_within(address: &str, base: &str) -> bool {
|
||||
let address = address.to_ascii_lowercase();
|
||||
let base = base.to_ascii_lowercase();
|
||||
if base.contains('@') {
|
||||
return address == base;
|
||||
}
|
||||
let Some((_, host)) = address.rsplit_once('@') else { return false };
|
||||
if let Some(domain) = base.strip_prefix('.') {
|
||||
return host.len() > domain.len() && host.ends_with(domain) && host.as_bytes().get(host.len() - domain.len() - 1) == Some(&b'.');
|
||||
}
|
||||
host == base
|
||||
}
|
||||
|
||||
/// Whether the name `rdns` is within the directory name `base`: it begins with all of it, each
|
||||
/// relative name compared using the supported ASCII subset of RFC 5280 §7.1.
|
||||
/// Unsupported string types or non-ASCII values must fail closed in the caller.
|
||||
pub fn dir_within(rdns: &[Vec<u8>], base: &[Vec<u8>]) -> bool {
|
||||
rdns.len() >= base.len() && rdns.iter().zip(base).all(|(a, b)| matches!((rdn_key(a), rdn_key(b)), (Some(x), Some(y)) if x == y))
|
||||
}
|
||||
|
||||
/// Whether every relative name is within the supported comparison profile.
|
||||
pub fn directory_supported(rdns: &[Vec<u8>]) -> bool {
|
||||
rdns.iter().all(|rdn| rdn_key(rdn).is_some())
|
||||
}
|
||||
|
||||
fn rdn_key(der: &[u8]) -> Option<Vec<(String, Vec<u8>)>> {
|
||||
use der::Tag;
|
||||
let rdn = x509_cert::name::RelativeDistinguishedName::from_der(der).ok()?;
|
||||
let mut key: Vec<(String, Vec<u8>)> = rdn
|
||||
.iter()
|
||||
.map(|atv| {
|
||||
let value = match der::Tagged::tag(&atv.value) {
|
||||
Tag::PrintableString | Tag::Utf8String => {
|
||||
let text = std::str::from_utf8(atv.value.value()).ok()?;
|
||||
// RFC 5280 7.1 requires StringPrep for non-ASCII names. Until the
|
||||
// complete profile is implemented, constrained chains fail closed.
|
||||
if !text.is_ascii() {
|
||||
return None;
|
||||
}
|
||||
let folded: Vec<String> = text.split_whitespace().map(str::to_lowercase).collect();
|
||||
let mut v = b"s".to_vec();
|
||||
v.extend_from_slice(folded.join(" ").as_bytes());
|
||||
v
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some((atv.oid.to_string(), value))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
key.sort();
|
||||
Some(key)
|
||||
}
|
||||
|
||||
/// A name for people: its common name, else the whole of it as RFC 4514 writes it.
|
||||
fn name_of(name: &x509_cert::name::Name) -> String {
|
||||
if let Ok(Some(cn)) = name.common_name() {
|
||||
let cn = signer_text(&cn.value());
|
||||
if !cn.is_empty() {
|
||||
return cn;
|
||||
}
|
||||
}
|
||||
signer_text(&name.to_string())
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Whether a signer's certificate rests on a trust anchor (RFC 5280 §6, as S/MIME needs it): a
|
||||
//! path from it through certification authorities' certificates that came with the message, to
|
||||
//! a certificate the host trusts. Each link's signature is checked, and every certificate on the
|
||||
//! path must be valid at the time of the check and keep its authorities' constraints. Bounded: a
|
||||
//! path is at most [`MAX_PATH`] long, and the signatures checked come out of the message's
|
||||
//! budget ([`crate::MAX_VERIFICATIONS`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::Timestamp;
|
||||
use crate::digital_signature::Why;
|
||||
|
||||
use crate::algorithms::Fault;
|
||||
use crate::cert::{Cert, Constraints, dir_within, directory_supported, mail_within};
|
||||
|
||||
/// The most certificates between a signer's and a trust anchor.
|
||||
pub const MAX_PATH: usize = 6;
|
||||
/// The most trust anchors kept.
|
||||
pub const MAX_ANCHORS: usize = 4_000;
|
||||
|
||||
/// The certificates the host trusts (the system's certification authorities, handed in: this
|
||||
/// crate never reads a store of its own).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Anchors {
|
||||
certs: Vec<Cert>,
|
||||
by_subject: HashMap<Vec<u8>, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl Anchors {
|
||||
/// Anchors from certificates in DER; one that isn't a certificate is left out, as is
|
||||
/// everything past [`MAX_ANCHORS`].
|
||||
pub fn new<I, B>(ders: I) -> Anchors
|
||||
where
|
||||
I: IntoIterator<Item = B>,
|
||||
B: AsRef<[u8]>,
|
||||
{
|
||||
let mut anchors = Anchors::default();
|
||||
for der in ders {
|
||||
if anchors.certs.len() >= MAX_ANCHORS {
|
||||
break;
|
||||
}
|
||||
if let Some(cert) = Cert::from_der(der.as_ref()) {
|
||||
anchors.by_subject.entry(cert.subject().to_vec()).or_default().push(anchors.certs.len());
|
||||
anchors.certs.push(cert);
|
||||
}
|
||||
}
|
||||
anchors
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.certs.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.certs.is_empty()
|
||||
}
|
||||
|
||||
fn named(&self, subject: &[u8]) -> impl Iterator<Item = &Cert> {
|
||||
self.by_subject.get(subject).into_iter().flatten().filter_map(|i| self.certs.get(*i))
|
||||
}
|
||||
|
||||
fn holds(&self, cert: &Cert) -> bool {
|
||||
self.named(cert.subject()).any(|a| a == cert)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `leaf` rests on one of `anchors` through the certificates of `pool`, at `now`,
|
||||
/// checking at most `budget` signatures (taken from it). Every path to an anchor is tried until
|
||||
/// one holds (RFC 5280 §6.1): each certificate on it valid at `now`, none with a critical
|
||||
/// extension not known here, each authority's path length and name constraints kept, and every
|
||||
/// authority's extended key usage, when it has one, allowing mail.
|
||||
///
|
||||
/// (Validity is checked at the time of the check, not the signing time the signer gives: that is
|
||||
/// the signer's own word, and a certificate that ran out or was replaced since is said.)
|
||||
pub fn trust(leaf: &Cert, pool: &[Cert], anchors: &Anchors, now: Timestamp, budget: &mut usize) -> Result<(), Why> {
|
||||
let mut search = Search { leaf, pool, anchors, now, budget, weak: false, refused: None, ran_out: false };
|
||||
let mut path = Vec::new();
|
||||
if search.walk(leaf, &mut path) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(match search.refused {
|
||||
// (A path left untried may hold: no answer, rather than the first refusal's.)
|
||||
_ if search.ran_out => Why::TooMuch,
|
||||
Some(why) => why,
|
||||
None if search.weak => Why::WeakAlgorithm,
|
||||
None if leaf.self_issued() => Why::SelfSigned,
|
||||
None => Why::UnknownIssuer,
|
||||
})
|
||||
}
|
||||
|
||||
struct Search<'a, 'b> {
|
||||
leaf: &'a Cert,
|
||||
pool: &'a [Cert],
|
||||
anchors: &'a Anchors,
|
||||
now: Timestamp,
|
||||
budget: &'b mut usize,
|
||||
/// A link was signed with an algorithm that's no longer safe.
|
||||
weak: bool,
|
||||
/// Why the first path found to an anchor didn't hold.
|
||||
refused: Option<Why>,
|
||||
/// The budget ran out before every path was tried.
|
||||
ran_out: bool,
|
||||
}
|
||||
|
||||
impl<'a> Search<'a, '_> {
|
||||
/// Whether `cert` rests on an anchor by a path that holds; `path` has the certificates above
|
||||
/// the leaf so far, the anchor last once one is reached.
|
||||
fn walk(&mut self, cert: &'a Cert, path: &mut Vec<&'a Cert>) -> bool {
|
||||
// A certificate the host trusts itself ends the path, whether it holds or not.
|
||||
if self.anchors.holds(cert) {
|
||||
return self.holds(path);
|
||||
}
|
||||
for anchor in self.anchors.named(cert.issuer()) {
|
||||
if self.signed(cert, anchor) {
|
||||
path.push(anchor);
|
||||
if self.holds(path) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
if path.len() >= MAX_PATH {
|
||||
return false;
|
||||
}
|
||||
for issuer in self.pool.iter().filter(|c| c.subject() == cert.issuer() && *c != cert && c.is_ca()) {
|
||||
// (No certificate twice on a path.)
|
||||
if path.contains(&issuer) || !self.signed(cert, issuer) {
|
||||
continue;
|
||||
}
|
||||
path.push(issuer);
|
||||
if self.walk(issuer, path) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the path from the leaf through `above` (the anchor last) holds; why not is kept.
|
||||
fn holds(&mut self, above: &[&Cert]) -> bool {
|
||||
let full: Vec<&Cert> = std::iter::once(self.leaf).chain(above.iter().copied()).collect();
|
||||
match judge(&full, self.now) {
|
||||
Ok(()) => true,
|
||||
Err(why) => {
|
||||
self.refused.get_or_insert(why);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn signed(&mut self, cert: &Cert, by: &Cert) -> bool {
|
||||
if *self.budget == 0 {
|
||||
self.ran_out = true;
|
||||
return false;
|
||||
}
|
||||
*self.budget -= 1;
|
||||
match cert.signed_by(by) {
|
||||
Ok(()) => true,
|
||||
Err(Fault::Weak) => {
|
||||
self.weak = true;
|
||||
false
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the path `full` (the leaf first, the anchor last) holds at `now` (RFC 5280 §6.1).
|
||||
pub(crate) fn judge(full: &[&Cert], now: Timestamp) -> Result<(), Why> {
|
||||
if full.iter().any(|c| !c.valid_at(now)) {
|
||||
return Err(Why::Expired);
|
||||
}
|
||||
// (The anchor is the host's to vouch for, extensions and all.)
|
||||
let last = full.len().saturating_sub(1);
|
||||
if full.iter().take(last).any(|c| c.unknown_critical()) {
|
||||
return Err(Why::Constrained);
|
||||
}
|
||||
for (k, ca) in full.iter().enumerate().skip(1) {
|
||||
if !ca.may_vouch_for_mail() {
|
||||
return Err(Why::Constrained);
|
||||
}
|
||||
// The certificates below it that count: the leaf, and every authority's not issued by
|
||||
// itself (§6.1.4 (l), §6.1.3 (b)).
|
||||
let below: Vec<&Cert> = full.iter().take(k).enumerate().filter(|(j, c)| *j == 0 || !c.self_issued()).map(|(_, c)| *c).collect();
|
||||
if let Some(n) = ca.path_len()
|
||||
&& below.len().saturating_sub(1) > usize::from(n)
|
||||
{
|
||||
return Err(Why::Constrained);
|
||||
}
|
||||
let Ok(constraints) = ca.constraints() else { return Err(Why::Constrained) };
|
||||
if let Some(c) = constraints
|
||||
&& !below.iter().all(|cert| within(cert, &c))
|
||||
{
|
||||
return Err(Why::Constrained);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the names of `cert` are within `c`.
|
||||
fn within(cert: &Cert, c: &Constraints) -> bool {
|
||||
let mail = cert.raw_addresses();
|
||||
if let Some(permitted) = &c.permitted_mail
|
||||
&& !mail.iter().all(|a| permitted.iter().any(|p| mail_within(a, p)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if mail.iter().any(|a| c.excluded_mail.iter().any(|e| mail_within(a, e))) {
|
||||
return false;
|
||||
}
|
||||
// Unsupported normalization must not make an excluded subtree look different.
|
||||
if c.permitted_dirs.is_none() && c.excluded_dirs.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let Some(names) = cert.directory_names() else { return false };
|
||||
if !names.iter().all(|name| directory_supported(name))
|
||||
|| !c.excluded_dirs.iter().all(|name| directory_supported(name))
|
||||
|| c.permitted_dirs.as_ref().is_some_and(|names| !names.iter().all(|name| directory_supported(name)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
names.iter().all(|rdns| {
|
||||
if let Some(permitted) = &c.permitted_dirs
|
||||
&& !permitted.iter().any(|p| dir_within(rdns, p))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
!c.excluded_dirs.iter().any(|e| dir_within(rdns, e))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! What checking a message's Digital signature found (#30), whichever format it is in: S/MIME
|
||||
//! (`craft-smime`) or OpenPGP. One of four results ([`Verdict`]), why when it isn't the
|
||||
//! first ([`Why`]), and what is known of who signed it ([`Signer`]). Worked out from the bytes the
|
||||
//! message came as, in memory, and never written to the mailbox file: it is checked again when
|
||||
//! the message is next looked at, against the trust and the clock of that moment.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Timestamp;
|
||||
|
||||
/// The format of a Digital signature.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SignatureFormat {
|
||||
/// S/MIME (RFC 8551): CMS signed data and an X.509 certificate.
|
||||
Smime,
|
||||
/// OpenPGP (RFC 9580), as PGP/MIME (RFC 3156) or inline.
|
||||
OpenPgp,
|
||||
}
|
||||
|
||||
impl SignatureFormat {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
SignatureFormat::Smime => "smime",
|
||||
SignatureFormat::OpenPgp => "openpgp",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The four results a check has, best first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Verdict {
|
||||
/// The Digital signature is valid, its signer is trusted, the signer's address is the
|
||||
/// message's one From address (verified is for that signer and that address together, never
|
||||
/// for a key alone), and what was signed is the whole message ([`Coverage::Whole`]).
|
||||
Verified,
|
||||
/// The Digital signature is valid, but its signer isn't verified ([`Why`] says how): an
|
||||
/// unknown issuer, a certificate out of date or not for mail, an address that isn't the From
|
||||
/// address, an OpenPGP key nobody marked verified.
|
||||
NotVerified,
|
||||
/// The message was changed after it was signed: what is shown isn't what was signed.
|
||||
Changed,
|
||||
/// The Digital signature can't be checked ([`Why`] says why): an algorithm that's no longer
|
||||
/// safe or isn't known, no Public key, or a signature that can't be read.
|
||||
Unchecked,
|
||||
}
|
||||
|
||||
impl Verdict {
|
||||
/// Its name for an agent and a script: `verified`, `notVerified`, `changed`, `unchecked`.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Verdict::Verified => "verified",
|
||||
Verdict::NotVerified => "notVerified",
|
||||
Verdict::Changed => "changed",
|
||||
Verdict::Unchecked => "unchecked",
|
||||
}
|
||||
}
|
||||
|
||||
/// The better of two results ([`Verdict::Verified`] best): of several signers of one
|
||||
/// message, the best one stands.
|
||||
pub fn best(self, other: Verdict) -> Verdict {
|
||||
self.min(other)
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a check found less than [`Verdict::Verified`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Why {
|
||||
// Not verified.
|
||||
/// The certificate wasn't issued by a certification authority this computer trusts.
|
||||
UnknownIssuer,
|
||||
/// The certificate signed itself, and isn't one this computer trusts.
|
||||
SelfSigned,
|
||||
/// The certificate, or one of those it rests on, is out of date (or not valid yet).
|
||||
Expired,
|
||||
/// The certificate isn't for signing mail (its key usage or extended key usage say so).
|
||||
NotForEmail,
|
||||
/// The certificate is for another address than the message's From address.
|
||||
AddressMismatch,
|
||||
/// An authority on the way to a trusted one doesn't allow the certificate to be used this
|
||||
/// way: a name outside what it may vouch for, a path too long, a use it doesn't allow, or a
|
||||
/// critical extension not known here (RFC 5280 §4.2, §6.1).
|
||||
Constrained,
|
||||
/// No certification authorities for mail could be read on this computer, so no signer can be
|
||||
/// verified here.
|
||||
NoAuthorities,
|
||||
/// This computer's certification authorities haven't been read yet (they are read at start):
|
||||
/// the check is made again when they are.
|
||||
AuthoritiesNotRead,
|
||||
/// An OpenPGP key that the owner hasn't marked Verified.
|
||||
KeyNotVerified,
|
||||
/// Only part of the message was signed (a wrapper such as a list's footer holds it), so
|
||||
/// what is outside that part could say anything.
|
||||
PartlySigned,
|
||||
// Changed.
|
||||
/// What was signed isn't what arrived.
|
||||
Altered,
|
||||
// Can't be checked.
|
||||
/// It uses an algorithm that's no longer safe (MD5, SHA-1, a short RSA key).
|
||||
WeakAlgorithm,
|
||||
/// It uses an algorithm MailCraft doesn't know.
|
||||
UnknownAlgorithm,
|
||||
/// The signer's Public key (certificate) isn't in the message or kept here.
|
||||
NoPublicKey,
|
||||
/// The signer's OpenPGP key was revoked by its owner, for when the message was signed.
|
||||
KeyRevoked,
|
||||
/// The signer's OpenPGP key had expired when the message was signed.
|
||||
KeyExpired,
|
||||
/// The OpenPGP key that made it isn't one that may sign.
|
||||
NotASigningKey,
|
||||
/// The Digital signature itself has expired (it said until when it holds).
|
||||
SignatureExpired,
|
||||
/// The Digital signature can't be read.
|
||||
Unreadable,
|
||||
/// The bytes the message came as aren't here (it was read before they were kept): Check
|
||||
/// again downloads them.
|
||||
NoOriginal,
|
||||
/// There is more to check than a message is allowed (many certificates, or many ways to a
|
||||
/// trusted authority): it was stopped before an answer.
|
||||
TooMuch,
|
||||
}
|
||||
|
||||
impl Why {
|
||||
/// Its name for an agent and a script.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Why::UnknownIssuer => "unknownIssuer",
|
||||
Why::SelfSigned => "selfSigned",
|
||||
Why::Expired => "expired",
|
||||
Why::NotForEmail => "notForEmail",
|
||||
Why::AddressMismatch => "addressMismatch",
|
||||
Why::Constrained => "constrained",
|
||||
Why::NoAuthorities => "noAuthorities",
|
||||
Why::AuthoritiesNotRead => "authoritiesNotRead",
|
||||
Why::KeyNotVerified => "keyNotVerified",
|
||||
Why::PartlySigned => "partlySigned",
|
||||
Why::Altered => "altered",
|
||||
Why::WeakAlgorithm => "weakAlgorithm",
|
||||
Why::UnknownAlgorithm => "unknownAlgorithm",
|
||||
Why::NoPublicKey => "noPublicKey",
|
||||
Why::KeyRevoked => "keyRevoked",
|
||||
Why::KeyExpired => "keyExpired",
|
||||
Why::NotASigningKey => "notASigningKey",
|
||||
Why::SignatureExpired => "signatureExpired",
|
||||
Why::Unreadable => "unreadable",
|
||||
Why::NoOriginal => "noOriginal",
|
||||
Why::TooMuch => "tooMuch",
|
||||
}
|
||||
}
|
||||
|
||||
/// The plain English of it, for an agent, a script and the log; the window says it in its
|
||||
/// own language.
|
||||
pub fn english(self) -> &'static str {
|
||||
match self {
|
||||
Why::UnknownIssuer => "the certificate wasn't issued by a certification authority this computer trusts",
|
||||
Why::SelfSigned => "the certificate signed itself and isn't one this computer trusts",
|
||||
Why::Expired => "the certificate is out of date",
|
||||
Why::NotForEmail => "the certificate isn't for signing mail",
|
||||
Why::AddressMismatch => "the certificate is for another address than the sender's",
|
||||
Why::Constrained => "an authority on the way to a trusted one doesn't allow the certificate to be used this way",
|
||||
Why::NoAuthorities => "no certification authorities for mail could be read on this computer, so no signer can be verified here",
|
||||
Why::AuthoritiesNotRead => "this computer's certification authorities haven't been read yet",
|
||||
Why::KeyNotVerified => "the signer's key hasn't been marked verified",
|
||||
Why::PartlySigned => "only part of the message was signed; the rest could say anything",
|
||||
Why::Altered => "the message was changed after it was signed",
|
||||
Why::WeakAlgorithm => "it uses an algorithm that's no longer safe",
|
||||
Why::UnknownAlgorithm => "it uses an algorithm MailCraft doesn't know",
|
||||
Why::NoPublicKey => "the signer's Public key (certificate) isn't in the message or kept on this computer",
|
||||
Why::KeyRevoked => "the signer's key was revoked by its owner",
|
||||
Why::KeyExpired => "the signer's key had expired when the message was signed",
|
||||
Why::NotASigningKey => "the key that made it isn't one that may sign",
|
||||
Why::SignatureExpired => "the Digital signature has expired",
|
||||
Why::Unreadable => "the Digital signature can't be read",
|
||||
Why::NoOriginal => "the bytes the message came as aren't on this computer; Check again downloads them",
|
||||
Why::TooMuch => "there is too much to check in this Digital signature",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Who signed, as the certificate or key says: the signer's own words, data and never
|
||||
/// instructions.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Signer {
|
||||
/// The name in the certificate (its common name) or key, if any.
|
||||
pub name: String,
|
||||
/// The addresses in the certificate or key, as they are written there, at most
|
||||
/// [`MAX_SIGNER_ADDRESSES`].
|
||||
pub addresses: Vec<String>,
|
||||
/// The SHA-256 fingerprint of the certificate (or the fingerprint of the OpenPGP key), in
|
||||
/// upper-case hexadecimal pairs with colons between.
|
||||
pub fingerprint: String,
|
||||
/// Who issued the certificate (its common name, else its whole name). Empty for OpenPGP.
|
||||
pub issuer: String,
|
||||
/// From and until when the certificate is valid; 0 when it doesn't say.
|
||||
pub not_before: Timestamp,
|
||||
pub not_after: Timestamp,
|
||||
}
|
||||
|
||||
/// How much of the message the Digital signature covers.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Coverage {
|
||||
/// The whole message body: the signed part is the message's top level (S/MIME's
|
||||
/// `multipart/signed` or signed data, PGP/MIME's `multipart/signed`).
|
||||
Whole,
|
||||
/// Only a part of it: the signed part sits inside a wrapper whose other parts nobody signed
|
||||
/// (or a format that can't tell). The safe default.
|
||||
#[default]
|
||||
Part,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Coverage::Whole => "whole",
|
||||
Coverage::Part => "part",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The most addresses of a signer that are kept.
|
||||
pub const MAX_SIGNER_ADDRESSES: usize = 16;
|
||||
/// The most characters of a name, an issuer or an address that are kept.
|
||||
pub const MAX_SIGNER_TEXT: usize = 256;
|
||||
|
||||
/// What checking a message's Digital signature found.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DigitalSignature {
|
||||
pub format: SignatureFormat,
|
||||
pub verdict: Verdict,
|
||||
/// Why it is less than verified; `None` when it is verified.
|
||||
pub why: Option<Why>,
|
||||
/// Who signed, when the signer's certificate or key was found.
|
||||
pub signer: Option<Signer>,
|
||||
/// When the signer says they signed it (S/MIME's signing time): the signer's word, not
|
||||
/// checked by anybody.
|
||||
pub signed_at: Option<Timestamp>,
|
||||
/// Whether the certificate was checked against its issuer's list of revoked certificates.
|
||||
/// Never yet (#30 R7): the details say "Revocation not checked".
|
||||
pub revocation_checked: bool,
|
||||
/// How much of the message was signed; set with [`DigitalSignature::covering`].
|
||||
#[serde(default)]
|
||||
pub coverage: Coverage,
|
||||
}
|
||||
|
||||
impl DigitalSignature {
|
||||
/// A result of `verdict` for `why`, with nothing known of the signer.
|
||||
pub fn bare(format: SignatureFormat, verdict: Verdict, why: Why) -> DigitalSignature {
|
||||
DigitalSignature { format, verdict, why: Some(why), signer: None, signed_at: None, revocation_checked: false, coverage: Coverage::Part }
|
||||
}
|
||||
|
||||
/// This result for a signature that covers `coverage` of the message: a valid signature by a
|
||||
/// trusted signer over only part of it is [`Verdict::NotVerified`] ([`Why::PartlySigned`]),
|
||||
/// never verified for the message. Either format's checker ends with it.
|
||||
pub fn covering(mut self, coverage: Coverage) -> DigitalSignature {
|
||||
self.coverage = coverage;
|
||||
if coverage == Coverage::Part && self.verdict == Verdict::Verified {
|
||||
self.verdict = Verdict::NotVerified;
|
||||
self.why = Some(Why::PartlySigned);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` (a name or address from a certificate) as a name coming in is kept
|
||||
/// ([`crate::names::incoming`]): one line, without control or format characters (no
|
||||
/// reordering by a bidirectional override, nothing hidden by a zero-width one), at most
|
||||
/// [`MAX_SIGNER_TEXT`] characters.
|
||||
pub fn signer_text(text: &str) -> String {
|
||||
crate::names::incoming(text, MAX_SIGNER_TEXT).unwrap_or_default()
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Certificates read from a file the owner imports as Public keys (#30): DER or PEM, what each
|
||||
//! one is for, and whether the file holds a private key instead (which is never a Public key
|
||||
//! to import, and goes through File › Options › Security in the window). No I/O; the file is
|
||||
//! hostile: sizes and counts are capped, and nothing here panics on any bytes.
|
||||
|
||||
use crate::Timestamp;
|
||||
use base64::Engine as _;
|
||||
use craft_ber as ber;
|
||||
|
||||
use crate::cert::{Cert, MAX_CERT_BYTES, printable};
|
||||
|
||||
/// The most certificates read from one file.
|
||||
pub const MAX_IMPORT_CERTIFICATES: usize = 16;
|
||||
/// The most addresses a certificate is kept for.
|
||||
const MAX_ADDRESSES: usize = 16;
|
||||
|
||||
/// What a certificate to import says of itself.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CertificateInfo {
|
||||
/// The certificate, in DER.
|
||||
pub der: Vec<u8>,
|
||||
/// Its SHA-256 fingerprint, as a Digital signature's details have it.
|
||||
pub fingerprint: String,
|
||||
/// The mail addresses it is for (subject alternative names, and an `emailAddress` in its
|
||||
/// subject), in lower case: plain ASCII only, as a signer's address is compared.
|
||||
pub addresses: Vec<String>,
|
||||
/// Until when it is valid.
|
||||
pub not_after: Timestamp,
|
||||
/// Whether it is for mail ([`Cert::for_mail`]).
|
||||
pub for_mail: bool,
|
||||
/// Whether it is a certification authority's.
|
||||
pub authority: bool,
|
||||
/// Who it is for (its subject's common name, else its whole subject), cleaned.
|
||||
pub name: String,
|
||||
/// Who issued it (the issuer's common name, else its whole name), cleaned.
|
||||
pub issuer: String,
|
||||
}
|
||||
|
||||
/// What the certificate `der` says of itself; `None` when it isn't one.
|
||||
pub fn certificate_info(der: &[u8]) -> Option<CertificateInfo> {
|
||||
let cert = Cert::from_der(der)?;
|
||||
let mut addresses: Vec<String> = Vec::new();
|
||||
for a in cert.raw_addresses() {
|
||||
let a = a.to_ascii_lowercase();
|
||||
if printable(&a) && a.contains('@') && !addresses.contains(&a) && addresses.len() < MAX_ADDRESSES {
|
||||
addresses.push(a);
|
||||
}
|
||||
}
|
||||
Some(CertificateInfo {
|
||||
der: cert.der().to_vec(),
|
||||
fingerprint: cert.fingerprint(),
|
||||
addresses,
|
||||
not_after: cert.validity().1,
|
||||
for_mail: cert.for_mail(),
|
||||
authority: cert.is_authority(),
|
||||
name: cert.name(),
|
||||
issuer: cert.issuer_name(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The certificates in `bytes`: PEM `CERTIFICATE` blocks (as many as there are, at most
|
||||
/// [`MAX_IMPORT_CERTIFICATES`]), else one certificate in DER (or BER). Empty when there is none.
|
||||
pub fn certificates_in(bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
let blocks = pem_blocks(bytes, "CERTIFICATE");
|
||||
if !blocks.is_empty() {
|
||||
return blocks.into_iter().filter(|b| Cert::from_der(b).is_some()).take(MAX_IMPORT_CERTIFICATES).collect();
|
||||
}
|
||||
if bytes.len() > MAX_CERT_BYTES {
|
||||
return Vec::new();
|
||||
}
|
||||
match ber::to_der(bytes) {
|
||||
Some(der) if Cert::from_der(&der).is_some() => vec![der],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoded bodies of the PEM blocks labelled `label` in `bytes` (RFC 7468), each at most a
|
||||
/// certificate's size, at most [`MAX_IMPORT_CERTIFICATES`].
|
||||
fn pem_blocks(bytes: &[u8], label: &str) -> Vec<Vec<u8>> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let begin = format!("-----BEGIN {label}-----");
|
||||
let end = format!("-----END {label}-----");
|
||||
let mut out = Vec::new();
|
||||
let mut body: Option<String> = None;
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
match body.as_mut() {
|
||||
None if line == begin => body = Some(String::new()),
|
||||
None => {}
|
||||
Some(b) if line == end => {
|
||||
if let Ok(der) = base64::engine::general_purpose::STANDARD.decode(b.as_bytes())
|
||||
&& der.len() <= MAX_CERT_BYTES
|
||||
{
|
||||
out.push(der);
|
||||
}
|
||||
body = None;
|
||||
if out.len() >= MAX_IMPORT_CERTIFICATES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(b) => {
|
||||
// (A header line of RFC 1421's kind is no base64: such a block won't decode.)
|
||||
if !append_pem_line(b, line) {
|
||||
body = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `bytes` hold a private key in a form S/MIME's tools write: a PEM block of any kind of
|
||||
/// `PRIVATE KEY` (PKCS #8, encrypted or not, PKCS #1, SEC 1, OpenSSH, OpenPGP's armour too), a
|
||||
/// PKCS #12 file, or a PKCS #8, PKCS #1 or SEC 1 key in DER.
|
||||
pub fn holds_private_key(bytes: &[u8]) -> bool {
|
||||
let text = String::from_utf8_lossy(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default());
|
||||
if text.lines().any(|l| {
|
||||
let l = l.trim();
|
||||
l.starts_with("-----BEGIN ") && l.contains("PRIVATE KEY")
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
if crate::pkcs12::looks_like(bytes) {
|
||||
return true;
|
||||
}
|
||||
let Some(der) = ber::to_der(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default()) else { return false };
|
||||
let Some((outer, _)) = ber::read(&der) else { return false };
|
||||
if outer.tag != 0x30 {
|
||||
return false;
|
||||
}
|
||||
let Some(fields) = ber::children(outer.value) else { return false };
|
||||
let tags: Vec<u8> = fields.iter().map(|f| f.tag).collect();
|
||||
let first_int = |v: &[u8]| fields.first().is_some_and(|f| f.tag == 0x02 && f.value == v);
|
||||
// PKCS #8 PrivateKeyInfo / OneAsymmetricKey: version, algorithm, the key in an OCTET STRING.
|
||||
let pkcs8 = matches!(tags.as_slice(), [0x02, 0x30, 0x04, ..]) && (first_int(&[0]) || first_int(&[1]));
|
||||
// EncryptedPrivateKeyInfo: algorithm, the encrypted key.
|
||||
let encrypted = matches!(tags.as_slice(), [0x30, 0x04]);
|
||||
// PKCS #1 RSAPrivateKey: version 0 and eight INTEGERs.
|
||||
let rsa = tags.len() >= 9 && tags.iter().take(9).all(|t| *t == 0x02) && first_int(&[0]);
|
||||
// SEC 1 ECPrivateKey: version 1, the key in an OCTET STRING.
|
||||
let ec = matches!(tags.as_slice(), [0x02, 0x04, ..]) && first_int(&[1]);
|
||||
pkcs8 || encrypted || rsa || ec
|
||||
}
|
||||
|
||||
// Check the prospective length before allocation, including a single oversized line.
|
||||
fn append_pem_line(body: &mut String, line: &str) -> bool {
|
||||
if body.len().checked_add(line.len()).is_none_or(|len| len > MAX_CERT_BYTES.saturating_mul(2)) {
|
||||
return false;
|
||||
}
|
||||
body.push_str(line);
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bounded_pem_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oversized_pem_lines_are_refused_before_accumulation() {
|
||||
let cap = MAX_CERT_BYTES * 2;
|
||||
let mut body = String::new();
|
||||
assert!(!append_pem_line(&mut body, &"A".repeat(cap + 1)));
|
||||
assert!(body.is_empty());
|
||||
assert!(append_pem_line(&mut body, &"A".repeat(cap - 1)));
|
||||
assert!(append_pem_line(&mut body, "A"));
|
||||
assert!(!append_pem_line(&mut body, "A"));
|
||||
assert_eq!(body.len(), cap);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Certificates read for import, and private keys told apart (#30). The certificates are those
|
||||
//! of `pkcs12_tests` (synthetic `example.org` people under a test authority), and one made for a
|
||||
//! web server with Bob's key.
|
||||
|
||||
use base64::Engine as _;
|
||||
use proptest::prelude::*;
|
||||
|
||||
use crate::import::{certificate_info, certificates_in, holds_private_key};
|
||||
use crate::pkcs12_tests::{ALICE_PEM, CA_PEM, MODERN};
|
||||
|
||||
/// Bob's key, certified for `www.example.org` and for serving the web only.
|
||||
pub(crate) const SERVER_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIICeTCCAWGgAwIBAgITBZjuab1kWRuw6iskHm6GfE5XsDANBgkqhkiG9w0BAQsF\nADAsMRgwFgYDVQQDDA9FeGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUw\nIBcNMjYxMTEwMjM1NzM0WhgPMjEyNjEwMTcyMzU3MzRaMBYxFDASBgNVBAMMC0Jv\nYiBFeGFtcGxlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVMGX6KffvBxXYqhk\nGl7wd0hrcjrtj18zbj1rN23ToDZ6d+Iy3rQQZvU5gCfqoP/scGZ9K377DvfqOzR8\n8VGPoKNzMHEwGgYDVR0RBBMwEYIPd3d3LmV4YW1wbGUub3JnMBMGA1UdJQQMMAoG\nCCsGAQUFBwMBMB0GA1UdDgQWBBQNf+WUyk2rA7Ol2+DplbqCmjDuOTAfBgNVHSME\nGDAWgBQDV2BK6ZYA5LKhPQiiQ98tSGv7JjANBgkqhkiG9w0BAQsFAAOCAQEAUlZu\nif7xv5ZXlsWt0KX458+G2vekBcqdE3UD21hTvJ9tbCrnfIuXa9pigZsYUzqV5Xwt\npaXU+7JedPYNZs0qqk2nPw+VULsxBNhaKre5V+v4tdHxq16MTsAalT6GfeOtX8+G\nZ5CwUqqe5SW9kkUi0QnaR/BDZuTKIOKKBCJ4AEOmi9cbDWUQiKkQRR4mEQH7wAJM\nfBXlNb7YHRikSE/ZHAjsLKNwSEpOsKnKav8KxPy/moR+emB9AFIHAsGjmPTMNhdG\nQ5DrRP3eAtKBGCrFGOj+JSxXW4O2eqKGuMHy7fLrCD2st7qBv4Lm7lEw1SDsXAQ/\nx1BBQKVBaJYfE2pKOA==\n-----END CERTIFICATE-----\n";
|
||||
|
||||
#[test]
|
||||
fn certificates_are_read_from_pem_and_der() {
|
||||
let both = format!("{ALICE_PEM}{CA_PEM}");
|
||||
let read = certificates_in(both.as_bytes());
|
||||
assert_eq!(read.len(), 2);
|
||||
assert_eq!(certificates_in(&read[0]), vec![read[0].clone()], "DER");
|
||||
assert!(certificates_in(b"no certificate").is_empty());
|
||||
assert!(certificates_in(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_a_certificate_is_for_is_told() {
|
||||
let alice = certificate_info(&certificates_in(ALICE_PEM.as_bytes())[0]).unwrap();
|
||||
assert_eq!(alice.addresses, vec!["alice@example.org".to_string()], "its alternative name and its subject's address, once");
|
||||
assert!(alice.for_mail);
|
||||
assert!(!alice.authority);
|
||||
assert_eq!(alice.fingerprint, "10:33:B4:36:A1:40:16:60:4A:21:D5:BC:F3:B1:69:38:60:22:DF:01:85:71:8D:BC:F5:BB:63:4B:09:CB:AA:FC");
|
||||
assert!(alice.not_after > 4_000_000_000);
|
||||
let server = certificate_info(&certificates_in(SERVER_PEM.as_bytes())[0]).unwrap();
|
||||
assert!(!server.for_mail, "for the web only");
|
||||
assert!(server.addresses.is_empty());
|
||||
let ca = certificate_info(&certificates_in(CA_PEM.as_bytes())[0]).unwrap();
|
||||
assert!(ca.authority);
|
||||
assert!(certificate_info(b"junk").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_key_in_any_form_is_told() {
|
||||
for label in ["PRIVATE KEY", "ENCRYPTED PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "PGP PRIVATE KEY BLOCK"] {
|
||||
let pem = format!("-----BEGIN {label}-----\nAAAA\n-----END {label}-----\n");
|
||||
assert!(holds_private_key(pem.as_bytes()), "{label}");
|
||||
}
|
||||
assert!(holds_private_key(&base64::engine::general_purpose::STANDARD.decode(MODERN).unwrap()), "a PKCS #12 file");
|
||||
// PKCS #8: version 0, an algorithm, the key in an OCTET STRING.
|
||||
let pkcs8 = [0x30, 0x0b, 0x02, 0x01, 0x00, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00];
|
||||
assert!(holds_private_key(&pkcs8));
|
||||
// EncryptedPrivateKeyInfo.
|
||||
assert!(holds_private_key(&[0x30, 0x08, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00]));
|
||||
// SEC 1: version 1, the key.
|
||||
assert!(holds_private_key(&[0x30, 0x06, 0x02, 0x01, 0x01, 0x04, 0x01, 0x07]));
|
||||
// PKCS #1: nine INTEGERs, the first 0.
|
||||
let mut rsa = vec![0x30, 27];
|
||||
for _ in 0..9 {
|
||||
rsa.extend_from_slice(&[0x02, 0x01, 0x00]);
|
||||
}
|
||||
assert!(holds_private_key(&rsa));
|
||||
for public in [ALICE_PEM.as_bytes(), &certificates_in(ALICE_PEM.as_bytes())[0], b"-----BEGIN PGP PUBLIC KEY BLOCK-----", b""] {
|
||||
assert!(!holds_private_key(public));
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn any_bytes_are_read_without_a_panic(bytes in proptest::collection::vec(any::<u8>(), 0..2048)) {
|
||||
let _ = certificates_in(&bytes);
|
||||
let _ = certificate_info(&bytes);
|
||||
let _ = holds_private_key(&bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! MailCraft's S/MIME (RFC 8551): Digital signatures checked (#30), written from the public
|
||||
//! specifications (RFC 5652 for CMS, RFC 5280 for X.509, RFC 5754, RFC 4055 and RFC 5480 for
|
||||
//! the algorithms). No I/O: the host hands in the certificates it trusts ([`Anchors`]), the
|
||||
//! message's halves come from `mailcraft-mime`, and the result is
|
||||
//! [`crate::digital_signature::DigitalSignature`], which OpenPGP shares.
|
||||
//!
|
||||
//! [`check`] reads the CMS SignedData of a detached or an opaque Digital signature, finds the
|
||||
//! signer's certificate, compares the signer's digest with the message's, checks the signature
|
||||
//! (RSA PKCS #1 v1.5 or PSS of 2048 bits or more, ECDSA on P-256 or P-384, over SHA-2), and then
|
||||
//! whether the certificate rests on a trust anchor, is for signing mail and is for the From
|
||||
//! address. MD5 and SHA-1 are no longer safe and are said to be. Revocation isn't checked.
|
||||
//!
|
||||
//! Directory-name constraints currently support ASCII PrintableString/UTF8String names.
|
||||
//! Constrained chains requiring other string profiles are refused, not approximately matched.
|
||||
//! Opaque CMS content is verified as exact octets; only detached transport text permits LF repair.
|
||||
//!
|
||||
//! Input is hostile: BER is turned into DER with nesting bounded, every length is checked
|
||||
//! against what is there, the certificates, signers and the path to an anchor are capped, and
|
||||
//! nothing here panics on any bytes.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
||||
|
||||
/// Seconds since the Unix epoch, UTC.
|
||||
pub type Timestamp = i64;
|
||||
|
||||
mod algorithms;
|
||||
mod cert;
|
||||
mod chain;
|
||||
pub mod digital_signature;
|
||||
pub mod import;
|
||||
mod names;
|
||||
pub mod pkcs12;
|
||||
mod verify;
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod import_tests;
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod pkcs12_tests;
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod tests;
|
||||
|
||||
pub use chain::{Anchors, MAX_ANCHORS};
|
||||
pub use verify::{Checked, Context, MAX_CERTS, MAX_SIGNERS, MAX_VERIFICATIONS, Signed, check};
|
||||
|
||||
/// The fingerprint and addresses of a certificate in DER, as a Digital signature's details show
|
||||
/// them: `None` when it isn't one.
|
||||
pub fn certificate_summary(der: &[u8]) -> Option<(String, Vec<String>, crate::Timestamp)> {
|
||||
let cert = cert::Cert::from_der(der)?;
|
||||
Some((cert.fingerprint(), cert.addresses(), cert.validity().1))
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Bounded certificate display-name sanitization extracted from MailCraft.
|
||||
|
||||
/// Whether `c` is one of Unicode's format characters (general category Cf, Unicode 17.0): the
|
||||
/// soft hyphen, the Arabic number signs and end-of-ayah marks, the Syriac abbreviation mark, the
|
||||
/// Arabic pound and piastre marks above, the Mongolian vowel separator, zero-width marks and
|
||||
/// joiners, bidirectional marks, embeddings, overrides and isolates, the word joiner and
|
||||
/// invisible operators, the deprecated shaping controls, the byte-order mark, interlinear
|
||||
/// annotations, the Kaithi number signs, the Egyptian hieroglyph, shorthand and musical format
|
||||
/// controls, and tags.
|
||||
pub fn is_format(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{00ad}'
|
||||
| '\u{0600}'..='\u{0605}'
|
||||
| '\u{061c}'
|
||||
| '\u{06dd}'
|
||||
| '\u{070f}'
|
||||
| '\u{0890}'..='\u{0891}'
|
||||
| '\u{08e2}'
|
||||
| '\u{180e}'
|
||||
| '\u{200b}'..='\u{200f}'
|
||||
| '\u{202a}'..='\u{202e}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{206f}'
|
||||
| '\u{feff}'
|
||||
| '\u{fff9}'..='\u{fffb}'
|
||||
| '\u{110bd}'
|
||||
| '\u{110cd}'
|
||||
| '\u{13430}'..='\u{1343f}'
|
||||
| '\u{1bca0}'..='\u{1bca3}'
|
||||
| '\u{1d173}'..='\u{1d17a}'
|
||||
| '\u{e0001}'
|
||||
| '\u{e0020}'..='\u{e007f}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether `c` is the zero-width non-joiner or joiner (U+200C, U+200D): format characters that
|
||||
/// are part of a word where they stand inside one.
|
||||
pub fn is_joiner(c: char) -> bool {
|
||||
matches!(c, '\u{200c}' | '\u{200d}')
|
||||
}
|
||||
|
||||
/// A name as it is kept: one line (a line break, a tab or any other white space parts words, and
|
||||
/// words are parted by one space), without control characters or the characters Unicode marks as
|
||||
/// showing nothing (a joiner inside a word and one variation selector after a character stay),
|
||||
/// trimmed, at most `max` characters. `None` when nothing is left.
|
||||
pub fn incoming(text: &str, max: usize) -> Option<String> {
|
||||
let (name, _) = clean(text, max);
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// Whether `c` is one of the rest of Unicode's default-ignorable code points
|
||||
/// (`Default_Ignorable_Code_Point`, Unicode 17.0, less the format characters and the variation
|
||||
/// selectors): the combining grapheme joiner, the Hangul fillers, the Khmer inherent vowels, and
|
||||
/// the code points Unicode keeps for more characters that show nothing.
|
||||
fn is_ignorable(c: char) -> bool {
|
||||
matches!(
|
||||
c,
|
||||
'\u{034f}'
|
||||
| '\u{115f}'..='\u{1160}'
|
||||
| '\u{17b4}'..='\u{17b5}'
|
||||
| '\u{2065}'
|
||||
| '\u{3164}'
|
||||
| '\u{ffa0}'
|
||||
| '\u{fff0}'..='\u{fff8}'
|
||||
| '\u{e0000}'
|
||||
| '\u{e0002}'..='\u{e001f}'
|
||||
| '\u{e0080}'..='\u{e00ff}'
|
||||
| '\u{e01f0}'..='\u{e0fff}'
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether `c` is a variation selector (`Variation_Selector`, Unicode 17.0): it picks how the
|
||||
/// character before it is drawn.
|
||||
fn is_selector(c: char) -> bool {
|
||||
matches!(c, '\u{180b}'..='\u{180d}' | '\u{180f}' | '\u{fe00}'..='\u{fe0f}' | '\u{e0100}'..='\u{e01ef}')
|
||||
}
|
||||
|
||||
/// The braille pattern blank: a symbol to Unicode, and in braille the space between words.
|
||||
const BRAILLE_BLANK: char = '\u{2800}';
|
||||
|
||||
/// `text` cleaned and cut to at most `max` characters, and whether something was left out for
|
||||
/// the length. Nothing past it is read.
|
||||
fn clean(text: &str, max: usize) -> (String, bool) {
|
||||
let mut out = String::new();
|
||||
let mut count = 0usize;
|
||||
// A space between words, and a joiner inside one, come only with the character after them.
|
||||
let mut space = false;
|
||||
let mut joiner: Option<char> = None;
|
||||
// Whether the last character written shows, so that a variation selector may follow it.
|
||||
let mut selectable = false;
|
||||
for c in text.chars() {
|
||||
if is_joiner(c) {
|
||||
if count > 0 && !space {
|
||||
joiner = Some(c);
|
||||
}
|
||||
} else if c.is_whitespace() || c == BRAILLE_BLANK {
|
||||
space = count > 0;
|
||||
joiner = None;
|
||||
} else if is_selector(c) {
|
||||
if selectable && !space && joiner.is_none() {
|
||||
if count >= max {
|
||||
return (out, true);
|
||||
}
|
||||
out.push(c);
|
||||
count = count.saturating_add(1);
|
||||
selectable = false;
|
||||
}
|
||||
} else if !c.is_control() && !is_format(c) && !is_ignorable(c) {
|
||||
let needed = 1 + usize::from(space) + usize::from(joiner.is_some());
|
||||
if count.saturating_add(needed) > max {
|
||||
return (out, true);
|
||||
}
|
||||
if std::mem::take(&mut space) {
|
||||
out.push(' ');
|
||||
}
|
||||
if let Some(j) = joiner.take() {
|
||||
out.push(j);
|
||||
}
|
||||
out.push(c);
|
||||
count = count.saturating_add(needed);
|
||||
selectable = true;
|
||||
}
|
||||
}
|
||||
(out, false)
|
||||
}
|
||||
@@ -0,0 +1,794 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! A PKCS #12 file (`.p12`, `.pfx`; RFC 7292) opened with its passphrase (#30 R13): the
|
||||
//! certificate and private key an owner's IT department hands out, for the window to put in the
|
||||
//! system's credential store. No I/O, and nothing kept: what is opened goes back to the caller,
|
||||
//! the private key in memory that is wiped when it is let go of.
|
||||
//!
|
||||
//! The file is believed only when its MAC checks with the passphrase (RFC 7292 §5.1, the
|
||||
//! password-integrity mode, HMAC with SHA-1 or SHA-2 keyed by the PKCS #12 key derivation of
|
||||
//! Appendix B): a file without one, or with a public-key integrity mode, is refused, and a MAC
|
||||
//! that doesn't check is a wrong passphrase. The bags may be encrypted with PBES2 (RFC 8018:
|
||||
//! PBKDF2 with HMAC-SHA-1 or SHA-2, and AES-128/192/256-CBC or 3DES-CBC) or with the old
|
||||
//! pbeWithSHAAnd3-KeyTripleDES-CBC (RFC 7292 Appendix C); RC2, RC4, two-key 3DES, DES and the
|
||||
//! 40-bit schemes are no longer safe and are refused.
|
||||
//!
|
||||
//! The file is hostile: its size, the bags, their nesting and every iteration count (and their
|
||||
//! sum) are capped, lengths are checked against what is there, and nothing here panics on any
|
||||
//! bytes. The cryptography is RustCrypto's (`pkcs12`'s key derivation, `pbkdf2`, `hmac`, `sha1`,
|
||||
//! `sha2`, `aes`, `des`, `cbc`); only the layout is read here.
|
||||
|
||||
use aes::cipher::block_padding::Pkcs7;
|
||||
use aes::cipher::{BlockModeDecrypt, KeyIvInit};
|
||||
use const_oid::ObjectIdentifier;
|
||||
use craft_ber::{self as ber, Tlv};
|
||||
use der::Decode;
|
||||
use hmac::{KeyInit, Mac};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The largest file opened (the window reads at most as much).
|
||||
pub const MAX_P12_LEN: usize = 1 << 20;
|
||||
/// The most bags read, in all.
|
||||
pub const MAX_BAGS: usize = 64;
|
||||
/// The most iterations one key derivation may ask for: past it the file is refused as
|
||||
/// unreasonable rather than spent time on.
|
||||
pub const MAX_ITERATIONS: u64 = 1_000_000;
|
||||
/// The most iterations every key derivation of one file may ask for together.
|
||||
const MAX_TOTAL_ITERATIONS: u64 = 8_000_000;
|
||||
/// How deep safe-contents bags may nest in each other.
|
||||
const MAX_NESTING: usize = 4;
|
||||
/// The most certificates kept from one file.
|
||||
const MAX_CERTIFICATES: usize = 32;
|
||||
|
||||
const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
|
||||
const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6");
|
||||
const KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.1");
|
||||
const SHROUDED_KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2");
|
||||
const CERT_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.3");
|
||||
const SAFE_CONTENTS_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.6");
|
||||
const X509_CERTIFICATE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.22.1");
|
||||
const LOCAL_KEY_ID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.21");
|
||||
|
||||
const SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.26");
|
||||
const SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
|
||||
const SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
|
||||
const SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");
|
||||
|
||||
const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13");
|
||||
const PBKDF2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.12");
|
||||
const HMAC_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.7");
|
||||
const HMAC_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.9");
|
||||
const HMAC_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.10");
|
||||
const HMAC_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.11");
|
||||
const AES128_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.2");
|
||||
const AES192_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.22");
|
||||
const AES256_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.42");
|
||||
const DES_EDE3_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.3.7");
|
||||
const SHA_3DES: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3");
|
||||
/// The PKCS #12 schemes that are no longer safe (RC4, two-key 3DES, RC2), and PKCS #5 v1.5's
|
||||
/// (DES and RC2 with MD2, MD5 or SHA-1).
|
||||
const WEAK: [&str; 11] = [
|
||||
"1.2.840.113549.1.12.1.1",
|
||||
"1.2.840.113549.1.12.1.2",
|
||||
"1.2.840.113549.1.12.1.4",
|
||||
"1.2.840.113549.1.12.1.5",
|
||||
"1.2.840.113549.1.12.1.6",
|
||||
"1.2.840.113549.1.5.1",
|
||||
"1.2.840.113549.1.5.3",
|
||||
"1.2.840.113549.1.5.4",
|
||||
"1.2.840.113549.1.5.6",
|
||||
"1.2.840.113549.1.5.10",
|
||||
"1.2.840.113549.1.5.11",
|
||||
];
|
||||
|
||||
/// Why a PKCS #12 file couldn't be opened.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Larger than any such file is.
|
||||
#[error("the file is larger than a certificate file can be")]
|
||||
TooLarge,
|
||||
/// Not a PKCS #12 file, or a damaged one.
|
||||
#[error("the file isn't a certificate file (.p12 or .pfx) that can be read")]
|
||||
Unreadable,
|
||||
/// It has no MAC with a passphrase: nothing vouches that it is as it was made.
|
||||
#[error("the file isn't protected with a passphrase, so nothing vouches for it")]
|
||||
NoMac,
|
||||
/// The MAC doesn't check: the passphrase is wrong (or the file was changed).
|
||||
#[error("the passphrase is wrong")]
|
||||
WrongPassphrase,
|
||||
/// It is encrypted with a scheme that is no longer safe (RC2, RC4, DES, 40-bit keys).
|
||||
#[error("the file is encrypted in a way that is no longer safe (RC2, RC4, DES or 40-bit keys); export it again with AES")]
|
||||
WeakEncryption,
|
||||
/// It uses an algorithm this program doesn't know.
|
||||
#[error("the file uses an algorithm MailCraft doesn't know")]
|
||||
UnknownAlgorithm,
|
||||
/// It asks for more iterations than any file needs, or more bags or nesting than there is room for.
|
||||
#[error("the file asks for more work than a certificate file needs")]
|
||||
Unreasonable,
|
||||
/// It holds no private key, or more than one.
|
||||
#[error("the file holds no private key, or more than one")]
|
||||
NoPrivateKey,
|
||||
/// It holds no certificate for its private key.
|
||||
#[error("the file holds no certificate for its private key")]
|
||||
NoCertificate,
|
||||
}
|
||||
|
||||
/// What a PKCS #12 file holds, opened.
|
||||
pub struct Opened {
|
||||
/// The certificate of the private key, in DER: the one whose public key is the key's, else
|
||||
/// the one with the key's local key id.
|
||||
pub certificate: Vec<u8>,
|
||||
/// The other certificates (the authorities on the way to a trusted one), in DER.
|
||||
pub others: Vec<Vec<u8>>,
|
||||
/// The private key as PKCS #8 `PrivateKeyInfo` in DER, wiped when let go of.
|
||||
pub private_key: Zeroizing<Vec<u8>>,
|
||||
/// What kind of key the private key is, read from its own PKCS #8 algorithm identifier (and
|
||||
/// curve): whether it may be used here. The certificate is of the same kind.
|
||||
pub key_kind: KeyKind,
|
||||
/// Whether the private key was encrypted in the file (a shrouded key bag, or a bag in an
|
||||
/// encrypted safe), and not merely vouched for by the MAC: a key in a plain key bag of a
|
||||
/// plain safe is in the file in clear.
|
||||
pub key_encrypted: bool,
|
||||
}
|
||||
|
||||
/// What kind of key a certificate holds.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum KeyKind {
|
||||
/// RSA, with a modulus of so many bits.
|
||||
Rsa { bits: usize },
|
||||
/// ECDSA on NIST P-256.
|
||||
P256,
|
||||
/// ECDSA on NIST P-384.
|
||||
P384,
|
||||
/// Any other.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Opened {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Opened")
|
||||
.field("certificate", &self.certificate.len())
|
||||
.field("others", &self.others.len())
|
||||
.field("private_key", &"[redacted]")
|
||||
.field("key_kind", &self.key_kind)
|
||||
.field("key_encrypted", &self.key_encrypted)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bytes` look like a PKCS #12 file (a version 3 PFX), without opening it: so that a
|
||||
/// private key is never taken for a Public key to import.
|
||||
pub fn looks_like(bytes: &[u8]) -> bool {
|
||||
let Some(der) = ber::to_der(bytes.get(..bytes.len().min(MAX_P12_LEN)).unwrap_or_default()).map(Zeroizing::new) else { return false };
|
||||
let Some((pfx, _)) = ber::read(&der) else { return false };
|
||||
let Some(fields) = ber::children(pfx.value) else { return false };
|
||||
matches!(fields.as_slice(), [version, info, ..] if version.tag == 0x02 && version.value == [3] && info.tag == 0x30)
|
||||
}
|
||||
|
||||
/// Open the PKCS #12 file `p12` with `passphrase`.
|
||||
pub fn open(p12: &[u8], passphrase: &str) -> Result<Opened, Error> {
|
||||
if p12.len() > MAX_P12_LEN {
|
||||
return Err(Error::TooLarge);
|
||||
}
|
||||
let der = Zeroizing::new(ber::to_der(p12).ok_or(Error::Unreadable)?);
|
||||
let (pfx, rest) = ber::read(&der).ok_or(Error::Unreadable)?;
|
||||
if pfx.tag != 0x30 || !rest.is_empty() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(pfx.value).ok_or(Error::Unreadable)?;
|
||||
let (version, auth_safe, mac) = match fields.as_slice() {
|
||||
[v, a, m] => (v, a, Some(m)),
|
||||
[v, a] => (v, a, None),
|
||||
_ => return Err(Error::Unreadable),
|
||||
};
|
||||
if version.tag != 0x02 || version.value != [3] {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let mut work = Work { iterations: 0, bags: 0 };
|
||||
// Only the password-integrity mode: the authenticated safe is data, and the MAC is over it.
|
||||
let (content_type, content) = content_info(auth_safe)?;
|
||||
if content_type != DATA {
|
||||
return Err(Error::NoMac);
|
||||
}
|
||||
let safe = Zeroizing::new(octets(content)?);
|
||||
let mac = mac.ok_or(Error::NoMac)?;
|
||||
let legacy_password = check_mac(mac, &safe, passphrase, &mut work)?;
|
||||
let safe = Zeroizing::new(ber::to_der(&safe).ok_or(Error::Unreadable)?);
|
||||
let mut found = Found::default();
|
||||
let (list, rest) = ber::read(&safe).ok_or(Error::Unreadable)?;
|
||||
if list.tag != 0x30 || !rest.is_empty() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
for info in ber::children(list.value).ok_or(Error::Unreadable)? {
|
||||
let (kind, content) = content_info(&info)?;
|
||||
let (contents, encrypted) = if kind == DATA {
|
||||
(Zeroizing::new(octets(content)?), false)
|
||||
} else if kind == ENCRYPTED_DATA {
|
||||
(encrypted_data(content, passphrase, &legacy_password, &mut work)?, true)
|
||||
} else {
|
||||
// (Enveloped data, which needs a key of the owner's to open: not a file to import.)
|
||||
return Err(Error::UnknownAlgorithm);
|
||||
};
|
||||
safe_contents(&contents, Safe { passphrase, legacy_password: &legacy_password, encrypted, depth: 0 }, &mut work, &mut found)?;
|
||||
}
|
||||
found.finish()
|
||||
}
|
||||
|
||||
/// What opening costs so far.
|
||||
struct Work {
|
||||
iterations: u64,
|
||||
bags: usize,
|
||||
}
|
||||
|
||||
impl Work {
|
||||
/// Count a key derivation of `iterations`: refused past the caps.
|
||||
fn derive(&mut self, iterations: u64) -> Result<(), Error> {
|
||||
if iterations == 0 || iterations > MAX_ITERATIONS {
|
||||
return Err(Error::Unreasonable);
|
||||
}
|
||||
self.iterations = self.iterations.saturating_add(iterations);
|
||||
if self.iterations > MAX_TOTAL_ITERATIONS { Err(Error::Unreasonable) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A private-key bag and whether it was encrypted.
|
||||
struct KeyBag {
|
||||
key: Zeroizing<Vec<u8>>,
|
||||
encrypted: bool,
|
||||
}
|
||||
|
||||
/// The bags found.
|
||||
#[derive(Default)]
|
||||
struct Found {
|
||||
/// Each private key and whether it was encrypted in the file.
|
||||
keys: Vec<KeyBag>,
|
||||
certificates: Vec<(Vec<u8>, Option<Vec<u8>>)>,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// Pair only by verified public key, never by untrusted bag metadata.
|
||||
fn finish(mut self) -> Result<Opened, Error> {
|
||||
let KeyBag { key, encrypted: key_encrypted } = match self.keys.len() {
|
||||
1 => self.keys.pop().ok_or(Error::NoPrivateKey)?,
|
||||
_ => return Err(Error::NoPrivateKey),
|
||||
};
|
||||
let key_kind = private_key_kind(&key);
|
||||
let kind_of = |c: &[u8]| crate::cert::Cert::from_der(c).map_or(KeyKind::Other, |c| crate::algorithms::key_kind(c.public_key()));
|
||||
let public = public_of(&key);
|
||||
let by_key = public.as_ref().and_then(|p| self.certificates.iter().position(|(c, _)| certificate_key(c).as_ref() == Some(p)));
|
||||
// localKeyId is untrusted metadata, not proof of key ownership.
|
||||
let at = by_key.ok_or(Error::NoCertificate)?;
|
||||
let (certificate, _) = self.certificates.remove(at);
|
||||
if kind_of(&certificate) != key_kind {
|
||||
return Err(Error::NoCertificate);
|
||||
}
|
||||
Ok(Opened { certificate, others: self.certificates.into_iter().map(|(c, _)| c).collect(), private_key: key, key_kind, key_encrypted })
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of key a PKCS #8 `PrivateKeyInfo` is, by its own algorithm identifier: RSA by its
|
||||
/// modulus, EC by its named curve (the identifier's parameters, else the `ECPrivateKey`'s own).
|
||||
fn private_key_kind(pkcs8: &[u8]) -> KeyKind {
|
||||
let read = || -> Option<KeyKind> {
|
||||
let (info, _) = ber::read(pkcs8)?;
|
||||
let fields = ber::children(info.value)?;
|
||||
let [_, alg, key, ..] = fields.as_slice() else { return None };
|
||||
if key.tag != 0x04 {
|
||||
return None;
|
||||
}
|
||||
let (oid, params) = algorithm(alg).ok()?;
|
||||
let (inner, _) = ber::read(key.value)?;
|
||||
let parts = ber::children(inner.value)?;
|
||||
let curve_of = |t: &Tlv<'_>| oid_of(t).ok();
|
||||
let curve = params.as_ref().and_then(curve_of).or_else(|| {
|
||||
// ECPrivateKey (RFC 5915): [0] parameters, a named curve.
|
||||
let explicit = parts.iter().find(|p| p.tag == 0xa0)?;
|
||||
let (named, _) = ber::read(explicit.value)?;
|
||||
curve_of(&named)
|
||||
});
|
||||
// RSAPrivateKey (RFC 8017 A.1.2): version, modulus, …
|
||||
let modulus = parts.get(1).filter(|n| n.tag == 0x02).map(|n| n.value);
|
||||
Some(crate::algorithms::private_key_kind(oid, curve, modulus))
|
||||
};
|
||||
read().unwrap_or(KeyKind::Other)
|
||||
}
|
||||
|
||||
/// A ContentInfo's type and content (inside its `[0] EXPLICIT`).
|
||||
fn content_info<'a>(info: &Tlv<'a>) -> Result<(ObjectIdentifier, Tlv<'a>), Error> {
|
||||
if info.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(info.value).ok_or(Error::Unreadable)?;
|
||||
let [oid, explicit] = fields.as_slice() else { return Err(Error::Unreadable) };
|
||||
if explicit.tag != 0xa0 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let (content, rest) = ber::read(explicit.value).ok_or(Error::Unreadable)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
Ok((oid_of(oid)?, content))
|
||||
}
|
||||
|
||||
fn oid_of(tlv: &Tlv<'_>) -> Result<ObjectIdentifier, Error> {
|
||||
if tlv.tag != 0x06 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
ObjectIdentifier::from_der(tlv.whole).map_err(|_| Error::Unreadable)
|
||||
}
|
||||
|
||||
/// An OCTET STRING's octets: in one piece, or (BER) in pieces under a constructed tag.
|
||||
fn octets(tlv: Tlv<'_>) -> Result<Vec<u8>, Error> {
|
||||
match tlv.tag {
|
||||
0x04 | 0x80 => Ok(tlv.value.to_vec()),
|
||||
0x24 | 0xa0 => {
|
||||
let mut out = Vec::new();
|
||||
for piece in ber::children(tlv.value).ok_or(Error::Unreadable)? {
|
||||
if piece.tag != 0x04 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
out.extend_from_slice(piece.value);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
_ => Err(Error::Unreadable),
|
||||
}
|
||||
}
|
||||
|
||||
/// An INTEGER that fits, not negative.
|
||||
fn uint(tlv: &Tlv<'_>) -> Result<u64, Error> {
|
||||
if tlv.tag != 0x02 || tlv.value.is_empty() || tlv.value.len() > 9 || tlv.value.first().is_some_and(|b| b & 0x80 != 0) {
|
||||
return Err(Error::Unreasonable);
|
||||
}
|
||||
let digits = tlv.value.strip_prefix(&[0]).unwrap_or(tlv.value);
|
||||
if digits.len() > 8 {
|
||||
return Err(Error::Unreasonable);
|
||||
}
|
||||
Ok(digits.iter().fold(0u64, |acc, d| (acc << 8) | u64::from(*d)))
|
||||
}
|
||||
|
||||
/// An AlgorithmIdentifier: its OID and its parameters, if any.
|
||||
fn algorithm<'a>(tlv: &Tlv<'a>) -> Result<(ObjectIdentifier, Option<Tlv<'a>>), Error> {
|
||||
if tlv.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(tlv.value).ok_or(Error::Unreadable)?;
|
||||
match fields.as_slice() {
|
||||
[oid] => Ok((oid_of(oid)?, None)),
|
||||
[oid, params] => Ok((oid_of(oid)?, (params.tag != 0x05).then_some(*params))),
|
||||
_ => Err(Error::Unreadable),
|
||||
}
|
||||
}
|
||||
|
||||
/// The hashes a MAC or a key derivation is made with.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Hash {
|
||||
Sha1,
|
||||
Sha256,
|
||||
Sha384,
|
||||
Sha512,
|
||||
}
|
||||
|
||||
impl Hash {
|
||||
fn digest(oid: ObjectIdentifier) -> Result<Hash, Error> {
|
||||
Ok(match oid {
|
||||
SHA1 => Hash::Sha1,
|
||||
SHA256 => Hash::Sha256,
|
||||
SHA384 => Hash::Sha384,
|
||||
SHA512 => Hash::Sha512,
|
||||
_ => return Err(Error::UnknownAlgorithm),
|
||||
})
|
||||
}
|
||||
|
||||
fn hmac(oid: ObjectIdentifier) -> Result<Hash, Error> {
|
||||
Ok(match oid {
|
||||
HMAC_SHA1 => Hash::Sha1,
|
||||
HMAC_SHA256 => Hash::Sha256,
|
||||
HMAC_SHA384 => Hash::Sha384,
|
||||
HMAC_SHA512 => Hash::Sha512,
|
||||
_ => return Err(Error::UnknownAlgorithm),
|
||||
})
|
||||
}
|
||||
|
||||
fn len(self) -> usize {
|
||||
match self {
|
||||
Hash::Sha1 => 20,
|
||||
Hash::Sha256 => 32,
|
||||
Hash::Sha384 => 48,
|
||||
Hash::Sha512 => 64,
|
||||
}
|
||||
}
|
||||
|
||||
/// The PKCS #12 key derivation (RFC 7292 Appendix B.2) of `len` bytes for `purpose`.
|
||||
fn pkcs12_kdf(self, password: &[u8], salt: &[u8], purpose: Purpose, iterations: u64, len: usize) -> Result<Zeroizing<Vec<u8>>, Error> {
|
||||
use pkcs12::kdf::{Pkcs12KeyType, derive_key};
|
||||
let id = match purpose {
|
||||
Purpose::Key => Pkcs12KeyType::EncryptionKey,
|
||||
Purpose::Iv => Pkcs12KeyType::Iv,
|
||||
Purpose::Mac => Pkcs12KeyType::Mac,
|
||||
};
|
||||
let rounds = i32::try_from(iterations).map_err(|_| Error::Unreasonable)?;
|
||||
let out = match self {
|
||||
Hash::Sha1 => derive_key::<sha1::Sha1>(password, salt, id, rounds, len),
|
||||
Hash::Sha256 => derive_key::<sha2::Sha256>(password, salt, id, rounds, len),
|
||||
Hash::Sha384 => derive_key::<sha2::Sha384>(password, salt, id, rounds, len),
|
||||
Hash::Sha512 => derive_key::<sha2::Sha512>(password, salt, id, rounds, len),
|
||||
};
|
||||
out.map(Zeroizing::new).map_err(|_| Error::Unreadable)
|
||||
}
|
||||
|
||||
/// Whether the HMAC of `data` under `key` is `tag`, in constant time.
|
||||
fn hmac_checks(self, key: &[u8], data: &[u8], tag: &[u8]) -> bool {
|
||||
fn check<M: Mac + KeyInit>(key: &[u8], data: &[u8], tag: &[u8]) -> bool {
|
||||
match <M as KeyInit>::new_from_slice(key) {
|
||||
Ok(mut mac) => {
|
||||
mac.update(data);
|
||||
mac.verify_slice(tag).is_ok()
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
match self {
|
||||
Hash::Sha1 => check::<hmac::Hmac<sha1::Sha1>>(key, data, tag),
|
||||
Hash::Sha256 => check::<hmac::Hmac<sha2::Sha256>>(key, data, tag),
|
||||
Hash::Sha384 => check::<hmac::Hmac<sha2::Sha384>>(key, data, tag),
|
||||
Hash::Sha512 => check::<hmac::Hmac<sha2::Sha512>>(key, data, tag),
|
||||
}
|
||||
}
|
||||
|
||||
fn pbkdf2(self, password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) {
|
||||
match self {
|
||||
Hash::Sha1 => pbkdf2::pbkdf2_hmac::<sha1::Sha1>(password, salt, iterations, out),
|
||||
Hash::Sha256 => pbkdf2::pbkdf2_hmac::<sha2::Sha256>(password, salt, iterations, out),
|
||||
Hash::Sha384 => pbkdf2::pbkdf2_hmac::<sha2::Sha384>(password, salt, iterations, out),
|
||||
Hash::Sha512 => pbkdf2::pbkdf2_hmac::<sha2::Sha512>(password, salt, iterations, out),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Purpose {
|
||||
Key,
|
||||
Iv,
|
||||
Mac,
|
||||
}
|
||||
|
||||
/// The passphrase as the PKCS #12 key derivation takes it (RFC 7292 Appendix B.1): a BMPString,
|
||||
/// two bytes to a character, ended by two zero bytes. `None` for a character outside the BMP.
|
||||
fn bmp(passphrase: &str) -> Option<Zeroizing<Vec<u8>>> {
|
||||
let mut out = Zeroizing::new(Vec::with_capacity(passphrase.len().saturating_mul(2).saturating_add(2)));
|
||||
for c in passphrase.chars() {
|
||||
let unit = u16::try_from(u32::from(c)).ok()?;
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&[0, 0]);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The forms of the passphrase a file may have been made with: the BMPString, and for an empty
|
||||
/// one also nothing at all (which some writers use).
|
||||
fn passwords(passphrase: &str) -> Vec<Zeroizing<Vec<u8>>> {
|
||||
let mut out: Vec<Zeroizing<Vec<u8>>> = bmp(passphrase).into_iter().collect();
|
||||
if passphrase.is_empty() {
|
||||
out.push(Zeroizing::new(Vec::new()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Check the file's MAC (RFC 7292 §5.1, Appendix B.4) over `safe`.
|
||||
fn check_mac(mac: &Tlv<'_>, safe: &[u8], passphrase: &str, work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> {
|
||||
if mac.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(mac.value).ok_or(Error::Unreadable)?;
|
||||
let (digest_info, salt, iterations) = match fields.as_slice() {
|
||||
[d, s] => (d, s, 1),
|
||||
[d, s, i] => (d, s, uint(i)?),
|
||||
_ => return Err(Error::Unreadable),
|
||||
};
|
||||
if digest_info.tag != 0x30 || salt.tag != 0x04 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let parts = ber::children(digest_info.value).ok_or(Error::Unreadable)?;
|
||||
let [alg, digest] = parts.as_slice() else { return Err(Error::Unreadable) };
|
||||
if digest.tag != 0x04 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let (oid, _) = algorithm(alg)?;
|
||||
let hash = Hash::digest(oid)?;
|
||||
if digest.value.len() != hash.len() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
for password in passwords(passphrase) {
|
||||
work.derive(iterations)?;
|
||||
let key = hash.pkcs12_kdf(&password, salt.value, Purpose::Mac, iterations, hash.len())?;
|
||||
if hash.hmac_checks(&key, safe, digest.value) {
|
||||
return Ok(password);
|
||||
}
|
||||
}
|
||||
Err(Error::WrongPassphrase)
|
||||
}
|
||||
|
||||
/// The contents of an EncryptedData (RFC 5652 §8), decrypted.
|
||||
fn encrypted_data(content: Tlv<'_>, passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> {
|
||||
if content.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(content.value).ok_or(Error::Unreadable)?;
|
||||
let info = fields.get(1).ok_or(Error::Unreadable)?;
|
||||
if info.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let parts = ber::children(info.value).ok_or(Error::Unreadable)?;
|
||||
let [kind, alg, encrypted] = parts.as_slice() else { return Err(Error::Unreadable) };
|
||||
if oid_of(kind)? != DATA {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let ciphertext = octets(*encrypted)?;
|
||||
decrypt(alg, &ciphertext, passphrase, legacy_password, work)
|
||||
}
|
||||
|
||||
/// `ciphertext` decrypted with the passphrase as the algorithm identifier `alg` says.
|
||||
fn decrypt(alg: &Tlv<'_>, ciphertext: &[u8], passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result<Zeroizing<Vec<u8>>, Error> {
|
||||
let (oid, params) = algorithm(alg)?;
|
||||
if WEAK.iter().any(|w| oid.to_string() == *w) {
|
||||
return Err(Error::WeakEncryption);
|
||||
}
|
||||
let params = params.ok_or(Error::Unreadable)?;
|
||||
if oid == SHA_3DES {
|
||||
// RFC 7292 Appendix C: pkcs-12PbeParams, the key and IV from the PKCS #12 derivation.
|
||||
let fields = ber::children(params.value).ok_or(Error::Unreadable)?;
|
||||
let [salt, iterations] = fields.as_slice() else { return Err(Error::Unreadable) };
|
||||
if salt.tag != 0x04 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let iterations = uint(iterations)?;
|
||||
// Reuse the exact representation authenticated by the MAC, including empty bytes.
|
||||
let password = legacy_password;
|
||||
work.derive(iterations)?;
|
||||
let key = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Key, iterations, 24)?;
|
||||
work.derive(iterations)?;
|
||||
let iv = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Iv, iterations, 8)?;
|
||||
return cbc_decrypt::<des::TdesEde3>(&key, &iv, ciphertext);
|
||||
}
|
||||
if oid != PBES2 {
|
||||
return Err(Error::UnknownAlgorithm);
|
||||
}
|
||||
let fields = ber::children(params.value).ok_or(Error::Unreadable)?;
|
||||
let [kdf, scheme] = fields.as_slice() else { return Err(Error::Unreadable) };
|
||||
let (kdf_oid, kdf_params) = algorithm(kdf)?;
|
||||
if kdf_oid != PBKDF2 {
|
||||
return Err(Error::UnknownAlgorithm);
|
||||
}
|
||||
let kdf_fields = ber::children(kdf_params.ok_or(Error::Unreadable)?.value).ok_or(Error::Unreadable)?;
|
||||
let mut kdf_fields = kdf_fields.iter();
|
||||
let salt = kdf_fields.next().filter(|s| s.tag == 0x04).ok_or(Error::UnknownAlgorithm)?;
|
||||
let iterations = uint(kdf_fields.next().ok_or(Error::Unreadable)?)?;
|
||||
let mut prf = Hash::Sha1;
|
||||
let mut key_length: Option<u64> = None;
|
||||
for field in kdf_fields {
|
||||
match field.tag {
|
||||
0x02 if key_length.is_none() => key_length = Some(uint(field)?),
|
||||
0x30 => prf = Hash::hmac(algorithm(field)?.0)?,
|
||||
_ => return Err(Error::Unreadable),
|
||||
}
|
||||
}
|
||||
let (cipher, iv) = algorithm(scheme)?;
|
||||
let iv = iv.filter(|v| v.tag == 0x04).ok_or(Error::Unreadable)?;
|
||||
let size = match cipher {
|
||||
AES128_CBC => 16,
|
||||
AES192_CBC => 24,
|
||||
AES256_CBC => 32,
|
||||
DES_EDE3_CBC => 24,
|
||||
_ => return Err(Error::UnknownAlgorithm),
|
||||
};
|
||||
if key_length.is_some_and(|l| l != size as u64) {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
work.derive(iterations)?;
|
||||
let rounds = u32::try_from(iterations).map_err(|_| Error::Unreasonable)?;
|
||||
let mut key = Zeroizing::new(vec![0u8; size]);
|
||||
// (RFC 8018 takes the passphrase as octets: its UTF-8, as the writers do.)
|
||||
prf.pbkdf2(passphrase.as_bytes(), salt.value, rounds, &mut key);
|
||||
match cipher {
|
||||
AES128_CBC => cbc_decrypt::<aes::Aes128>(&key, iv.value, ciphertext),
|
||||
AES192_CBC => cbc_decrypt::<aes::Aes192>(&key, iv.value, ciphertext),
|
||||
AES256_CBC => cbc_decrypt::<aes::Aes256>(&key, iv.value, ciphertext),
|
||||
_ => cbc_decrypt::<des::TdesEde3>(&key, iv.value, ciphertext),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ciphertext` decrypted in CBC mode with PKCS #7 padding. A wrong key shows as bad padding,
|
||||
/// which is said as a wrong passphrase (the MAC has checked by then, so it seldom is).
|
||||
fn cbc_decrypt<C>(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error>
|
||||
where
|
||||
C: aes::cipher::BlockCipherDecrypt + aes::cipher::KeyInit,
|
||||
cbc::Decryptor<C>: KeyIvInit + BlockModeDecrypt,
|
||||
{
|
||||
let decryptor = cbc::Decryptor::<C>::new_from_slices(key, iv).map_err(|_| Error::Unreadable)?;
|
||||
let mut buffer = Zeroizing::new(ciphertext.to_vec());
|
||||
let len = decryptor.decrypt_padded::<Pkcs7>(&mut buffer).map_err(|_| Error::WrongPassphrase)?.len();
|
||||
buffer.truncate(len);
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
/// Where a SafeContents is: the passphrase, whether it came out of an encrypted safe, and how
|
||||
/// deep in other bags.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Safe<'a> {
|
||||
passphrase: &'a str,
|
||||
legacy_password: &'a [u8],
|
||||
encrypted: bool,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// The bags of a SafeContents, into `found`.
|
||||
fn safe_contents(bytes: &[u8], safe: Safe<'_>, work: &mut Work, found: &mut Found) -> Result<(), Error> {
|
||||
let Safe { passphrase, legacy_password, encrypted, depth } = safe;
|
||||
if depth > MAX_NESTING {
|
||||
return Err(Error::Unreasonable);
|
||||
}
|
||||
let der = Zeroizing::new(ber::to_der(bytes).ok_or(Error::Unreadable)?);
|
||||
let (list, rest) = ber::read(&der).ok_or(Error::Unreadable)?;
|
||||
if list.tag != 0x30 || !rest.is_empty() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
for bag in ber::children(list.value).ok_or(Error::Unreadable)? {
|
||||
work.bags = work.bags.saturating_add(1);
|
||||
if work.bags > MAX_BAGS {
|
||||
return Err(Error::Unreasonable);
|
||||
}
|
||||
if bag.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let fields = ber::children(bag.value).ok_or(Error::Unreadable)?;
|
||||
let (kind, value, attributes) = match fields.as_slice() {
|
||||
[k, v] => (k, v, None),
|
||||
[k, v, a] => (k, v, Some(a)),
|
||||
_ => return Err(Error::Unreadable),
|
||||
};
|
||||
if value.tag != 0xa0 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let (value, rest) = ber::read(value.value).ok_or(Error::Unreadable)?;
|
||||
if !rest.is_empty() {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let key_id = attributes.and_then(local_key_id);
|
||||
match oid_of(kind)? {
|
||||
KEY_BAG => found.keys.push(KeyBag { key: Zeroizing::new(value.whole.to_vec()), encrypted }),
|
||||
SHROUDED_KEY_BAG => {
|
||||
// EncryptedPrivateKeyInfo (RFC 5958 §3).
|
||||
if value.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let parts = ber::children(value.value).ok_or(Error::Unreadable)?;
|
||||
let [alg, data] = parts.as_slice() else { return Err(Error::Unreadable) };
|
||||
let ciphertext = octets(*data)?;
|
||||
let key = decrypt(alg, &ciphertext, passphrase, legacy_password, work)?;
|
||||
if ber::read(&key).is_none_or(|(k, rest)| k.tag != 0x30 || !rest.is_empty()) {
|
||||
return Err(Error::WrongPassphrase);
|
||||
}
|
||||
found.keys.push(KeyBag { key, encrypted: true });
|
||||
}
|
||||
CERT_BAG => {
|
||||
if value.tag != 0x30 {
|
||||
return Err(Error::Unreadable);
|
||||
}
|
||||
let parts = ber::children(value.value).ok_or(Error::Unreadable)?;
|
||||
let [cert_kind, cert] = parts.as_slice() else { return Err(Error::Unreadable) };
|
||||
// (SDSI certificates are of no use for mail: left out.)
|
||||
if oid_of(cert_kind)? != X509_CERTIFICATE || cert.tag != 0xa0 {
|
||||
continue;
|
||||
}
|
||||
let (octet, _) = ber::read(cert.value).ok_or(Error::Unreadable)?;
|
||||
let der = ber::to_der(&octets(octet)?).ok_or(Error::Unreadable)?;
|
||||
if found.certificates.len() < MAX_CERTIFICATES && crate::cert::Cert::from_der(&der).is_some() {
|
||||
found.certificates.push((der, key_id));
|
||||
}
|
||||
}
|
||||
SAFE_CONTENTS_BAG => safe_contents(value.whole, Safe { depth: depth.saturating_add(1), ..safe }, work, found)?,
|
||||
// CRLs and secrets: of no use here.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A bag's localKeyId attribute (PKCS #9), when it has one.
|
||||
fn local_key_id(attributes: &Tlv<'_>) -> Option<Vec<u8>> {
|
||||
for attribute in ber::children(attributes.value)? {
|
||||
let parts = ber::children(attribute.value)?;
|
||||
let [oid, values] = parts.as_slice() else { continue };
|
||||
if oid_of(oid).ok()? == LOCAL_KEY_ID {
|
||||
let (value, _) = ber::read(values.value)?;
|
||||
return (value.tag == 0x04).then(|| value.value.to_vec());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What of a private key (PKCS #8) its certificate's public key must match: an RSA key's modulus
|
||||
/// and exponent as `RSAPublicKey`, an EC key's public point derived from its scalar.
|
||||
fn public_of(pkcs8: &[u8]) -> Option<Vec<u8>> {
|
||||
let (info, _) = ber::read(pkcs8)?;
|
||||
let fields = ber::children(info.value)?;
|
||||
let [_, alg, key, ..] = fields.as_slice() else { return None };
|
||||
if key.tag != 0x04 {
|
||||
return None;
|
||||
}
|
||||
let (oid, _) = algorithm(alg).ok()?;
|
||||
let (inner, _) = ber::read(key.value)?;
|
||||
let parts = ber::children(inner.value)?;
|
||||
if oid.to_string() == "1.2.840.113549.1.1.1" {
|
||||
// RSAPrivateKey (RFC 8017 A.1.2): version, modulus, publicExponent, …
|
||||
let [_, n, e, ..] = parts.as_slice() else { return None };
|
||||
let mut body = n.whole.to_vec();
|
||||
body.extend_from_slice(e.whole);
|
||||
return Some(rsa_public(&body));
|
||||
}
|
||||
// RFC 5915 makes the public point optional. Derive it from the private scalar,
|
||||
// and refuse an inconsistent supplied point rather than trusting bag metadata.
|
||||
let scalar = parts.get(1).filter(|p| p.tag == 0x04)?.value;
|
||||
let supplied = parts.iter().find(|p| p.tag == 0xa1).map(|p| {
|
||||
let (bits, rest) = ber::read(p.value)?;
|
||||
if !rest.is_empty() || bits.tag != 0x03 || bits.value.first() != Some(&0) {
|
||||
return None;
|
||||
}
|
||||
bits.value.get(1..)
|
||||
});
|
||||
use p256::elliptic_curve::sec1::ToSec1Point;
|
||||
let point = match private_key_kind(pkcs8) {
|
||||
KeyKind::P256 => {
|
||||
let public = p256::SecretKey::from_slice(scalar).ok()?.public_key();
|
||||
if let Some(encoded) = supplied
|
||||
&& p256::PublicKey::from_sec1_bytes(encoded?).ok()? != public
|
||||
{
|
||||
return None;
|
||||
}
|
||||
public.to_sec1_point(false).as_bytes().to_vec()
|
||||
}
|
||||
KeyKind::P384 => {
|
||||
let public = p384::SecretKey::from_slice(scalar).ok()?.public_key();
|
||||
if let Some(encoded) = supplied
|
||||
&& p384::PublicKey::from_sec1_bytes(encoded?).ok()? != public
|
||||
{
|
||||
return None;
|
||||
}
|
||||
public.to_sec1_point(false).as_bytes().to_vec()
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let mut bits = vec![0];
|
||||
bits.extend(point);
|
||||
Some(bits)
|
||||
}
|
||||
|
||||
/// `RSAPublicKey ::= SEQUENCE { modulus, publicExponent }` around `body`.
|
||||
fn rsa_public(body: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![0x30];
|
||||
let len = body.len();
|
||||
if len < 0x80 {
|
||||
out.push(len as u8);
|
||||
} else {
|
||||
let bytes: Vec<u8> = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect();
|
||||
out.push(0x80 | bytes.len() as u8);
|
||||
out.extend(bytes);
|
||||
}
|
||||
out.extend_from_slice(body);
|
||||
out
|
||||
}
|
||||
|
||||
/// A certificate's public key as [`public_of`] gives it: the subjectPublicKey's bits.
|
||||
fn certificate_key(der: &[u8]) -> Option<Vec<u8>> {
|
||||
let cert = crate::cert::Cert::from_der(der)?;
|
||||
let spki = cert.public_key();
|
||||
let bits = spki.subject_public_key.as_bytes()?;
|
||||
if spki.algorithm.oid.to_string() == "1.2.840.113549.1.1.1" {
|
||||
return Some(bits.to_vec());
|
||||
}
|
||||
// (An EC point: the BIT STRING's octets, after its unused-bits byte, as `public_of` gives.)
|
||||
let mut with_unused = vec![0u8];
|
||||
with_unused.extend_from_slice(bits);
|
||||
Some(with_unused)
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! PKCS #12 files opened (#30 R13). The files were made with OpenSSL 3 for synthetic
|
||||
//! `example.org` people (an RSA key for Alice, a P-256 key for Bob, both under a test authority
|
||||
//! made for these tests alone), with the passphrase `example-pass`:
|
||||
//! `openssl pkcs12 -export` (PBES2, AES-256-CBC, HMAC-SHA-256), with `-keypbe PBE-SHA1-3DES
|
||||
//! -certpbe PBE-SHA1-3DES -macalg sha1` (the old scheme), `-legacy` (RC2-40), `-nomac`,
|
||||
//! `-keypbe AES-128-CBC -certpbe NONE -macalg sha512` (Bob's), `-passout pass:` (no passphrase)
|
||||
//! and `-iter 2000000`.
|
||||
|
||||
use base64::Engine as _;
|
||||
use proptest::prelude::*;
|
||||
|
||||
use crate::pkcs12::{Error, KeyKind, MAX_P12_LEN, looks_like, open};
|
||||
|
||||
const PASS: &str = "example-pass";
|
||||
|
||||
fn bytes(b64: &str) -> Vec<u8> {
|
||||
base64::engine::general_purpose::STANDARD.decode(b64).unwrap()
|
||||
}
|
||||
|
||||
fn der(pem: &str) -> Vec<u8> {
|
||||
crate::import::certificates_in(pem.as_bytes()).remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modern_file_opens_with_its_certificate_its_authority_and_its_key() {
|
||||
let opened = open(&bytes(MODERN), PASS).unwrap();
|
||||
assert_eq!(opened.certificate, der(ALICE_PEM));
|
||||
assert_eq!(opened.others, vec![der(CA_PEM)]);
|
||||
assert_eq!(opened.key_kind, KeyKind::Rsa { bits: 2048 }, "RSA keys aren't used here: the window is told");
|
||||
// PKCS #8 PrivateKeyInfo, RSA.
|
||||
assert_eq!(opened.private_key.first(), Some(&0x30));
|
||||
assert!(opened.private_key.windows(9).any(|w| w == [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01]));
|
||||
// Never shown, even in a log.
|
||||
let shown = format!("{opened:?}");
|
||||
assert!(shown.contains("redacted"), "{shown}");
|
||||
assert!(!shown.contains("48, 130"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_old_triple_des_scheme_opens() {
|
||||
let opened = open(&bytes(LEGACY), PASS).unwrap();
|
||||
assert_eq!(opened.certificate, der(ALICE_PEM));
|
||||
assert_eq!(opened.others.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ec_key_finds_its_certificate_by_its_public_key() {
|
||||
let opened = open(&bytes(EC), PASS).unwrap();
|
||||
let info = crate::import::certificate_info(&opened.certificate).unwrap();
|
||||
assert_eq!(info.addresses, vec!["bob@example.org".to_string()]);
|
||||
assert_eq!(opened.key_kind, KeyKind::P256);
|
||||
assert!(opened.others.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_passphrase_opens_with_none() {
|
||||
assert!(open(&bytes(EMPTY), "").is_ok());
|
||||
assert_eq!(open(&bytes(EMPTY), PASS).err(), Some(Error::WrongPassphrase));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_passphrase_is_said_as_one() {
|
||||
for file in [MODERN, LEGACY, EC] {
|
||||
assert_eq!(open(&bytes(file), "wrong").err(), Some(Error::WrongPassphrase));
|
||||
}
|
||||
// A passphrase with a character past the BMP can't be one a file was made with.
|
||||
assert_eq!(open(&bytes(MODERN), "\u{1F600}").err(), Some(Error::WrongPassphrase));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_file_fails_its_mac() {
|
||||
let mut file = bytes(MODERN);
|
||||
// The MAC's digest is near the end: change its last byte, then a byte of the content.
|
||||
let last = file.len() - 30;
|
||||
file[last] ^= 1;
|
||||
assert_eq!(open(&file, PASS).err(), Some(Error::WrongPassphrase));
|
||||
let mut file = bytes(MODERN);
|
||||
file[200] ^= 0x40;
|
||||
assert!(open(&file, PASS).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_no_longer_safe_or_unvouched_for_is_refused() {
|
||||
assert_eq!(open(&bytes(RC2), PASS).err(), Some(Error::WeakEncryption));
|
||||
assert_eq!(open(&bytes(NO_MAC), PASS).err(), Some(Error::NoMac));
|
||||
assert_eq!(open(&bytes(SLOW), PASS).err(), Some(Error::Unreasonable));
|
||||
assert_eq!(open(&vec![0x30; MAX_P12_LEN + 1], PASS).err(), Some(Error::TooLarge));
|
||||
assert_eq!(open(b"not a file", PASS).err(), Some(Error::Unreadable));
|
||||
assert_eq!(open(ALICE_PEM.as_bytes(), PASS).err(), Some(Error::Unreadable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pkcs12_file_is_told_from_a_certificate() {
|
||||
for file in [MODERN, LEGACY, RC2, NO_MAC, EC] {
|
||||
assert!(looks_like(&bytes(file)));
|
||||
}
|
||||
assert!(!looks_like(&der(ALICE_PEM)));
|
||||
assert!(!looks_like(b""));
|
||||
}
|
||||
|
||||
/// A DER element of `tag` around `content`.
|
||||
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![tag];
|
||||
let len = content.len();
|
||||
if len < 0x80 {
|
||||
out.push(len as u8);
|
||||
} else {
|
||||
let bytes: Vec<u8> = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect();
|
||||
out.push(0x80 | bytes.len() as u8);
|
||||
out.extend(bytes);
|
||||
}
|
||||
out.extend_from_slice(content);
|
||||
out
|
||||
}
|
||||
|
||||
fn seq(parts: &[Vec<u8>]) -> Vec<u8> {
|
||||
tlv(0x30, &parts.concat())
|
||||
}
|
||||
|
||||
fn oid(dotted: &str) -> Vec<u8> {
|
||||
use der::Encode;
|
||||
const_oid::ObjectIdentifier::new(dotted).unwrap().to_der().unwrap()
|
||||
}
|
||||
|
||||
/// A bag of `kind` holding `value`, with the local key id `id`.
|
||||
fn bag(kind: &str, value: Vec<u8>, id: &[u8]) -> Vec<u8> {
|
||||
let local_key_id = seq(&[oid("1.2.840.113549.1.9.21"), tlv(0x31, &tlv(0x04, id))]);
|
||||
seq(&[oid(kind), tlv(0xa0, &value), tlv(0x31, &local_key_id)])
|
||||
}
|
||||
|
||||
/// A PKCS #12 file of one plain safe (no encryption at all) holding `key` in a plain key bag
|
||||
/// and `certificate`, both with the local key id `id`, under a SHA-256 MAC with [`PASS`]: what
|
||||
/// `openssl pkcs12 -export -keypbe NONE -certpbe NONE` writes, and a file that pairs any key with
|
||||
/// any certificate.
|
||||
fn plain_p12(key: &[u8], certificate: &[u8], id: &[u8]) -> Vec<u8> {
|
||||
use hmac::{KeyInit, Mac};
|
||||
let key_bag = bag("1.2.840.113549.1.12.10.1.1", key.to_vec(), id);
|
||||
let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, certificate))]);
|
||||
let cert_bag = bag("1.2.840.113549.1.12.10.1.3", cert, id);
|
||||
let safe = seq(&[key_bag, cert_bag]);
|
||||
let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]);
|
||||
let auth_safe = seq(&[data(&safe)]);
|
||||
let salt = b"example salt";
|
||||
let password: Vec<u8> = PASS.encode_utf16().flat_map(u16::to_be_bytes).chain([0, 0]).collect();
|
||||
let mac_key = pkcs12::kdf::derive_key::<sha2::Sha256>(&password, salt, pkcs12::kdf::Pkcs12KeyType::Mac, 2048, 32).unwrap();
|
||||
let mut mac = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(&mac_key).unwrap();
|
||||
mac.update(&auth_safe);
|
||||
let digest = mac.finalize().into_bytes();
|
||||
let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0x00]]);
|
||||
let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]);
|
||||
seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data])
|
||||
}
|
||||
|
||||
/// The private keys of the fixtures, as PKCS #8.
|
||||
fn rsa_key() -> Vec<u8> {
|
||||
open(&bytes(MODERN), PASS).unwrap().private_key.to_vec()
|
||||
}
|
||||
|
||||
fn p256_key() -> Vec<u8> {
|
||||
open(&bytes(EC), PASS).unwrap().private_key.to_vec()
|
||||
}
|
||||
|
||||
fn p256_certificate() -> Vec<u8> {
|
||||
open(&bytes(EC), PASS).unwrap().certificate
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_kind_said_is_the_private_keys_own() {
|
||||
// A P-256 key with its own certificate, in a plain safe: it opens, and is said to be in
|
||||
// clear in the file.
|
||||
let opened = open(&plain_p12(&p256_key(), &p256_certificate(), b"1"), PASS).unwrap();
|
||||
assert_eq!(opened.key_kind, KeyKind::P256);
|
||||
assert!(!opened.key_encrypted, "a plain key bag in a plain safe");
|
||||
assert!(open(&bytes(EC), PASS).unwrap().key_encrypted);
|
||||
assert!(open(&bytes(MODERN), PASS).unwrap().key_encrypted);
|
||||
// An RSA key with a P-256 certificate sharing its local key id: no certificate is its.
|
||||
assert_eq!(open(&plain_p12(&rsa_key(), &p256_certificate(), b"1"), PASS).err(), Some(Error::NoCertificate));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn any_bytes_open_without_a_panic(junk in proptest::collection::vec(any::<u8>(), 0..1024)) {
|
||||
let _ = open(&junk, PASS);
|
||||
let _ = looks_like(&junk);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_file_opens_without_a_panic(at in 0usize..4096, byte in any::<u8>()) {
|
||||
static FILE: std::sync::LazyLock<Vec<u8>> = std::sync::LazyLock::new(|| bytes(EC));
|
||||
let mut file = FILE.clone();
|
||||
let len = file.len();
|
||||
if let Some(b) = file.get_mut(at % len) {
|
||||
*b = byte;
|
||||
}
|
||||
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XlzGGRYAMC49eLPAAPvO\n6CL+ZPvNByZKTRy6pt+Tr06nbj7YH92z4xO601vILQBmBwwhsQNMotKDZ/Qedb8t\ng6maxc83l5rKOR/XHze6nIoFQR1uYWrvLT/JpwTZ9SfDk5pbMVCRyExACSAQL3NF\nS1boSb2RndOIHAcwKUF7uEYm+uoMbttCFcFZTcNcO1swL43/562cJ8w2AWwCBv4j\nz0Kcna6idZx/eTZxkHizZwMGzJL9Hzbvui0gPBu0RNAbBUTeJawC/1IOEFQq43Fj\nMxttmH5D5Ax3nffhFlrAH2IgjiHTI+IbzIzNR1J0Xw==\n-----END CERTIFICATE-----\n";
|
||||
|
||||
#[test]
|
||||
fn matching_local_id_cannot_override_a_different_public_key() {
|
||||
// Both are 2048-bit RSA, but the CA certificate does not belong to Alice's key.
|
||||
let key = rsa_key();
|
||||
let alice = der(ALICE_PEM);
|
||||
let other = der(CA_PEM);
|
||||
let alice_key = crate::cert::Cert::from_der(&alice).unwrap();
|
||||
let other_key = crate::cert::Cert::from_der(&other).unwrap();
|
||||
assert_eq!(crate::algorithms::key_kind(alice_key.public_key()), crate::algorithms::key_kind(other_key.public_key()));
|
||||
assert_ne!(alice_key.public_key(), other_key.public_key());
|
||||
assert!(open(&plain_p12(&key, &alice, b"same-id"), PASS).is_ok());
|
||||
assert_eq!(open(&plain_p12(&key, &other, b"same-id"), PASS).err(), Some(Error::NoCertificate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ec_key_pairing_is_derived_not_claimed_by_metadata() {
|
||||
for algorithm in [&rcgen::PKCS_ECDSA_P256_SHA256, &rcgen::PKCS_ECDSA_P384_SHA384] {
|
||||
let key = rcgen::KeyPair::generate_for(algorithm).unwrap();
|
||||
let other = rcgen::KeyPair::generate_for(algorithm).unwrap();
|
||||
let params = rcgen::CertificateParams::new(vec!["example.org".into()]).unwrap();
|
||||
let certificate = params.self_signed(&key).unwrap();
|
||||
let wrong = params.self_signed(&other).unwrap();
|
||||
let pkcs8 = key.serialize_der();
|
||||
let (info, _) = craft_ber::read(&pkcs8).unwrap();
|
||||
let fields = craft_ber::children(info.value).unwrap();
|
||||
let (inner, _) = craft_ber::read(fields[2].value).unwrap();
|
||||
let parts = craft_ber::children(inner.value).unwrap();
|
||||
let without_point: Vec<Vec<u8>> = parts.iter().filter(|p| p.tag != 0xa1).map(|p| p.whole.to_vec()).collect();
|
||||
let omitted = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&without_point))]);
|
||||
assert!(open(&plain_p12(&omitted, certificate.der(), b"same-id"), PASS).is_ok());
|
||||
assert_eq!(open(&plain_p12(&omitted, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate));
|
||||
|
||||
let other_der = other.serialize_der();
|
||||
let (other_info, _) = craft_ber::read(&other_der).unwrap();
|
||||
let other_fields = craft_ber::children(other_info.value).unwrap();
|
||||
let (other_inner, _) = craft_ber::read(other_fields[2].value).unwrap();
|
||||
let other_parts = craft_ber::children(other_inner.value).unwrap();
|
||||
let point = other_parts.iter().find(|p| p.tag == 0xa1).unwrap();
|
||||
let mut forged_parts = without_point;
|
||||
forged_parts.push(point.whole.to_vec());
|
||||
let forged = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&forged_parts))]);
|
||||
assert_eq!(open(&plain_p12(&forged, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_decryption_uses_the_empty_password_representation_verified_by_the_mac() {
|
||||
use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||||
use hmac::{KeyInit, Mac};
|
||||
use pkcs12::kdf::{Pkcs12KeyType, derive_key};
|
||||
let salt = b"empty password fixture salt";
|
||||
let key = rsa_key();
|
||||
let certificate = der(ALICE_PEM);
|
||||
for password in [b"".as_slice(), &[0, 0][..]] {
|
||||
for encrypt_safe in [false, true] {
|
||||
let encrypt = |plain: &[u8]| {
|
||||
let key = derive_key::<sha1::Sha1>(password, salt, Pkcs12KeyType::EncryptionKey, 2048, 24).unwrap();
|
||||
let iv = derive_key::<sha1::Sha1>(password, salt, Pkcs12KeyType::Iv, 2048, 8).unwrap();
|
||||
let mut buffer = plain.to_vec();
|
||||
buffer.resize(plain.len() + 8, 0);
|
||||
cbc::Encryptor::<des::TdesEde3>::new_from_slices(&key, &iv)
|
||||
.unwrap()
|
||||
.encrypt_padded::<Pkcs7>(&mut buffer, plain.len())
|
||||
.unwrap()
|
||||
.to_vec()
|
||||
};
|
||||
let algorithm = seq(&[oid("1.2.840.113549.1.12.1.3"), seq(&[tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])])]);
|
||||
let key_bag = if encrypt_safe {
|
||||
bag("1.2.840.113549.1.12.10.1.1", key.clone(), b"id")
|
||||
} else {
|
||||
bag("1.2.840.113549.1.12.10.1.2", seq(&[algorithm.clone(), tlv(0x04, &encrypt(&key))]), b"id")
|
||||
};
|
||||
let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, &certificate))]);
|
||||
let safe = seq(&[key_bag, bag("1.2.840.113549.1.12.10.1.3", cert, b"id")]);
|
||||
let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]);
|
||||
let content = if encrypt_safe {
|
||||
let encrypted_info = seq(&[oid("1.2.840.113549.1.7.1"), algorithm, tlv(0x80, &encrypt(&safe))]);
|
||||
seq(&[oid("1.2.840.113549.1.7.6"), tlv(0xa0, &seq(&[tlv(0x02, &[0]), encrypted_info]))])
|
||||
} else {
|
||||
data(&safe)
|
||||
};
|
||||
let auth_safe = seq(&[content]);
|
||||
let mac_key = derive_key::<sha2::Sha256>(password, salt, Pkcs12KeyType::Mac, 2048, 32).unwrap();
|
||||
let mut mac = <hmac::Hmac<sha2::Sha256> as KeyInit>::new_from_slice(&mac_key).unwrap();
|
||||
mac.update(&auth_safe);
|
||||
let digest = mac.finalize().into_bytes();
|
||||
let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0]]);
|
||||
let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]);
|
||||
let p12 = seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data]);
|
||||
let opened = open(&p12, "").unwrap();
|
||||
assert_eq!(&*opened.private_key, &key);
|
||||
assert_eq!(opened.certificate, certificate);
|
||||
assert!(opened.key_encrypted);
|
||||
assert_eq!(open(&p12, "wrong").err(), Some(Error::WrongPassphrase));
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,478 @@
|
||||
// SPDX-FileCopyrightText: MailCraft contributors
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Checking CMS SignedData (RFC 5652 §5) as S/MIME carries it (RFC 8551 §3.5): the signer's
|
||||
//! digest of what was signed, their signature over it, and whether their certificate is trusted
|
||||
//! and for the message's sender.
|
||||
|
||||
use crate::Timestamp;
|
||||
use crate::digital_signature::{Coverage, DigitalSignature, SignatureFormat, Signer, Verdict, Why};
|
||||
use cms::signed_data::{EncapsulatedContentInfo, SignerIdentifier, SignerInfo};
|
||||
use const_oid::ObjectIdentifier;
|
||||
use der::asn1::OctetString;
|
||||
use der::{Decode, Encode};
|
||||
|
||||
use crate::algorithms::{self, Fault, Hash};
|
||||
use crate::cert::Cert;
|
||||
use crate::chain::{self, Anchors};
|
||||
use craft_ber::{self as ber, Tlv};
|
||||
|
||||
/// The most certificates read from one message.
|
||||
pub const MAX_CERTS: usize = 32;
|
||||
/// The most signers of one message that are checked.
|
||||
pub const MAX_SIGNERS: usize = 8;
|
||||
/// The most signatures checked for one message, its signers' and their certificates' together
|
||||
/// (#30): an RSA key of 8192 bits takes a while, and a message may carry many.
|
||||
pub const MAX_VERIFICATIONS: usize = 32;
|
||||
/// The most certificates tried for one signer: those that its identifier names (the message
|
||||
/// may carry several of one name; only the one whose key made the signature is the signer's).
|
||||
pub const MAX_CANDIDATES: usize = 4;
|
||||
|
||||
const SIGNED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2");
|
||||
const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1");
|
||||
const CONTENT_TYPE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.3");
|
||||
const MESSAGE_DIGEST: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.4");
|
||||
const SIGNING_TIME: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.5");
|
||||
|
||||
/// What a check is made against.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Context<'a> {
|
||||
/// The certificates the host trusts.
|
||||
pub anchors: &'a Anchors,
|
||||
/// The message's From address.
|
||||
pub from: &'a str,
|
||||
/// The time of the check, seconds since 1970.
|
||||
pub now: Timestamp,
|
||||
/// Certificates kept for the sender already, in DER: a message that doesn't carry its
|
||||
/// signer's certificate may be checked with one of them.
|
||||
pub known: &'a [&'a [u8]],
|
||||
/// How much of the message the signed part is: the whole of it only when it is the
|
||||
/// message's top level. A part is never verified for the message.
|
||||
pub coverage: Coverage,
|
||||
}
|
||||
|
||||
/// A Digitally signed message's two halves.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Signed<'a> {
|
||||
/// `multipart/signed`: the signed part as it came (its MIME header and body) and the
|
||||
/// signature part's bytes (the CMS SignedData, decoded from base64).
|
||||
Detached { content: &'a [u8], signature: &'a [u8] },
|
||||
/// `application/pkcs7-mime; smime-type=signed-data`: the CMS SignedData holding what was
|
||||
/// signed (decoded from base64).
|
||||
Opaque(&'a [u8]),
|
||||
}
|
||||
|
||||
/// What a check found.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Checked {
|
||||
pub signature: DigitalSignature,
|
||||
/// The signer's certificate, in DER, when the signature over the message is the signer's
|
||||
/// and the certificate is for the From address: worth keeping for that address (#30 R9).
|
||||
pub certificate: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Check `signed` against `context`. `None` when the CMS isn't SignedData at all (an Encrypted
|
||||
/// message's enveloped data, say): not a Digital signature. Never fails otherwise: what can't be
|
||||
/// read is [`Verdict::Unchecked`].
|
||||
pub fn check(signed: Signed<'_>, context: &Context<'_>) -> Option<Checked> {
|
||||
check_within(signed, context, MAX_VERIFICATIONS)
|
||||
}
|
||||
|
||||
/// [`check`] with at most `verifications` signatures checked (for the tests, which spend a
|
||||
/// smaller budget).
|
||||
pub(crate) fn check_within(signed: Signed<'_>, context: &Context<'_>, verifications: usize) -> Option<Checked> {
|
||||
let blob = match signed {
|
||||
Signed::Detached { signature, .. } => signature,
|
||||
Signed::Opaque(blob) => blob,
|
||||
};
|
||||
let unreadable = || Some(unchecked(Why::Unreadable));
|
||||
let Some(der) = ber::to_der(blob) else { return unreadable() };
|
||||
let Some(parts) = content_info(&der) else { return unreadable() };
|
||||
if parts.content_type != SIGNED_DATA {
|
||||
return None;
|
||||
}
|
||||
let Some(data) = signed_data(parts.content) else { return unreadable() };
|
||||
let Ok(eci) = EncapsulatedContentInfo::from_der(data.encap.whole) else { return unreadable() };
|
||||
// What mail signs is MIME, id-data (RFC 8551 §3.5); a detached signature carries none of it
|
||||
// and an opaque one all of it.
|
||||
if eci.econtent_type != DATA {
|
||||
return unreadable();
|
||||
}
|
||||
let content: &[u8] = match (signed, econtent(&data.encap)) {
|
||||
(Signed::Detached { content, .. }, None) if eci.econtent.is_none() => content,
|
||||
(Signed::Opaque(_), Some(c)) => c,
|
||||
_ => return unreadable(),
|
||||
};
|
||||
let mut pool: Vec<Cert> = data.certificates.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c.whole)).collect();
|
||||
pool.extend(context.known.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c)));
|
||||
let mut digests = Digests::new(content, matches!(signed, Signed::Detached { .. }));
|
||||
let mut budget = verifications;
|
||||
let mut best: Option<Checked> = None;
|
||||
for signer in data.signers.iter().take(MAX_SIGNERS) {
|
||||
let found = one_signer(signer, &eci, &mut digests, &pool, context, &mut budget);
|
||||
best = Some(match best {
|
||||
Some(b) if b.signature.verdict <= found.signature.verdict => b,
|
||||
_ => found,
|
||||
});
|
||||
}
|
||||
best.or_else(unreadable).map(|mut c| {
|
||||
c.signature = c.signature.covering(context.coverage);
|
||||
c
|
||||
})
|
||||
}
|
||||
|
||||
/// What was signed and its digests, each worked out once (#30: a long message isn't hashed
|
||||
/// again for every signer and key tried), as it came and in its canonical form.
|
||||
struct Digests<'a> {
|
||||
content: &'a [u8],
|
||||
allow_transport_normalization: bool,
|
||||
/// The content with lone LFs made CRLF, when it has any: worked out at its first use.
|
||||
canonical: Option<Option<Vec<u8>>>,
|
||||
plain: Vec<(Hash, Vec<u8>)>,
|
||||
crlf: Vec<(Hash, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl<'a> Digests<'a> {
|
||||
fn new(content: &'a [u8], allow_transport_normalization: bool) -> Self {
|
||||
Digests { content, allow_transport_normalization, canonical: None, plain: Vec::new(), crlf: Vec::new() }
|
||||
}
|
||||
|
||||
fn of(&mut self, hash: Hash) -> Vec<u8> {
|
||||
if let Some((_, d)) = self.plain.iter().find(|(h, _)| *h == hash) {
|
||||
return d.clone();
|
||||
}
|
||||
let d = hash.digest(self.content);
|
||||
self.plain.push((hash, d.clone()));
|
||||
d
|
||||
}
|
||||
|
||||
/// The digest of the canonical form; `None` when the content has no lone LF (it is its own).
|
||||
fn of_canonical(&mut self, hash: Hash) -> Option<Vec<u8>> {
|
||||
// Encapsulated content is already the exact signed octet sequence. Rewriting
|
||||
// binary payload newlines would authenticate different bytes than we expose.
|
||||
if !self.allow_transport_normalization {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, d)) = self.crlf.iter().find(|(h, _)| *h == hash) {
|
||||
return Some(d.clone());
|
||||
}
|
||||
let content = self.content;
|
||||
let canonical = self.canonical.get_or_insert_with(|| canonical(content)).as_ref()?;
|
||||
let d = hash.digest(canonical);
|
||||
self.crlf.push((hash, d.clone()));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Whether `said` is the digest of the content as it came or in its canonical form.
|
||||
fn matches(&mut self, hash: Hash, said: &[u8]) -> bool {
|
||||
self.of(hash) == said || self.of_canonical(hash).is_some_and(|d| d == said)
|
||||
}
|
||||
}
|
||||
|
||||
fn unchecked(why: Why) -> Checked {
|
||||
Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Unchecked, why), certificate: None }
|
||||
}
|
||||
|
||||
struct ContentInfoParts<'a> {
|
||||
content_type: ObjectIdentifier,
|
||||
content: &'a [u8],
|
||||
}
|
||||
|
||||
/// ContentInfo: its type, and the value inside its `[0] EXPLICIT`.
|
||||
fn content_info(der: &[u8]) -> Option<ContentInfoParts<'_>> {
|
||||
let (outer, rest) = ber::read(der)?;
|
||||
if outer.tag != 0x30 || !rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fields = ber::children(outer.value)?;
|
||||
let [oid, explicit] = fields.as_slice() else { return None };
|
||||
if oid.tag != 0x06 || explicit.tag != 0xa0 {
|
||||
return None;
|
||||
}
|
||||
let content_type = ObjectIdentifier::from_der(oid.whole).ok()?;
|
||||
Some(ContentInfoParts { content_type, content: explicit.value })
|
||||
}
|
||||
|
||||
/// SignedData's parts as they came, so that signatures are checked over the bytes the signer
|
||||
/// wrote: what is inside, the certificates, and the signers.
|
||||
struct SignedDataParts<'a> {
|
||||
encap: Tlv<'a>,
|
||||
certificates: Vec<Tlv<'a>>,
|
||||
signers: Vec<Tlv<'a>>,
|
||||
}
|
||||
|
||||
/// SignedData read strictly (RFC 5652 §5.1): its version one of those defined, its digest
|
||||
/// algorithms a SET of algorithm identifiers, encapContentInfo, the certificates and the
|
||||
/// revocation lists when they are there, in that order, and the signers last: nothing else, and
|
||||
/// nothing after.
|
||||
fn signed_data(content: &[u8]) -> Option<SignedDataParts<'_>> {
|
||||
let (outer, rest) = ber::read(content)?;
|
||||
if outer.tag != 0x30 || !rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fields = ber::children(outer.value)?;
|
||||
let mut fields = fields.into_iter();
|
||||
let version = fields.next().filter(|f| f.tag == 0x02)?;
|
||||
if !matches!(version.value, [1] | [3] | [4] | [5]) {
|
||||
return None;
|
||||
}
|
||||
let digests = fields.next().filter(|f| f.tag == 0x31)?;
|
||||
for d in ber::children(digests.value)? {
|
||||
spki::AlgorithmIdentifierOwned::from_der(d.whole).ok()?;
|
||||
}
|
||||
let encap = fields.next().filter(|f| f.tag == 0x30)?;
|
||||
let mut next = fields.next()?;
|
||||
let mut certificates = Vec::new();
|
||||
if next.tag == 0xa0 {
|
||||
// (Other kinds of certificate, [0]..[3] IMPLICIT, are left out; they are never a path.)
|
||||
certificates = ber::children(next.value)?.into_iter().filter(|c| c.tag == 0x30).collect();
|
||||
next = fields.next()?;
|
||||
}
|
||||
if next.tag == 0xa1 {
|
||||
next = fields.next()?;
|
||||
}
|
||||
if next.tag != 0x31 || fields.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(SignedDataParts { encap, certificates, signers: ber::children(next.value)? })
|
||||
}
|
||||
|
||||
/// The OCTET STRING inside encapContentInfo's `[0] EXPLICIT eContent`, when there is one (and
|
||||
/// nothing else is there).
|
||||
fn econtent<'a>(encap: &Tlv<'a>) -> Option<&'a [u8]> {
|
||||
let fields = ber::children(encap.value)?;
|
||||
let explicit = fields.get(1).filter(|f| f.tag == 0xa0)?;
|
||||
let (octets, rest) = ber::read(explicit.value)?;
|
||||
(octets.tag == 0x04 && rest.is_empty()).then_some(octets.value)
|
||||
}
|
||||
|
||||
/// The value of the signed attribute `oid`, in DER (its one value), when there is one.
|
||||
fn attribute(info: &SignerInfo, oid: ObjectIdentifier) -> Option<Vec<u8>> {
|
||||
let attrs = info.signed_attrs.as_ref()?;
|
||||
let attr = attrs.iter().find(|a| a.oid == oid)?;
|
||||
if attr.values.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
attr.values.iter().next()?.to_der().ok()
|
||||
}
|
||||
|
||||
/// The bytes a signer with signed attributes signed (RFC 5652 §5.4): the attributes as they came,
|
||||
/// with their `[0] IMPLICIT` tag made the SET OF's.
|
||||
fn signed_attributes(raw: &Tlv<'_>) -> Option<Vec<u8>> {
|
||||
let fields = ber::children(raw.value)?;
|
||||
let attrs = fields.iter().find(|f| f.tag == 0xa0)?;
|
||||
let mut out = attrs.whole.to_vec();
|
||||
*out.first_mut()? = 0x31;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `content` with every lone LF made CRLF (RFC 8551 §3.1.1's canonical form), when it has one.
|
||||
fn canonical(content: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut lone = false;
|
||||
let mut out = Vec::with_capacity(content.len().saturating_add(content.len() / 32));
|
||||
let mut previous = 0u8;
|
||||
for &b in content {
|
||||
if b == b'\n' && previous != b'\r' {
|
||||
out.push(b'\r');
|
||||
lone = true;
|
||||
}
|
||||
out.push(b);
|
||||
previous = b;
|
||||
}
|
||||
lone.then_some(out)
|
||||
}
|
||||
|
||||
fn one_signer(
|
||||
raw: &Tlv<'_>,
|
||||
eci: &EncapsulatedContentInfo,
|
||||
digests: &mut Digests<'_>,
|
||||
pool: &[Cert],
|
||||
context: &Context<'_>,
|
||||
budget: &mut usize,
|
||||
) -> Checked {
|
||||
let Ok(info) = SignerInfo::from_der(raw.whole) else { return unchecked(Why::Unreadable) };
|
||||
let hash = match Hash::of(&info.digest_alg) {
|
||||
Ok(hash) => hash,
|
||||
Err(fault) => return unchecked(why_not(fault)),
|
||||
};
|
||||
let candidates = signer_certs(&info.sid, pool);
|
||||
if candidates.is_empty() {
|
||||
return unchecked(Why::NoPublicKey);
|
||||
}
|
||||
let signature = info.signature.as_bytes();
|
||||
// What the signer's key signed: the signed attributes (which hold the content's digest), or
|
||||
// without them the content itself, as it came or in its canonical form.
|
||||
let attributes = match &info.signed_attrs {
|
||||
Some(_) => match signed_attributes(raw) {
|
||||
Some(bytes) => Some(bytes),
|
||||
None => return unchecked(Why::Unreadable),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
// The signer is the certificate whose key made the signature, of those its identifier names:
|
||||
// another one of the same name (any can be put in a message) makes no difference.
|
||||
let mut fault: Option<Fault> = None;
|
||||
let mut signer: Option<(&Cert, Result<(), Why>)> = None;
|
||||
let mut ran_out = false;
|
||||
for cert in candidates {
|
||||
let Some(left) = budget.checked_sub(1) else {
|
||||
ran_out = true;
|
||||
break;
|
||||
};
|
||||
*budget = left;
|
||||
let verified = match &attributes {
|
||||
Some(bytes) => algorithms::verify(cert.public_key(), &info.signature_algorithm, Some(hash), bytes, signature),
|
||||
None => {
|
||||
let plain = algorithms::verify_hashed(cert.public_key(), &info.signature_algorithm, Some(hash), &mut |h| digests.of(h), signature);
|
||||
// (Signed in its canonical form, perhaps: another verification, from the budget.)
|
||||
if plain == Err(Fault::Invalid) && digests.of_canonical(hash).is_some() {
|
||||
let Some(left) = budget.checked_sub(1) else {
|
||||
ran_out = true;
|
||||
break;
|
||||
};
|
||||
*budget = left;
|
||||
algorithms::verify_hashed(
|
||||
cert.public_key(),
|
||||
&info.signature_algorithm,
|
||||
Some(hash),
|
||||
&mut |h| digests.of_canonical(h).unwrap_or_default(),
|
||||
signature,
|
||||
)
|
||||
} else {
|
||||
plain
|
||||
}
|
||||
}
|
||||
};
|
||||
match verified {
|
||||
Ok(()) => {
|
||||
// Matching keys can occur in expired or renewed certificates. A valid
|
||||
// signature alone does not select the certificate we can trust for mail.
|
||||
let for_email = cert.for_email() && !cert.is_authority();
|
||||
let trust = chain::trust(cert, pool, context.anchors, context.now, budget)
|
||||
.and_then(|()| for_email.then_some(()).ok_or(Why::NotForEmail))
|
||||
.and_then(|()| if cert.is_for(context.from) { Ok(()) } else { Err(Why::AddressMismatch) });
|
||||
if trust.is_ok() {
|
||||
signer = Some((cert, trust));
|
||||
break;
|
||||
}
|
||||
if signer.is_none() {
|
||||
signer = Some((cert, trust));
|
||||
}
|
||||
if trust == Err(Why::TooMuch) {
|
||||
ran_out = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// (Of several faults, what says most: an algorithm, then a malformed key, then no
|
||||
// match.)
|
||||
Err(f) => fault = Some(fault.map_or(f, |g| worse(g, f))),
|
||||
}
|
||||
}
|
||||
let Some((cert, mut trust)) = signer else {
|
||||
return match fault {
|
||||
// (A certificate not tried may have made it: no answer.)
|
||||
_ if ran_out => unchecked(Why::TooMuch),
|
||||
// No key it names made it: changed after signing, or never signed by any of them;
|
||||
// nobody is named, since none of them fits.
|
||||
Some(Fault::Invalid) | None => {
|
||||
Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Changed, Why::Altered), certificate: None }
|
||||
}
|
||||
Some(f) => unchecked(why_not(f)),
|
||||
};
|
||||
};
|
||||
let result = |verdict: Verdict, why: Option<Why>| Checked {
|
||||
signature: DigitalSignature {
|
||||
format: SignatureFormat::Smime,
|
||||
verdict,
|
||||
why,
|
||||
signer: Some(signer_of(cert)),
|
||||
signed_at: signing_time(&info),
|
||||
revocation_checked: false,
|
||||
// (`check` says, from where in the message the signed part sat.)
|
||||
coverage: Coverage::Part,
|
||||
},
|
||||
certificate: None,
|
||||
};
|
||||
if attributes.is_some() {
|
||||
// The attributes are the signer's own words now: what they say of the content holds.
|
||||
let Some(said_type) = attribute(&info, CONTENT_TYPE).and_then(|d| ObjectIdentifier::from_der(&d).ok()) else {
|
||||
return unchecked(Why::Unreadable);
|
||||
};
|
||||
let Some(said_digest) = attribute(&info, MESSAGE_DIGEST).and_then(|d| OctetString::from_der(&d).ok()) else {
|
||||
return unchecked(Why::Unreadable);
|
||||
};
|
||||
if said_type != eci.econtent_type || !digests.matches(hash, said_digest.as_bytes()) {
|
||||
return result(Verdict::Changed, Some(Why::Altered));
|
||||
}
|
||||
}
|
||||
// A candidate left untried may be acceptable. Do not report the first
|
||||
// refusal as definitive when the shared verification budget was exhausted.
|
||||
if ran_out {
|
||||
trust = Err(Why::TooMuch);
|
||||
}
|
||||
let mut r = match trust {
|
||||
Ok(()) => result(Verdict::Verified, None),
|
||||
Err(Why::TooMuch) => result(Verdict::Unchecked, Some(Why::TooMuch)),
|
||||
// (An algorithm that's no longer safe on the way to a trust anchor: the certificate can't
|
||||
// be relied on, but the message is as it was signed.)
|
||||
Err(why) => result(Verdict::NotVerified, Some(why)),
|
||||
};
|
||||
// Kept for the sender only when it is trusted, valid now and theirs: it is what mail to them
|
||||
// will be encrypted with.
|
||||
if trust.is_ok() {
|
||||
r.certificate = Some(cert.der().to_vec());
|
||||
}
|
||||
// The signer's address that is the sender's comes first: it is the one said.
|
||||
if let (Some(address), Some(signer)) = (cert.address_for(context.from), r.signature.signer.as_mut()) {
|
||||
let shown = crate::digital_signature::signer_text(&address);
|
||||
signer.addresses.retain(|a| !a.eq_ignore_ascii_case(&shown));
|
||||
signer.addresses.insert(0, shown);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Of two faults, the one that says most of why a signature can't be relied on.
|
||||
fn worse(a: Fault, b: Fault) -> Fault {
|
||||
let rank = |f: Fault| match f {
|
||||
Fault::Weak => 0,
|
||||
Fault::Unknown => 1,
|
||||
Fault::Malformed => 2,
|
||||
Fault::Invalid => 3,
|
||||
};
|
||||
if rank(b) < rank(a) { b } else { a }
|
||||
}
|
||||
|
||||
fn why_not(fault: Fault) -> Why {
|
||||
match fault {
|
||||
Fault::Weak => Why::WeakAlgorithm,
|
||||
Fault::Unknown => Why::UnknownAlgorithm,
|
||||
Fault::Invalid => Why::Altered,
|
||||
Fault::Malformed => Why::Unreadable,
|
||||
}
|
||||
}
|
||||
|
||||
/// The certificates in `pool` that `sid` names, at most [`MAX_CANDIDATES`].
|
||||
fn signer_certs<'a>(sid: &SignerIdentifier, pool: &'a [Cert]) -> Vec<&'a Cert> {
|
||||
match sid {
|
||||
SignerIdentifier::IssuerAndSerialNumber(isn) => {
|
||||
let Ok(issuer) = isn.issuer.to_der() else { return Vec::new() };
|
||||
let serial = isn.serial_number.as_bytes();
|
||||
pool.iter().filter(|c| c.issuer() == issuer.as_slice() && c.serial() == serial).take(MAX_CANDIDATES).collect()
|
||||
}
|
||||
SignerIdentifier::SubjectKeyIdentifier(ski) => {
|
||||
let id = ski.0.as_bytes();
|
||||
pool.iter().filter(|c| c.key_id().as_deref() == Some(id)).take(MAX_CANDIDATES).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn signer_of(cert: &Cert) -> Signer {
|
||||
let (not_before, not_after) = cert.validity();
|
||||
Signer { name: cert.name(), addresses: cert.addresses(), fingerprint: cert.fingerprint(), issuer: cert.issuer_name(), not_before, not_after }
|
||||
}
|
||||
|
||||
/// The signing time the signer gives (RFC 5652 §11.3): their word, unchecked.
|
||||
fn signing_time(info: &SignerInfo) -> Option<Timestamp> {
|
||||
let der = attribute(info, SIGNING_TIME)?;
|
||||
let time = x509_cert::time::Time::from_der(&der).ok()?;
|
||||
Timestamp::try_from(time.to_unix_duration().as_secs()).ok()
|
||||
}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
# S/MIME test vectors
|
||||
|
||||
Restored from `UCS-Care-Group/mailcraft` commit
|
||||
`240d1d42fe394cf3274402b180663ba9b43ca180`, `crates/smime/testdata`.
|
||||
The source test suite identifies these as RFC 9216 example certificates and
|
||||
OpenSSL-generated message vectors. These are public examples, not user mail or keys.
|
||||
Source attribution: MailCraft contributors, MIT OR Apache-2.0.
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: Signed minutes
|
||||
MIME-Version: 1.0
|
||||
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----011A3E8D1DC66D3261BBFB3EB4674ACD"
|
||||
|
||||
This is an S/MIME signed message
|
||||
|
||||
------011A3E8D1DC66D3261BBFB3EB4674ACD
|
||||
Content-Type: text/plain; charset=us-ascii
|
||||
|
||||
Hello Bob,
|
||||
|
||||
The minutes of Tuesday are attached in spirit.
|
||||
|
||||
Alice
|
||||
|
||||
------011A3E8D1DC66D3261BBFB3EB4674ACD
|
||||
Content-Type: application/pkcs7-signature; name="smime.p7s"
|
||||
Content-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="smime.p7s"
|
||||
|
||||
MIIGiQYJKoZIhvcNAQcCoIIGejCCBnYCAQExDTALBglghkgBZQMEAgEwCwYJKoZI
|
||||
hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ
|
||||
KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx
|
||||
MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
|
||||
dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT
|
||||
BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj
|
||||
ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2
|
||||
KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0
|
||||
FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL
|
||||
PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL
|
||||
cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD
|
||||
z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45b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
MAsGCWCGSAFlAwQBKjALBglghkgBZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3
|
||||
DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggq
|
||||
hkiG9w0DAgIBKDANBgkqhkiG9w0BAQEFAASCAQCda8b7o1a3/12TBKbRDLoAW5sm
|
||||
1MBd1j0huWs+wTdj6G3q0cOAPJ2OxZuNfZnUwce+CNAWsKyNyPXIm9k997yW837b
|
||||
e//lUIXPh8b12hUM6te298xvNqCdNNA0Y3/ihNZvb0fbl4nJfu0X+QMo2VqcFI6w
|
||||
cSRBcbMB1/pB47AZF1qOR1+WlvxWTfJ1gHRMvpgtmd5NwNx96jM4i8yMxa4zoXmW
|
||||
ROlOHYcNSDpVkkuhH+m60zxk52vOdTmOdg6CY+rFcMrgY6R2qZu/sfQrWAFiKOYl
|
||||
CSgqvp/pPEty15Kt8inC+DYrIDNdlLg9A1RPpV+H4XxTSgRiEPTFbPKdOjG/
|
||||
|
||||
------011A3E8D1DC66D3261BBFB3EB4674ACD--
|
||||
|
||||
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: No attributes
|
||||
MIME-Version: 1.0
|
||||
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----9D215F381F61DA9DBEC8E6CEAF3E2E88"
|
||||
|
||||
This is an S/MIME signed message
|
||||
|
||||
------9D215F381F61DA9DBEC8E6CEAF3E2E88
|
||||
Content-Type: text/plain; charset=us-ascii
|
||||
|
||||
Hello Bob,
|
||||
|
||||
The minutes of Tuesday are attached in spirit.
|
||||
|
||||
Alice
|
||||
|
||||
------9D215F381F61DA9DBEC8E6CEAF3E2E88
|
||||
Content-Type: application/pkcs7-signature; name="smime.p7s"
|
||||
Content-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="smime.p7s"
|
||||
|
||||
MIIFogYJKoZIhvc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
||||
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: No certificate
|
||||
MIME-Version: 1.0
|
||||
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----C714793EB4AEA5E36741725AF174BFC1"
|
||||
|
||||
This is an S/MIME signed message
|
||||
|
||||
------C714793EB4AEA5E36741725AF174BFC1
|
||||
Content-Type: text/plain; charset=us-ascii
|
||||
|
||||
Hello Bob,
|
||||
|
||||
The minutes of Tuesday are attached in spirit.
|
||||
|
||||
Alice
|
||||
|
||||
------C714793EB4AEA5E36741725AF174BFC1
|
||||
Content-Type: application/pkcs7-signature; name="smime.p7s"
|
||||
Content-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="smime.p7s"
|
||||
|
||||
MIICsgYJKoZIhvcNAQcCoIICozCCAp8CAQExDTALBglghkgBZQMEAgEwCwYJKoZI
|
||||
hvcNAQcBMYICfDCCAngCAQEwbDBVMQ0wCwYDVQQKEwRJRVRGMREwDwYDVQQLEwhM
|
||||
QU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBTIFJTQSBDZXJ0aWZpY2F0aW9u
|
||||
IEF1dGhvcml0eQITN0EFee11f0Kpolw69Phqzpqp1zALBglghkgBZQMEAgGggeQw
|
||||
GAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMjYxMTA5
|
||||
MTIwOTUxWjAvBgkqhkiG9w0BCQQxIgQgpd47XK9W43g0XBneB6ES11oZAarzptGM
|
||||
JcOx+gGBdqcweQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZIAWUD
|
||||
BAEWMAsGCWCGSAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYI
|
||||
KoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcNAQEB
|
||||
BQAEggEAnQNd8e5Phn1idVWgZqoGUqKXZQF2ojmQ9duGv5gAIzTmOpI6l4WaKj4t
|
||||
T2EFa8cwQaIVhFz9ZKshEPSDep9y7IukzVi379CuHRonelJ9rwPQhkX7KLJVfnmh
|
||||
AFc5XH9AdVxHPvpnP59ZankXO6MvzVO9kYKQdflZC8gv5Bl7Sh+FpS/0VGPEXNH+
|
||||
tkRGeX2jo5YY5Xsj2gGTBbiZQ07urn+dcETJxeGI+cLa5tkg3YBeLKthGEMekv9t
|
||||
JakkfMsvpMW5m4TsiOz0A8gBrk5zP5YWEU+h+jKvSlQXyYcGbU04+Ir+y0HSa2ob
|
||||
KUozlJlOmmhYzeok0wAsFf+V6qipCg==
|
||||
|
||||
------C714793EB4AEA5E36741725AF174BFC1--
|
||||
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: Opaque minutes
|
||||
MIME-Version: 1.0
|
||||
Content-Disposition: attachment; filename="smime.p7m"
|
||||
Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"
|
||||
Content-Transfer-Encoding: base64
|
||||
|
||||
MIAGCSqGSIb3DQEHAqCAMIACAQExDTALBglghkgBZQMEAgEwgAYJKoZIhvcNAQcB
|
||||
oIAkgAR1Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PXVzLWFzY2lp
|
||||
DQoNCkhlbGxvIEJvYiwNCg0KVGhlIG1pbnV0ZXMgb2YgVHVlc2RheSBhcmUgYXR0
|
||||
YWNoZWQgaW4gc3Bpcml0Lg0KDQpBbGljZQ0KAAAAAAAAoIID0zCCA88wggK3oAMC
|
||||
AQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJKoZIhvcNAQENBQAwVTENMAsGA1UE
|
||||
ChMESUVURjERMA8GA1UECxMITEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1Q
|
||||
UyBSU0EgQ2VydGlmaWNhdGlvbiBBd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VBfJhwZtTTj4iv7LQdJr
|
||||
ahspSjOUmU6aaFjN6iTTACwV/5XqqKkKAAAAAAAA
|
||||
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: Opaque minutes
|
||||
MIME-Version: 1.0
|
||||
Content-Disposition: attachment; filename="smime.p7m"
|
||||
Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"
|
||||
Content-Transfer-Encoding: base64
|
||||
|
||||
MIIHAwYJKoZIhvcNAQcCoIIG9DCCBvACAQExDTALBglghkgBZQMEAgEwgYQGCSqG
|
||||
SIb3DQEHAaB3BHVDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXMt
|
||||
YXNjaWkNCg0KSGVsbG8gQm9iLA0KDQpUaGUgbWludXRlcyBvZiBUdWVzZGF5IGFy
|
||||
ZSBhdHRhY2hlZCBpbiBzcGlyaXQuDQoNCkFsaWNlDQqgggPTMIIDzzCCAregAwIB
|
||||
AgITN0EFee11f0Kpolw69Phqzpqp1zANBgkqhkiG9w0BAQ0FADBVMQ0wCwYDVQQK
|
||||
EwRJRVRGMREwDwYDVQQLEwhMQU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBT
|
||||
IFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAgFw0xOTExMjAwNjU0MThaGA8y
|
||||
MDUyMDkyNzA2NTQxOFowOzENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMg
|
||||
V0cxFzAVBgNVBAMTDkFsaWNlIExvdmVsYWNlMIIBIjANBgkqhkiG9w0BAQEFAAOC
|
||||
AQ8AMIIBCgKCAQEAtPSJ6Fg4Fj5Nmn9PkrYo0jTkfCv4TfA/pdO/KLpZbJOAEr0s
|
||||
I7AjaO7B1GuMUFJeSTulamNfCwDcDkY63PQWl+DILs7GxVwXurhYdZlaV5hcUqVA
|
||||
ckPvedDBc/3rz4D/esFfs+E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ZIAWUDBAIBoIHk
|
||||
MBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTEw
|
||||
OTEyMDk1MVowLwYJKoZIhvcNAQkEMSIEIKXeO1yvVuN4NFwZ3gehEtdaGQGq86bR
|
||||
jCXDsfoBgXanMHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFl
|
||||
AwQBFjALBglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0G
|
||||
CCqGSIb3DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMA0GCSqGSIb3DQEB
|
||||
AQUABIIBAJ0DXfHuT4Z9YnVVoGaqBlKil2UBdqI5kPXbhr+YACM05jqSOpeFmio+
|
||||
LU9hBWvHMEGiFYRc/WSrIRD0g3qfcuyLpM1Yt+/Qrh0aJ3pSfa8D0IZF+yiyVX55
|
||||
oQBXOVx/QHVcRz76Zz+fWWp5FzujL81TvZGCkHX5WQvIL+QZe0ofhaUv9FRjxFzR
|
||||
/rZERnl9o6OWGOV7I9oBkwW4mUNO7q5/nXBEycXhiPnC2ubZIN2AXiyrYRhDHpL/
|
||||
bSWpJHzLL6TFuZuE7Ijs9APIAa5Ocz+WFhFPofoyr0pUF8mHBm1NOPiK/stB0mtq
|
||||
GylKM5SZTppoWM3qJNMALBX/leqoqQo=
|
||||
|
||||
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: PSS minutes
|
||||
MIME-Version: 1.0
|
||||
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-384"; boundary="----E33A7E587DACB5F6484402726C200129"
|
||||
|
||||
This is an S/MIME signed message
|
||||
|
||||
------E33A7E587DACB5F6484402726C200129
|
||||
Content-Type: text/plain; charset=us-ascii
|
||||
|
||||
Hello Bob,
|
||||
|
||||
The minutes of Tuesday are attached in spirit.
|
||||
|
||||
Alice
|
||||
|
||||
------E33A7E587DACB5F6484402726C200129
|
||||
Content-Type: application/pkcs7-signature; name="smime.p7s"
|
||||
Content-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="smime.p7s"
|
||||
|
||||
MIIGzQYJKoZIhvcNAQcCoIIGvjCCBroCAQExDTALBglghkgBZQMEAgIwCwYJKoZI
|
||||
hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ
|
||||
KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx
|
||||
MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
|
||||
dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT
|
||||
BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj
|
||||
ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2
|
||||
KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0
|
||||
FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL
|
||||
PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL
|
||||
cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD
|
||||
z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC
|
||||
SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD
|
||||
AgEwATAeBgNVHREEFz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AgICAIAwDQYIKoZIhvcNAwIC
|
||||
AUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwQQYJKoZIhvcNAQEKMDSgDzANBglg
|
||||
hkgBZQMEAgIFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgIFAKIDAgEwBIIB
|
||||
AFYJfuEecetLuIAZBdhyppBpqzeF9JN9RuGyi7qmrUFFU8xSyNh8/NFFE7UJ91Eo
|
||||
+/zbQkuz0lfak8NSA1dw+qr2LnmnvpjD7LelEDJawTWJwzFnAVQaW7PaduLBwxZU
|
||||
WmJRV6h4UZ1YEh8XEjpCqeUHTfqSiEyCaw0XOct6UoPOZQ64/7ytBOwrMUdMZNO5
|
||||
upqKR/NZSTwG91Izy78ORpW97ckbFcsklPOedHypUuecJTK5gzMEh2w5TGYZGRNs
|
||||
x2kz6OqzzdhMUdT9DG84PGmZDTrp+Gw8lBWCUJs/1AMYm8ZKx/eSJwasJpeGaFUS
|
||||
gPrYtiiA1mEl+vujBbhlwSo=
|
||||
|
||||
------E33A7E587DACB5F6484402726C200129--
|
||||
|
||||
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
To: bob@smime.example
|
||||
From: alice@smime.example
|
||||
Subject: Old minutes
|
||||
MIME-Version: 1.0
|
||||
Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha1"; boundary="----C0EDEE0A5F012496F372EFC5533B6179"
|
||||
|
||||
This is an S/MIME signed message
|
||||
|
||||
------C0EDEE0A5F012496F372EFC5533B6179
|
||||
Content-Type: text/plain; charset=us-ascii
|
||||
|
||||
Hello Bob,
|
||||
|
||||
The minutes of Tuesday are attached in spirit.
|
||||
|
||||
Alice
|
||||
|
||||
------C0EDEE0A5F012496F372EFC5533B6179
|
||||
Content-Type: application/pkcs7-signature; name="smime.p7s"
|
||||
Content-Transfer-Encoding: base64
|
||||
Content-Disposition: attachment; filename="smime.p7s"
|
||||
|
||||
MIIGdQYJKoZIhvcNAQcCoIIGZjCCBmICAQExCT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+lxO4kYjiHfb34egKPjgBiX6kUCpoxEZeV6joAtFRgBnkbUL4H
|
||||
B2R+aiYiJt5jO1kB5beMf/gSFoIaycOf3EuTifNpPm2LsNGuEFZ72CRl2aHs2njc
|
||||
O6XSZr8kODvUsPKJlXeqtThamr7Iy3NRvxQjDPFiW6i3TW9eo1/1LKSpDjjP8qet
|
||||
p+iNds1neRoqaaDEkLifdykzuBLA0Sig8Q==
|
||||
|
||||
------C0EDEE0A5F012496F372EFC5533B6179--
|
||||
|
||||
Reference in new issue
Block a user