PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M9.1–M9.3: new sign crate: DER, X.509, CMS SignedData, PKCS #12 (PBES2 and legacy, MAC) on RustCrypto with aws-lc-rs for RSA private keys; PAdES B-B signing (new or existing field, visible or invisible, DocMDP certification) with an incremental placeholder save; validation (digest, signature, chain against a trust store, changes after signing classified under DocMDP); checked against pdfsig and OpenSSL
Brandon Thomase06a98adaa22
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.mdindex dc364e0e6..9b1a58c53 100644--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@ -4,7 +4,7 @@Every asset PrintCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).-## In this repository (221)+## In this repository (222)| Asset | Title | Author | Licence | Source | Used for ||---|---|---|---|---|---|@@ -229,6 +229,7 @@ Every asset PrintCraft includes, bundles or uses to build its published material| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PrintCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/forms.rs, commands.rs) || `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs || `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |+| `crates/sign/tests/data/openssl-signed.pdf` | One-page PDF signed with OpenSSL CMS (adbe.pkcs7.detached) by the RSA test key | PrintCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl cms -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/pdf.rs): a signature PrintCraft did not make |## Compiled in through dependencies (6)diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.tomlindex 341097f84..eaf613c59 100644--- a/ATTRIBUTION.toml+++ b/ATTRIBUTION.toml@@ -2772,3 +2772,14 @@ licence_file = "assets/icons/LICENSE-lucide.txt"kind = "icon"usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"sha256 = "69a76b4cd352dbdea61c63ed1e8d1e02083ee1773b3ced2a1c8cdf8c90fb2055"++[[asset]]+path = "crates/sign/tests/data/openssl-signed.pdf"+title = "One-page PDF signed with OpenSSL CMS (adbe.pkcs7.detached) by the RSA test key"+author = "PrintCraft contributors"+source = "Contributor-original: hand-written PDF objects; signature made with `openssl cms -sign` over its byte ranges (see crates/sign/tests/data/README.md)"+licence = "MIT OR Apache-2.0"+licence_file = "LICENSE-MIT"+kind = "document"+usage = "Signature validation tests (crates/sign/tests/pdf.rs): a signature PrintCraft did not make"+sha256 = "8b91c3b4e39c4a31717a0dd0685bd7d0468671df32aee5b9818d44dc72c2bc3c"diff --git a/Cargo.lock b/Cargo.lockindex b7749a4d8..444edeec2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -436,12 +436,47 @@ version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"+[[package]]+name = "aws-lc-rs"+version = "1.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"+dependencies = [+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",+ "pkg-config",+]++[[package]]+name = "base16ct"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"+[[package]]name = "base64"version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]name = "bit-set"version = "0.8.0"@@ -729,6 +764,21 @@ dependencies = ["error-code",]+[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]++[[package]]+name = "cmov"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"+[[package]]name = "codespan-reporting"version = "0.13.1"@@ -881,13 +931,52 @@ version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"+[[package]]+name = "crypto-bigint"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"+dependencies = [+ "cpubits",+ "ctutils",+ "getrandom 0.4.3",+ "hybrid-array",+ "num-traits",+ "rand_core 0.10.1",+ "serdect",+ "subtle",+ "zeroize",+]+[[package]]name = "crypto-common"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"dependencies = [+ "getrandom 0.4.3","hybrid-array",+ "rand_core 0.10.1",+]++[[package]]+name = "crypto-primes"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"+dependencies = [+ "crypto-bigint",+ "rand_core 0.10.1",+]++[[package]]+name = "ctutils"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"+dependencies = [+ "cmov",+ "subtle",][[package]]@@ -902,6 +991,26 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+[[package]]+name = "der"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a"+dependencies = [+ "const-oid",+ "pem-rfc7468",+ "zeroize",+]++[[package]]+name = "des"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a"+dependencies = [+ "cipher",+]+[[package]]name = "digest"version = "0.11.3"@@ -911,6 +1020,7 @@ dependencies = ["block-buffer","const-oid","crypto-common",+ "ctutils",][[package]]@@ -972,6 +1082,12 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]name = "ecb"version = "0.2.1"@@ -981,6 +1097,21 @@ dependencies = ["cipher",]+[[package]]+name = "ecdsa"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0"+dependencies = [+ "der",+ "digest",+ "elliptic-curve",+ "rfc6979",+ "signature",+ "spki",+ "zeroize",+]+[[package]]name = "ecolor"version = "0.36.2"@@ -1148,6 +1279,26 @@ version = "1.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"+[[package]]+name = "elliptic-curve"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65"+dependencies = [+ "base16ct",+ "crypto-bigint",+ "crypto-common",+ "digest",+ "ff",+ "group",+ "hybrid-array",+ "pkcs8",+ "rand_core 0.10.1",+ "sec1",+ "subtle",+ "zeroize",+]+[[package]]name = "emath"version = "0.36.2"@@ -1340,6 +1491,22 @@ version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"+[[package]]+name = "ff"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f"+dependencies = [+ "rand_core 0.10.1",+ "subtle",+]++[[package]]+name = "fiat-crypto"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"+[[package]]name = "find-msvc-tools"version = "0.1.14"@@ -1430,6 +1597,12 @@ dependencies = ["percent-encoding",]+[[package]]+name = "fs_extra"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"+[[package]]name = "futures-core"version = "0.3.34"@@ -1667,6 +1840,17 @@ dependencies = ["windows",]+[[package]]+name = "group"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4"+dependencies = [+ "ff",+ "rand_core 0.10.1",+ "subtle",+]+[[package]]name = "guillotiere"version = "0.7.0"@@ -1816,13 +2000,24 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hmac"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"+dependencies = [+ "digest",+]+[[package]]name = "hybrid-array"version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"dependencies = [+ "subtle","typenum",+ "zeroize",][[package]]@@ -2780,6 +2975,33 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "p256"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "primefield",+ "primeorder",+ "sha2",+]++[[package]]+name = "p384"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "fiat-crypto",+ "primefield",+ "primeorder",+ "sha2",+]+[[package]]name = "parking"version = "2.2.1"@@ -2809,6 +3031,25 @@ dependencies = ["windows-link",]+[[package]]+name = "pbkdf2"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"+dependencies = [+ "digest",+ "hmac",+]++[[package]]+name = "pem-rfc7468"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"+dependencies = [+ "base64ct",+]+[[package]]name = "peniko"version = "0.6.1"@@ -2924,6 +3165,26 @@ dependencies = ["futures-io",]+[[package]]+name = "pkcs1"+version = "0.8.0-rc.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e"+dependencies = [+ "der",+ "spki",+]++[[package]]+name = "pkcs8"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"+dependencies = [+ "der",+ "spki",+]+[[package]]name = "pkg-config"version = "0.3.34"@@ -3036,6 +3297,33 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"+[[package]]+name = "primefield"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4"+dependencies = [+ "crypto-bigint",+ "crypto-common",+ "ff",+ "rand_core 0.10.1",+ "subtle",+ "zeroize",+]++[[package]]+name = "primeorder"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06"+dependencies = [+ "elliptic-curve",+ "once_cell",+ "primefield",+ "serdect",+ "wnaf",+]+[[package]]name = "printcraft"version = "0.1.0"@@ -3239,6 +3527,29 @@ dependencies = ["thiserror 2.0.21",]+[[package]]+name = "printcraft-sign"+version = "0.1.0"+dependencies = [+ "aes",+ "aws-lc-rs",+ "cbc",+ "des",+ "getrandom 0.4.3",+ "hmac",+ "p256",+ "p384",+ "pbkdf2",+ "printcraft-annot",+ "printcraft-cos",+ "printcraft-fonts",+ "rc2",+ "rsa",+ "sha1",+ "sha2",+ "thiserror 2.0.21",+]+[[package]]name = "printcraft-ui-egui"version = "0.1.0"@@ -3486,6 +3797,15 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "rc2"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ceda21af1ae61033b63175653a1af86cae399d79cd03ca80ba347eb3a6c4a7fe"+dependencies = [+ "cipher",+]+[[package]]name = "read-fonts"version = "0.39.2"@@ -3560,6 +3880,16 @@ dependencies = ["usvg",]+[[package]]+name = "rfc6979"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"+dependencies = [+ "crypto-bigint",+ "hmac",+]+[[package]]name = "rfd"version = "0.17.2"@@ -3616,6 +3946,23 @@ version = "0.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"+[[package]]+name = "rsa"+version = "0.10.0-rc.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf"+dependencies = [+ "const-oid",+ "crypto-bigint",+ "crypto-primes",+ "digest",+ "pkcs1",+ "pkcs8",+ "rand_core 0.10.1",+ "signature",+ "zeroize",+]+[[package]]name = "rustc-hash"version = "1.1.0"@@ -3702,6 +4049,20 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "sec1"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"+dependencies = [+ "base16ct",+ "ctutils",+ "der",+ "hybrid-array",+ "subtle",+ "zeroize",+]+[[package]]name = "self_cell"version = "1.3.0"@@ -3777,6 +4138,27 @@ dependencies = ["serde_core",]+[[package]]+name = "serdect"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"+dependencies = [+ "base16ct",+ "serde",+]++[[package]]+name = "sha1"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "sha2"version = "0.11.0"@@ -3804,6 +4186,16 @@ dependencies = ["libc",]+[[package]]+name = "signature"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"+dependencies = [+ "digest",+ "rand_core 0.10.1",+]+[[package]]name = "simd-adler32"version = "0.3.10"@@ -3966,6 +4358,16 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "spki"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f"+dependencies = [+ "base64ct",+ "der",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -3998,6 +4400,12 @@ dependencies = ["unicode-properties",]+[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]name = "svgtypes"version = "0.15.3"@@ -5265,6 +5673,18 @@ version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "wnaf"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa"+dependencies = [+ "ff",+ "group",+ "hybrid-array",+ "primefield",+]+[[package]]name = "writeable"version = "0.6.4"@@ -5523,6 +5943,12 @@ dependencies = ["synstructure",]+[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"+[[package]]name = "zerotrie"version = "0.2.5"diff --git a/Cargo.toml b/Cargo.tomlindex c32e89539..6255bbdc8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -25,6 +25,7 @@ printcraft-content = { path = "crates/content", version = "0.1.0" }printcraft-redact = { path = "crates/redact", version = "0.1.0" }printcraft-print = { path = "crates/print", version = "0.1.0" }printcraft-xfdf = { path = "crates/xfdf", version = "0.1.0" }+printcraft-sign = { path = "crates/sign", version = "0.1.0" }printcraft-edit = { path = "crates/edit", version = "0.1.0" }printcraft-create = { path = "crates/create", version = "0.1.0" }printcraft-forms = { path = "crates/forms", version = "0.1.0" }diff --git a/crates/sign/Cargo.toml b/crates/sign/Cargo.tomlnew file mode 100644index 000000000..eabfc6bfd--- /dev/null+++ b/crates/sign/Cargo.toml@@ -0,0 +1,37 @@+[package]+name = "printcraft-sign"+description = "Digital signatures (ISO 32000-2 §12.8, PAdES): X.509, CMS, PKCS #12, signing and validation"+version.workspace = true+edition.workspace = true+license.workspace = true+rust-version.workspace = true+repository.workspace = true++[lints]+workspace = true++[dependencies]+printcraft-cos = { workspace = true }+printcraft-annot = { workspace = true }+printcraft-fonts = { workspace = true }+thiserror.workspace = true+sha1 = "0.11"+sha2 = "0.11"+p256 = { version = "0.14", default-features = false, features = ["ecdsa", "std"] }+p384 = { version = "0.14", default-features = false, features = ["ecdsa", "std"] }+# Verification only on native targets (RSA private-key operations use aws-lc-rs, ADR-0009).+rsa = { version = "=0.10.0-rc.18", default-features = false, features = ["std"] }+pbkdf2 = { version = "0.13", default-features = false, features = ["hmac"] }+hmac = "0.13"+aes = "0.9"+cbc = { version = "0.2", features = ["alloc", "block-padding"] }+des = "0.9"+rc2 = "0.9"++[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+aws-lc-rs = { version = "1.18", default-features = false, features = ["aws-lc-sys", "prebuilt-nasm"] }+getrandom = "0.4"++[target.'cfg(target_arch = "wasm32")'.dependencies]+# crypto-bigint asks for randomness; in the browser it comes from Web Crypto.+getrandom = { version = "0.4", features = ["wasm_js"] }diff --git a/crates/sign/README.md b/crates/sign/README.mdnew file mode 100644index 000000000..e21157772--- /dev/null+++ b/crates/sign/README.md@@ -0,0 +1,36 @@+# printcraft-sign++Layer L4: digital signatures (execution plan M9; ISO 32000-2 §12.8; PAdES, ETSI EN 319 142).++```rust+let id = pkcs12::open(&std::fs::read("me.p12")?, "password")?; // a digital ID+let signed = sign(&doc, &id, &SignOptions { page: 0, rect: Some(r), date, ..Default::default() })?;+for s in signatures(&doc, &bytes, &trust) { // list + validate+ println!("{}: {} — {:?}", s.field, s.summary(), s.details);+}+```++- **Formats, on RustCrypto primitives:** a small DER reader and writer (`der`), X.509+ certificates (`x509`), CMS SignedData (`cms`), and PKCS #12 digital ID files (`pkcs12`):+ PBES2 (PBKDF2 + AES/3DES), the legacy SHA-1 3DES/RC2 schemes, and MAC checks. Writing uses+ OpenSSL 3's defaults (AES-256-CBC, HMAC-SHA-256).+- **Keys:** RSA, ECDSA P-256 and P-384. Verification uses RustCrypto everywhere. RSA+ private-key operations (signing, key generation) use `aws-lc-rs` on native targets and are+ refused in the browser (ADR-0009: the `rsa` crate's Marvin advisory, RUSTSEC-2023-0071, has+ no fix, so `rsa` is only used to verify). ECDSA signs with deterministic nonces (RFC 6979).+- **Signing:** PAdES B-B (`ETSI.CAdES.detached`, signing-certificate-v2, SHA-256/384, no SHA-1).+ An existing unsigned field or a new one (visible with Acrobat's name-and-details appearance,+ or invisible); certification with DocMDP P=1/2/3. The document is written incrementally+ with a zero-filled `/Contents` and fixed-width `/ByteRange`, which are then patched in+ place. Encrypted documents are refused for now.+- **Validation:** `/ByteRange` and the CMS are read from the file's own bytes; the digest,+ the signature value and the signer's chain (against a `TrustStore`) are checked. Later+ revisions are diffed against the signed one, and the changes are classified (signing, form+ fill, comments, metadata, page content, document structure) under the DocMDP permissions.+ The verdict follows Acrobat: valid, unknown (intact but the identity isn't trusted) or invalid.++Not yet: RFC 3161 timestamps, LTV (DSS/VRI, OCSP, CRL), FieldMDP locks, certificate security,+OS key stores and PKCS #11 tokens.++Oracles: poppler's `pdfsig` reports our signatures valid; OpenSSL reads our `.p12` files and+verifies our CMS; `tests/data/openssl-signed.pdf` is a signature OpenSSL made, which we validate.diff --git a/crates/sign/src/cms.rs b/crates/sign/src/cms.rsnew file mode 100644index 000000000..4e08f56e1--- /dev/null+++ b/crates/sign/src/cms.rs@@ -0,0 +1,230 @@+//! CMS SignedData (RFC 5652) as PDF signatures use it: detached (`adbe.pkcs7.detached`,+//! `ETSI.CAdES.detached`) or with the digest encapsulated (`adbe.pkcs7.sha1`).++use crate::SignError;+use crate::der::{self, Time, Tlv, tag};+use crate::keys::{DigestAlg, PrivateKey, Scheme, signature_algorithm};+use crate::x509::Certificate;++pub const SIGNED_DATA: &str = "1.2.840.113549.1.7.2";+pub const DATA: &str = "1.2.840.113549.1.7.1";+const CONTENT_TYPE: &str = "1.2.840.113549.1.9.3";+const MESSAGE_DIGEST: &str = "1.2.840.113549.1.9.4";+const SIGNING_TIME: &str = "1.2.840.113549.1.9.5";+const SIGNING_CERT_V2: &str = "1.2.840.113549.1.9.16.2.47";+const SIGNING_CERT: &str = "1.2.840.113549.1.9.16.2.12";+const TIMESTAMP_TOKEN: &str = "1.2.840.113549.1.9.16.2.14";++/// How a signer names its certificate.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum SignerId {+ IssuerSerial { issuer: Vec<u8>, serial: Vec<u8> },+ KeyId(Vec<u8>),+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct SignerInfo {+ pub sid: SignerId,+ pub digest: DigestAlg,+ /// The signed attributes as the SET that was signed (`None`: the signature covers the+ /// content itself).+ pub signed_attrs: Option<Vec<u8>>,+ pub message_digest: Option<Vec<u8>>,+ pub content_type: Option<String>,+ pub signing_time: Option<Time>,+ /// ESS signing-certificate(-v2) present (CAdES).+ pub signing_certificate: bool,+ pub scheme: Scheme,+ /// The digest named by the signature algorithm, when it names one.+ pub scheme_digest: Option<DigestAlg>,+ pub signature: Vec<u8>,+ /// An RFC 3161 timestamp token is attached (unsigned attribute).+ pub timestamp: bool,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct SignedData {+ pub certificates: Vec<Certificate>,+ pub signer: SignerInfo,+ /// Encapsulated content (`adbe.pkcs7.sha1` carries the document digest here).+ pub content: Option<Vec<u8>>,+}++fn bad(what: &str) -> SignError {+ SignError::Malformed(format!("CMS: {what}"))+}++impl SignedData {+ /// Parse a `ContentInfo` holding SignedData. Bytes after it (a PDF placeholder's zero+ /// padding) are ignored.+ pub fn parse(bytes: &[u8]) -> Result<SignedData, SignError> {+ let (ci, _) = Tlv::parse(bytes)?;+ let ci = ci.expect(tag::SEQUENCE, "ContentInfo")?.children()?;+ let [ct, content] = ci.as_slice() else { return Err(bad("ContentInfo")) };+ if ct.oid()? != SIGNED_DATA {+ return Err(bad("not SignedData"));+ }+ let sd = content.expect(tag::ctx(0), "content")?.inner()?.children()?;+ let mut it = sd.into_iter();+ let _version = it.next();+ let _digest_algs = it.next();+ let encap = it.next().ok_or_else(|| bad("encapContentInfo"))?.children()?;+ let content = match encap.get(1) {+ Some(c) if c.tag == tag::ctx(0) => {+ let inner = c.inner()?;+ // Constructed OCTET STRINGs (BER) are not expected in DER-signed PDFs.+ Some(inner.expect(tag::OCTET_STRING, "eContent")?.value.to_vec())+ }+ _ => None,+ };+ let mut certificates = Vec::new();+ let mut signer_infos = None;+ for t in it {+ match t.tag {+ t2 if t2 == tag::ctx(0) => {+ for c in t.children()? {+ // Other certificate formats (attribute certificates) are skipped.+ if c.tag == tag::SEQUENCE+ && let Ok(cert) = Certificate::parse(c.raw)+ {+ certificates.push(cert);+ }+ }+ }+ tag::SET => signer_infos = Some(t),+ _ => {}+ }+ }+ let infos = signer_infos.ok_or_else(|| bad("no signerInfos"))?.children()?;+ let si = infos.first().ok_or_else(|| bad("no signer"))?;+ Ok(SignedData { certificates, signer: parse_signer(si)?, content })+ }++ /// The signer's certificate among those carried.+ pub fn signer_certificate(&self) -> Option<&Certificate> {+ self.certificates.iter().find(|c| match &self.signer.sid {+ SignerId::IssuerSerial { issuer, serial } => &c.issuer.raw == issuer && strip(&c.serial) == strip(serial),+ SignerId::KeyId(k) => c.subject_key_id.as_ref() == Some(k),+ })+ }++ /// Check the signature value with `cert`'s key. `content_digest` is the digest of the+ /// signed content (the document byte ranges) when there are no signed attributes.+ pub fn verify_signature(&self, cert: &Certificate, content_digest: &[u8]) -> bool {+ let s = &self.signer;+ let alg = s.scheme_digest.unwrap_or(s.digest);+ let digest = match &s.signed_attrs {+ Some(attrs) => alg.digest(&[attrs]),+ None => content_digest.to_vec(),+ };+ cert.public_key.verify(s.scheme, alg, &digest, &s.signature).unwrap_or(false)+ }+}++fn strip(b: &[u8]) -> &[u8] {+ match b {+ [0, rest @ ..] if !rest.is_empty() => rest,+ _ => b,+ }+}++fn parse_signer(si: &Tlv<'_>) -> Result<SignerInfo, SignError> {+ let f = si.children()?;+ let mut it = f.into_iter();+ let _version = it.next();+ let sid = it.next().ok_or_else(|| bad("sid"))?;+ let sid = if sid.tag == tag::SEQUENCE {+ let p = sid.children()?;+ let [issuer, serial] = p.as_slice() else { return Err(bad("issuerAndSerialNumber")) };+ SignerId::IssuerSerial { issuer: issuer.raw.to_vec(), serial: serial.value.to_vec() }+ } else {+ SignerId::KeyId(sid.value.to_vec())+ };+ let digest_alg = it.next().ok_or_else(|| bad("digestAlgorithm"))?.children()?;+ let d_oid = digest_alg.first().ok_or_else(|| bad("digestAlgorithm"))?.oid()?;+ let digest = DigestAlg::from_oid(&d_oid).ok_or_else(|| SignError::Unsupported(format!("digest {d_oid}")))?;+ let mut next = it.next().ok_or_else(|| bad("signatureAlgorithm"))?;+ let mut signed_attrs = None;+ let (mut message_digest, mut content_type, mut signing_time, mut signing_certificate) = (None, None, None, false);+ if next.tag == tag::ctx(0) {+ // Signed over the DER SET OF, i.e. the same contents with the universal SET tag.+ let mut set = next.raw.to_vec();+ set[0] = tag::SET;+ for a in next.children()? {+ let p = a.children()?;+ let Some(o) = p.first().and_then(|o| o.oid().ok()) else { continue };+ let value = p.get(1).and_then(|v| v.children().ok()).and_then(|v| v.into_iter().next());+ match (o.as_str(), value) {+ (MESSAGE_DIGEST, Some(v)) => message_digest = Some(v.value.to_vec()),+ (CONTENT_TYPE, Some(v)) => content_type = v.oid().ok(),+ (SIGNING_TIME, Some(v)) => signing_time = v.time().ok(),+ (SIGNING_CERT_V2 | SIGNING_CERT, _) => signing_certificate = true,+ _ => {}+ }+ }+ signed_attrs = Some(set);+ next = it.next().ok_or_else(|| bad("signatureAlgorithm"))?;+ }+ let (scheme, scheme_digest) = signature_algorithm(&next)?;+ let signature = it.next().ok_or_else(|| bad("signature"))?.expect(tag::OCTET_STRING, "signature")?.value.to_vec();+ let mut timestamp = false;+ for t in it {+ if t.tag == tag::ctx(1) {+ for a in t.children()? {+ if a.children()?.first().and_then(|o| o.oid().ok()).as_deref() == Some(TIMESTAMP_TOKEN) {+ timestamp = true;+ }+ }+ }+ }+ Ok(SignerInfo {+ sid,+ digest,+ signed_attrs,+ message_digest,+ content_type,+ signing_time,+ signing_certificate,+ scheme,+ scheme_digest,+ signature,+ timestamp,+ })+}++fn attribute(o: &str, value: &[u8]) -> Vec<u8> {+ der::seq(&[&der::oid(o), &der::set_of(&[value])])+}++/// A detached CAdES signature (PAdES B-B): signed attributes content-type, message-digest and+/// signing-certificate-v2 (no signing-time: PAdES takes the time from the signature+/// dictionary's `/M`). `chain` holds further certificates to embed (issuers).+pub fn sign_detached(+ key: &PrivateKey,+ cert: &Certificate,+ chain: &[Certificate],+ alg: DigestAlg,+ content_digest: &[u8],+) -> Result<Vec<u8>, SignError> {+ let cert_hash = DigestAlg::Sha256.digest(&[&cert.raw]);+ let general_names = der::seq(&[&der::explicit(4, &cert.issuer.raw)]);+ let ess = der::seq(&[&der::seq(&[&der::seq(&[&der::octets(&cert_hash), &der::seq(&[&general_names, &der::uint(&cert.serial)])])])]);+ let attrs = [attribute(CONTENT_TYPE, &der::oid(DATA)), attribute(MESSAGE_DIGEST, &der::octets(content_digest)), attribute(SIGNING_CERT_V2, &ess)];+ let refs: Vec<&[u8]> = attrs.iter().map(Vec::as_slice).collect();+ let set = der::set_of(&refs);+ let signature = key.sign(alg, &set)?;+ let mut signed_attrs = set.clone();+ signed_attrs[0] = tag::ctx(0);+ let sid = der::seq(&[&cert.issuer.raw, &der::uint(&cert.serial)]);+ let signer = der::seq(&[&der::int(1), &sid, &alg.algorithm(), &signed_attrs, &key.signature_algorithm(alg), &der::octets(&signature)]);+ let mut certs: Vec<&[u8]> = vec![&cert.raw];+ certs.extend(chain.iter().filter(|c| c.raw != cert.raw).map(|c| c.raw.as_slice()));+ let signed_data = der::seq(&[+ &der::int(1),+ &der::set_of(&[&alg.algorithm()]),+ &der::seq(&[&der::oid(DATA)]),+ &der::tlv(tag::ctx(0), &certs.concat()),+ &der::set_of(&[&signer]),+ ]);+ Ok(der::seq(&[&der::oid(SIGNED_DATA), &der::explicit(0, &signed_data)]))+}diff --git a/crates/sign/src/der.rs b/crates/sign/src/der.rsnew file mode 100644index 000000000..611494b5f--- /dev/null+++ b/crates/sign/src/der.rs@@ -0,0 +1,423 @@+//! A small DER reader and writer (ITU-T X.690): just what X.509, CMS and PKCS#12 need.+//!+//! [`Tlv`] borrows from the input and keeps its full encoding (`raw`), so signed structures can+//! be verified over the exact bytes that were signed.++use crate::SignError;++/// Universal tags (single-byte identifiers).+pub mod tag {+ pub const BOOLEAN: u8 = 0x01;+ pub const INTEGER: u8 = 0x02;+ pub const BIT_STRING: u8 = 0x03;+ pub const OCTET_STRING: u8 = 0x04;+ pub const NULL: u8 = 0x05;+ pub const OID: u8 = 0x06;+ pub const UTF8_STRING: u8 = 0x0C;+ pub const PRINTABLE_STRING: u8 = 0x13;+ pub const T61_STRING: u8 = 0x14;+ pub const IA5_STRING: u8 = 0x16;+ pub const UTC_TIME: u8 = 0x17;+ pub const GENERALIZED_TIME: u8 = 0x18;+ pub const BMP_STRING: u8 = 0x1E;+ pub const SEQUENCE: u8 = 0x30;+ pub const SET: u8 = 0x31;+ /// `[n]` context-specific, constructed (EXPLICIT, or IMPLICIT over a constructed type).+ pub const fn ctx(n: u8) -> u8 {+ 0xA0 | n+ }+ /// `[n]` context-specific, primitive (IMPLICIT over a primitive type).+ pub const fn ctx_prim(n: u8) -> u8 {+ 0x80 | n+ }+}++fn bad(what: &str) -> SignError {+ SignError::Malformed(what.to_string())+}++/// One DER element.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Tlv<'a> {+ pub tag: u8,+ /// The contents octets.+ pub value: &'a [u8],+ /// The whole encoding (identifier, length and contents).+ pub raw: &'a [u8],+}++impl<'a> Tlv<'a> {+ /// Parse one element at the start of `input`; returns it and the rest.+ pub fn parse(input: &'a [u8]) -> Result<(Tlv<'a>, &'a [u8]), SignError> {+ let (&tag, rest) = input.split_first().ok_or_else(|| bad("truncated DER"))?;+ if tag & 0x1F == 0x1F {+ return Err(bad("multi-byte DER tags are not supported"));+ }+ let (&first, rest) = rest.split_first().ok_or_else(|| bad("truncated DER length"))?;+ let (len, rest) = if first < 0x80 {+ (first as usize, rest)+ } else {+ let n = (first & 0x7F) as usize;+ if n == 0 || n > 4 || rest.len() < n {+ return Err(bad("unsupported DER length"));+ }+ let len = rest[..n].iter().fold(0usize, |acc, b| (acc << 8) | *b as usize);+ (len, &rest[n..])+ };+ if rest.len() < len {+ return Err(bad("DER element runs past the end"));+ }+ let header = input.len() - rest.len();+ Ok((Tlv { tag, value: &rest[..len], raw: &input[..header + len] }, &rest[len..]))+ }++ /// Parse `input` as exactly one element.+ pub fn parse_all(input: &'a [u8]) -> Result<Tlv<'a>, SignError> {+ let (t, rest) = Tlv::parse(input)?;+ if !rest.is_empty() {+ return Err(bad("trailing bytes after DER element"));+ }+ Ok(t)+ }++ /// The children of a constructed element.+ pub fn children(&self) -> Result<Vec<Tlv<'a>>, SignError> {+ let mut out = Vec::new();+ let mut rest = self.value;+ while !rest.is_empty() {+ let (t, r) = Tlv::parse(rest)?;+ out.push(t);+ rest = r;+ }+ Ok(out)+ }++ /// Check the tag, for a clear error.+ pub fn expect(self, tag: u8, what: &str) -> Result<Tlv<'a>, SignError> {+ if self.tag == tag { Ok(self) } else { Err(bad(&format!("{what}: expected tag {tag:#04x}, found {:#04x}", self.tag))) }+ }++ /// The element inside an EXPLICIT tag.+ pub fn inner(&self) -> Result<Tlv<'a>, SignError> {+ Tlv::parse_all(self.value)+ }++ /// An OID in dotted form.+ pub fn oid(&self) -> Result<String, SignError> {+ if self.tag != tag::OID {+ return Err(bad("expected an OID"));+ }+ oid_to_string(self.value)+ }++ /// A non-negative INTEGER that fits in a u64.+ pub fn u64(&self) -> Result<u64, SignError> {+ if self.tag != tag::INTEGER || self.value.is_empty() || self.value.len() > 9 || self.value[0] & 0x80 != 0 {+ return Err(bad("expected a small non-negative INTEGER"));+ }+ Ok(self.value.iter().fold(0u64, |acc, b| (acc << 8) | *b as u64))+ }++ /// The magnitude of an INTEGER (leading zero dropped).+ pub fn uint_bytes(&self) -> &'a [u8] {+ match self.value {+ [0, rest @ ..] if !rest.is_empty() => rest,+ v => v,+ }+ }++ /// A BIT STRING's bytes (no unused bits allowed).+ pub fn bits(&self) -> Result<&'a [u8], SignError> {+ match self.value {+ [0, rest @ ..] if self.tag == tag::BIT_STRING => Ok(rest),+ _ => Err(bad("expected a whole-byte BIT STRING")),+ }+ }++ /// A string type as text (UTF-8, Printable, IA5, T61 as Latin-1, BMP).+ pub fn text(&self) -> Option<String> {+ match self.tag {+ tag::UTF8_STRING | tag::PRINTABLE_STRING | tag::IA5_STRING => Some(String::from_utf8_lossy(self.value).into_owned()),+ tag::T61_STRING => Some(self.value.iter().map(|b| *b as char).collect()),+ tag::BMP_STRING => {+ let units: Vec<u16> = self.value.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();+ Some(String::from_utf16_lossy(&units))+ }+ _ => None,+ }+ }++ /// UTCTime / GeneralizedTime as (year, month, day, hour, minute, second) in UTC.+ pub fn time(&self) -> Result<Time, SignError> {+ let s = std::str::from_utf8(self.value).map_err(|_| bad("time"))?;+ let s = s.strip_suffix('Z').ok_or_else(|| bad("times must be in UTC (Z)"))?;+ let num = |r: std::ops::Range<usize>| s.get(r).and_then(|x| x.parse::<u32>().ok()).ok_or_else(|| bad("time"));+ let (year, rest) = match self.tag {+ tag::UTC_TIME => {+ let y = num(0..2)?;+ (if y >= 50 { 1900 + y } else { 2000 + y }, 2)+ }+ tag::GENERALIZED_TIME => (num(0..4)?, 4),+ _ => return Err(bad("expected a time")),+ };+ let t = Time {+ year,+ month: num(rest..rest + 2)?,+ day: num(rest + 2..rest + 4)?,+ hour: num(rest + 4..rest + 6)?,+ minute: num(rest + 6..rest + 8)?,+ second: if s.len() >= rest + 10 { num(rest + 8..rest + 10)? } else { 0 },+ };+ Ok(t)+ }+}++/// A UTC time.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub struct Time {+ pub year: u32,+ pub month: u32,+ pub day: u32,+ pub hour: u32,+ pub minute: u32,+ pub second: u32,+}++impl Time {+ /// From a PDF date (`D:YYYYMMDDHHmmSS±HH'mm'`), converted to UTC.+ pub fn from_pdf(s: &str) -> Option<Time> {+ let s = s.strip_prefix("D:").unwrap_or(s);+ let d = |r: std::ops::Range<usize>, default: u32| s.get(r).map_or(Some(default), |x| x.parse::<u32>().ok());+ let mut t =+ Time { year: d(0..4, 0)?, month: d(4..6, 1)?, day: d(6..8, 1)?, hour: d(8..10, 0)?, minute: d(10..12, 0)?, second: d(12..14, 0)? };+ if t.year == 0 {+ return None;+ }+ let tz = s.get(14..).unwrap_or("");+ let sign = match tz.chars().next() {+ Some('+') => -1i64,+ Some('-') => 1,+ _ => 0,+ };+ if sign != 0 {+ let h = tz.get(1..3).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);+ let m = tz.get(4..6).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);+ t = t.add_seconds(sign * (h * 3600 + m * 60));+ }+ Some(t)+ }++ /// As a PDF date in UTC (`D:YYYYMMDDHHmmSSZ`).+ pub fn to_pdf(&self) -> String {+ format!("D:{:04}{:02}{:02}{:02}{:02}{:02}Z", self.year, self.month, self.day, self.hour, self.minute, self.second)+ }++ /// Seconds since 1970-01-01 (proleptic Gregorian).+ pub fn unix(&self) -> i64 {+ let (y, m) = if self.month <= 2 { (self.year as i64 - 1, self.month as i64 + 9) } else { (self.year as i64, self.month as i64 - 3) };+ let era = y.div_euclid(400);+ let yoe = y - era * 400;+ let doy = (153 * m + 2) / 5 + self.day as i64 - 1;+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ let days = era * 146_097 + doe - 719_468;+ days * 86_400 + self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64+ }++ pub fn from_unix(t: i64) -> Time {+ let days = t.div_euclid(86_400);+ let secs = t.rem_euclid(86_400);+ let z = days + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let day = (doy - (153 * mp + 2) / 5 + 1) as u32;+ let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;+ let year = (yoe + era * 400 + if month <= 2 { 1 } else { 0 }) as u32;+ Time { year, month, day, hour: (secs / 3600) as u32, minute: (secs % 3600 / 60) as u32, second: (secs % 60) as u32 }+ }++ pub fn add_seconds(&self, s: i64) -> Time {+ Time::from_unix(self.unix() + s)+ }++ /// UTCTime before 2050, GeneralizedTime from then on (RFC 5280 §4.1.2.5).+ pub fn encode(&self) -> Vec<u8> {+ if (1950..2050).contains(&self.year) {+ let s = format!("{:02}{:02}{:02}{:02}{:02}{:02}Z", self.year % 100, self.month, self.day, self.hour, self.minute, self.second);+ tlv(tag::UTC_TIME, s.as_bytes())+ } else {+ let s = format!("{:04}{:02}{:02}{:02}{:02}{:02}Z", self.year, self.month, self.day, self.hour, self.minute, self.second);+ tlv(tag::GENERALIZED_TIME, s.as_bytes())+ }+ }+}++impl std::fmt::Display for Time {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{:04}.{:02}.{:02} {:02}:{:02}:{:02} UTC", self.year, self.month, self.day, self.hour, self.minute, self.second)+ }+}++fn oid_to_string(v: &[u8]) -> Result<String, SignError> {+ let mut arcs: Vec<u64> = Vec::new();+ let mut acc = 0u64;+ for (i, b) in v.iter().enumerate() {+ acc = acc.checked_mul(128).ok_or_else(|| bad("OID arc too large"))? | (b & 0x7F) as u64;+ if b & 0x80 == 0 {+ if arcs.is_empty() {+ let first = (acc / 40).min(2);+ arcs.push(first);+ arcs.push(acc - first * 40);+ } else {+ arcs.push(acc);+ }+ acc = 0;+ } else if i + 1 == v.len() {+ return Err(bad("truncated OID"));+ }+ }+ Ok(arcs.iter().map(u64::to_string).collect::<Vec<_>>().join("."))+}++// ── writing ─────────────────────────────────────────────────────────────────────────────────++/// One element: identifier, definite length, contents.+pub fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {+ let mut out = vec![tag];+ let n = value.len();+ if n < 0x80 {+ out.push(n as u8);+ } else {+ let bytes: Vec<u8> = n.to_be_bytes().iter().copied().skip_while(|b| *b == 0).collect();+ out.push(0x80 | bytes.len() as u8);+ out.extend(bytes);+ }+ out.extend_from_slice(value);+ out+}++pub fn seq(parts: &[&[u8]]) -> Vec<u8> {+ tlv(tag::SEQUENCE, &parts.concat())+}++/// A SET OF, in DER order (sorted encodings, X.690 §11.6).+pub fn set_of(parts: &[&[u8]]) -> Vec<u8> {+ let mut v: Vec<&[u8]> = parts.to_vec();+ v.sort();+ tlv(tag::SET, &v.concat())+}++pub fn explicit(n: u8, inner: &[u8]) -> Vec<u8> {+ tlv(tag::ctx(n), inner)+}++pub fn oid(dotted: &str) -> Vec<u8> {+ let arcs: Vec<u64> = dotted.split('.').map(|a| a.parse().expect("valid OID constant")).collect();+ let mut body = Vec::new();+ let mut push = |mut v: u64| {+ let mut tmp = vec![(v & 0x7F) as u8];+ v >>= 7;+ while v > 0 {+ tmp.push(0x80 | (v & 0x7F) as u8);+ v >>= 7;+ }+ tmp.reverse();+ body.extend(tmp);+ };+ push(arcs[0] * 40 + arcs[1]);+ for a in &arcs[2..] {+ push(*a);+ }+ tlv(tag::OID, &body)+}++/// An unsigned big-endian integer.+pub fn uint(bytes: &[u8]) -> Vec<u8> {+ let b: &[u8] = match bytes.iter().position(|x| *x != 0) {+ Some(i) => &bytes[i..],+ None => &[0],+ };+ if b[0] & 0x80 != 0 {+ let mut v = vec![0];+ v.extend_from_slice(b);+ tlv(tag::INTEGER, &v)+ } else {+ tlv(tag::INTEGER, b)+ }+}++pub fn int(n: u64) -> Vec<u8> {+ uint(&n.to_be_bytes())+}++pub fn octets(b: &[u8]) -> Vec<u8> {+ tlv(tag::OCTET_STRING, b)+}++pub fn bit_string(b: &[u8]) -> Vec<u8> {+ let mut v = vec![0];+ v.extend_from_slice(b);+ tlv(tag::BIT_STRING, &v)+}++pub fn null() -> Vec<u8> {+ vec![tag::NULL, 0]+}++pub fn utf8(s: &str) -> Vec<u8> {+ tlv(tag::UTF8_STRING, s.as_bytes())+}++pub fn printable(s: &str) -> Vec<u8> {+ tlv(tag::PRINTABLE_STRING, s.as_bytes())+}++pub fn ia5(s: &str) -> Vec<u8> {+ tlv(tag::IA5_STRING, s.as_bytes())+}++pub fn boolean(b: bool) -> Vec<u8> {+ tlv(tag::BOOLEAN, &[if b { 0xFF } else { 0 }])+}++/// `AlgorithmIdentifier` with optional parameters.+pub fn algorithm(oid_s: &str, params: Option<&[u8]>) -> Vec<u8> {+ match params {+ Some(p) => seq(&[&oid(oid_s), p]),+ None => seq(&[&oid(oid_s)]),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_trips() {+ let o = oid("1.2.840.113549.1.7.2");+ let t = Tlv::parse_all(&o).unwrap();+ assert_eq!(t.oid().unwrap(), "1.2.840.113549.1.7.2");+ let big = vec![7u8; 300];+ let e = octets(&big);+ assert_eq!(&e[..4], &[0x04, 0x82, 0x01, 0x2C]);+ assert_eq!(Tlv::parse_all(&e).unwrap().value, &big[..]);+ assert_eq!(uint(&[0x80, 1]), vec![0x02, 3, 0, 0x80, 1]);+ assert_eq!(Tlv::parse_all(&int(65537)).unwrap().u64().unwrap(), 65537);+ let s = set_of(&[&int(2), &int(1)]);+ assert_eq!(s, vec![0x31, 6, 2, 1, 1, 2, 1, 2]);+ assert!(Tlv::parse(&[0x30, 5, 1]).is_err());+ }++ #[test]+ fn times() {+ let t = Time { year: 2026, month: 10, day: 2, hour: 9, minute: 30, second: 5 };+ assert_eq!(Time::from_unix(t.unix()), t);+ assert_eq!(Tlv::parse_all(&t.encode()).unwrap().time().unwrap(), t);+ let far = Time { year: 2051, ..t };+ assert_eq!(Tlv::parse_all(&far.encode()).unwrap().tag, tag::GENERALIZED_TIME);+ assert_eq!(Time::from_pdf("D:20261002113005+02'00'"), Some(Time { year: 2026, month: 10, day: 2, hour: 9, minute: 30, second: 5 }));+ assert_eq!(Time::from_unix(0), Time { year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0 });+ }+}diff --git a/crates/sign/src/keys.rs b/crates/sign/src/keys.rsnew file mode 100644index 000000000..b6aa05e8e--- /dev/null+++ b/crates/sign/src/keys.rs@@ -0,0 +1,391 @@+//! Digests, public keys (verification everywhere) and private keys (signing).+//!+//! Verification uses RustCrypto. RSA private-key operations use `aws-lc-rs` on native targets+//! (constant-time; ADR-0009: the `rsa` crate is never used for private keys there). ECDSA+//! signing uses RustCrypto with deterministic nonces (RFC 6979).++use crate::SignError;+use crate::der::{self, Tlv, tag};++pub mod oid {+ pub const SHA1: &str = "1.3.14.3.2.26";+ pub const SHA256: &str = "2.16.840.1.101.3.4.2.1";+ pub const SHA384: &str = "2.16.840.1.101.3.4.2.2";+ pub const SHA512: &str = "2.16.840.1.101.3.4.2.3";+ pub const RSA: &str = "1.2.840.113549.1.1.1";+ pub const RSA_SHA1: &str = "1.2.840.113549.1.1.5";+ pub const RSA_PSS: &str = "1.2.840.113549.1.1.10";+ pub const RSA_SHA256: &str = "1.2.840.113549.1.1.11";+ pub const RSA_SHA384: &str = "1.2.840.113549.1.1.12";+ pub const RSA_SHA512: &str = "1.2.840.113549.1.1.13";+ pub const MGF1: &str = "1.2.840.113549.1.1.8";+ pub const EC: &str = "1.2.840.10045.2.1";+ pub const P256: &str = "1.2.840.10045.3.1.7";+ pub const P384: &str = "1.3.132.0.34";+ pub const ECDSA_SHA1: &str = "1.2.840.10045.4.1";+ pub const ECDSA_SHA256: &str = "1.2.840.10045.4.3.2";+ pub const ECDSA_SHA384: &str = "1.2.840.10045.4.3.3";+ pub const ECDSA_SHA512: &str = "1.2.840.10045.4.3.4";+}++/// Message digests.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DigestAlg {+ Sha1,+ Sha256,+ Sha384,+ Sha512,+}++impl DigestAlg {+ pub fn from_oid(o: &str) -> Option<DigestAlg> {+ Some(match o {+ oid::SHA1 => DigestAlg::Sha1,+ oid::SHA256 => DigestAlg::Sha256,+ oid::SHA384 => DigestAlg::Sha384,+ oid::SHA512 => DigestAlg::Sha512,+ _ => return None,+ })+ }++ pub fn oid(self) -> &'static str {+ match self {+ DigestAlg::Sha1 => oid::SHA1,+ DigestAlg::Sha256 => oid::SHA256,+ DigestAlg::Sha384 => oid::SHA384,+ DigestAlg::Sha512 => oid::SHA512,+ }+ }++ pub fn name(self) -> &'static str {+ match self {+ DigestAlg::Sha1 => "SHA-1",+ DigestAlg::Sha256 => "SHA-256",+ DigestAlg::Sha384 => "SHA-384",+ DigestAlg::Sha512 => "SHA-512",+ }+ }++ /// The digest of the concatenation of `parts`.+ pub fn digest(self, parts: &[&[u8]]) -> Vec<u8> {+ fn run<D: sha2::Digest>(parts: &[&[u8]]) -> Vec<u8> {+ let mut h = D::new();+ for p in parts {+ h.update(p);+ }+ h.finalize().to_vec()+ }+ match self {+ DigestAlg::Sha1 => run::<sha1::Sha1>(parts),+ DigestAlg::Sha256 => run::<sha2::Sha256>(parts),+ DigestAlg::Sha384 => run::<sha2::Sha384>(parts),+ DigestAlg::Sha512 => run::<sha2::Sha512>(parts),+ }+ }++ /// The `AlgorithmIdentifier` (no parameters, as RFC 5754 recommends).+ pub fn algorithm(self) -> Vec<u8> {+ der::algorithm(self.oid(), None)+ }+}++/// How a signature value is computed.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Scheme {+ RsaPkcs1,+ RsaPss,+ Ecdsa,+}++/// A signature `AlgorithmIdentifier`: the scheme and, when the identifier names one, the digest.+pub fn signature_algorithm(alg: &Tlv<'_>) -> Result<(Scheme, Option<DigestAlg>), SignError> {+ let parts = alg.children()?;+ let o = parts.first().ok_or_else(|| SignError::Malformed("empty algorithm".into()))?.oid()?;+ Ok(match o.as_str() {+ oid::RSA => (Scheme::RsaPkcs1, None),+ oid::RSA_SHA1 => (Scheme::RsaPkcs1, Some(DigestAlg::Sha1)),+ oid::RSA_SHA256 => (Scheme::RsaPkcs1, Some(DigestAlg::Sha256)),+ oid::RSA_SHA384 => (Scheme::RsaPkcs1, Some(DigestAlg::Sha384)),+ oid::RSA_SHA512 => (Scheme::RsaPkcs1, Some(DigestAlg::Sha512)),+ oid::RSA_PSS => {+ // RSASSA-PSS-params: [0] hashAlgorithm (default SHA-1).+ let hash = parts+ .get(1)+ .and_then(|p| p.children().ok())+ .and_then(|c| c.into_iter().find(|t| t.tag == tag::ctx(0)))+ .and_then(|h| h.inner().ok())+ .and_then(|a| a.children().ok())+ .and_then(|a| a.first().and_then(|o| o.oid().ok()))+ .and_then(|o| DigestAlg::from_oid(&o))+ .unwrap_or(DigestAlg::Sha1);+ (Scheme::RsaPss, Some(hash))+ }+ oid::ECDSA_SHA1 => (Scheme::Ecdsa, Some(DigestAlg::Sha1)),+ oid::ECDSA_SHA256 => (Scheme::Ecdsa, Some(DigestAlg::Sha256)),+ oid::ECDSA_SHA384 => (Scheme::Ecdsa, Some(DigestAlg::Sha384)),+ oid::ECDSA_SHA512 => (Scheme::Ecdsa, Some(DigestAlg::Sha512)),+ oid::EC => (Scheme::Ecdsa, None),+ other => return Err(SignError::Unsupported(format!("signature algorithm {other}"))),+ })+}++/// A public key from a `SubjectPublicKeyInfo`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum PublicKey {+ Rsa { n: Vec<u8>, e: Vec<u8> },+ P256(Vec<u8>),+ P384(Vec<u8>),+}++impl PublicKey {+ pub fn from_spki(spki: &Tlv<'_>) -> Result<PublicKey, SignError> {+ let parts = spki.children()?;+ let [alg, key] = parts.as_slice() else { return Err(SignError::Malformed("SubjectPublicKeyInfo".into())) };+ let alg = alg.children()?;+ let o = alg.first().ok_or_else(|| SignError::Malformed("key algorithm".into()))?.oid()?;+ let bits = key.bits()?;+ match o.as_str() {+ oid::RSA => {+ let k = Tlv::parse_all(bits)?.children()?;+ let [n, e] = k.as_slice() else { return Err(SignError::Malformed("RSAPublicKey".into())) };+ Ok(PublicKey::Rsa { n: n.uint_bytes().to_vec(), e: e.uint_bytes().to_vec() })+ }+ oid::EC => match alg.get(1).map(|c| c.oid()).transpose()?.as_deref() {+ Some(oid::P256) => Ok(PublicKey::P256(bits.to_vec())),+ Some(oid::P384) => Ok(PublicKey::P384(bits.to_vec())),+ other => Err(SignError::Unsupported(format!("elliptic curve {}", other.unwrap_or("?")))),+ },+ other => Err(SignError::Unsupported(format!("public key algorithm {other}"))),+ }+ }++ /// The `SubjectPublicKeyInfo` encoding.+ pub fn spki(&self) -> Vec<u8> {+ match self {+ PublicKey::Rsa { n, e } => {+ let rsa = der::seq(&[&der::uint(n), &der::uint(e)]);+ der::seq(&[&der::algorithm(oid::RSA, Some(&der::null())), &der::bit_string(&rsa)])+ }+ PublicKey::P256(p) => der::seq(&[&der::seq(&[&der::oid(oid::EC), &der::oid(oid::P256)]), &der::bit_string(p)]),+ PublicKey::P384(p) => der::seq(&[&der::seq(&[&der::oid(oid::EC), &der::oid(oid::P384)]), &der::bit_string(p)]),+ }+ }++ /// "RSA 2048-bit", "ECDSA P-256"…+ pub fn describe(&self) -> String {+ match self {+ PublicKey::Rsa { n, .. } => format!("RSA {}-bit", n.len() * 8),+ PublicKey::P256(_) => "ECDSA P-256".into(),+ PublicKey::P384(_) => "ECDSA P-384".into(),+ }+ }++ /// Check `sig` over a message whose digest (with `alg`) is `digest`.+ pub fn verify(&self, scheme: Scheme, alg: DigestAlg, digest: &[u8], sig: &[u8]) -> Result<bool, SignError> {+ match (self, scheme) {+ (PublicKey::Rsa { n, e }, Scheme::RsaPkcs1 | Scheme::RsaPss) => {+ use rsa::{BoxedUint, Pkcs1v15Sign, RsaPublicKey, pss::Pss};+ let key = RsaPublicKey::new(BoxedUint::from_be_slice_vartime(n), BoxedUint::from_be_slice_vartime(e))+ .map_err(|e| SignError::Malformed(format!("RSA key: {e}")))?;+ let ok = match (scheme, alg) {+ (Scheme::RsaPkcs1, DigestAlg::Sha1) => key.verify(Pkcs1v15Sign::new::<sha1::Sha1>(), digest, sig),+ (Scheme::RsaPkcs1, DigestAlg::Sha256) => key.verify(Pkcs1v15Sign::new::<sha2::Sha256>(), digest, sig),+ (Scheme::RsaPkcs1, DigestAlg::Sha384) => key.verify(Pkcs1v15Sign::new::<sha2::Sha384>(), digest, sig),+ (Scheme::RsaPkcs1, DigestAlg::Sha512) => key.verify(Pkcs1v15Sign::new::<sha2::Sha512>(), digest, sig),+ (_, DigestAlg::Sha1) => key.verify(Pss::<sha1::Sha1>::new(), digest, sig),+ (_, DigestAlg::Sha256) => key.verify(Pss::<sha2::Sha256>::new(), digest, sig),+ (_, DigestAlg::Sha384) => key.verify(Pss::<sha2::Sha384>::new(), digest, sig),+ (_, DigestAlg::Sha512) => key.verify(Pss::<sha2::Sha512>::new(), digest, sig),+ };+ Ok(ok.is_ok())+ }+ (PublicKey::P256(p), Scheme::Ecdsa) => {+ use p256::ecdsa::signature::hazmat::PrehashVerifier;+ let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(p).map_err(|_| SignError::Malformed("P-256 key".into()))?;+ let Ok(s) = p256::ecdsa::Signature::from_der(sig) else { return Ok(false) };+ Ok(key.verify_prehash(digest, &s).is_ok())+ }+ (PublicKey::P384(p), Scheme::Ecdsa) => {+ use p384::ecdsa::signature::hazmat::PrehashVerifier;+ let key = p384::ecdsa::VerifyingKey::from_sec1_bytes(p).map_err(|_| SignError::Malformed("P-384 key".into()))?;+ let Ok(s) = p384::ecdsa::Signature::from_der(sig) else { return Ok(false) };+ Ok(key.verify_prehash(digest, &s).is_ok())+ }+ _ => Ok(false),+ }+ }+}++enum Inner {+ #[cfg(not(target_arch = "wasm32"))]+ Rsa(aws_lc_rs::signature::RsaKeyPair),+ #[cfg(target_arch = "wasm32")]+ Rsa,+ P256(p256::ecdsa::SigningKey),+ P384(p384::ecdsa::SigningKey),+}++/// A private key that can sign.+pub struct PrivateKey {+ inner: Inner,+ public: PublicKey,+ /// The PKCS#8 `PrivateKeyInfo` it came from (to write it back into a PKCS#12 file).+ pkcs8: Vec<u8>,+}++impl std::fmt::Debug for PrivateKey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "PrivateKey({})", self.public.describe())+ }+}++impl PrivateKey {+ /// From a PKCS#8 `PrivateKeyInfo`.+ pub fn from_pkcs8(info: &[u8]) -> Result<PrivateKey, SignError> {+ let t = Tlv::parse_all(info)?.children()?;+ let [_version, alg, key, ..] = t.as_slice() else { return Err(SignError::Malformed("PrivateKeyInfo".into())) };+ let alg = alg.children()?;+ let o = alg.first().ok_or_else(|| SignError::Malformed("key algorithm".into()))?.oid()?;+ let key = key.expect(tag::OCTET_STRING, "private key")?;+ match o.as_str() {+ oid::RSA => {+ let k = Tlv::parse_all(key.value)?.children()?;+ let (n, e) = match k.as_slice() {+ [_, n, e, ..] => (n.uint_bytes().to_vec(), e.uint_bytes().to_vec()),+ _ => return Err(SignError::Malformed("RSAPrivateKey".into())),+ };+ #[cfg(not(target_arch = "wasm32"))]+ let inner = Inner::Rsa(+ aws_lc_rs::signature::RsaKeyPair::from_pkcs8(info)+ .or_else(|_| aws_lc_rs::signature::RsaKeyPair::from_der(key.value))+ .map_err(|e| SignError::Malformed(format!("RSA private key: {e}")))?,+ );+ #[cfg(target_arch = "wasm32")]+ let inner = Inner::Rsa;+ Ok(PrivateKey { inner, public: PublicKey::Rsa { n, e }, pkcs8: info.to_vec() })+ }+ oid::EC => {+ // ECPrivateKey: version, privateKey OCTET STRING, [0] parameters, [1] publicKey.+ let ec = Tlv::parse_all(key.value)?.children()?;+ let d = ec.get(1).ok_or_else(|| SignError::Malformed("ECPrivateKey".into()))?.expect(tag::OCTET_STRING, "EC private key")?.value;+ let curve = match alg.get(1).map(|c| c.oid()).transpose()? {+ Some(c) => c,+ None => ec+ .iter()+ .find(|t| t.tag == tag::ctx(0))+ .and_then(|p| p.inner().ok())+ .and_then(|p| p.oid().ok())+ .ok_or_else(|| SignError::Malformed("EC curve".into()))?,+ };+ match curve.as_str() {+ oid::P256 => {+ let k = p256::ecdsa::SigningKey::from_slice(d).map_err(|_| SignError::Malformed("P-256 key".into()))?;+ let public = PublicKey::P256(k.verifying_key().to_sec1_point(false).as_bytes().to_vec());+ Ok(PrivateKey { inner: Inner::P256(k), public, pkcs8: info.to_vec() })+ }+ oid::P384 => {+ let k = p384::ecdsa::SigningKey::from_slice(d).map_err(|_| SignError::Malformed("P-384 key".into()))?;+ let public = PublicKey::P384(k.verifying_key().to_sec1_point(false).as_bytes().to_vec());+ Ok(PrivateKey { inner: Inner::P384(k), public, pkcs8: info.to_vec() })+ }+ other => Err(SignError::Unsupported(format!("elliptic curve {other}"))),+ }+ }+ other => Err(SignError::Unsupported(format!("private key algorithm {other}"))),+ }+ }++ /// A new RSA key (Acrobat's default for a self-signed digital ID is 2048-bit RSA).+ #[cfg(not(target_arch = "wasm32"))]+ pub fn generate_rsa(bits: usize) -> Result<PrivateKey, SignError> {+ use aws_lc_rs::encoding::AsDer;+ use aws_lc_rs::rsa::KeySize;+ let size = match bits {+ 2048 => KeySize::Rsa2048,+ 3072 => KeySize::Rsa3072,+ 4096 => KeySize::Rsa4096,+ _ => return Err(SignError::Unsupported(format!("{bits}-bit RSA keys"))),+ };+ let kp = aws_lc_rs::signature::RsaKeyPair::generate(size).map_err(|_| SignError::Crypto("RSA key generation failed".into()))?;+ let der = kp.as_der().map_err(|_| SignError::Crypto("RSA key encoding failed".into()))?;+ PrivateKey::from_pkcs8(der.as_ref())+ }++ /// A new P-256 key.+ pub fn generate_p256() -> Result<PrivateKey, SignError> {+ loop {+ let mut d = [0u8; 32];+ getrandom::fill(&mut d).map_err(|e| SignError::Crypto(format!("no randomness: {e}")))?;+ if let Ok(k) = p256::ecdsa::SigningKey::from_slice(&d) {+ let point = k.verifying_key().to_sec1_point(false).as_bytes().to_vec();+ // PKCS#8 with an ECPrivateKey (RFC 5915) carrying the public key.+ let ec = der::seq(&[&der::int(1), &der::octets(&d), &der::explicit(1, &der::bit_string(&point))]);+ let info = der::seq(&[&der::int(0), &der::seq(&[&der::oid(oid::EC), &der::oid(oid::P256)]), &der::octets(&ec)]);+ return PrivateKey::from_pkcs8(&info);+ }+ }+ }++ pub fn public_key(&self) -> &PublicKey {+ &self.public+ }++ pub fn pkcs8(&self) -> &[u8] {+ &self.pkcs8+ }++ /// The signature `AlgorithmIdentifier` this key writes with `alg`.+ pub fn signature_algorithm(&self, alg: DigestAlg) -> Vec<u8> {+ match (&self.public, alg) {+ (PublicKey::Rsa { .. }, DigestAlg::Sha1) => der::algorithm(oid::RSA_SHA1, Some(&der::null())),+ (PublicKey::Rsa { .. }, DigestAlg::Sha256) => der::algorithm(oid::RSA_SHA256, Some(&der::null())),+ (PublicKey::Rsa { .. }, DigestAlg::Sha384) => der::algorithm(oid::RSA_SHA384, Some(&der::null())),+ (PublicKey::Rsa { .. }, DigestAlg::Sha512) => der::algorithm(oid::RSA_SHA512, Some(&der::null())),+ (_, DigestAlg::Sha1) => der::algorithm(oid::ECDSA_SHA1, None),+ (_, DigestAlg::Sha256) => der::algorithm(oid::ECDSA_SHA256, None),+ (_, DigestAlg::Sha384) => der::algorithm(oid::ECDSA_SHA384, None),+ (_, DigestAlg::Sha512) => der::algorithm(oid::ECDSA_SHA512, None),+ }+ }++ /// The digest a signature with this key should use: SHA-256, or SHA-384 for P-384.+ pub fn preferred_digest(&self) -> DigestAlg {+ match self.public {+ PublicKey::P384(_) => DigestAlg::Sha384,+ _ => DigestAlg::Sha256,+ }+ }++ /// Sign `msg` (hashed with `alg`). New signatures never use SHA-1.+ pub fn sign(&self, alg: DigestAlg, msg: &[u8]) -> Result<Vec<u8>, SignError> {+ if alg == DigestAlg::Sha1 {+ return Err(SignError::Unsupported("SHA-1 for new signatures".into()));+ }+ match &self.inner {+ #[cfg(not(target_arch = "wasm32"))]+ Inner::Rsa(kp) => {+ use aws_lc_rs::signature::{RSA_PKCS1_SHA256, RSA_PKCS1_SHA384, RSA_PKCS1_SHA512};+ let enc: &'static dyn aws_lc_rs::signature::RsaEncoding = match alg {+ DigestAlg::Sha384 => &RSA_PKCS1_SHA384,+ DigestAlg::Sha512 => &RSA_PKCS1_SHA512,+ _ => &RSA_PKCS1_SHA256,+ };+ let mut sig = vec![0u8; kp.public_modulus_len()];+ kp.sign(enc, &aws_lc_rs::rand::SystemRandom::new(), msg, &mut sig).map_err(|_| SignError::Crypto("RSA signing failed".into()))?;+ Ok(sig)+ }+ #[cfg(target_arch = "wasm32")]+ Inner::Rsa => Err(SignError::Unsupported("RSA signing in the browser".into())),+ Inner::P256(k) => {+ use p256::ecdsa::signature::hazmat::PrehashSigner;+ let s: p256::ecdsa::Signature = k.sign_prehash(&alg.digest(&[msg])).map_err(|e| SignError::Crypto(e.to_string()))?;+ Ok(s.to_der().as_bytes().to_vec())+ }+ Inner::P384(k) => {+ use p384::ecdsa::signature::hazmat::PrehashSigner;+ let s: p384::ecdsa::Signature = k.sign_prehash(&alg.digest(&[msg])).map_err(|e| SignError::Crypto(e.to_string()))?;+ Ok(s.to_der().as_bytes().to_vec())+ }+ }+ }+}diff --git a/crates/sign/src/lib.rs b/crates/sign/src/lib.rsnew file mode 100644index 000000000..ad62160ce--- /dev/null+++ b/crates/sign/src/lib.rs@@ -0,0 +1,35 @@+//! Digital signatures (execution plan M9; ISO 32000-2 §12.8; ETSI EN 319 142 PAdES).+//!+//! - [`der`], [`x509`], [`cms`], [`pkcs12`], [`keys`]: the cryptographic formats, on RustCrypto+//! primitives (RSA private-key operations use aws-lc-rs on native targets, ADR-0009).+//! - [`pdf`]: signature fields in a document — listing and validating them, and signing+//! (PAdES B-B, `ETSI.CAdES.detached`) with an incremental save.++pub mod cms;+pub mod der;+pub mod keys;+pub mod pdf;+pub mod pkcs12;+pub mod x509;++pub use der::Time;+pub use keys::{DigestAlg, PrivateKey, PublicKey};+pub use pdf::{Appearance, Modification, SignOptions, SignatureInfo, Status, TrustStore, list as signatures, sign, validate};+pub use pkcs12::DigitalId;+pub use x509::{Certificate, Name};++#[derive(Debug, thiserror::Error)]+pub enum SignError {+ #[error("malformed data: {0}")]+ Malformed(String),+ #[error("not supported: {0}")]+ Unsupported(String),+ #[error("the password is incorrect")]+ WrongPassword,+ #[error("{0}")]+ Crypto(String),+ #[error("{0}")]+ Pdf(String),+ #[error(transparent)]+ Cos(#[from] printcraft_cos::CosError),+}diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rsnew file mode 100644index 000000000..a96065fc9--- /dev/null+++ b/crates/sign/src/pdf.rs@@ -0,0 +1,883 @@+//! Signatures in a PDF (ISO 32000-2 §12.8): listing and validating signature fields, and+//! signing with an incremental save.+//!+//! **Validation** reads `/ByteRange` and the CMS from the file's own bytes (not from the parsed+//! string, which a security handler would have transformed), recomputes the digest, checks the+//! signature and the signer's chain against the trust store, and diffs later revisions against+//! the signed one to classify changes made after signing (form fill, comments, further+//! signatures, or anything else) under the DocMDP permissions.+//!+//! **Signing** adds or fills a signature field, writes the document incrementally with a+//! zero-filled `/Contents` and a fixed-width `/ByteRange`, then patches both in place: the+//! PAdES B-B recipe (`ETSI.CAdES.detached`).++use std::collections::{HashMap, HashSet};+use std::sync::Arc;++use printcraft_cos::{Dict, Document, ObjRef, Object, PdfString, SaveOptions, Stream};++use crate::SignError;+use crate::cms::SignedData;+use crate::der::Time;+use crate::keys::DigestAlg;+use crate::pkcs12::DigitalId;+use crate::x509::{Certificate, build_chain};++/// Certificates the user trusts for signing (Acrobat: Trusted Certificates).+#[derive(Clone, Debug, Default)]+pub struct TrustStore {+ pub certs: Vec<Certificate>,+}++impl TrustStore {+ fn trusts(&self, c: &Certificate) -> bool {+ self.certs.iter().any(|t| t.raw == c.raw)+ }+}++/// Acrobat's three verdicts.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Status {+ /// Intact, signed by a trusted identity, and any later changes are permitted.+ Valid,+ /// Intact, but the signer's identity can't be established (not trusted), or validity+ /// couldn't be determined.+ Unknown,+ /// The signed bytes changed, the signature doesn't verify, or later changes aren't permitted.+ Invalid,+}++/// Changes made after signing.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Modification {+ /// The signature covers the whole file.+ None,+ /// Later revisions only make changes the signature permits (listed).+ Allowed(Vec<String>),+ /// Later revisions make changes it doesn't permit (listed).+ Disallowed(Vec<String>),+}++/// One signature field.+#[derive(Clone, Debug)]+pub struct SignatureInfo {+ /// Fully qualified field name.+ pub field: String,+ pub signed: bool,+ /// 0-based page of its widget, and the widget rectangle (user space).+ pub page: Option<usize>,+ pub rect: Option<[f64; 4]>,+ pub visible: bool,+ /// The signer: the certificate's common name, else `/Name`.+ pub signer: Option<String>,+ pub certificate: Option<Certificate>,+ /// The chain as built (signer first).+ pub chain: Vec<Certificate>,+ /// `/M` as written, and the signing time used for checks.+ pub date: Option<String>,+ pub signing_time: Option<Time>,+ pub reason: Option<String>,+ pub location: Option<String>,+ pub contact: Option<String>,+ pub sub_filter: Option<String>,+ /// DocMDP permissions when this is a certification signature (1–3).+ pub certify: Option<u8>,+ /// 1-based revision the signature covers.+ pub revision: usize,+ /// Length of the signed revision (bytes) — "View signed version".+ pub signed_len: usize,+ pub digest: Option<DigestAlg>,+ pub algorithm: Option<String>,+ pub timestamp: bool,+ pub status: Status,+ pub modification: Modification,+ /// Acrobat-style sentences explaining the verdict.+ pub details: Vec<String>,+}++impl SignatureInfo {+ /// The one-line summary under the signature in the Signatures panel.+ pub fn summary(&self) -> &'static str {+ if !self.signed {+ return "Unsigned signature field";+ }+ match self.status {+ Status::Valid => "Signature is valid",+ Status::Unknown => "Signature validity is unknown",+ Status::Invalid => "Signature is invalid",+ }+ }+}++fn text(doc: &Document, d: &Dict, key: &[u8]) -> Option<String> {+ let o = doc.resolve(d.get(key)?);+ let s = match &*o {+ Object::String(s) => s.to_text(),+ Object::Name(n) => String::from_utf8_lossy(n).into_owned(),+ _ => return None,+ };+ let s = s.trim_matches('\0').trim().to_string();+ (!s.is_empty()).then_some(s)+}++struct Field {+ name: String,+ /// The field dictionary (and its widget(s)).+ r: Option<ObjRef>,+ dict: Dict,+ widgets: Vec<(Option<ObjRef>, Dict)>,+}++/// Every signature field, depth first in `/Fields` order.+fn sig_fields(doc: &Document) -> Vec<Field> {+ let mut out = Vec::new();+ let Some(root) = doc.root() else { return out };+ let Some(af) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").map(|a| doc.resolve(a))).and_then(|a| a.as_dict().cloned()) else {+ return out;+ };+ let Some(fields) = af.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()) else { return out };+ let mut seen = HashSet::new();+ let mut stack: Vec<(Object, String, Option<Vec<u8>>)> = fields.into_iter().rev().map(|f| (f, String::new(), None)).collect();+ while let Some((o, prefix, inherited_ft)) = stack.pop() {+ if let Some(r) = o.as_ref()+ && !seen.insert(r)+ {+ continue;+ }+ let Some(d) = doc.resolve(&o).as_dict().cloned() else { continue };+ let part = text(doc, &d, b"T");+ let name = match (&part, prefix.is_empty()) {+ (Some(p), true) => p.clone(),+ (Some(p), false) => format!("{prefix}.{p}"),+ (None, _) => prefix.clone(),+ };+ let ft = d.name(b"FT").map(<[u8]>::to_vec).or(inherited_ft);+ let kids: Vec<Object> = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();+ // Kids with a /T are fields; others are this field's widgets.+ let (sub, widgets): (Vec<Object>, Vec<Object>) = kids.into_iter().partition(|k| doc.resolve(k).as_dict().is_some_and(|kd| kd.contains(b"T")));+ for k in sub.into_iter().rev() {+ stack.push((k, name.clone(), ft.clone()));+ }+ if ft.as_deref() == Some(b"Sig") && part.is_some() {+ let mut ws: Vec<(Option<ObjRef>, Dict)> =+ widgets.iter().filter_map(|w| doc.resolve(w).as_dict().cloned().map(|wd| (w.as_ref(), wd))).collect();+ if d.name(b"Subtype") == Some(b"Widget") {+ ws.insert(0, (o.as_ref(), d.clone()));+ }+ out.push(Field { name, r: o.as_ref(), dict: d, widgets: ws });+ }+ }+ out+}++/// Which page holds each annotation.+fn annot_pages(doc: &Document) -> HashMap<ObjRef, usize> {+ let mut map = HashMap::new();+ for (i, p) in printcraft_annot::page_refs(doc).unwrap_or_default().into_iter().enumerate() {+ if let Some(a) = doc.get(p).as_dict().and_then(|d| d.get(b"Annots").map(|a| doc.resolve(a))).and_then(|a| a.as_array().cloned()) {+ for r in a.iter().filter_map(Object::as_ref) {+ map.insert(r, i);+ }+ }+ }+ map+}++fn nums(doc: &Document, d: &Dict, key: &[u8]) -> Option<Vec<f64>> {+ doc.resolve(d.get(key)?).as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())+}++/// List and validate every signature field. `bytes` is the file as stored (the ranges index it).+pub fn list(doc: &Document, bytes: &[u8], trust: &TrustStore) -> Vec<SignatureInfo> {+ let pages = annot_pages(doc);+ let mut out = Vec::new();+ for f in sig_fields(doc) {+ let widget = f.widgets.first();+ let page = widget.and_then(|(r, w)| r.and_then(|r| pages.get(&r).copied()).or_else(|| w.reference(b"P").and_then(|p| page_index(doc, p))));+ let rect = widget+ .and_then(|(_, w)| nums(doc, w, b"Rect"))+ .filter(|r| r.len() == 4)+ .map(|r| [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]);+ let visible = rect.is_some_and(|r| r[2] - r[0] > 0.5 && r[3] - r[1] > 0.5);+ let v = f.dict.get(b"V").map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned());+ let mut info = SignatureInfo {+ field: f.name.clone(),+ signed: v.is_some(),+ page,+ rect,+ visible,+ signer: None,+ certificate: None,+ chain: Vec::new(),+ date: None,+ signing_time: None,+ reason: None,+ location: None,+ contact: None,+ sub_filter: None,+ certify: None,+ revision: 0,+ signed_len: 0,+ digest: None,+ algorithm: None,+ timestamp: false,+ status: Status::Unknown,+ modification: Modification::None,+ details: Vec::new(),+ };+ if let Some(v) = v {+ validate_into(doc, bytes, trust, &v, &mut info);+ }+ out.push(info);+ }+ out+}++fn page_index(doc: &Document, p: ObjRef) -> Option<usize> {+ printcraft_annot::page_refs(doc).ok()?.iter().position(|r| *r == p)+}++/// Validate one signature dictionary.+pub fn validate(doc: &Document, bytes: &[u8], trust: &TrustStore, field: &str) -> Option<SignatureInfo> {+ list(doc, bytes, trust).into_iter().find(|s| s.field == field)+}++fn unhex(s: &[u8]) -> Option<Vec<u8>> {+ let digits: Vec<u8> = s.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect();+ let val = |c: u8| (c as char).to_digit(16).map(|d| d as u8);+ digits.chunks(2).map(|p| Some(val(p[0])? << 4 | p.get(1).map_or(Some(0), |c| val(*c))?)).collect()+}++fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: &Dict, info: &mut SignatureInfo) {+ info.date = text(doc, v, b"M");+ info.reason = text(doc, v, b"Reason");+ info.location = text(doc, v, b"Location");+ info.contact = text(doc, v, b"ContactInfo");+ info.sub_filter = v.name(b"SubFilter").map(|s| String::from_utf8_lossy(s).into_owned());+ info.signer = text(doc, v, b"Name");+ info.certify = v+ .get(b"Reference")+ .map(|r| doc.resolve(r))+ .and_then(|r| r.as_array().cloned())+ .into_iter()+ .flatten()+ .filter_map(|r| doc.resolve(&r).as_dict().cloned())+ .find(|r| r.name(b"TransformMethod") == Some(b"DocMDP"))+ .map(|r| {+ r.get(b"TransformParams").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().and_then(|p| p.int(b"P"))).unwrap_or(2).clamp(1, 3) as u8+ });+ let invalid = |info: &mut SignatureInfo, why: &str| {+ info.status = Status::Invalid;+ info.details.push(why.to_string());+ };+ // Byte ranges: [0 a b c] with the gap holding exactly the hex /Contents.+ let Some(br) = nums(doc, v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else {+ return invalid(info, "The signature has no valid byte range.");+ };+ let [o0, l0, o1, l1] = [br[0] as usize, br[1] as usize, br[2] as usize, br[3] as usize];+ if o0 != 0 || o1 < l0 || o1.checked_add(l1).is_none_or(|end| end > bytes.len()) || o1 - l0 < 2 {+ return invalid(info, "The signature's byte range does not match the file.");+ }+ let gap = &bytes[l0..o1];+ if gap.first() != Some(&b'<') || gap.last() != Some(&b'>') {+ return invalid(info, "The signature's byte range does not exclude exactly its contents.");+ }+ let Some(contents) = unhex(&gap[1..gap.len() - 1]) else { return invalid(info, "The signature contents are not hexadecimal.") };+ let covered = o1 + l1;+ info.signed_len = covered;+ info.revision = bytes[..covered].windows(5).filter(|w| *w == b"%%EOF").count().max(1);+ let ranges: [&[u8]; 2] = [&bytes[..l0], &bytes[o1..covered]];+ if info.sub_filter.as_deref() == Some("adbe.x509.rsa_sha1") {+ info.details.push("This signature uses the legacy adbe.x509.rsa_sha1 format, which PrintCraft does not validate yet.".into());+ return;+ }+ let sd = match SignedData::parse(&contents) {+ Ok(sd) => sd,+ Err(e) => return invalid(info, &format!("The signature could not be read ({e}).")),+ };+ let s = &sd.signer;+ info.digest = Some(s.digest);+ info.timestamp = s.timestamp;+ // The digest the signature commits to.+ let content_digest = match &sd.content {+ // adbe.pkcs7.sha1: the document's SHA-1 digest is the signed content.+ Some(c) => {+ if *c != DigestAlg::Sha1.digest(&ranges) {+ return invalid(info, "The document has been altered or corrupted since the signature was applied.");+ }+ s.digest.digest(&[c])+ }+ None => s.digest.digest(&ranges),+ };+ if let Some(md) = &s.message_digest+ && *md != content_digest+ {+ return invalid(info, "The document has been altered or corrupted since the signature was applied.");+ }+ let Some(cert) = sd.signer_certificate().cloned() else {+ return invalid(info, "The signer's certificate is not in the signature.");+ };+ info.algorithm = Some(format!("{} with {}", cert.public_key.describe(), s.scheme_digest.unwrap_or(s.digest).name()));+ info.signer = Some(cert.display_name());+ if !sd.verify_signature(&cert, &content_digest) {+ info.certificate = Some(cert);+ return invalid(info, "The signature value does not match the signer's certificate: the signature is corrupt.");+ }+ info.signing_time = s.signing_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf));+ let mut pool = sd.certificates.clone();+ pool.extend(trust.certs.iter().cloned());+ let chain: Vec<Certificate> = build_chain(&cert, &pool).into_iter().cloned().collect();+ let trusted = chain.iter().any(|c| trust.trusts(c));+ info.chain = chain;+ info.certificate = Some(cert.clone());+ // Changes after signing.+ info.modification = if covered == bytes.len() || bytes[covered..].iter().all(|b| b.is_ascii_whitespace() || *b == 0) {+ Modification::None+ } else {+ classify_changes(doc, &bytes[..covered], info.certify)+ };+ let mut problems = false;+ match &info.modification {+ Modification::None => info.details.push("This document has not been modified since this signature was applied.".into()),+ Modification::Allowed(kinds) => info+ .details+ .push(format!("The document has been modified since this signature was applied, but the changes are permitted ({}).", kinds.join(", "))),+ Modification::Disallowed(kinds) => {+ info.status = Status::Invalid;+ info.details+ .push(format!("The document has been altered since this signature was applied in ways it does not permit ({}).", kinds.join(", ")));+ problems = true;+ }+ }+ if let Some(t) = info.signing_time+ && !cert.valid_at(t)+ {+ info.details.push("The signer's certificate was not valid at the time of signing.".into());+ if !problems {+ info.status = Status::Unknown;+ }+ problems = true;+ }+ if !trusted {+ info.details.push(+ "The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates."+ .into(),+ );+ if !problems {+ info.status = Status::Unknown;+ }+ } else {+ info.details.push("The signer's identity is valid.".into());+ if !problems {+ info.status = Status::Valid;+ }+ }+ if info.timestamp {+ info.details.push("The signature includes an embedded timestamp.".into());+ } else {+ info.details.push("Signing time is from the clock on the signer's computer.".into());+ }+}++/// What later revisions changed, classified as Acrobat reports it, under DocMDP `p` (or none:+/// an approval signature permits form fill, comments and further signatures).+fn classify_changes(doc: &Document, signed: &[u8], p: Option<u8>) -> Modification {+ let Ok(old) = Document::open(Arc::new(signed.to_vec())) else {+ return Modification::Disallowed(vec!["the signed version could not be read".into()]);+ };+ let old_content: HashSet<ObjRef> = printcraft_annot::page_refs(&old)+ .unwrap_or_default()+ .into_iter()+ .flat_map(|pg| {+ let c = old.get(pg).as_dict().and_then(|d| d.get(b"Contents").cloned());+ match c {+ Some(Object::Ref(r)) => match &*old.get(r) {+ Object::Array(a) => a.iter().filter_map(Object::as_ref).chain([r]).collect::<Vec<_>>(),+ _ => vec![r],+ },+ Some(Object::Array(a)) => a.iter().filter_map(Object::as_ref).collect(),+ _ => Vec::new(),+ }+ })+ .collect();+ let (mut allowed, mut disallowed): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());+ for num in doc.object_numbers() {+ let r = ObjRef { num, generation: doc.generation(num) };+ let new = doc.get(r);+ let before = old.try_get(num).ok().filter(|o| !matches!(**o, Object::Null));+ if before.as_deref() == Some(&*new) {+ continue;+ }+ let kind = match &*new {+ Object::Dict(d) => change_kind(doc, &old, d, before.as_deref().and_then(Object::as_dict)),+ Object::Stream(s) => {+ if old_content.contains(&r) {+ "page content"+ } else if s.dict.name(b"Type") == Some(b"XRef") || s.dict.name(b"Type") == Some(b"ObjStm") || before.is_none() {+ continue;+ } else {+ "other changes"+ }+ }+ _ if before.is_none() => continue,+ _ => "other changes",+ };+ let ok = match (kind, p) {+ ("signature" | "document security store", _) => true,+ ("form fill", Some(2 | 3) | None) => true,+ ("comments", Some(3) | None) => true,+ // Every save updates /Info (ModDate), signing included.+ ("metadata", _) => true,+ _ => false,+ };+ let list = if ok { &mut allowed } else { &mut disallowed };+ if !list.contains(&kind) {+ list.push(kind);+ }+ }+ let own = |v: Vec<&str>| v.into_iter().map(str::to_string).collect::<Vec<_>>();+ if disallowed.is_empty() { Modification::Allowed(own(allowed)) } else { Modification::Disallowed(own(disallowed)) }+}++/// What adding `added` annotations amounts to: signing (signature widgets only), form fill+/// (other widgets) or comments.+fn added_annots(doc: &Document, added: &[ObjRef]) -> &'static str {+ let kinds: Vec<(bool, bool)> = added+ .iter()+ .map(|r| {+ let o = doc.get(*r);+ let d = o.as_dict();+ (d.is_some_and(|d| d.name(b"Subtype") == Some(b"Widget")), d.is_some_and(|d| d.name(b"FT") == Some(b"Sig")))+ })+ .collect();+ if !kinds.is_empty() && kinds.iter().all(|(w, s)| *w && *s) {+ "signature"+ } else if !kinds.is_empty() && kinds.iter().all(|(w, _)| *w) {+ "form fill"+ } else {+ "comments"+ }+}++fn refs(doc: &Document, o: Option<&Object>) -> Vec<ObjRef> {+ o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(Object::as_ref).collect())).unwrap_or_default()+}++/// The interactive form dictionary of a document, resolved.+fn acroform(doc: &Document) -> Option<Dict> {+ let c = doc.get(doc.root()?).as_dict()?.get(b"AcroForm").cloned()?;+ doc.resolve(&c).as_dict().cloned()+}++/// An AcroForm change that only adds signature fields (and sets `/SigFlags`) is signing.+/// Without `before`, the signed revision's AcroForm (wherever it was) is the reference.+fn acroform_kind(doc: &Document, old: &Document, now: &Dict, before: Option<&Dict>) -> &'static str {+ let fallback = acroform(old).unwrap_or_default();+ let before = before.unwrap_or(&fallback);+ let strip = |d: &Dict| -> Vec<(Vec<u8>, Object)> {+ let mut v: Vec<(Vec<u8>, Object)> =+ d.iter().filter(|(k, _)| !matches!(k.as_slice(), b"Fields" | b"SigFlags")).map(|(k, o)| (k.to_vec(), o.clone())).collect();+ v.sort_by(|a, b| a.0.cmp(&b.0));+ v+ };+ if strip(now) != strip(before) {+ return "form fill";+ }+ let old_fields = refs(old, before.get(b"Fields"));+ let added: Vec<ObjRef> = refs(doc, now.get(b"Fields")).into_iter().filter(|r| !old_fields.contains(r)).collect();+ if added.is_empty() || added_annots(doc, &added) == "signature" { "signature" } else { "form fill" }+}++fn change_kind(doc: &Document, old: &Document, d: &Dict, before: Option<&Dict>) -> &'static str {+ let ty = d.name(b"Type");+ let without = |x: &Dict, keys: &[&[u8]]| -> Vec<(Vec<u8>, Object)> {+ let mut v: Vec<(Vec<u8>, Object)> = x.iter().filter(|(k, _)| !keys.contains(&k.as_slice())).map(|(k, o)| (k.to_vec(), o.clone())).collect();+ v.sort_by(|a, b| a.0.cmp(&b.0));+ v+ };+ match ty {+ Some(b"Sig" | b"DocTimeStamp" | b"SigRef" | b"TransformParams") => return "signature",+ Some(b"DSS") => return "document security store",+ Some(b"Catalog") => {+ let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"NeedsRendering"];+ return match before {+ Some(b) if without(d, keys) != without(b, keys) => "document structure",+ Some(b) => {+ if d.get(b"AcroForm") != b.get(b"AcroForm") {+ // Compare the forms themselves, inline or not.+ let now = acroform(doc).unwrap_or_default();+ acroform_kind(doc, old, &now, None)+ } else if b.get(b"Perms") != d.get(b"Perms") {+ "signature"+ } else {+ "metadata"+ }+ }+ None => "form fill",+ };+ }+ Some(b"Page") => {+ return match before {+ Some(b) if without(d, &[b"Annots"]) != without(b, &[b"Annots"]) => "page content",+ Some(b) => {+ let was = refs(old, b.get(b"Annots"));+ let added: Vec<ObjRef> = refs(doc, d.get(b"Annots")).into_iter().filter(|r| !was.contains(r)).collect();+ added_annots(doc, &added)+ }+ None => "comments",+ };+ }+ Some(b"Pages") => return if before.is_some() { "pages added or removed" } else { "document structure" },+ Some(b"Metadata") => return "metadata",+ _ => {}+ }+ match d.name(b"Subtype") {+ Some(b"Widget") => return if d.name(b"FT") == Some(b"Sig") { "signature" } else { "form fill" },+ Some(b"Link") => return "links",+ Some(_) if ty == Some(b"Annot") || d.contains(b"Rect") => return "comments",+ _ => {}+ }+ if d.name(b"FT") == Some(b"Sig") {+ return "signature";+ }+ if d.contains(b"Fields") {+ return acroform_kind(doc, old, d, before);+ }+ if d.contains(b"FT") || (d.contains(b"T") && d.contains(b"Kids")) || d.contains(b"DR") {+ return "form fill";+ }+ if d.contains(b"Producer") || d.contains(b"ModDate") || d.contains(b"CreationDate") {+ return "metadata";+ }+ if before.is_none() {+ // New objects referenced by changed ones (fonts, appearance resources).+ return "form fill";+ }+ "other changes"+}++// ── signing ─────────────────────────────────────────────────────────────────────────────────++/// What the visible signature shows (Acrobat: Configure Signature Appearance).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Appearance {+ pub name: bool,+ pub date: bool,+ pub reason: bool,+ pub location: bool,+ pub distinguished_name: bool,+ pub labels: bool,+}++impl Default for Appearance {+ fn default() -> Self {+ Self { name: true, date: true, reason: false, location: false, distinguished_name: false, labels: true }+ }+}++#[derive(Clone, Debug, Default)]+pub struct SignOptions {+ /// Sign this existing, unsigned signature field.+ pub field: Option<String>,+ /// Or create a field on this page (0-based) with this rectangle (`None`: invisible).+ pub page: usize,+ pub rect: Option<[f64; 4]>,+ /// Name for a new field (default `Signature1`, `Signature2`…).+ pub new_field_name: Option<String>,+ pub reason: Option<String>,+ pub location: Option<String>,+ pub contact: Option<String>,+ /// The signing time as a PDF date (`/M`), from the caller's clock.+ pub date: String,+ /// Certify with these DocMDP permissions (1 no changes, 2 form fill and signing, 3 also comments).+ pub certify: Option<u8>,+ pub appearance: Appearance,+}++/// Placeholder `/ByteRange` values: fixed width, patched after writing.+const BR_MARK: [i64; 3] = [1_111_111_111, 2_222_222_222, 3_333_333_333];++/// Sign `doc` with `id`; returns the signed file (an incremental update when possible).+pub fn sign(doc: &Document, id: &DigitalId, opts: &SignOptions) -> Result<Vec<u8>, SignError> {+ if doc.security().is_some() || doc.output_handler().is_some() {+ return Err(SignError::Unsupported("signing encrypted documents".into()));+ }+ let mut doc = doc.clone();+ let root = doc.root().ok_or_else(|| SignError::Pdf("the document has no catalog".into()))?;+ let alg = id.key.preferred_digest();+ let reserve = 8192 + id.certificate.raw.len() + id.chain.iter().map(|c| c.raw.len()).sum::<usize>();+ let name = id.certificate.display_name();+ // The signature dictionary.+ let mut v = Dict::new();+ v.set(b"Type".to_vec(), Object::name("Sig"));+ v.set(b"Filter".to_vec(), Object::name("Adobe.PPKLite"));+ v.set(b"SubFilter".to_vec(), Object::name("ETSI.CAdES.detached"));+ v.set(b"ByteRange".to_vec(), Object::Array([0].iter().chain(BR_MARK.iter()).map(|n| Object::Int(*n)).collect()));+ v.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0; reserve], hex: true }));+ v.set(b"M".to_vec(), PdfString::literal(opts.date.as_bytes().to_vec()));+ v.set(b"Name".to_vec(), PdfString::text(&name));+ for (k, val) in [(&b"Reason"[..], &opts.reason), (b"Location", &opts.location), (b"ContactInfo", &opts.contact)] {+ if let Some(s) = val.as_deref().filter(|s| !s.trim().is_empty()) {+ v.set(k.to_vec(), PdfString::text(s));+ }+ }+ let mut app = Dict::new();+ app.set(b"Name".to_vec(), Object::name("PrintCraft"));+ let mut build = Dict::new();+ build.set(b"App".to_vec(), Object::Dict(app));+ v.set(b"Prop_Build".to_vec(), Object::Dict(build));+ if let Some(p) = opts.certify {+ let mut tp = Dict::new();+ tp.set(b"Type".to_vec(), Object::name("TransformParams"));+ tp.set(b"P".to_vec(), Object::Int(p.clamp(1, 3) as i64));+ tp.set(b"V".to_vec(), Object::name("1.2"));+ let mut sr = Dict::new();+ sr.set(b"Type".to_vec(), Object::name("SigRef"));+ sr.set(b"TransformMethod".to_vec(), Object::name("DocMDP"));+ sr.set(b"TransformParams".to_vec(), Object::Dict(tp));+ v.set(b"Reference".to_vec(), Object::Array(vec![Object::Dict(sr)]));+ }+ let sig = doc.add(Object::Dict(v.clone()));+ if opts.certify.is_some() {+ // Catalog /Perms /DocMDP points at the certification signature.+ let mut perms = Dict::new();+ perms.set(b"DocMDP".to_vec(), Object::Ref(sig));+ doc.update_dict(root, |c| c.set(b"Perms".to_vec(), Object::Dict(perms)))?;+ }+ // The field and its widget.+ let pages = printcraft_annot::page_refs(&doc).map_err(|e| SignError::Pdf(e.to_string()))?;+ let existing = opts+ .field+ .as_deref()+ .map(|n| sig_fields(&doc).into_iter().find(|f| f.name == n).ok_or_else(|| SignError::Pdf(format!("there is no signature field {n:?}"))));+ let (widget, rect) = match existing {+ Some(f) => {+ let f = f?;+ if f.dict.contains(b"V") {+ return Err(SignError::Pdf(format!("the field {:?} is already signed", f.name)));+ }+ let fr = f.r.ok_or_else(|| SignError::Pdf("the field is not an indirect object".into()))?;+ doc.update_dict(fr, |d| d.set(b"V".to_vec(), Object::Ref(sig)))?;+ let (wr, wd) = f.widgets.first().cloned().ok_or_else(|| SignError::Pdf("the field has no widget".into()))?;+ let rect = nums(&doc, &wd, b"Rect").filter(|r| r.len() == 4).map(|r| [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]);+ (wr.unwrap_or(fr), rect.unwrap_or([0.0; 4]))+ }+ None => {+ let page = *pages.get(opts.page).ok_or_else(|| SignError::Pdf(format!("page {} does not exist", opts.page + 1)))?;+ let taken: HashSet<String> = sig_fields(&doc).into_iter().map(|f| f.name).collect();+ let fname = opts+ .new_field_name+ .clone()+ .unwrap_or_else(|| (1..).map(|i| format!("Signature{i}")).find(|n| !taken.contains(n)).unwrap_or_default());+ let rect = opts.rect.unwrap_or([0.0; 4]);+ let mut w = Dict::new();+ w.set(b"Type".to_vec(), Object::name("Annot"));+ w.set(b"Subtype".to_vec(), Object::name("Widget"));+ w.set(b"FT".to_vec(), Object::name("Sig"));+ w.set(b"T".to_vec(), PdfString::text(&fname));+ w.set(b"V".to_vec(), Object::Ref(sig));+ w.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|x| Object::Real(*x)).collect()));+ w.set(b"P".to_vec(), Object::Ref(page));+ // Print + Locked.+ w.set(b"F".to_vec(), Object::Int(4 | 128));+ let wr = doc.add(Object::Dict(w));+ // Page /Annots (indirect arrays are updated in place).+ let pd = doc.get(page).as_dict().cloned().unwrap_or_default();+ match pd.get(b"Annots") {+ Some(Object::Ref(ar)) => {+ let mut a = doc.get(*ar).as_array().cloned().unwrap_or_default();+ a.push(Object::Ref(wr));+ doc.set(*ar, Object::Array(a));+ }+ other => {+ let mut a = other.and_then(|o| o.as_array().cloned()).unwrap_or_default();+ a.push(Object::Ref(wr));+ doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(a)))?;+ }+ }+ // AcroForm /Fields and /SigFlags (signatures exist, append only).+ let catalog = doc.get(root).as_dict().cloned().unwrap_or_default();+ let (af_ref, mut af) = match catalog.get(b"AcroForm") {+ Some(Object::Ref(r)) => (Some(*r), doc.get(*r).as_dict().cloned().unwrap_or_default()),+ Some(Object::Dict(d)) => (None, d.clone()),+ _ => (None, Dict::new()),+ };+ let mut fields = match af.get(b"Fields") {+ Some(Object::Ref(r)) => doc.get(*r).as_array().cloned().unwrap_or_default(),+ Some(Object::Array(a)) => a.clone(),+ _ => Vec::new(),+ };+ fields.push(Object::Ref(wr));+ af.set(b"Fields".to_vec(), Object::Array(fields));+ af.set(b"SigFlags".to_vec(), Object::Int(3));+ match af_ref {+ Some(r) => doc.set(r, Object::Dict(af)),+ // Inline (or new) AcroForms stay in the catalog.+ None => doc.update_dict(root, |c| c.set(b"AcroForm".to_vec(), Object::Dict(af)))?,+ }+ (wr, rect)+ }+ };+ if opts.field.is_some() {+ doc.update_dict(root, |c| {+ if let Some(Object::Dict(af)) = c.get_mut(b"AcroForm") {+ af.set(b"SigFlags".to_vec(), Object::Int(3));+ }+ })?;+ if let Some(Object::Ref(r)) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").cloned()) {+ doc.update_dict(r, |af| af.set(b"SigFlags".to_vec(), Object::Int(3)))?;+ }+ }+ // The appearance.+ let ap = appearance(rect, &name, &id.certificate, opts);+ let ap_ref = doc.add(Object::Stream(ap));+ let mut apd = Dict::new();+ apd.set(b"N".to_vec(), Object::Ref(ap_ref));+ doc.update_dict(widget, |w| w.set(b"AP".to_vec(), Object::Dict(apd)))?;+ // Write with the placeholders, then patch them.+ let save = SaveOptions { mod_date: Some(opts.date.clone()), object_streams: false, ..SaveOptions::default() };+ let mut out = printcraft_cos::write_incremental(&doc, &save)?;+ let (br_at, gap) = locate(&out, sig.num, reserve)?;+ let (start, end) = gap;+ let ranges = [0usize, start, end, out.len() - end];+ let mut br_text = format!("0 {} {} {}", ranges[1], ranges[2], ranges[3]).into_bytes();+ let width = format!("0 {} {} {}", BR_MARK[0], BR_MARK[1], BR_MARK[2]).len();+ if br_text.len() > width {+ return Err(SignError::Pdf("the document is too large to sign".into()));+ }+ br_text.resize(width, b' ');+ out[br_at..br_at + width].copy_from_slice(&br_text);+ let digest = alg.digest(&[&out[..start], &out[end..]]);+ let cms = crate::cms::sign_detached(&id.key, &id.certificate, &id.chain, alg, &digest)?;+ if cms.len() > reserve {+ return Err(SignError::Pdf("the signature does not fit its placeholder".into()));+ }+ let hex: Vec<u8> = cms.iter().flat_map(|b| format!("{b:02X}").into_bytes()).collect();+ out[start + 1..start + 1 + hex.len()].copy_from_slice(&hex);+ Ok(out)+}++/// Find the placeholders of signature object `num` in the written file: the offset of the+/// ByteRange numbers, and the `<…>` hex string's span.+fn locate(out: &[u8], num: u32, reserve: usize) -> Result<(usize, (usize, usize)), SignError> {+ let head = format!("{num} 0 obj");+ let starts: Vec<usize> = out+ .windows(head.len())+ .enumerate()+ .filter(|(i, w)| *w == head.as_bytes() && (*i == 0 || matches!(out[i - 1], b'\n' | b'\r' | b' ')))+ .map(|(i, _)| i)+ .collect();+ let obj = *starts.last().ok_or_else(|| SignError::Pdf("the signature object was not written".into()))?;+ let end = obj + out[obj..].windows(6).position(|w| w == b"endobj").ok_or_else(|| SignError::Pdf("unterminated signature object".into()))?;+ let region = &out[obj..end];+ let mark = format!("0 {} {} {}", BR_MARK[0], BR_MARK[1], BR_MARK[2]);+ let br = region.windows(mark.len()).position(|w| w == mark.as_bytes()).ok_or_else(|| SignError::Pdf("ByteRange placeholder not found".into()))?;+ let mut zeros = vec![b'<'];+ zeros.extend(std::iter::repeat_n(b'0', reserve * 2));+ zeros.push(b'>');+ let c = region.windows(zeros.len()).position(|w| w == zeros.as_slice()).ok_or_else(|| SignError::Pdf("Contents placeholder not found".into()))?;+ Ok((obj + br, (obj + c, obj + c + zeros.len())))+}++/// "2026.10.02 14:03:11 +02'00'" from a PDF date.+pub fn display_date(pdf: &str) -> String {+ let s = pdf.strip_prefix("D:").unwrap_or(pdf);+ let g = |r: std::ops::Range<usize>| s.get(r).unwrap_or("00");+ let tz = match s.get(14..).filter(|z| !z.is_empty()) {+ Some(z) if z.starts_with('Z') => " Z".to_string(),+ Some(z) => format!(" {z}"),+ None => String::new(),+ };+ format!("{}.{}.{} {}:{}:{}{tz}", g(0..4), g(4..6), g(6..8), g(8..10), g(10..12), g(12..14))+}++/// The visible signature: the signer's name large on the left, the details on the right+/// (Acrobat's standard layout), in Helvetica.+fn appearance(rect: [f64; 4], name: &str, cert: &Certificate, opts: &SignOptions) -> Stream {+ use printcraft_fonts::{helvetica_width, literal, win_ansi, wrap};+ let (w, h) = ((rect[2] - rect[0]).max(0.0), (rect[3] - rect[1]).max(0.0));+ let a = &opts.appearance;+ let mut lines: Vec<String> = Vec::new();+ let label = |l: &str, v: &str| if a.labels { format!("{l}{v}") } else { v.to_string() };+ if a.name {+ lines.push(if a.labels { "Digitally signed by".into() } else { String::new() });+ lines.push(name.to_string());+ }+ if a.distinguished_name {+ lines.push(label("DN: ", &cert.subject.display()));+ }+ if a.reason+ && let Some(r) = opts.reason.as_deref().filter(|r| !r.is_empty())+ {+ lines.push(label("Reason: ", r));+ }+ if a.location+ && let Some(l) = opts.location.as_deref().filter(|l| !l.is_empty())+ {+ lines.push(label("Location: ", l));+ }+ if a.date {+ lines.push(label("Date: ", &display_date(&opts.date)));+ }+ lines.retain(|l| !l.is_empty());+ let mut out = Vec::new();+ if w > 1.0 && h > 1.0 {+ let pad = (h * 0.06).clamp(1.0, 6.0);+ let (left_w, right_x) = if a.name { (w * 0.5, w * 0.5 + pad) } else { (0.0, pad) };+ let right_w = (w - right_x - pad).max(1.0);+ out.extend_from_slice(b"BT\n0 g\n");+ if a.name {+ // The name fills the left half.+ let mut size = (h * 0.4).min(36.0);+ let fit = (left_w - 2.0 * pad).max(1.0);+ let longest = helvetica_width(name, 1.0).max(0.01);+ size = size.min(fit / longest).max(4.0);+ let words = wrap(name, size, fit);+ let total = words.len() as f64 * size * 1.1;+ let mut y = (h + total) / 2.0 - size * 0.85;+ for l in &words {+ out.extend(format!("/Helv {} Tf 1 0 0 1 {} {} Tm ", fmt(size), fmt(pad), fmt(y)).bytes());+ out.extend(literal(&win_ansi(l)));+ out.extend_from_slice(b" Tj\n");+ y -= size * 1.1;+ }+ }+ // The details, shrunk to fit the right side.+ let mut size = (h / (lines.len().max(1) as f64 * 1.15)).min(12.0);+ let wrapped = loop {+ let all: Vec<String> = lines.iter().flat_map(|l| wrap(l, size, right_w)).collect();+ if all.len() as f64 * size * 1.15 <= h - 2.0 * pad || size <= 3.0 {+ break all;+ }+ size *= 0.9;+ };+ let mut y = h - pad - size * 0.9;+ for l in &wrapped {+ out.extend(format!("/Helv {} Tf 1 0 0 1 {} {} Tm ", fmt(size), fmt(right_x), fmt(y)).bytes());+ out.extend(literal(&win_ansi(l)));+ out.extend_from_slice(b" Tj\n");+ y -= size * 1.15;+ }+ out.extend_from_slice(b"ET\n");+ }+ let mut d = Dict::new();+ d.set(b"Type".to_vec(), Object::name("XObject"));+ d.set(b"Subtype".to_vec(), Object::name("Form"));+ d.set(b"BBox".to_vec(), Object::Array([0.0, 0.0, w, h].iter().map(|x| Object::Real(*x)).collect()));+ let mut font = Dict::new();+ font.set(b"Type".to_vec(), Object::name("Font"));+ font.set(b"Subtype".to_vec(), Object::name("Type1"));+ font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ let mut fonts = Dict::new();+ fonts.set(b"Helv".to_vec(), Object::Dict(font));+ let mut res = Dict::new();+ res.set(b"Font".to_vec(), Object::Dict(fonts));+ d.set(b"Resources".to_vec(), Object::Dict(res));+ Stream::flate(d, &out)+}++fn fmt(v: f64) -> String {+ let s = format!("{v:.2}");+ s.trim_end_matches('0').trim_end_matches('.').to_string()+}diff --git a/crates/sign/src/pkcs12.rs b/crates/sign/src/pkcs12.rsnew file mode 100644index 000000000..3511462d2--- /dev/null+++ b/crates/sign/src/pkcs12.rs@@ -0,0 +1,407 @@+//! PKCS #12 digital ID files (RFC 7292): `.p12` / `.pfx`, as Acrobat, OpenSSL, macOS Keychain+//! and Windows export them.+//!+//! Reading supports PBES2 (PBKDF2 with HMAC-SHA-1/256/384/512; AES-128/192/256-CBC or+//! 3DES-CBC) and the legacy PKCS #12 PBE schemes (SHA-1 with 3DES or RC2), and checks the MAC.+//! Writing uses PBES2 AES-256-CBC with PBKDF2-HMAC-SHA-256 and an HMAC-SHA-256 MAC, OpenSSL 3's+//! defaults.++use cbc::cipher::block_padding::Pkcs7;+use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, InnerIvInit, KeyIvInit};+use hmac::Mac;++use crate::SignError;+use crate::der::{self, Tlv, tag};+use crate::keys::{DigestAlg, PrivateKey};+use crate::x509::Certificate;++const DATA: &str = "1.2.840.113549.1.7.1";+const ENCRYPTED_DATA: &str = "1.2.840.113549.1.7.6";+const KEY_BAG: &str = "1.2.840.113549.1.12.10.1.1";+const SHROUDED_KEY_BAG: &str = "1.2.840.113549.1.12.10.1.2";+const CERT_BAG: &str = "1.2.840.113549.1.12.10.1.3";+const X509_CERT: &str = "1.2.840.113549.1.9.22.1";+const FRIENDLY_NAME: &str = "1.2.840.113549.1.9.20";+const LOCAL_KEY_ID: &str = "1.2.840.113549.1.9.21";+const PBES2: &str = "1.2.840.113549.1.5.13";+const PBKDF2: &str = "1.2.840.113549.1.5.12";+const HMAC_SHA1: &str = "1.2.840.113549.2.7";+const HMAC_SHA256: &str = "1.2.840.113549.2.9";+const HMAC_SHA384: &str = "1.2.840.113549.2.10";+const HMAC_SHA512: &str = "1.2.840.113549.2.11";+const AES128_CBC: &str = "2.16.840.1.101.3.4.1.2";+const AES192_CBC: &str = "2.16.840.1.101.3.4.1.22";+const AES256_CBC: &str = "2.16.840.1.101.3.4.1.42";+const DES_EDE3_CBC: &str = "1.2.840.113549.3.7";+const PBE_SHA_3DES: &str = "1.2.840.113549.1.12.1.3";+const PBE_SHA_2DES: &str = "1.2.840.113549.1.12.1.4";+const PBE_SHA_RC2_128: &str = "1.2.840.113549.1.12.1.5";+const PBE_SHA_RC2_40: &str = "1.2.840.113549.1.12.1.6";++/// What a digital ID file holds: the signing key, its certificate and any others (issuers).+#[derive(Debug)]+pub struct DigitalId {+ pub key: PrivateKey,+ pub certificate: Certificate,+ /// The other certificates in the file (the chain), without the signer's.+ pub chain: Vec<Certificate>,+ pub friendly_name: Option<String>,+}++fn bad(what: &str) -> SignError {+ SignError::Malformed(format!("PKCS #12: {what}"))+}++/// The password as a BMPString with its terminating NUL (RFC 7292 Appendix B.1).+fn bmp(password: &str) -> Vec<u8> {+ let mut v: Vec<u8> = password.encode_utf16().flat_map(u16::to_be_bytes).collect();+ v.extend([0, 0]);+ v+}++/// The PKCS #12 key derivation function (RFC 7292 Appendix B.2).+fn pkcs12_kdf(alg: DigestAlg, password: &[u8], salt: &[u8], id: u8, iterations: u32, n: usize) -> Vec<u8> {+ let (u, v) = match alg {+ DigestAlg::Sha1 => (20, 64),+ DigestAlg::Sha256 => (32, 64),+ DigestAlg::Sha384 => (48, 128),+ DigestAlg::Sha512 => (64, 128),+ };+ let _ = u;+ let fill = |s: &[u8]| -> Vec<u8> {+ if s.is_empty() {+ return Vec::new();+ }+ let len = v * s.len().div_ceil(v);+ s.iter().cycle().take(len).copied().collect()+ };+ let d = vec![id; v];+ let mut i: Vec<u8> = [fill(salt), fill(password)].concat();+ let mut out = Vec::with_capacity(n);+ while out.len() < n {+ let mut a = alg.digest(&[&d, &i]);+ for _ in 1..iterations.max(1) {+ a = alg.digest(&[&a]);+ }+ let b: Vec<u8> = a.iter().cycle().take(v).copied().collect();+ for chunk in i.chunks_mut(v) {+ // chunk = (chunk + b + 1) mod 2^(8v)+ let mut carry = 1u16;+ for k in (0..v).rev() {+ let s = chunk[k] as u16 + b[k] as u16 + carry;+ chunk[k] = s as u8;+ carry = s >> 8;+ }+ }+ out.extend_from_slice(&a);+ }+ out.truncate(n);+ out+}++#[derive(Clone, Copy)]+enum Cipher {+ Aes128,+ Aes192,+ Aes256,+ TripleDes,+ Rc2(usize),+}++impl Cipher {+ fn key_len(self) -> usize {+ match self {+ Cipher::Aes128 => 16,+ Cipher::Aes192 => 24,+ Cipher::Aes256 => 32,+ Cipher::TripleDes => 24,+ Cipher::Rc2(bits) => bits / 8,+ }+ }++ fn decrypt(self, key: &[u8], iv: &[u8], ct: &[u8]) -> Result<Vec<u8>, SignError> {+ let wrong = || SignError::WrongPassword;+ let r = match self {+ Cipher::Aes128 => cbc::Decryptor::<aes::Aes128>::new_from_slices(key, iv).map_err(|_| wrong())?.decrypt_padded_vec::<Pkcs7>(ct),+ Cipher::Aes192 => cbc::Decryptor::<aes::Aes192>::new_from_slices(key, iv).map_err(|_| wrong())?.decrypt_padded_vec::<Pkcs7>(ct),+ Cipher::Aes256 => cbc::Decryptor::<aes::Aes256>::new_from_slices(key, iv).map_err(|_| wrong())?.decrypt_padded_vec::<Pkcs7>(ct),+ Cipher::TripleDes => cbc::Decryptor::<des::TdesEde3>::new_from_slices(key, iv).map_err(|_| wrong())?.decrypt_padded_vec::<Pkcs7>(ct),+ Cipher::Rc2(bits) => {+ let c = rc2::Rc2::new_with_eff_key_len(key, bits);+ cbc::Decryptor::<rc2::Rc2>::inner_iv_slice_init(c, iv).map_err(|_| wrong())?.decrypt_padded_vec::<Pkcs7>(ct)+ }+ };+ r.map_err(|_| wrong())+ }+}++fn hmac(alg: DigestAlg, key: &[u8], data: &[u8]) -> Vec<u8> {+ fn run<D: hmac::EagerHash>(key: &[u8], data: &[u8]) -> Vec<u8>+ where+ hmac::Hmac<D>: hmac::KeyInit + Mac,+ {+ let mut m = <hmac::Hmac<D> as hmac::KeyInit>::new_from_slice(key).expect("HMAC takes any key length");+ m.update(data);+ m.finalize().into_bytes().to_vec()+ }+ match alg {+ DigestAlg::Sha1 => run::<sha1::Sha1>(key, data),+ DigestAlg::Sha256 => run::<sha2::Sha256>(key, data),+ DigestAlg::Sha384 => run::<sha2::Sha384>(key, data),+ DigestAlg::Sha512 => run::<sha2::Sha512>(key, data),+ }+}++fn pbkdf2(prf: DigestAlg, password: &[u8], salt: &[u8], rounds: u32, len: usize) -> Vec<u8> {+ let mut out = vec![0u8; len];+ match prf {+ DigestAlg::Sha1 => pbkdf2::pbkdf2_hmac::<sha1::Sha1>(password, salt, rounds, &mut out),+ DigestAlg::Sha256 => pbkdf2::pbkdf2_hmac::<sha2::Sha256>(password, salt, rounds, &mut out),+ DigestAlg::Sha384 => pbkdf2::pbkdf2_hmac::<sha2::Sha384>(password, salt, rounds, &mut out),+ DigestAlg::Sha512 => pbkdf2::pbkdf2_hmac::<sha2::Sha512>(password, salt, rounds, &mut out),+ }+ out+}++/// Decrypt `ct` with the password-based scheme `alg` (an AlgorithmIdentifier).+fn pbe_decrypt(alg: &Tlv<'_>, password: &str, ct: &[u8]) -> Result<Vec<u8>, SignError> {+ let parts = alg.children()?;+ let o = parts.first().ok_or_else(|| bad("algorithm"))?.oid()?;+ let params = parts.get(1).ok_or_else(|| bad("algorithm parameters"))?;+ match o.as_str() {+ PBES2 => {+ let p = params.children()?;+ let [kdf, scheme] = p.as_slice() else { return Err(bad("PBES2 parameters")) };+ let kdf = kdf.children()?;+ if kdf.first().map(|o| o.oid()).transpose()?.as_deref() != Some(PBKDF2) {+ return Err(SignError::Unsupported("PBES2 key derivation other than PBKDF2".into()));+ }+ let kp = kdf.get(1).ok_or_else(|| bad("PBKDF2 parameters"))?.children()?;+ let salt = kp.first().ok_or_else(|| bad("salt"))?.expect(tag::OCTET_STRING, "salt")?.value;+ let rounds = kp.get(1).ok_or_else(|| bad("iterations"))?.u64()? as u32;+ let prf = match kp+ .iter()+ .skip(2)+ .find(|t| t.tag == tag::SEQUENCE)+ .and_then(|a| a.children().ok())+ .and_then(|a| a.first().and_then(|o| o.oid().ok()))+ {+ None => DigestAlg::Sha1,+ Some(o) => match o.as_str() {+ HMAC_SHA1 => DigestAlg::Sha1,+ HMAC_SHA256 => DigestAlg::Sha256,+ HMAC_SHA384 => DigestAlg::Sha384,+ HMAC_SHA512 => DigestAlg::Sha512,+ other => return Err(SignError::Unsupported(format!("PBKDF2 PRF {other}"))),+ },+ };+ let sc = scheme.children()?;+ let cipher = match sc.first().map(|o| o.oid()).transpose()?.as_deref() {+ Some(AES128_CBC) => Cipher::Aes128,+ Some(AES192_CBC) => Cipher::Aes192,+ Some(AES256_CBC) => Cipher::Aes256,+ Some(DES_EDE3_CBC) => Cipher::TripleDes,+ other => return Err(SignError::Unsupported(format!("PBES2 cipher {}", other.unwrap_or("?")))),+ };+ let iv = sc.get(1).ok_or_else(|| bad("IV"))?.expect(tag::OCTET_STRING, "IV")?.value;+ let key = pbkdf2(prf, password.as_bytes(), salt, rounds, cipher.key_len());+ cipher.decrypt(&key, iv, ct)+ }+ PBE_SHA_3DES | PBE_SHA_2DES | PBE_SHA_RC2_128 | PBE_SHA_RC2_40 => {+ let p = params.children()?;+ let salt = p.first().ok_or_else(|| bad("salt"))?.expect(tag::OCTET_STRING, "salt")?.value;+ let rounds = p.get(1).ok_or_else(|| bad("iterations"))?.u64()? as u32;+ let (cipher, key_len, iv_len) = match o.as_str() {+ PBE_SHA_3DES => (Cipher::TripleDes, 24, 8),+ PBE_SHA_2DES => (Cipher::TripleDes, 16, 8),+ PBE_SHA_RC2_128 => (Cipher::Rc2(128), 16, 8),+ _ => (Cipher::Rc2(40), 5, 8),+ };+ let pw = bmp(password);+ let mut key = pkcs12_kdf(DigestAlg::Sha1, &pw, salt, 1, rounds, key_len);+ if key.len() == 16 && matches!(cipher, Cipher::TripleDes) {+ // Two-key 3DES: K1 K2 K1.+ let k1 = key[..8].to_vec();+ key.extend(k1);+ }+ let iv = pkcs12_kdf(DigestAlg::Sha1, &pw, salt, 2, rounds, iv_len);+ cipher.decrypt(&key, &iv, ct)+ }+ other => Err(SignError::Unsupported(format!("PKCS #12 encryption {other}"))),+ }+}++struct Bag {+ kind: BagKind,+ local_key_id: Option<Vec<u8>>,+ friendly_name: Option<String>,+}++enum BagKind {+ Key(Vec<u8>),+ Cert(Vec<u8>),+}++fn bags(safe_contents: &[u8], password: &str, out: &mut Vec<Bag>) -> Result<(), SignError> {+ for bag in Tlv::parse_all(safe_contents)?.children()? {+ let f = bag.children()?;+ let Some(id) = f.first().and_then(|o| o.oid().ok()) else { continue };+ let Some(value) = f.get(1).filter(|v| v.tag == tag::ctx(0)).and_then(|v| v.inner().ok()) else { continue };+ let (mut local_key_id, mut friendly_name) = (None, None);+ if let Some(attrs) = f.get(2) {+ for a in attrs.children()? {+ let p = a.children()?;+ let v = p.get(1).and_then(|s| s.children().ok()).and_then(|s| s.into_iter().next());+ match (p.first().and_then(|o| o.oid().ok()).as_deref(), v) {+ (Some(LOCAL_KEY_ID), Some(v)) => local_key_id = Some(v.value.to_vec()),+ (Some(FRIENDLY_NAME), Some(v)) => friendly_name = v.text(),+ _ => {}+ }+ }+ }+ let kind = match id.as_str() {+ KEY_BAG => BagKind::Key(value.raw.to_vec()),+ SHROUDED_KEY_BAG => {+ let p = value.children()?;+ let [alg, data] = p.as_slice() else { return Err(bad("EncryptedPrivateKeyInfo")) };+ BagKind::Key(pbe_decrypt(alg, password, data.value)?)+ }+ CERT_BAG => {+ let p = value.children()?;+ if p.first().and_then(|o| o.oid().ok()).as_deref() != Some(X509_CERT) {+ continue;+ }+ let Some(c) = p.get(1).and_then(|c| c.inner().ok()) else { continue };+ BagKind::Cert(c.value.to_vec())+ }+ _ => continue,+ };+ out.push(Bag { kind, local_key_id, friendly_name });+ }+ Ok(())+}++/// Open a `.p12` / `.pfx` file. A wrong password is [`SignError::WrongPassword`].+pub fn open(bytes: &[u8], password: &str) -> Result<DigitalId, SignError> {+ let pfx = Tlv::parse_all(bytes).map_err(|_| bad("not a PKCS #12 file"))?.children()?;+ let auth_safe = pfx.get(1).ok_or_else(|| bad("authSafe"))?.children()?;+ if auth_safe.first().map(|o| o.oid()).transpose()?.as_deref() != Some(DATA) {+ return Err(SignError::Unsupported("public-key protected PKCS #12 files".into()));+ }+ let content = auth_safe.get(1).ok_or_else(|| bad("authSafe content"))?.inner()?.expect(tag::OCTET_STRING, "authSafe")?.value;+ // The MAC proves the password before anything is decrypted.+ if let Some(mac) = pfx.get(2) {+ let m = mac.children()?;+ let digest_info = m.first().ok_or_else(|| bad("MacData"))?.children()?;+ let alg = digest_info.first().ok_or_else(|| bad("MAC algorithm"))?.children()?;+ let alg_oid = alg.first().ok_or_else(|| bad("MAC algorithm"))?.oid()?;+ let alg = DigestAlg::from_oid(&alg_oid).ok_or_else(|| SignError::Unsupported(format!("MAC digest {alg_oid}")))?;+ let expected = digest_info.get(1).ok_or_else(|| bad("MAC"))?.value;+ let salt = m.get(1).ok_or_else(|| bad("MAC salt"))?.value;+ let iterations = m.get(2).map(|i| i.u64()).transpose()?.unwrap_or(1) as u32;+ let key_len = alg.digest(&[]).len();+ let key = pkcs12_kdf(alg, &bmp(password), salt, 3, iterations, key_len);+ if hmac(alg, &key, content) != expected {+ return Err(SignError::WrongPassword);+ }+ }+ let mut all = Vec::new();+ for ci in Tlv::parse_all(content)?.children()? {+ let p = ci.children()?;+ let kind = p.first().ok_or_else(|| bad("ContentInfo"))?.oid()?;+ let body = p.get(1).ok_or_else(|| bad("ContentInfo content"))?.inner()?;+ match kind.as_str() {+ DATA => bags(body.expect(tag::OCTET_STRING, "SafeContents")?.value, password, &mut all)?,+ ENCRYPTED_DATA => {+ let ed = body.children()?;+ let eci = ed.get(1).ok_or_else(|| bad("EncryptedContentInfo"))?.children()?;+ let alg = eci.get(1).ok_or_else(|| bad("content encryption algorithm"))?;+ let ct = match eci.get(2) {+ Some(t) if t.tag == tag::ctx_prim(0) => t.value.to_vec(),+ // Constructed form: a sequence of OCTET STRING segments.+ Some(t) if t.tag == tag::ctx(0) => t.children()?.iter().flat_map(|s| s.value.iter().copied()).collect(),+ _ => return Err(bad("encryptedContent")),+ };+ let plain = pbe_decrypt(alg, password, &ct)?;+ bags(&plain, password, &mut all)?;+ }+ _ => {}+ }+ }+ let key_bag = all.iter().find(|b| matches!(b.kind, BagKind::Key(_))).ok_or_else(|| bad("no private key"))?;+ let BagKind::Key(pkcs8) = &key_bag.kind else { unreachable!() };+ let key = PrivateKey::from_pkcs8(pkcs8)?;+ let certs: Vec<(Certificate, &Bag)> = all+ .iter()+ .filter_map(|b| match &b.kind {+ BagKind::Cert(c) => Certificate::parse(c).ok().map(|c| (c, b)),+ _ => None,+ })+ .collect();+ // The signer's certificate: the same local key id, else the one with the key's public key.+ let idx = certs+ .iter()+ .position(|(_, b)| key_bag.local_key_id.is_some() && b.local_key_id == key_bag.local_key_id)+ .or_else(|| certs.iter().position(|(c, _)| &c.public_key == key.public_key()))+ .ok_or_else(|| bad("no certificate for the private key"))?;+ let friendly_name = key_bag.friendly_name.clone().or_else(|| certs[idx].1.friendly_name.clone());+ let mut certs: Vec<Certificate> = certs.into_iter().map(|(c, _)| c).collect();+ let certificate = certs.remove(idx);+ if &certificate.public_key != key.public_key() {+ return Err(bad("the certificate does not match the private key"));+ }+ Ok(DigitalId { key, certificate, chain: certs, friendly_name })+}++fn random(n: usize) -> Result<Vec<u8>, SignError> {+ let mut v = vec![0u8; n];+ getrandom::fill(&mut v).map_err(|e| SignError::Crypto(format!("no randomness: {e}")))?;+ Ok(v)+}++/// Write a digital ID as a `.p12` protected by `password`.+pub fn write(id: &DigitalId, password: &str) -> Result<Vec<u8>, SignError> {+ const ITER: u32 = 2048;+ let encrypt = |plain: &[u8]| -> Result<Vec<u8>, SignError> {+ let (salt, iv) = (random(16)?, random(16)?);+ let key = pbkdf2(DigestAlg::Sha256, password.as_bytes(), &salt, ITER, 32);+ let ct = cbc::Encryptor::<aes::Aes256>::new_from_slices(&key, &iv)+ .map_err(|_| SignError::Crypto("AES".into()))?+ .encrypt_padded_vec::<Pkcs7>(plain);+ let kdf = der::seq(&[+ &der::oid(PBKDF2),+ &der::seq(&[&der::octets(&salt), &der::int(ITER as u64), &der::seq(&[&der::oid(HMAC_SHA256), &der::null()])]),+ ]);+ let alg = der::seq(&[&der::oid(PBES2), &der::seq(&[&kdf, &der::seq(&[&der::oid(AES256_CBC), &der::octets(&iv)])])]);+ Ok(der::seq(&[&alg, &der::octets(&ct)]))+ };+ let local_id = DigestAlg::Sha1.digest(&[&id.certificate.raw]);+ let mut attrs: Vec<Vec<u8>> = vec![der::seq(&[&der::oid(LOCAL_KEY_ID), &der::set_of(&[&der::octets(&local_id)])])];+ if let Some(n) = &id.friendly_name {+ let v: Vec<u8> = n.encode_utf16().flat_map(u16::to_be_bytes).collect();+ attrs.push(der::seq(&[&der::oid(FRIENDLY_NAME), &der::set_of(&[&der::tlv(tag::BMP_STRING, &v)])]));+ }+ let attr_refs: Vec<&[u8]> = attrs.iter().map(Vec::as_slice).collect();+ let attr_set = der::set_of(&attr_refs);+ let cert_bag = |c: &Certificate, with_attrs: bool| {+ let value = der::explicit(0, &der::seq(&[&der::oid(X509_CERT), &der::explicit(0, &der::octets(&c.raw))]));+ if with_attrs { der::seq(&[&der::oid(CERT_BAG), &value, &attr_set]) } else { der::seq(&[&der::oid(CERT_BAG), &value]) }+ };+ let mut cert_bags = vec![cert_bag(&id.certificate, true)];+ cert_bags.extend(id.chain.iter().map(|c| cert_bag(c, false)));+ let certs_plain = der::seq(&cert_bags.iter().map(Vec::as_slice).collect::<Vec<_>>());+ let enc_certs = encrypt(&certs_plain)?;+ // EncryptedData: version 0, EncryptedContentInfo { data, algorithm, [0] IMPLICIT ct }.+ let enc_parts = Tlv::parse_all(&enc_certs)?.children()?;+ let eci = der::seq(&[&der::oid(DATA), enc_parts[0].raw, &der::tlv(tag::ctx_prim(0), enc_parts[1].value)]);+ let encrypted_data = der::seq(&[&der::int(0), &eci]);+ let ci_certs = der::seq(&[&der::oid(ENCRYPTED_DATA), &der::explicit(0, &encrypted_data)]);+ let key_bag = der::seq(&[&der::oid(SHROUDED_KEY_BAG), &der::explicit(0, &encrypt(id.key.pkcs8())?), &attr_set]);+ let ci_key = der::seq(&[&der::oid(DATA), &der::explicit(0, &der::octets(&der::seq(&[&key_bag])))]);+ let auth_safe = der::seq(&[&ci_certs, &ci_key]);+ let salt = random(16)?;+ let mac_key = pkcs12_kdf(DigestAlg::Sha256, &bmp(password), &salt, 3, ITER, 32);+ let mac = hmac(DigestAlg::Sha256, &mac_key, &auth_safe);+ let mac_data = der::seq(&[&der::seq(&[&DigestAlg::Sha256.algorithm(), &der::octets(&mac)]), &der::octets(&salt), &der::int(ITER as u64)]);+ Ok(der::seq(&[&der::int(3), &der::seq(&[&der::oid(DATA), &der::explicit(0, &der::octets(&auth_safe))]), &mac_data]))+}diff --git a/crates/sign/src/x509.rs b/crates/sign/src/x509.rsnew file mode 100644index 000000000..786697957--- /dev/null+++ b/crates/sign/src/x509.rs@@ -0,0 +1,280 @@+//! X.509 certificates (RFC 5280): the fields signing and validation need, signature checks+//! along a chain, and a self-signed certificate builder for new digital IDs.++use crate::SignError;+use crate::der::{self, Time, Tlv, tag};+use crate::keys::{self, DigestAlg, PrivateKey, PublicKey};++const CN: &str = "2.5.4.3";+const C: &str = "2.5.4.6";+const O: &str = "2.5.4.10";+const OU: &str = "2.5.4.11";+const EMAIL: &str = "1.2.840.113549.1.9.1";++/// A distinguished name: (attribute OID, value) in order.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Name {+ pub attrs: Vec<(String, String)>,+ /// The DER encoding, compared byte for byte when matching issuers to subjects.+ pub raw: Vec<u8>,+}++impl Name {+ fn parse(t: &Tlv<'_>) -> Result<Name, SignError> {+ let mut attrs = Vec::new();+ for rdn in t.expect(tag::SEQUENCE, "Name")?.children()? {+ for atv in rdn.children()? {+ let parts = atv.children()?;+ if let [o, v] = parts.as_slice() {+ attrs.push((o.oid()?, v.text().unwrap_or_default()));+ }+ }+ }+ Ok(Name { attrs, raw: t.raw.to_vec() })+ }++ fn get(&self, oid: &str) -> Option<&str> {+ self.attrs.iter().find(|(o, _)| o == oid).map(|(_, v)| v.as_str())+ }++ pub fn common_name(&self) -> Option<&str> {+ self.get(CN)+ }++ pub fn organization(&self) -> Option<&str> {+ self.get(O)+ }++ pub fn unit(&self) -> Option<&str> {+ self.get(OU)+ }++ pub fn email(&self) -> Option<&str> {+ self.get(EMAIL)+ }++ pub fn country(&self) -> Option<&str> {+ self.get(C)+ }++ /// "CN=Ada Lovelace, O=Example, [email protected]"+ pub fn display(&self) -> String {+ self.attrs+ .iter()+ .map(|(o, v)| {+ let k = match o.as_str() {+ CN => "CN",+ C => "C",+ O => "O",+ OU => "OU",+ EMAIL => "E",+ "2.5.4.7" => "L",+ "2.5.4.8" => "ST",+ other => other,+ };+ format!("{k}={v}")+ })+ .collect::<Vec<_>>()+ .join(", ")+ }++ /// A name from its parts (empty ones left out), in the usual order.+ pub fn build(cn: &str, ou: &str, o: &str, email: &str, country: &str) -> Name {+ let mut rdns: Vec<Vec<u8>> = Vec::new();+ let mut attrs = Vec::new();+ let mut add = |oid: &str, enc: Vec<u8>, v: &str| {+ if !v.trim().is_empty() {+ rdns.push(der::set_of(&[&der::seq(&[&der::oid(oid), &enc])]));+ attrs.push((oid.to_string(), v.trim().to_string()));+ }+ };+ let country = country.trim().to_ascii_uppercase();+ if country.len() == 2 {+ add(C, der::printable(&country), &country);+ }+ add(O, der::utf8(o.trim()), o);+ add(OU, der::utf8(ou.trim()), ou);+ add(CN, der::utf8(cn.trim()), cn);+ add(EMAIL, der::ia5(email.trim()), email);+ let raw = der::tlv(tag::SEQUENCE, &rdns.concat());+ Name { attrs, raw }+ }+}++/// A parsed certificate.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Certificate {+ /// The whole DER encoding.+ pub raw: Vec<u8>,+ tbs: Vec<u8>,+ sig_alg: Vec<u8>,+ signature: Vec<u8>,+ pub serial: Vec<u8>,+ pub issuer: Name,+ pub subject: Name,+ pub not_before: Time,+ pub not_after: Time,+ pub public_key: PublicKey,+ /// Basic constraints: a CA certificate.+ pub is_ca: bool,+ /// Key usage bits (bit 0 = digitalSignature, 1 = nonRepudiation, 5 = keyCertSign), if present.+ pub key_usage: Option<u16>,+ pub subject_key_id: Option<Vec<u8>>,+}++impl Certificate {+ pub fn parse(raw: &[u8]) -> Result<Certificate, SignError> {+ let cert = Tlv::parse_all(raw)?.expect(tag::SEQUENCE, "Certificate")?;+ let parts = cert.children()?;+ let [tbs, sig_alg, sig] = parts.as_slice() else { return Err(SignError::Malformed("Certificate".into())) };+ let mut f = tbs.children()?.into_iter().peekable();+ if f.peek().is_some_and(|t| t.tag == tag::ctx(0)) {+ f.next();+ }+ let serial = f.next().ok_or_else(|| SignError::Malformed("serial".into()))?.expect(tag::INTEGER, "serial")?.value.to_vec();+ let _inner_alg = f.next();+ let issuer = Name::parse(&f.next().ok_or_else(|| SignError::Malformed("issuer".into()))?)?;+ let validity = f.next().ok_or_else(|| SignError::Malformed("validity".into()))?.children()?;+ let [nb, na] = validity.as_slice() else { return Err(SignError::Malformed("validity".into())) };+ let subject = Name::parse(&f.next().ok_or_else(|| SignError::Malformed("subject".into()))?)?;+ let public_key = PublicKey::from_spki(&f.next().ok_or_else(|| SignError::Malformed("public key".into()))?)?;+ let mut is_ca = false;+ let mut key_usage = None;+ let mut subject_key_id = None;+ for t in f {+ if t.tag != tag::ctx(3) {+ continue;+ }+ for ext in t.inner()?.children()? {+ let e = ext.children()?;+ let Some(o) = e.first().and_then(|o| o.oid().ok()) else { continue };+ let Some(value) = e.last().filter(|v| v.tag == tag::OCTET_STRING) else { continue };+ match o.as_str() {+ "2.5.29.19" => {+ is_ca = Tlv::parse_all(value.value)?.children()?.first().is_some_and(|b| b.tag == tag::BOOLEAN && b.value != [0]);+ }+ "2.5.29.15" => {+ let bits = Tlv::parse_all(value.value)?;+ let v = bits.value;+ if let Some((_, b)) = v.split_first() {+ // Bit 0 is the most significant bit of the first byte.+ let mut u = 0u16;+ for (i, byte) in b.iter().take(2).enumerate() {+ for j in 0..8 {+ if byte & (0x80 >> j) != 0 {+ u |= 1 << (i * 8 + j);+ }+ }+ }+ key_usage = Some(u);+ }+ }+ "2.5.29.14" => subject_key_id = Some(Tlv::parse_all(value.value)?.value.to_vec()),+ _ => {}+ }+ }+ }+ Ok(Certificate {+ raw: raw.to_vec(),+ tbs: tbs.raw.to_vec(),+ sig_alg: sig_alg.raw.to_vec(),+ signature: sig.bits()?.to_vec(),+ serial,+ issuer,+ subject,+ not_before: nb.time()?,+ not_after: na.time()?,+ public_key,+ is_ca,+ key_usage,+ subject_key_id,+ })+ }++ /// Issued by itself (subject = issuer and its own key verifies it).+ pub fn is_self_signed(&self) -> bool {+ self.issuer.raw == self.subject.raw && self.signed_by(&self.public_key)+ }++ /// Whether `key` verifies this certificate's signature.+ pub fn signed_by(&self, key: &PublicKey) -> bool {+ let Ok(alg) = Tlv::parse_all(&self.sig_alg) else { return false };+ let Ok((scheme, Some(digest))) = keys::signature_algorithm(&alg) else { return false };+ key.verify(scheme, digest, &digest.digest(&[&self.tbs]), &self.signature).unwrap_or(false)+ }++ /// Valid at `t`.+ pub fn valid_at(&self, t: Time) -> bool {+ self.not_before <= t && t <= self.not_after+ }++ /// The display name Acrobat uses: the common name, else the organization, else the DN.+ pub fn display_name(&self) -> String {+ self.subject.common_name().or(self.subject.organization()).map(str::to_string).unwrap_or_else(|| self.subject.display())+ }++ /// SHA-256 fingerprint as upper-case hex pairs.+ pub fn fingerprint(&self) -> String {+ DigestAlg::Sha256.digest(&[&self.raw]).iter().map(|b| format!("{b:02X}")).collect::<Vec<_>>().join(" ")+ }++ pub fn serial_hex(&self) -> String {+ self.serial.iter().map(|b| format!("{b:02X}")).collect()+ }++ /// A self-signed certificate for `key`: what Acrobat's "Create a new digital ID ▸ save to+ /// file" makes. Valid from `from` for `years`; usable for signing (digital signature and+ /// non-repudiation).+ pub fn self_signed(name: &Name, key: &PrivateKey, from: Time, years: u32, serial: &[u8]) -> Result<Certificate, SignError> {+ let alg = key.preferred_digest();+ let sig_alg = key.signature_algorithm(alg);+ let until = Time { year: from.year + years, ..from };+ let spki = key.public_key().spki();+ let ski = DigestAlg::Sha1.digest(&[&spki]);+ let ext = |o: &str, critical: bool, value: &[u8]| {+ if critical {+ der::seq(&[&der::oid(o), &der::boolean(true), &der::octets(value)])+ } else {+ der::seq(&[&der::oid(o), &der::octets(value)])+ }+ };+ // keyUsage: digitalSignature (bit 0) and nonRepudiation (bit 1) → 0b1100_0000, 6 unused bits.+ let key_usage = der::tlv(tag::BIT_STRING, &[6, 0b1100_0000]);+ let extensions = der::seq(&[+ &ext("2.5.29.15", true, &key_usage),+ &ext("2.5.29.14", false, &der::octets(&ski)),+ // extKeyUsage: emailProtection and Adobe's document signing (1.2.840.113583.1.1.5).+ &ext("2.5.29.37", false, &der::seq(&[&der::oid("1.3.6.1.5.5.7.3.4"), &der::oid("1.2.840.113583.1.1.5")])),+ ]);+ let tbs = der::seq(&[+ &der::explicit(0, &der::int(2)),+ &der::uint(serial),+ &sig_alg,+ &name.raw,+ &der::seq(&[&from.encode(), &until.encode()]),+ &name.raw,+ &spki,+ &der::explicit(3, &extensions),+ ]);+ let signature = key.sign(alg, &tbs)?;+ let cert = der::seq(&[&tbs, &sig_alg, &der::bit_string(&signature)]);+ Certificate::parse(&cert)+ }+}++/// The chain from `leaf` up through `pool`, as far as issuers can be found and their keys+/// verify the certificate below. Stops at a self-signed certificate.+pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate]) -> Vec<&'a Certificate> {+ let mut chain = vec![leaf];+ while chain.len() < 10 {+ let last = *chain.last().expect("non-empty");+ if last.issuer.raw == last.subject.raw {+ break;+ }+ let Some(issuer) = pool.iter().find(|c| c.subject.raw == last.issuer.raw && !chain.contains(c) && last.signed_by(&c.public_key)) else {+ break;+ };+ chain.push(issuer);+ }+ chain+}diff --git a/crates/sign/tests/crypto.rs b/crates/sign/tests/crypto.rsnew file mode 100644index 000000000..382824b25--- /dev/null+++ b/crates/sign/tests/crypto.rs@@ -0,0 +1,117 @@+//! The cryptographic core against files made by OpenSSL 3 (tests/data/README.md).++use printcraft_sign::der::Time;+use printcraft_sign::keys::DigestAlg;+use printcraft_sign::{Certificate, Name, PublicKey, SignError, cms, pkcs12};++fn data(name: &str) -> Vec<u8> {+ std::fs::read(format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"))).unwrap()+}++fn pem(name: &str) -> Vec<u8> {+ let text = String::from_utf8(data(name)).unwrap();+ let b64: String = text.lines().filter(|l| !l.starts_with("-----")).collect();+ decode_base64(&b64)+}++fn decode_base64(s: &str) -> Vec<u8> {+ let val = |c: u8| match c {+ b'A'..=b'Z' => c - b'A',+ b'a'..=b'z' => c - b'a' + 26,+ b'0'..=b'9' => c - b'0' + 52,+ b'+' => 62,+ _ => 63,+ };+ let bytes: Vec<u8> = s.bytes().filter(|c| *c != b'=').map(val).collect();+ bytes+ .chunks(4)+ .flat_map(|c| {+ let n = c.iter().enumerate().fold(0u32, |acc, (i, v)| acc | (*v as u32) << (18 - 6 * i));+ let k = c.len() * 6 / 8;+ (0..k).map(move |i| (n >> (16 - 8 * i)) as u8)+ })+ .collect()+}++#[test]+fn opens_every_openssl_flavour_of_pkcs12() {+ for (file, cn, key) in [+ ("rsa-aes.p12", "Test Signer RSA", "RSA 2048-bit"),+ ("rsa-legacy.p12", "Test Signer RSA", "RSA 2048-bit"),+ ("ec-p256.p12", "Test Signer EC", "ECDSA P-256"),+ ("ec-p384.p12", "Test Signer P384", "ECDSA P-384"),+ ("chain.p12", "Ada Lovelace", "RSA 2048-bit"),+ ] {+ let id = pkcs12::open(&data(file), "test").unwrap_or_else(|e| panic!("{file}: {e}"));+ assert_eq!(id.certificate.subject.common_name(), Some(cn), "{file}");+ assert_eq!(id.key.public_key().describe(), key, "{file}");+ assert_eq!(&id.certificate.public_key, id.key.public_key());+ assert!(matches!(pkcs12::open(&data(file), "nope"), Err(SignError::WrongPassword)), "{file}");+ }+ assert_eq!(pkcs12::open(&data("rsa-aes.p12"), "test").unwrap().friendly_name.as_deref(), Some("Test Signer RSA"));+ let chain = pkcs12::open(&data("chain.p12"), "test").unwrap();+ assert_eq!(chain.chain.len(), 1);+ assert_eq!(chain.certificate.subject.email(), Some("[email protected]"));+ assert!(chain.chain[0].is_ca && chain.chain[0].is_self_signed());+ assert!(chain.certificate.signed_by(&chain.chain[0].public_key), "the leaf is issued by the root");+ assert!(!chain.certificate.is_self_signed());+ assert_eq!(chain.certificate.key_usage.map(|u| u & 0b11), Some(0b11), "digitalSignature + nonRepudiation");+}++#[test]+fn certificates_parse_as_openssl_made_them() {+ let c = Certificate::parse(&pem("rsa.crt.pem")).unwrap();+ assert_eq!(c.subject.display(), "CN=Test Signer RSA, O=PrintCraft Tests, C=US");+ assert_eq!(c.serial_hex(), "03E9");+ assert!(c.is_self_signed());+ assert!(c.not_after.year >= c.not_before.year + 9);+ let ca = Certificate::parse(&pem("ca.crt.pem")).unwrap();+ assert!(ca.is_ca && ca.is_self_signed());+ assert!(matches!(ca.public_key, PublicKey::P256(_)));+}++#[test]+fn signatures_round_trip_for_every_key_type() {+ for file in ["rsa-aes.p12", "ec-p256.p12", "ec-p384.p12", "chain.p12"] {+ let id = pkcs12::open(&data(file), "test").unwrap();+ let alg = id.key.preferred_digest();+ let digest = alg.digest(&[b"the document bytes"]);+ let sig = cms::sign_detached(&id.key, &id.certificate, &id.chain, alg, &digest).unwrap();+ let mut padded = sig.clone();+ padded.extend([0u8; 64]);+ let sd = cms::SignedData::parse(&padded).unwrap();+ let signer = sd.signer_certificate().expect("the signer's certificate is embedded");+ assert_eq!(signer, &id.certificate);+ assert_eq!(sd.signer.message_digest.as_deref(), Some(&digest[..]));+ assert!(sd.signer.signing_certificate, "CAdES signing-certificate-v2");+ assert!(sd.verify_signature(signer, &digest), "{file}");+ assert_eq!(sd.certificates.len(), 1 + id.chain.len());+ // Tampering with the signature breaks it.+ let mut bad = sd.clone();+ bad.signer.signature[5] ^= 1;+ assert!(!bad.verify_signature(signer, &digest), "{file}");+ }+}++#[test]+fn new_digital_ids_are_self_signed_and_survive_a_p12_round_trip() {+ let name = Name::build("Grace Hopper", "Compilers", "Navy", "[email protected]", "us");+ let now = Time { year: 2026, month: 10, day: 2, hour: 12, minute: 0, second: 0 };+ for key in [printcraft_sign::PrivateKey::generate_rsa(2048).unwrap(), printcraft_sign::PrivateKey::generate_p256().unwrap()] {+ let cert = Certificate::self_signed(&name, &key, now, 5, &[0x42, 0x01]).unwrap();+ assert!(cert.is_self_signed());+ assert_eq!(cert.subject.display(), "C=US, O=Navy, OU=Compilers, CN=Grace Hopper, [email protected]");+ assert_eq!(cert.not_after.year, 2031);+ assert_eq!(cert.key_usage.map(|u| u & 0b11), Some(0b11));+ let id = pkcs12::DigitalId { key, certificate: cert, chain: Vec::new(), friendly_name: Some("Grace Hopper".into()) };+ let p12 = pkcs12::write(&id, "s3cret").unwrap();+ let back = pkcs12::open(&p12, "s3cret").unwrap();+ assert_eq!(back.certificate, id.certificate);+ assert_eq!(back.friendly_name.as_deref(), Some("Grace Hopper"));+ assert!(matches!(pkcs12::open(&p12, "wrong"), Err(SignError::WrongPassword)));+ let d = DigestAlg::Sha256.digest(&[b"x"]);+ let sig = cms::sign_detached(&back.key, &back.certificate, &[], DigestAlg::Sha256, &d).unwrap();+ let sd = cms::SignedData::parse(&sig).unwrap();+ assert!(sd.verify_signature(&back.certificate, &d));+ }+}diff --git a/crates/sign/tests/data/README.md b/crates/sign/tests/data/README.mdnew file mode 100644index 000000000..18524c7ee--- /dev/null+++ b/crates/sign/tests/data/README.md@@ -0,0 +1,35 @@+# Signing test data++Test-only keys and certificates, generated for these tests with OpenSSL 3. They protect nothing.+The password of every `.p12` is `test`.++| File | What |+|---|---|+| `rsa-aes.p12` | RSA 2048 self-signed "Test Signer RSA"; PBES2 AES-256-CBC, SHA-256 MAC (OpenSSL 3 default) |+| `rsa-legacy.p12` | the same key and certificate; RC2-40 certificates, 3DES key, SHA-1 MAC (`-legacy`) |+| `ec-p256.p12` | P-256 self-signed "Test Signer EC", no friendly name |+| `ec-p384.p12` | P-384 self-signed "Test Signer P384"; AES-128-CBC, SHA-1 MAC |+| `chain.p12` | RSA 2048 "Ada Lovelace" issued by a P-256 test root, chain included |+| `rsa.crt.pem`, `ca.crt.pem` | the RSA certificate and the test root alone |++Regenerate with:++```sh+openssl req -x509 -newkey rsa:2048 -nodes -keyout rsa.key -out rsa.crt -days 3650 -subj "/CN=Test Signer RSA/O=PrintCraft Tests/C=US" -set_serial 1001+openssl pkcs12 -export -inkey rsa.key -in rsa.crt -out rsa-aes.p12 -passout pass:test -name "Test Signer RSA"+openssl pkcs12 -export -legacy -inkey rsa.key -in rsa.crt -out rsa-legacy.p12 -passout pass:test -name "Test Signer RSA"+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout ec.key -out ec.crt -days 3650 -subj "/CN=Test Signer EC/O=PrintCraft Tests" -set_serial 2002+openssl pkcs12 -export -inkey ec.key -in ec.crt -out ec-p256.p12 -passout pass:test+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-384 -nodes -keyout ec3.key -out ec3.crt -days 3650 -subj "/CN=Test Signer P384" -set_serial 3003+openssl pkcs12 -export -inkey ec3.key -in ec3.crt -out ec-p384.p12 -passout pass:test -certpbe AES-128-CBC -keypbe AES-128-CBC -macalg sha1+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout ca.key -out ca.crt -days 3650 -subj "/CN=PrintCraft Test Root CA/O=PrintCraft Tests" -set_serial 1 -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign"+openssl req -newkey rsa:2048 -nodes -keyout leaf.key -out leaf.csr -subj "/CN=Ada Lovelace/O=PrintCraft Tests/[email protected]"+printf "basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature,nonRepudiation\n" > leaf.ext+openssl x509 -req -in leaf.csr -CA ca.crt -CAkey ca.key -set_serial 77 -days 3650 -extfile leaf.ext -out leaf.crt+openssl pkcs12 -export -inkey leaf.key -in leaf.crt -certfile ca.crt -out chain.p12 -passout pass:test -name "Ada Lovelace"+```++`openssl-signed.pdf` is a hand-written one-page PDF with a `/Contents` placeholder, signed with+`openssl cms -sign -binary -md sha256 -outform DER -signer rsa.crt -inkey rsa.key` over its+byte ranges (`adbe.pkcs7.detached`, with OpenSSL's signing-time attribute). It checks the+validator against a signature PrintCraft did not make; poppler's `pdfsig` reports it valid.diff --git a/crates/sign/tests/data/ca.crt.pem b/crates/sign/tests/data/ca.crt.pemnew file mode 100644index 000000000..2eb1f3618--- /dev/null+++ b/crates/sign/tests/data/ca.crt.pem@@ -0,0 +1,12 @@+-----BEGIN CERTIFICATE-----+MIIByzCCAXKgAwIBAgIBATAKBggqhkjOPQQDAjA9MSAwHgYDVQQDDBdQcmludENy+YWZ0IFRlc3QgUm9vdCBDQTEZMBcGA1UECgwQUHJpbnRDcmFmdCBUZXN0czAeFw0y+NjEwMDIwNjE3NDlaFw0zNjA5MjkwNjE3NDlaMD0xIDAeBgNVBAMMF1ByaW50Q3Jh+ZnQgVGVzdCBSb290IENBMRkwFwYDVQQKDBBQcmludENyYWZ0IFRlc3RzMFkwEwYH+KoZIzj0CAQYIKoZIzj0DAQcDQgAEHzN6qxrMUelog5zRgDla65Dp0XLVvK+0I/0M+uNhWDorE1CqrUrVqLkYBPSIWFfu36o0h5vF3RI0JBq932TsrS6NjMGEwHQYDVR0O+BBYEFENYzD54+vd7a43BOQZRdfvhb8DwMB8GA1UdIwQYMBaAFENYzD54+vd7a43B+OQZRdfvhb8DwMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqG+SM49BAMCA0cAMEQCIAR4KSUsZM8EG6IiDCtbVvF7aadd652Hbs5ZVguYAJYPAiAX+zSun5lH712+mzakkZtbfhuutsYYliZt84UuiSI+SpA==+-----END CERTIFICATE-----diff --git a/crates/sign/tests/data/chain.p12 b/crates/sign/tests/data/chain.p12new file mode 100644index 000000000..0cd7ab8c3Binary files /dev/null and b/crates/sign/tests/data/chain.p12 differdiff --git a/crates/sign/tests/data/ec-p256.p12 b/crates/sign/tests/data/ec-p256.p12new file mode 100644index 000000000..a859c7eb2Binary files /dev/null and b/crates/sign/tests/data/ec-p256.p12 differdiff --git a/crates/sign/tests/data/ec-p384.p12 b/crates/sign/tests/data/ec-p384.p12new file mode 100644index 000000000..14b5eb4bdBinary files /dev/null and b/crates/sign/tests/data/ec-p384.p12 differdiff --git a/crates/sign/tests/data/openssl-signed.pdf b/crates/sign/tests/data/openssl-signed.pdfnew file mode 100644index 000000000..85b7b800b--- /dev/null+++ b/crates/sign/tests/data/openssl-signed.pdf@@ -0,0 +1,40 @@+%PDF-1.7+1 0 obj+<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] /SigFlags 3 >> >>+endobj+2 0 obj+<< /Type /Pages /Kids [3 0 R] /Count 1 >>+endobj+3 0 obj+<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>+endobj+4 0 obj+<< /Length 46 >>+stream+BT /F1 14 Tf 20 250 Td (Signed by OpenSSL) Tj ET+endstream+endobj+5 0 obj+<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>+endobj+6 0 obj+<< /Type /Annot /Subtype /Widget /FT /Sig /T (OpenSSL) /Rect [0 0 0 0] /P 3 0 R /F 132 /V 7 0 R >>+endobj+7 0 obj+<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /M (D:20261002120000Z) /Reason (Oracle fixture) /ByteRange [0 766 17152 236 ] /Contents <308205E906092A864886F70D010702A08205DA308205D6020101310D300B0609608648016503040201300B06092A864886F70D010701A0820357308203533082023BA003020102020203E9300D06092A864886F70D01010B050030423118301606035504030C0F54657374205369676E65722052534131193017060355040A0C105072696E744372616674205465737473310B3009060355040613025553301E170D3236313030323036313733345A170D3336303932393036313733345A30423118301606035504030C0F54657374205369676E65722052534131193017060355040A0C105072696E744372616674205465737473310B300906035504061302555330820122300D06092A864886F70D01010105000382010F003082010A0282010100CBE14960A30AD858BD7301DACBD61437F2815DFDF9506277000EFE402B8E617A5421BFDCF019321BB80B8624FB72773794BCA818DD176558B24525E6AE768375889EA2951DA2D202C11181764210AA79B80790D139BA9D7008A995DCA64C4D6259D1E2A52FE69E91238E566028C171D7E625A8F1FBF611D20DD9562AAC97B4501BB81E4445C9BC5EB10ADCC7B77A090AF39724B45999EC2C6009011C8E1A87F3B48EB3165CBB27075EA81B59D0F233FD778BC0823AC1FD927762303B62AC2795F71DAACDF3433D07101291A4839143282EC07567A7CAACFC06617E4150A54C5E3E5BE9BE1CAB909DD1AEE44FC60CB82409ACB2224A8AD88BBA6F2C095F882DA10203010001A3533051301D0603551D0E0416041459098DD173D7761EF139CC9504B7DCA2D7D6F99F301F0603551D2304183016801459098DD173D7761EF139CC9504B7DCA2D7D6F99F300F0603551D130101FF040530030101FF300D06092A864886F70D01010B050003820101009B1FF9466ACD740894F2217BB203E9B5DA792A229555BDDF16B3B330FB06B7277B0670150ABCC75E325EF9DD8725CA8C3AC3714EF1AEE8D916B5A86D18CD4E2697B58A3A508C1C58259FD21DC23F31B2A6CD229919EA034296E00163F35CC5912FE97C5FC42D1BD5C29B6C85F26E7620BB5C62A206783B2F44D32493723486168D7B4C1914C2C043CF67AB4DE33386453450A071B7A10659D47AB8524EC3A48A7F51E3886C56D632437E2EA30B70A60A19D5EB13AE856BBAEB54038580512D5DABD840E63622B0683AB410B4B591220C130313A2B1C7191D17D5DFACC164B0A360CF001917875589E78BAC0A9812A836276C97F9725CE1CFB6538613CEFE42423182025830820254020101304830423118301606035504030C0F54657374205369676E65722052534131193017060355040A0C105072696E744372616674205465737473310B3009060355040613025553020203E9300B0609608648016503040201A081E4301806092A864886F70D010903310B06092A864886F70D010701301C06092A864886F70D010905310F170D3236313030323036333935335A302F06092A864886F70D01090431220420F533AB101C60E6648242F8AA828BD02B7932BC31C09D7F323397FD2A842528C4307906092A864886F70D01090F316C306A300B060960864801650304012A300B0609608648016503040116300B0609608648016503040102300A06082A864886F70D0307300E06082A864886F70D030202020080300D06082A864886F70D0302020140300706052B0E030207300D06082A864886F70D0302020128300D06092A864886F70D01010105000482010025BB738AE75E1B41169D57D62C9E1246E99DB874AC2D4A1240796556F46ADAEA041C111571B2EE8C26A1766B27C2D222BFF316B97D9FCE0B9BA8739289CD4A1E625D8390B27B00E524C0C47E24361489291CE7B2D36D733AFD1E5AC84CDD1721138BD88AF55F87C4422FB7484FAD9ED352E5E4290B382D0A9BB2B8B52EB5DA344F6AF84FC14A0948F5C2C62291805DA9798FCD81A8EB642B502E15F859860E415B863C3F6C312A37454C1C059A02A98F63C0F42CCE63B32A639C80743EB29CA4EC7CD518747D75F5C62D00DBCF301AD5FB843438DB3841DF1F3E8DA1E90A992D965FE6B3BC9393E58120EDBB1328A7900CD8A69B256AC43353902D56E898525E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000> >>+endobj+xref+0 8+0000000000 65535 f+0000000009 00000 n+0000000102 00000 n+0000000159 00000 n+0000000301 00000 n+0000000399 00000 n+0000000469 00000 n+0000000583 00000 n+trailer+<< /Size 8 /Root 1 0 R >>+startxref+17163+%%EOFdiff --git a/crates/sign/tests/data/rsa-aes.p12 b/crates/sign/tests/data/rsa-aes.p12new file mode 100644index 000000000..355e78127Binary files /dev/null and b/crates/sign/tests/data/rsa-aes.p12 differdiff --git a/crates/sign/tests/data/rsa-legacy.p12 b/crates/sign/tests/data/rsa-legacy.p12new file mode 100644index 000000000..32dc28d49Binary files /dev/null and b/crates/sign/tests/data/rsa-legacy.p12 differdiff --git a/crates/sign/tests/data/rsa.crt.pem b/crates/sign/tests/data/rsa.crt.pemnew file mode 100644index 000000000..d4db60a15--- /dev/null+++ b/crates/sign/tests/data/rsa.crt.pem@@ -0,0 +1,20 @@+-----BEGIN CERTIFICATE-----+MIIDUzCCAjugAwIBAgICA+kwDQYJKoZIhvcNAQELBQAwQjEYMBYGA1UEAwwPVGVz+dCBTaWduZXIgUlNBMRkwFwYDVQQKDBBQcmludENyYWZ0IFRlc3RzMQswCQYDVQQG+EwJVUzAeFw0yNjEwMDIwNjE3MzRaFw0zNjA5MjkwNjE3MzRaMEIxGDAWBgNVBAMM+D1Rlc3QgU2lnbmVyIFJTQTEZMBcGA1UECgwQUHJpbnRDcmFmdCBUZXN0czELMAkG+A1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDL4UlgowrY+WL1zAdrL1hQ38oFd/flQYncADv5AK45helQhv9zwGTIbuAuGJPtydzeUvKgY3Rdl+WLJFJeaudoN1iJ6ilR2i0gLBEYF2QhCqebgHkNE5up1wCKmV3KZMTWJZ0eKlL+ae+kSOOVmAowXHX5iWo8fv2EdIN2VYqrJe0UBu4HkRFybxesQrcx7d6CQrzlyS0WZns+LGAJARyOGofztI6zFly7JwdeqBtZ0PIz/XeLwII6wf2Sd2IwO2KsJ5X3HarN80M9+BxASkaSDkUMoLsB1Z6fKrPwGYX5BUKVMXj5b6b4cq5Cd0a7kT8YMuCQJrLIiSorY+i7pvLAlfiC2hAgMBAAGjUzBRMB0GA1UdDgQWBBRZCY3Rc9d2HvE5zJUEt9yi19b5+nzAfBgNVHSMEGDAWgBRZCY3Rc9d2HvE5zJUEt9yi19b5nzAPBgNVHRMBAf8EBTAD+AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCbH/lGas10CJTyIXuyA+m12nkqIpVVvd8W+s7Mw+wa3J3sGcBUKvMdeMl753Yclyow6w3FO8a7o2Ra1qG0YzU4ml7WKOlCMHFgl+n9Idwj8xsqbNIpkZ6gNCluABY/NcxZEv6XxfxC0b1cKbbIXybnYgu1xiogZ4Oy9E+0ySTcjSGFo17TBkUwsBDz2erTeMzhkU0UKBxt6EGWdR6uFJOw6SKf1HjiGxW1jJD+fi6jC3CmChnV6xOuhWu661QDhYBRLV2r2EDmNiKwaDq0ELS1kSIMEwMTorHHGR0X+1d+swWSwo2DPABkXh1WJ54usCpgSqDYnbJf5clzhz7ZThhPO/kJC+-----END CERTIFICATE-----diff --git a/crates/sign/tests/pdf.rs b/crates/sign/tests/pdf.rsnew file mode 100644index 000000000..0d2226897--- /dev/null+++ b/crates/sign/tests/pdf.rs@@ -0,0 +1,190 @@+//! Signing and validating whole documents.++use std::sync::Arc;++use printcraft_cos::{Document, Object, PdfString, SaveOptions, write_incremental};+use printcraft_sign::{Modification, SignOptions, Status, TrustStore, pkcs12, signatures};++fn data(name: &str) -> Vec<u8> {+ std::fs::read(format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"))).unwrap()+}++/// One page with text and an unsigned signature field "Approval".+fn fixture() -> Vec<u8> {+ let objs: Vec<&[u8]> = vec![+ b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] >> >>",+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>",+ b"<< /Length 44 >>\nstream\nBT /F1 14 Tf 20 250 Td (Contract text) Tj ET\nendstream",+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ b"<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /Rect [150 20 280 70] /P 3 0 R /F 4 >>",+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());+ out.extend_from_slice(o);+ out.extend_from_slice(b"\nendobj\n");+ }+ let xref = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+}++fn open(b: &[u8]) -> Document {+ Document::open(Arc::new(b.to_vec())).unwrap()+}++fn opts() -> SignOptions {+ SignOptions {+ page: 0,+ rect: Some([20.0, 100.0, 220.0, 150.0]),+ reason: Some("I approve this document".into()),+ location: Some("London".into()),+ date: "D:20261002120000+01'00'".into(),+ ..SignOptions::default()+ }+}++#[test]+fn signing_then_validating_with_and_without_trust() {+ for file in ["rsa-aes.p12", "ec-p256.p12", "ec-p384.p12", "chain.p12"] {+ let id = pkcs12::open(&data(file), "test").unwrap();+ let signed = printcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();+ assert!(signed.starts_with(&fixture()), "{file}: an incremental update");+ let doc = open(&signed);+ let sigs = signatures(&doc, &signed, &TrustStore::default());+ let s = sigs.iter().find(|s| s.signed).expect("a signed field");+ assert_eq!(s.field, "Signature1");+ assert_eq!(s.status, Status::Unknown, "{file}: {:?}", s.details);+ assert_eq!(s.modification, Modification::None);+ assert_eq!(s.signer.as_deref(), id.certificate.subject.common_name());+ assert_eq!((s.reason.as_deref(), s.location.as_deref(), s.page), (Some("I approve this document"), Some("London"), Some(0)));+ assert!(s.visible && s.signed_len == signed.len() && s.revision == 2);+ assert!(s.details.iter().any(|d| d.contains("identity is unknown")));+ // The unsigned field is listed too.+ assert!(sigs.iter().any(|s| s.field == "Approval" && !s.signed));+ // Trusting the signer (or its root) makes it valid.+ let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());+ let trusted = signatures(&doc, &signed, &TrustStore { certs: vec![anchor] });+ let s = trusted.iter().find(|s| s.signed).unwrap();+ assert_eq!(s.status, Status::Valid, "{file}: {:?}", s.details);+ assert_eq!(s.chain.len(), if file == "chain.p12" { 2 } else { 1 });+ // Changing one signed byte breaks it.+ let mut tampered = signed.clone();+ let i = tampered.windows(13).position(|w| w == b"Contract text").unwrap();+ tampered[i] = b'K';+ let s = signatures(&open(&tampered), &tampered, &TrustStore::default()).into_iter().find(|s| s.signed).unwrap();+ assert_eq!(s.status, Status::Invalid);+ assert!(s.details[0].contains("altered or corrupted"), "{:?}", s.details);+ }+}++#[test]+fn signing_an_existing_field_and_counter_signing() {+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();+ let first = printcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();+ let id2 = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();+ let second = printcraft_sign::sign(&open(&first), &id2, &opts()).unwrap();+ let doc = open(&second);+ let sigs = signatures(&doc, &second, &TrustStore::default());+ let a = sigs.iter().find(|s| s.field == "Approval").unwrap();+ assert!(a.signed);+ assert_eq!(a.rect, Some([150.0, 20.0, 280.0, 70.0]));+ assert_eq!(a.revision, 2);+ assert_eq!(a.modification, Modification::Allowed(vec!["signature".into()]), "{:?}", a.details);+ assert_eq!(a.status, Status::Unknown);+ let b = sigs.iter().find(|s| s.field == "Signature1").unwrap();+ assert_eq!((b.revision, b.modification.clone()), (3, Modification::None));+ assert!(matches!(+ printcraft_sign::sign(&doc, &id, &SignOptions { field: Some("Approval".into()), ..opts() }),+ Err(printcraft_sign::SignError::Pdf(_))+ ));+}++/// Append a revision that changes object `num` with `f`.+fn edit_after(signed: &[u8], f: impl FnOnce(&mut Document)) -> Vec<u8> {+ let mut doc = open(signed);+ f(&mut doc);+ write_incremental(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap()+}++fn add_comment(doc: &mut Document) {+ let mut d = printcraft_cos::Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name("Text"));+ d.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(10), Object::Int(10), Object::Int(30), Object::Int(30)]));+ d.set(b"Contents".to_vec(), PdfString::text("A note"));+ let r = doc.add(Object::Dict(d));+ let page = printcraft_cos::ObjRef { num: 3, generation: 0 };+ doc.update_dict(page, |p| {+ if let Some(Object::Array(a)) = p.get_mut(b"Annots") {+ a.push(Object::Ref(r));+ }+ })+ .unwrap();+}++fn change_text(doc: &mut Document) {+ let mut d = printcraft_cos::Dict::new();+ d.set(b"Length".to_vec(), Object::Int(40));+ let s = printcraft_cos::Stream::from_raw(d, b"BT /F1 14 Tf 20 250 Td (Other text) Tj ET".to_vec());+ doc.set(printcraft_cos::ObjRef { num: 4, generation: 0 }, Object::Stream(s));+}++#[test]+fn later_changes_are_classified_under_the_signature_permissions() {+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();+ let trust = TrustStore { certs: vec![id.certificate.clone()] };+ let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();+ // Approval signature: comments are permitted, rewriting page content is not.+ let signed = printcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();+ let s = check(&edit_after(&signed, add_comment));+ assert_eq!(s.status, Status::Valid, "{:?}", s.details);+ assert_eq!(s.modification, Modification::Allowed(vec!["comments".into()]));+ let s = check(&edit_after(&signed, change_text));+ assert_eq!(s.status, Status::Invalid);+ assert_eq!(s.modification, Modification::Disallowed(vec!["page content".into()]));+ // Certified with "no changes allowed": even a comment invalidates it.+ let certified = printcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();+ let s = check(&certified);+ assert_eq!((s.certify, s.status), (Some(1), Status::Valid));+ assert_eq!(check(&edit_after(&certified, add_comment)).status, Status::Invalid);+ // Certified allowing comments: fine.+ let certified3 = printcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(3), ..opts() }).unwrap();+ assert_eq!(check(&edit_after(&certified3, add_comment)).status, Status::Valid);+}++#[test]+fn invisible_signatures_and_refusals() {+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();+ let signed = printcraft_sign::sign(&open(&fixture()), &id, &SignOptions { rect: None, ..opts() }).unwrap();+ let s = signatures(&open(&signed), &signed, &TrustStore::default()).into_iter().find(|s| s.signed).unwrap();+ assert!(!s.visible);+ assert!(printcraft_sign::sign(&open(&fixture()), &id, &SignOptions { page: 5, ..opts() }).is_err());+ assert_eq!(printcraft_sign::pdf::display_date("D:20261002120000+01'00'"), "2026.10.02 12:00:00 +01'00'");+}++#[test]+fn validates_a_signature_made_by_openssl() {+ let bytes = data("openssl-signed.pdf");+ let doc = open(&bytes);+ let s = signatures(&doc, &bytes, &TrustStore::default()).into_iter().next().unwrap();+ assert_eq!((s.field.as_str(), s.sub_filter.as_deref()), ("OpenSSL", Some("adbe.pkcs7.detached")));+ assert_eq!(s.status, Status::Unknown, "{:?}", s.details);+ assert_eq!(s.signer.as_deref(), Some("Test Signer RSA"));+ assert!(s.signing_time.is_some_and(|t| t.year == 2026), "from the CMS signing-time attribute");+ assert!(!s.visible);+ let rsa = printcraft_sign::Certificate::parse(&pkcs12::open(&data("rsa-aes.p12"), "test").unwrap().certificate.raw).unwrap();+ let s = signatures(&doc, &bytes, &TrustStore { certs: vec![rsa] }).into_iter().next().unwrap();+ assert_eq!(s.status, Status::Valid, "{:?}", s.details);+ // A later comment is allowed for this approval signature.+ let edited = edit_after(&bytes, add_comment);+ let s = signatures(&open(&edited), &edited, &TrustStore::default()).into_iter().next().unwrap();+ assert_eq!(s.modification, Modification::Allowed(vec!["comments".into()]));+}diff --git a/deny.toml b/deny.tomlindex 5e010147d..61a8ec57d 100644--- a/deny.toml+++ b/deny.toml@@ -35,6 +35,13 @@ unknown-git = "deny"[advisories]yanked = "warn"+ignore = [+ # Marvin (RSA private-key timing side channel, no fixed `rsa` release). printcraft-sign uses+ # `rsa` only for public-key signature verification, which the advisory does not affect; RSA+ # private-key operations use aws-lc-rs on native targets and are refused in the browser+ # (ADR-0009). Revisit when a fixed `rsa` ships.+ { id = "RUSTSEC-2023-0071", reason = "rsa is used for verification only (ADR-0009)" },+]# egui's default UI fonts (Ubuntu-Light, Hack, emoji-icon-font): font licences on the AGENTS.md# §1.2 allowlist, attributed in ATTRIBUTION.toml as dependency-bundled assets.