From f6afe585ce13e9d9ea752e5979d180b2f67febb8 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Thu, 28 May 2026 23:10:52 -0600 Subject: [PATCH] ratkey: X.509 attestation chain verification RSA PKCS#1 v1.5 chain from the per-key/F9 attestation certs to a fingerprint-pinned Yubico root (legacy + new-PKI A/B/B2 intermediates bundled) with validity-window checks. chain_verified is set only on a real signature verification; no revocation/OCSP/name-constraints. Pending validation against a physical device's ATTEST output. --- Cargo.lock | 167 +++++ crates/rns-ratkey/Cargo.toml | 13 + crates/rns-ratkey/HARDWARE_STATUS.md | 9 +- .../yubico-attestation-intermediate-a-1.pem | 20 + .../yubico-attestation-intermediate-b-1.pem | 20 + .../certs/yubico-piv-attestation-a-1.pem | 20 + .../certs/yubico-piv-attestation-b-1.pem | 20 + .../certs/yubico-piv-attestation-b2-1.pem | 20 + crates/rns-ratkey/src/attestation.rs | 652 +++++++++++++++++- 9 files changed, 908 insertions(+), 33 deletions(-) create mode 100644 crates/rns-ratkey/certs/yubico-attestation-intermediate-a-1.pem create mode 100644 crates/rns-ratkey/certs/yubico-attestation-intermediate-b-1.pem create mode 100644 crates/rns-ratkey/certs/yubico-piv-attestation-a-1.pem create mode 100644 crates/rns-ratkey/certs/yubico-piv-attestation-b-1.pem create mode 100644 crates/rns-ratkey/certs/yubico-piv-attestation-b2-1.pem diff --git a/Cargo.lock b/Cargo.lock index 7255cc8..94017cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -550,9 +550,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", "zeroize", ] +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "digest" version = "0.10.7" @@ -560,6 +574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", "subtle", ] @@ -634,6 +649,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "fnv" version = "1.0.7" @@ -978,6 +999,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] [[package]] name = "leb128fmt" @@ -1006,6 +1030,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1091,6 +1121,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.5", + "smallvec", + "zeroize", +] + [[package]] name = "num-derive" version = "0.4.2" @@ -1102,6 +1148,26 @@ dependencies = [ "syn", ] +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1109,6 +1175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -1210,6 +1277,15 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "pin-project" version = "1.1.11" @@ -1236,6 +1312,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -1545,15 +1632,21 @@ name = "rns-ratkey" version = "0.9.4" dependencies = [ "aes", + "const-oid", + "der", "hex", "pcsc", + "rand 0.8.5", "rns-crypto", "rns-identity", "rns-link", + "rsa", "serde", + "sha2", "thiserror 2.0.18", "toml", "tracing", + "x509-cert", "zeroize", ] @@ -1639,6 +1732,27 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "sha2", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -1792,6 +1906,17 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sha2" version = "0.10.9" @@ -1828,6 +1953,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ + "digest", "rand_core 0.6.4", ] @@ -1863,6 +1989,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + [[package]] name = "spki" version = "0.7.3" @@ -1997,6 +2129,27 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "tokio" version = "1.50.0" @@ -2728,6 +2881,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid", + "der", + "sha1", + "signature", + "spki", + "tls_codec", +] + [[package]] name = "xml" version = "1.2.1" diff --git a/crates/rns-ratkey/Cargo.toml b/crates/rns-ratkey/Cargo.toml index d01aaa5..dd0ee90 100644 --- a/crates/rns-ratkey/Cargo.toml +++ b/crates/rns-ratkey/Cargo.toml @@ -17,10 +17,23 @@ zeroize = { workspace = true } aes = { workspace = true } toml = "0.8" +# X.509 attestation-chain verification (always compiled, not behind `hardware`). +x509-cert = { version = "0.2", features = ["pem"] } +rsa = "0.9" +# `oid` feature: lets RSA PKCS#1 v1.5 VerifyingKey build the DigestInfo prefix. +sha2 = { workspace = true, features = ["oid"] } +der = "0.7" +const-oid = "0.9" + [dev-dependencies] rns-crypto = { workspace = true, features = ["std"] } rns-identity = { workspace = true } rns-link = { path = "../rns-link" } +# Synthetic-chain test fixtures. +x509-cert = { version = "0.2", features = ["pem", "builder"] } +# `sha2` feature provides RsaSignatureAssociatedOid for the cert builder's signer. +rsa = { version = "0.9", features = ["sha2"] } +rand = { workspace = true } [features] default = [] diff --git a/crates/rns-ratkey/HARDWARE_STATUS.md b/crates/rns-ratkey/HARDWARE_STATUS.md index af1d117..c3882b9 100644 --- a/crates/rns-ratkey/HARDWARE_STATUS.md +++ b/crates/rns-ratkey/HARDWARE_STATUS.md @@ -37,9 +37,12 @@ Ed25519 (9A) / X25519 (9D): - **TDES management keys** are not supported (only AES-128/192/256). Pre-5.7 YubiKeys default to a TDES management key; provisioning those needs a `des` block cipher added to `mgmt.rs`. -- Cryptographic attestation certificate chain verification against the bundled - Yubico roots (`attestation.rs` is metadata/OID extraction only; `chain_verified` - is always false). +- Validate attestation-chain verification against a real device. `attestation.rs` + now does full RSA PKCS#1 v1.5 chain verification (per-key → device F9 → bundled, + fingerprint-pinned Yubico roots; legacy + new-PKI A/B/B2 intermediates bundled; + notBefore/notAfter checks; no CRL/OCSP/name-constraints). Exercised against + synthetic chains and the real published CA certs — not yet a physical YubiKey's + ATTEST output. - Edge cases on a real device: disconnect mid-operation, wrong PIN / lockout, touch timeout (if touch is ever enabled), and the `from_hwid` key-mismatch guard. - Decide and document the ratchet policy for hardware identities. PIV cannot hold diff --git a/crates/rns-ratkey/certs/yubico-attestation-intermediate-a-1.pem b/crates/rns-ratkey/certs/yubico-attestation-intermediate-a-1.pem new file mode 100644 index 0000000..069399b --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-attestation-intermediate-a-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSDCCAjCgAwIBAgIUUcmMXzRIFOgGTK0Tb3gEuZYZkBIwDQYJKoZIhvcNAQEL +BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy +MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0 +dGVzdGF0aW9uIEludGVybWVkaWF0ZSBBIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQDm555bWY9WW+tOY0rIWHldh+aNanoCZCFh7Gk3YZrQmPUw0hkS +G6qYHQtP+fZyS33VErvg+BQqnmumgNhfxFrkwEZELeidBcC8C4Ag4nqqiPWpzsvI +17NcxYlInLNLFcZY/+gOiN6ZOTihO5/vBZMbj9riaAcqliYmNGJPgTcMGaEAyMzE +MNy2nm6Ep+pjP5aF6gi21t/UQFsuJ1j2Rj/ynM/SdRt+ecal5OYotxHkFbL9vvv2 +A2Ov5ITZClw4bOS9npypQimOZ5QAYytmYaQpWl/pMYz6zSj8RqkVDNEJGqNfTKA2 +ivLYwX6lSttMPapg0J84l9X0voVN/FpS4VCVAgMBAAGjZjBkMB0GA1UdDgQWBBQg +KFAhG6RaW+hTy52dxeT8bC96HzAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm +8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG +9w0BAQsFAAOCAQEAYMzgLrJLIr0OovQnAZrRIGuabiHSUKSmbLRWpRkWeAtsChDE +HpXcJ/bgDNKYWoHqQ8xRUjB4CyepYevc3YlrG8o7zHxpfVcaoL5SeuJkzHxKn4bT +aSp9+Mvwamnp64kZMiNbFLknfP9kYKoRHkMWheRJ1UsP1z4ScmkCeILfsMs6vqov +qjWClFsJpBcsluYHWF7bBJ1n4Rwg+ATEopY4IgGv6Zvwc+A9r+AT2hqpoSkYoAl+ +ANYwgslOf9sJe0V+TA9YY/UlaBmPPTd0//r9wvcePWZkPjKoAC/zUNhfDbh4LV8G +Hs3lyX2XomL/LNc8JYzyIaDEhGQveoPhh/tr1g== +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/certs/yubico-attestation-intermediate-b-1.pem b/crates/rns-ratkey/certs/yubico-attestation-intermediate-b-1.pem new file mode 100644 index 0000000..72ee3d7 --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-attestation-intermediate-b-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSDCCAjCgAwIBAgIUDqERw+4RnGSggxgUewJFEPDRZ3YwDQYJKoZIhvcNAQEL +BQAwJDEiMCAGA1UEAwwZWXViaWNvIEF0dGVzdGF0aW9uIFJvb3QgMTAgFw0yNDEy +MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowLjEsMCoGA1UEAwwjWXViaWNvIEF0 +dGVzdGF0aW9uIEludGVybWVkaWF0ZSBCIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQDI7XnH+ZvDwMCQU8M8ZeV5qscublvVYaaRt3Ybaxn9godLx5sw +H0lXrdgjh5h7FpVgCgYYX7E4bl1vbzULemrMWT8N3WMGUe8QAJbBeioV7W/E+hTZ +P/0SKJVa3ewKBo6ULeMnfQZDrVORAk8wTLq2v5Llj5vMj7JtOotKa9J7nHS8kLmz +XXSaj0SwEPh5OAZUTNV4zs1bvoTAQQWrL4/J9QuKt6WCFE5nUNiRQcEbVF8mlqK2 +bx2z6okVltyDVLCxYbpUTELvY1usR3DTGPUoIClOm4crpwnDRLVHvjYePGBB//pE +yzxA/gcScxjwaH1ZUw9bnSbHyurKqbTa1KvjAgMBAAGjZjBkMB0GA1UdDgQWBBTq +t0KQngx7ZHrbVHwDunxOn9ihYTAfBgNVHSMEGDAWgBTS7u9aIo06bVwjlz3yhdUm +8SV7kjASBgNVHRMBAf8ECDAGAQH/AgECMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG +9w0BAQsFAAOCAQEAqQaCWMxTGqVVX7Sk7kkJmUueTSYKuU6+KBBSgwIRnlw9K7He +1IpxZ0hdwpPNikKjmcyFgFPzhImwHJgxxuT90Pw3vYOdcJJNktDg35PXOfzSn15c +FAx1RO0mPTmIb8dXiEWOpzoXvdwXDM41ZaCDYMT7w4IQtMyvE7xUBZq2bjtAnq/N +DUA7be4H8H3ipC+/+NKlUrcUh+j48K67WI0u1m6FeQueBA7n06j825rqDqsaLs9T +b7KAHAw8PmrWaNPG2kjKerxPEfecivlFawp2RWZvxrVtn3TV2SBxyCJCkXsND05d +CErVHSJIs+BdtTVNY9AwtyPmnyb0v4mSTzvWdw== +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/certs/yubico-piv-attestation-a-1.pem b/crates/rns-ratkey/certs/yubico-piv-attestation-a-1.pem new file mode 100644 index 0000000..e8d4226 --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-piv-attestation-a-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSTCCAjGgAwIBAgIUSiefkiKiicP9B63XwO7fKqevCkQwDQYJKoZIhvcNAQEL +BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBB +IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM +Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQSAxMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAyGCyrZjNrdPfChdDe4JWd+4TMLr8nbugcKJz12egglWi7oy5 +L9GT99/if9i1OrONdpEt0YrCa+qMb+dJJ0WUa8M5zXYnUDpn72vhFjH+Anb9P9+v ++ZrRqaj/jnR/MYP7NpVpeLHiH2dRCe/PX/NH1XE41GvdUEncDtqUUGaXUea0DfDY +McRDpPT2Qn5e8rn9FjzDA37SbOVuws5VlFTDzDdqR0FnqeWeIW0DFu17rzCqXcaB +VRDnQLTc5EEPDTpiRrQE/Ag+7Wg9ieLrueos75YMQ1EIkfjL49OBVogU1A7kwRGv +OnG8l7sYaY8LZ2b5FROe2hKqmsIy600qjn6b/QIDAQABo2YwZDAdBgNVHQ4EFgQU +hAuLXXtpQVBkcsbqyFlj6LVAadgwHwYDVR0jBBgwFoAUIChQIRukWlvoU8udncXk +/Gwveh8wEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI +hvcNAQELBQADggEBAFxL/2oFjxkLh2KVnFKdhy7Nf7MmEfYXDDFSx1rFDn445jHO +UP5kxQPbZc9r53jdvL5W0SQBqBjqA95PYh0r1CPMFsFJdiFXli8Hf3NQ0bTkeFSN +G3LsQCOKMb+o2WjYU3vHkRVjKgKGLxysxxKxGfMUcXdJ0qM6ZVeRHehC2zy7XuI6 +TQn7/V0ZHXjk7So7dUV55xQde094/3cCTnh9Q3j2aqMjkGx6tDboCsz/+W+tne7W +nMHG92ZiAAmOkP2bABjan461Qty/qBXPHomkfjqNbjUTluPXiMLYKCXHIyKwdkX6 +cphouSMU3QOTsb35Y2PeWNk54xu+Eds/3nhRMso= +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/certs/yubico-piv-attestation-b-1.pem b/crates/rns-ratkey/certs/yubico-piv-attestation-b-1.pem new file mode 100644 index 0000000..e2235bd --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-piv-attestation-b-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDSTCCAjGgAwIBAgIUWVf2oJG+t1qP8t8TicWgJ2KYan4wDQYJKoZIhvcNAQEL +BQAwLjEsMCoGA1UEAwwjWXViaWNvIEF0dGVzdGF0aW9uIEludGVybWVkaWF0ZSBC +IDEwIBcNMjQxMjAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMCUxIzAhBgNVBAMM +Gll1YmljbyBQSVYgQXR0ZXN0YXRpb24gQiAxMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAv7WBL9/5AKxSpCMoL63183WqRtFrOHY7tdyuGtoidoYWQrxV +aV9S+ZwH0aynh0IzD5A/PvCtuxdtL5w2cAI3tgsborOlEert4IZ904CZQfq3ooar +1an/wssbtMpPOQkC3MQiqrUyHlFS2BTbuwbBXY66lSVX/tGRuUgnBdfBJtcQKS6M +O4bU5ndPQqhGPyzcyY1LvlfzK7KJ1r/bixCRFqjhJRnPs0Czpg6rkRrFgC6cd5bK +1UgTsJy+3wrIqkv4CeV3EhSVnhnQjZgIrdIcI5WZ8T1Oq3OhMlWmY0K0dy/oZdP/ +bpbG2qbyHLa6gprLT/qChQWLmffxn6D2DAB1zQIDAQABo2YwZDAdBgNVHQ4EFgQU +M0Nt3QHo7eGzaKMZn2SmXT74vpcwHwYDVR0jBBgwFoAU6rdCkJ4Me2R621R8A7p8 +Tp/YoWEwEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZI +hvcNAQELBQADggEBAI0HwoS84fKMUyIof1LdUXvyeAMmEwW7+nVETvxNNlTMuwv7 +zPJ4XZAm9Fv95tz9CqZBj6l1PAPQn6Zht9LQA92OF7W7buuXuxuusBTgLM0C1iX2 +CGXqY/k/uSNvi3ZYfrpd44TIrfrr8bCG9ux7B5ZCRqb8adDUm92Yz3lK1aX2M6Cw +jC9IZVTXQWhLyP8Ys3p7rb20CO2jJzV94deJ/+AsEb+bnCQImPat1GDKwrBosar+ +BxtU7k6kgkxZ0G384O59GFXqnwkbw2b5HhORvOsX7nhOUhePFufzi1vT1g8Tzbwr ++TUfTwo2biKHHcI762KGtp8o6Bcv5y8WgExFuWY= +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/certs/yubico-piv-attestation-b2-1.pem b/crates/rns-ratkey/certs/yubico-piv-attestation-b2-1.pem new file mode 100644 index 0000000..935b09c --- /dev/null +++ b/crates/rns-ratkey/certs/yubico-piv-attestation-b2-1.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDRjCCAjCgAwIBAgIUM6Hs259YBTYRAMg98ZZlv/CDyO0wCwYJKoZIhvcNAQEL +MC4xLDAqBgNVBAMMI1l1YmljbyBBdHRlc3RhdGlvbiBJbnRlcm1lZGlhdGUgQiAx +MCAXDTI1MDgwMTAwMDAwMFoYDzk5OTkxMjMxMjM1OTU5WjAmMSQwIgYDVQQDDBtZ +dWJpY28gUElWIEF0dGVzdGF0aW9uIEIyIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQCxqNa82XHPD/QMqYffF8K4a9aoJIV7SU9NKXu3hBh+6nF0/HPP +UtSu/ChTdPoCk1Li2Sz7gkWzijJVCCSo6uRgRT2sUoTb8xjKo80N5QxAC3TVNRpA +lGh4Ba5KxamnXrf6s78tB73oTlTkMBUehVwvbQZGRpst00w58SxDP0nF7rO6qF+h +8M+kV4ycd8zUssMq6yxWhDAUZ+gT4l0SwvBEvUiJ8q7phFGJPyMjrKy1bifC50GW +xdLLJq7WRswaNxOsQ8hqJVRsoQ9pnZDCvo2WRkTzi3UrPPp5Soyy+aUOlNs0gwFu +07H75Gnswet+wffpeDFXZM2ITH3SN0LrpairAgMBAAGjZjBkMB0GA1UdDgQWBBSe +IRwEGD3d5SgceJxQn/ztOZHuVjAfBgNVHSMEGDAWgBTqt0KQngx7ZHrbVHwDunxO +n9ihYTASBgNVHRMBAf8ECDAGAQH/AgEBMA4GA1UdDwEB/wQEAwIBhjALBgkqhkiG +9w0BAQsDggEBAKK+IxeMsYsfqbLZ/Ld82tHWddLLlbXBaQojmRSDNHlBGbOvuQZg +rnbafjIEyb+Uv1+TdJnn5cV1P/MBSfJLBPqBuhKZ3lk4460CWRmcIKsxVRe0V5+V +bGCzLKpWtlrEBVkFTSbBQk4FQNVYw5pR4UzRIambsRyyGsyN0gppGyxyCqAR8/Od +GI+sUWh+VxFSlSpvaDT9GBGBN6eG0WMAZlEdu9k/tphesazHeK6MvXP6tBnb4DCd +09DUZeon7D8m1drYyw5kOjqgm1E3HPkNx4856iTdY7nAuVQ++i0hUhaJpc/5HZbw +wdlqXnmZ+XRIGSDLn2KKoxSWziowEvlU+04= +-----END CERTIFICATE----- diff --git a/crates/rns-ratkey/src/attestation.rs b/crates/rns-ratkey/src/attestation.rs index cc10089..769c97b 100644 --- a/crates/rns-ratkey/src/attestation.rs +++ b/crates/rns-ratkey/src/attestation.rs @@ -1,20 +1,51 @@ -//! YubiKey PIV attestation verification. Bundled root CAs — never fetched. +//! YubiKey PIV attestation verification. Bundled root CAs — never fetched at runtime. //! //! Legacy chain (firmware < 5.7.4): -//! Yubico PIV Root CA Serial 263751 → device intermediate (slot F9) → per-key attestation cert. +//! per-key attestation cert → device intermediate (slot F9) +//! → `Yubico PIV Root CA Serial 263751` (bundled root). //! //! New chain (firmware >= 5.7.4): -//! Yubico Attestation Root 1 → Intermediate A/B 1 → PIV Attestation A/B 1 -//! → device intermediate (slot F9) → per-key attestation cert. +//! per-key attestation cert → device intermediate (slot F9) +//! → `Yubico PIV Attestation {A,B,B2} 1` (bundled intermediate) +//! → `Yubico Attestation Intermediate {A,B} 1` (bundled intermediate) +//! → `Yubico Attestation Root 1` (bundled root). +//! The two tiers of intermediate CAs are not present on the device; they are +//! bundled here from Yubico's published attestation PKI (yubico-intermediate.pem). +//! Both A and B branches plus the 2025 B2 PIV intermediate are bundled, so any +//! firmware-5.7.4+ YubiKey PIV attestation chains to the bundled root. //! //! Nitrokey 3 does not support PIV attestation (firmware 1.8) — verification skipped. //! -//! Chain verification status: structural + OID extraction only. The -//! `verified` flag remains false until X.509 path validation is exercised -//! against real devices. See crates/rns-ratkey/HARDWARE_STATUS.md. +//! ## What `chain_verified == true` means here +//! +//! Every link from the per-key attestation cert up to (and including) a bundled +//! trust anchor has a valid RSA PKCS#1 v1.5 signature (issuer public key over the +//! child's TBS bytes), the terminal issuer's DER SHA-256 matches a pinned +//! fingerprint constant, and every certificate in the walked path is inside its +//! notBefore/notAfter validity window at verification time. +//! +//! ## Explicit non-goals (NOT checked) +//! +//! Revocation (CRL/OCSP), name constraints, basicConstraints/keyUsage/pathlen +//! enforcement, and the remainder of RFC 5280 path validation are intentionally +//! out of scope. The root's own self-signature is not verified — the root is +//! trusted by pinned fingerprint plus validity window. All required chain links +//! are sha256WithRSAEncryption; the per-cert signature OID is still inspected so +//! a sha512WithRSA link would be honored rather than silently mis-verified. use crate::error::RatkeyError; +use const_oid::ObjectIdentifier; +use der::Encode; +use rsa::RsaPublicKey; +use rsa::pkcs1::DecodeRsaPublicKey; +use rsa::pkcs1v15::{Signature as RsaSignature, VerifyingKey}; +use sha2::{Digest, Sha256, Sha512}; +use rsa::signature::Verifier; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use x509_cert::Certificate; +use x509_cert::der::Decode; + /// Yubico PIV Root CA (legacy, firmware < 5.7.4). Subject: "Yubico PIV Root CA Serial 263751". pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str = include_str!("../certs/yubico-piv-root-ca-legacy.pem"); @@ -23,9 +54,20 @@ pub const YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str = pub const YUBICO_ATTESTATION_ROOT_1_PEM: &str = include_str!("../certs/yubico-attestation-root-1.pem"); +// New-PKI intermediates (firmware >= 5.7.4). Bundled from Yubico's published +// yubico-intermediate.pem. A, B, and the 2025 B2 PIV branches are all covered. +const YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM: &str = + include_str!("../certs/yubico-attestation-intermediate-a-1.pem"); +const YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM: &str = + include_str!("../certs/yubico-attestation-intermediate-b-1.pem"); +const YUBICO_PIV_ATTESTATION_A_1_PEM: &str = include_str!("../certs/yubico-piv-attestation-a-1.pem"); +const YUBICO_PIV_ATTESTATION_B_1_PEM: &str = include_str!("../certs/yubico-piv-attestation-b-1.pem"); +const YUBICO_PIV_ATTESTATION_B2_1_PEM: &str = + include_str!("../certs/yubico-piv-attestation-b2-1.pem"); + /// SHA-256 fingerprint of the legacy Yubico PIV Root CA (belt-and-suspenders vs PEM swap). pub const YUBICO_LEGACY_ROOT_SHA256: &str = - "63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced73833120785b546"; + "63ece914e54dd87915f34033c85af4c0696ba1512f8add66ced738331207b546"; /// SHA-256 fingerprint of the new Yubico Attestation Root 1 (belt-and-suspenders vs PEM swap). pub const YUBICO_NEW_ROOT_SHA256: &str = @@ -46,6 +88,13 @@ pub const OID_USAGE_POLICY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, /// Form factor (1 byte). pub const OID_FORM_FACTOR: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xC4, 0x0A, 0x03, 0x09]; +// Signature algorithm OIDs (PKCS#1). +const OID_SHA256_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11"); +const OID_SHA512_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13"); + +// Guard against issuer cycles in a malformed/hostile pool. +const MAX_CHAIN_DEPTH: usize = 8; + #[derive(Debug, Clone)] pub struct AttestationInfo { pub firmware_version: Option<(u8, u8, u8)>, @@ -73,8 +122,12 @@ pub struct AttestationVerification { pub description: String, } -/// Verify chain: attestation cert (from ATTEST) + device intermediate (slot F9). -/// Currently structural + OID extraction only. +/// Verify chain: attestation cert (from ATTEST F9) + device intermediate (slot F9). +/// +/// Sets `verified`/`chain_verified == true` only when every signature from the +/// per-key cert up to a bundled, fingerprint-pinned Yubico root validates and +/// all walked certs are inside their validity window. See module docs for the +/// precise meaning and the explicit non-goals. pub fn verify_attestation( attestation_cert_der: &[u8], device_cert_der: &[u8], @@ -82,7 +135,6 @@ pub fn verify_attestation( let info = extract_attestation_info(attestation_cert_der, device_cert_der)?; let metadata_extracted = info.firmware_version.is_some(); - let chain_verified = false; let root_ca = if let Some((major, minor, patch)) = info.firmware_version { if major > 5 || (major == 5 && minor >= 7 && patch >= 4) { "new".to_string() @@ -93,17 +145,23 @@ pub fn verify_attestation( "unknown".to_string() }; - let description = if metadata_extracted { - let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0)); - format!( - "YubiKey firmware {maj}.{min}.{pat}{}; attestation chain not cryptographically verified", - info.serial_number - .map(|s| format!(", serial {s}")) - .unwrap_or_default() - ) - } else { - "could not extract YubiKey attestation metadata".to_string() - }; + let anchors = bundled_trust_anchors(); + let pool = bundled_intermediate_pool(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + + let chain_result = verify_chain( + attestation_cert_der, + device_cert_der, + &anchors, + &pool, + now, + ); + + let chain_verified = chain_result.is_ok(); + + let description = build_description(metadata_extracted, &info, &chain_result); Ok(AttestationVerification { verified: chain_verified, @@ -115,11 +173,250 @@ pub fn verify_attestation( }) } +fn build_description( + metadata_extracted: bool, + info: &AttestationInfo, + chain_result: &Result<(), ChainError>, +) -> String { + let prefix = if metadata_extracted { + let (maj, min, pat) = info.firmware_version.unwrap_or((0, 0, 0)); + format!( + "YubiKey firmware {maj}.{min}.{pat}{}", + info.serial_number + .map(|s| format!(", serial {s}")) + .unwrap_or_default() + ) + } else { + "could not extract YubiKey attestation metadata".to_string() + }; + + match chain_result { + Ok(()) => format!("{prefix}; attestation chain cryptographically verified to bundled Yubico root"), + Err(e) => format!("{prefix}; attestation chain not verified: {e}"), + } +} + /// YubiKey 5 (firmware >= 4.3.0) only. Nitrokey 3 has no PIV attestation. pub fn supports_attestation(device_type: &str) -> bool { device_type == "yubikey5" } +// --------------------------------------------------------------------------- +// Chain verification +// --------------------------------------------------------------------------- + +/// A parsed trust anchor. Only included after its DER SHA-256 matched a pinned +/// fingerprint constant (see `bundled_trust_anchors`), so reaching one is the +/// terminal trust condition. +#[derive(Clone)] +struct TrustAnchor { + cert: Certificate, +} + +#[derive(Debug)] +enum ChainError { + ParseLeaf, + ParseDevice, + IssuerNotFound, + SignatureInvalid, + Expired, + UnsupportedSignatureAlg(String), + BadPublicKey, + DepthExceeded, +} + +impl std::fmt::Display for ChainError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ChainError::ParseLeaf => write!(f, "attestation certificate did not parse as X.509"), + ChainError::ParseDevice => write!(f, "device (slot F9) certificate did not parse as X.509"), + ChainError::IssuerNotFound => { + write!(f, "no bundled/known issuer found for a certificate in the chain") + } + ChainError::SignatureInvalid => write!(f, "a certificate signature failed to verify"), + ChainError::Expired => write!(f, "a certificate is outside its validity window"), + ChainError::UnsupportedSignatureAlg(oid) => { + write!(f, "unsupported certificate signature algorithm {oid}") + } + ChainError::BadPublicKey => write!(f, "issuer public key could not be decoded as RSA"), + ChainError::DepthExceeded => write!(f, "chain exceeded maximum depth"), + } + } +} + +/// Bundled, fingerprint-pinned roots. A cert is only a valid terminal if its DER +/// SHA-256 matches one of these constants — guarding against a swapped PEM. +fn bundled_trust_anchors() -> Vec { + let mut anchors = Vec::new(); + for (pem, fp) in [ + (YUBICO_PIV_ROOT_CA_LEGACY_PEM, YUBICO_LEGACY_ROOT_SHA256), + (YUBICO_ATTESTATION_ROOT_1_PEM, YUBICO_NEW_ROOT_SHA256), + ] { + if let Some(der) = pem_to_der(pem) { + if hex::encode(Sha256::digest(&der)) == fp { + if let Ok(cert) = Certificate::from_der(&der) { + anchors.push(TrustAnchor { cert }); + } + } + } + } + anchors +} + +/// Bundled intermediate CAs (new-PKI A/B/B2 branches). Searchable issuers only — +/// never terminal trust anchors. +fn bundled_intermediate_pool() -> Vec { + [ + YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM, + YUBICO_ATTESTATION_INTERMEDIATE_B_1_PEM, + YUBICO_PIV_ATTESTATION_A_1_PEM, + YUBICO_PIV_ATTESTATION_B_1_PEM, + YUBICO_PIV_ATTESTATION_B2_1_PEM, + ] + .into_iter() + .filter_map(|pem| pem_to_der(pem).and_then(|der| Certificate::from_der(&der).ok())) + .collect() +} + +/// Walk from the leaf up to a pinned anchor, verifying each signature and every +/// cert's validity window. `now` is seconds since the Unix epoch. +fn verify_chain( + attestation_cert_der: &[u8], + device_cert_der: &[u8], + anchors: &[TrustAnchor], + intermediates: &[Certificate], + now: Duration, +) -> Result<(), ChainError> { + let leaf = Certificate::from_der(attestation_cert_der).map_err(|_| ChainError::ParseLeaf)?; + let device = Certificate::from_der(device_cert_der).map_err(|_| ChainError::ParseDevice)?; + + // Searchable issuers: the device F9 cert plus all bundled intermediates. + let mut searchable: Vec<&Certificate> = Vec::with_capacity(intermediates.len() + 1); + searchable.push(&device); + for c in intermediates { + searchable.push(c); + } + + check_validity(&leaf, now)?; + + let mut current = leaf.clone(); + let mut current_der = attestation_cert_der.to_vec(); + for _ in 0..MAX_CHAIN_DEPTH { + // Terminal: is `current` signed by a pinned anchor? + for anchor in anchors { + // `anchor` is trusted only because its DER SHA-256 matched a pinned + // constant in bundled_trust_anchors(); its self-signature is not checked. + if names_match(&anchor.cert.tbs_certificate.subject, ¤t.tbs_certificate.issuer) + && verify_signature(¤t, &anchor.cert).is_ok() + { + check_validity(&anchor.cert, now)?; + return Ok(()); + } + } + + // A self-issued cert that is not a pinned anchor is an untrusted root: + // the chain terminates here without reaching a trust anchor. (Anchors are + // checked above, so reaching this point means it is not pinned.) + if names_match(¤t.tbs_certificate.subject, ¤t.tbs_certificate.issuer) { + return Err(ChainError::IssuerNotFound); + } + + // Otherwise advance one link via a searchable (non-anchor) issuer. + let issuer = searchable.iter().copied().find(|cand| { + names_match(&cand.tbs_certificate.subject, ¤t.tbs_certificate.issuer) + && verify_signature(¤t, cand).is_ok() + }); + + match issuer { + Some(issuer_cert) => { + check_validity(issuer_cert, now)?; + let issuer_der = issuer_cert.to_der().map_err(|_| ChainError::IssuerNotFound)?; + // Cycle guard: a non-self-issued cert pointing back at itself. + if issuer_der == current_der { + return Err(ChainError::IssuerNotFound); + } + current = issuer_cert.clone(); + current_der = issuer_der; + } + None => { + // No pinned anchor and no searchable issuer signs `current`. + // Distinguish "issuer present but bad signature" for diagnostics. + let issuer_present = anchors + .iter() + .any(|a| names_match(&a.cert.tbs_certificate.subject, ¤t.tbs_certificate.issuer)) + || searchable.iter().any(|c| { + names_match(&c.tbs_certificate.subject, ¤t.tbs_certificate.issuer) + }); + return Err(if issuer_present { + ChainError::SignatureInvalid + } else { + ChainError::IssuerNotFound + }); + } + } + } + + Err(ChainError::DepthExceeded) +} + +/// RFC 5280 distinguished-name match via canonical DER encoding of the Name. +fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool { + match (a.to_der(), b.to_der()) { + (Ok(da), Ok(db)) => da == db, + _ => false, + } +} + +/// Verify `child`'s signature using `issuer`'s public key (RSA PKCS#1 v1.5). +fn verify_signature(child: &Certificate, issuer: &Certificate) -> Result<(), ChainError> { + let tbs = child + .tbs_certificate + .to_der() + .map_err(|_| ChainError::SignatureInvalid)?; + + let sig_bytes = child + .signature + .as_bytes() + .ok_or(ChainError::SignatureInvalid)?; + let sig = RsaSignature::try_from(sig_bytes).map_err(|_| ChainError::SignatureInvalid)?; + + let spki_key = issuer + .tbs_certificate + .subject_public_key_info + .subject_public_key + .as_bytes() + .ok_or(ChainError::BadPublicKey)?; + let pubkey = RsaPublicKey::from_pkcs1_der(spki_key).map_err(|_| ChainError::BadPublicKey)?; + + let alg = child.signature_algorithm.oid; + if alg == OID_SHA256_RSA { + VerifyingKey::::new(pubkey) + .verify(&tbs, &sig) + .map_err(|_| ChainError::SignatureInvalid) + } else if alg == OID_SHA512_RSA { + VerifyingKey::::new(pubkey) + .verify(&tbs, &sig) + .map_err(|_| ChainError::SignatureInvalid) + } else { + Err(ChainError::UnsupportedSignatureAlg(alg.to_string())) + } +} + +/// Reject certs outside their notBefore/notAfter window at time `now`. +fn check_validity(cert: &Certificate, now: Duration) -> Result<(), ChainError> { + let nb = cert.tbs_certificate.validity.not_before.to_unix_duration(); + let na = cert.tbs_certificate.validity.not_after.to_unix_duration(); + if now < nb || now > na { + Err(ChainError::Expired) + } else { + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// OID metadata extraction (byte-scan; unchanged behavior) +// --------------------------------------------------------------------------- + fn extract_attestation_info( attestation_cert_der: &[u8], device_cert_der: &[u8], @@ -379,8 +676,9 @@ mod tests { } #[test] - fn test_verify_attestation_synthetic() { - // Build a minimal attestation cert with firmware OID + fn test_verify_attestation_synthetic_metadata() { + // Minimal attestation cert with firmware OID; not a real X.509 cert, so the + // chain cannot verify — exercises metadata extraction + graceful chain failure. let mut attest_der = Vec::new(); let mut inner = Vec::new(); inner.push(0x06); @@ -394,7 +692,6 @@ mod tests { attest_der.push(inner.len() as u8); attest_der.extend_from_slice(&inner); - // Minimal device cert (just a SEQUENCE) let device_der = vec![0x30, 0x00]; let result = verify_attestation(&attest_der, &device_der).unwrap(); @@ -403,11 +700,7 @@ mod tests { assert!(!result.chain_verified); assert_eq!(result.root_ca, "legacy"); // 5.7.1 < 5.7.4 assert!(result.description.contains("5.7.1")); - assert!( - result - .description - .contains("not cryptographically verified") - ); + assert!(result.description.contains("not verified")); } #[test] @@ -442,4 +735,303 @@ mod tests { assert!(!result.chain_verified); assert_eq!(result.root_ca, "unknown"); } + + // --------------------------------------------------------------------- + // Pinned-fingerprint guards: compute the SHA-256 with our own code path + // (pem_to_der + sha2) and assert it equals the pinned constant. Catches a + // swapped PEM and validates the hand-rolled base64 against the same DER the + // x509 parser consumes. + // --------------------------------------------------------------------- + + #[test] + fn test_legacy_root_fingerprint_matches_constant() { + let der = pem_to_der(YUBICO_PIV_ROOT_CA_LEGACY_PEM).expect("decode legacy root"); + assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_LEGACY_ROOT_SHA256); + } + + #[test] + fn test_new_root_fingerprint_matches_constant() { + let der = pem_to_der(YUBICO_ATTESTATION_ROOT_1_PEM).expect("decode new root"); + assert_eq!(hex::encode(Sha256::digest(&der)), YUBICO_NEW_ROOT_SHA256); + } + + #[test] + fn test_bundled_anchors_and_pool_parse() { + let anchors = bundled_trust_anchors(); + assert_eq!(anchors.len(), 2, "both pinned roots must parse and match"); + let pool = bundled_intermediate_pool(); + assert_eq!(pool.len(), 5, "five PIV-chain intermediates bundled"); + } + + #[test] + fn test_real_intermediate_chains_to_pinned_root() { + // The bundled PIV Attestation A 1 cert chains to the bundled Attestation + // Root 1 via the bundled Intermediate A 1. Verify the new-PKI links work + // against the real published certs (using PIV Attestation A 1 as the + // synthetic "leaf"/"device" entry point). + let anchors = bundled_trust_anchors(); + let pool = bundled_intermediate_pool(); + // Use Intermediate A 1 as the leaf; its issuer is the pinned root. + let int_a = pem_to_der(YUBICO_ATTESTATION_INTERMEDIATE_A_1_PEM).unwrap(); + let now = Duration::from_secs(1_900_000_000); // ~2030, inside all windows + let res = verify_chain(&int_a, &int_a, &anchors, &pool, now); + assert!(res.is_ok(), "real intermediate must chain to pinned root: {res:?}"); + } + + // --------------------------------------------------------------------- + // Synthetic chains. Build our own root → sub-CA → leaf with the x509 + // builder, then exercise verify_chain directly with injected anchors. + // --------------------------------------------------------------------- + + use rsa::RsaPrivateKey; + use rsa::pkcs1v15::SigningKey; + use x509_cert::builder::{Builder, CertificateBuilder, Profile}; + use x509_cert::name::Name; + use x509_cert::serial_number::SerialNumber; + use x509_cert::spki::SubjectPublicKeyInfoOwned; + use x509_cert::time::{Time, Validity}; + use std::str::FromStr; + + struct Node { + cert: Certificate, + der: Vec, + } + + fn gen_key() -> RsaPrivateKey { + let mut rng = rand::thread_rng(); + RsaPrivateKey::new(&mut rng, 1024).expect("rsa keygen") + } + + fn spki_of(key: &RsaPrivateKey) -> SubjectPublicKeyInfoOwned { + use rsa::pkcs1::EncodeRsaPublicKey; + let pub_der = key.to_public_key().to_pkcs1_der().unwrap(); + // Wrap PKCS#1 RSAPublicKey in an rsaEncryption SubjectPublicKeyInfo. + use x509_cert::spki::AlgorithmIdentifierOwned; + SubjectPublicKeyInfoOwned { + algorithm: AlgorithmIdentifierOwned { + oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1"), + parameters: Some(der::Any::null()), + }, + subject_public_key: x509_cert::der::asn1::BitString::from_bytes(pub_der.as_bytes()) + .unwrap(), + } + } + + fn far_validity() -> Validity { + // Wide window covering "now". + Validity::from_now(Duration::from_secs(60 * 60 * 24 * 365 * 20)).unwrap() + } + + /// Build a cert with `subject`, signed by `signer_key` under `issuer` name. + fn build_cert( + profile: Profile, + subject: &str, + subject_key: &RsaPrivateKey, + signer_key: &RsaPrivateKey, + validity: Validity, + serial: u32, + ) -> Node { + let signer = SigningKey::::new(signer_key.clone()); + let builder = CertificateBuilder::new( + profile, + SerialNumber::from(serial), + validity, + Name::from_str(subject).unwrap(), + spki_of(subject_key), + &signer, + ) + .expect("builder"); + let cert: Certificate = builder.build::().expect("build/sign"); + let der = cert.to_der().expect("encode"); + Node { cert, der } + } + + /// Root self-signed; sub-CA signed by root; leaf signed by sub-CA. Returns + /// (leaf, sub_ca, root) so callers can inject the root as anchor and the + /// sub-CA into the searchable pool. + fn synthetic_chain() -> (Node, Node, Node) { + let root_key = gen_key(); + let sub_key = gen_key(); + let leaf_key = gen_key(); + + let root = build_cert( + Profile::Root, + "CN=Test Root", + &root_key, + &root_key, + far_validity(), + 1, + ); + let sub = build_cert( + Profile::SubCA { + issuer: Name::from_str("CN=Test Root").unwrap(), + path_len_constraint: Some(1), + }, + "CN=Test SubCA", + &sub_key, + &root_key, + far_validity(), + 2, + ); + let leaf = build_cert( + Profile::Leaf { + issuer: Name::from_str("CN=Test SubCA").unwrap(), + enable_key_agreement: false, + enable_key_encipherment: false, + }, + "CN=Test Leaf", + &leaf_key, + &sub_key, + far_validity(), + 3, + ); + (leaf, sub, root) + } + + fn anchor_of(node: &Node) -> TrustAnchor { + TrustAnchor { + cert: node.cert.clone(), + } + } + + fn now() -> Duration { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + } + + #[test] + fn test_synthetic_chain_verifies() { + let (leaf, sub, root) = synthetic_chain(); + // Device slot = sub-CA here; intermediates = [sub]. + let res = verify_chain( + &leaf.der, + &sub.der, + &[anchor_of(&root)], + &[sub.cert.clone()], + now(), + ); + assert!(res.is_ok(), "valid synthetic chain must verify: {res:?}"); + } + + #[test] + fn test_tampered_signature_fails() { + let (leaf, sub, root) = synthetic_chain(); + // Flip one byte in the leaf signature, re-encode. + let mut tampered = leaf.cert.clone(); + let mut sig = tampered.signature.as_bytes().unwrap().to_vec(); + sig[0] ^= 0x01; + tampered.signature = x509_cert::der::asn1::BitString::from_bytes(&sig).unwrap(); + let tampered_der = tampered.to_der().unwrap(); + + let res = verify_chain( + &tampered_der, + &sub.der, + &[anchor_of(&root)], + &[sub.cert.clone()], + now(), + ); + assert!(matches!(res, Err(ChainError::SignatureInvalid)), "got {res:?}"); + } + + #[test] + fn test_expired_cert_fails() { + let root_key = gen_key(); + let sub_key = gen_key(); + let leaf_key = gen_key(); + + let root = build_cert( + Profile::Root, + "CN=Test Root", + &root_key, + &root_key, + far_validity(), + 1, + ); + let sub = build_cert( + Profile::SubCA { + issuer: Name::from_str("CN=Test Root").unwrap(), + path_len_constraint: Some(1), + }, + "CN=Test SubCA", + &sub_key, + &root_key, + far_validity(), + 2, + ); + // Leaf already expired: notBefore..notAfter both in the past. + let expired = Validity { + not_before: Time::UtcTime( + x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(1_000_000_000)) + .unwrap(), + ), + not_after: Time::UtcTime( + x509_cert::der::asn1::UtcTime::from_unix_duration(Duration::from_secs(1_100_000_000)) + .unwrap(), + ), + }; + let leaf = build_cert( + Profile::Leaf { + issuer: Name::from_str("CN=Test SubCA").unwrap(), + enable_key_agreement: false, + enable_key_encipherment: false, + }, + "CN=Test Leaf", + &leaf_key, + &sub_key, + expired, + 3, + ); + + let res = verify_chain( + &leaf.der, + &sub.der, + &[anchor_of(&root)], + &[sub.cert.clone()], + now(), + ); + assert!(matches!(res, Err(ChainError::Expired)), "got {res:?}"); + } + + #[test] + fn test_wrong_root_fails_on_pin() { + // Build a fully valid chain, but the actual signing root is NOT pinned. + // Put the bogus root in the SEARCHABLE pool (so issuer-by-name succeeds and + // its signature verifies) but NOT in the anchor set. Verification must fail + // because no walked cert reaches a pinned terminal — exercises pin rejection, + // not a mere "issuer not found". + let (leaf, sub, bogus_root) = synthetic_chain(); + + // A second, unrelated key serves as the only *pinned* anchor — it signs + // nothing in this chain. + let other_root_key = gen_key(); + let other_root = build_cert( + Profile::Root, + "CN=Unrelated Pinned Root", + &other_root_key, + &other_root_key, + far_validity(), + 9, + ); + + let res = verify_chain( + &leaf.der, + &sub.der, + &[anchor_of(&other_root)], // pinned set: unrelated root only + &[sub.cert.clone(), bogus_root.cert.clone()], // searchable: real signer present + now(), + ); + // The real signing root is reachable by name+signature but is not pinned, + // so the walk terminates without a pinned anchor. + assert!( + matches!(res, Err(ChainError::IssuerNotFound)), + "wrong-root chain must be rejected at the pin, got {res:?}" + ); + } + + #[test] + fn test_unknown_issuer_fails() { + let (leaf, _sub, root) = synthetic_chain(); + // No sub-CA in the pool: leaf's issuer is unfindable. + let res = verify_chain(&leaf.der, &leaf.der, &[anchor_of(&root)], &[], now()); + assert!(matches!(res, Err(ChainError::IssuerNotFound)), "got {res:?}"); + } }