Compare commits

..
Author SHA1 Message Date
DeFiDude bb2c1eab65 ble: satisfy peer feature clippy 2026-06-03 23:58:52 -06:00
DeFiDude 21aa4f6308 ble: redundantly fan out proof packets 2026-06-03 23:07:22 -06:00
DeFiDude f9b407ef5a ble: suppress peer role collisions 2026-06-03 20:50:46 -06:00
DeFiDude 924d27f4b1 interface: expose Android BLE availability 2026-06-03 15:53:17 -06:00
DeFiDude 36706c1eff interface: emit BLE peer status events 2026-06-03 15:46:14 -06:00
DeFiDude 5a0ea04ad0 runtime: seed BLE reconnects by address 2026-06-03 15:41:15 -06:00
DeFiDude 104f425b4f interface: prefer single BLE peer path 2026-06-03 15:34:48 -06:00
DeFiDude c3b75f7577 interface: key BLE peer writers 2026-06-03 15:31:37 -06:00
DeFiDude c460a7c9d4 interface: reset BLE peer sessions cleanly 2026-06-03 15:26:31 -06:00
DeFiDude 27f901ec5d tests: move interop generator to harness 2026-05-30 21:07:59 -06:00
DeFiDude ab529e875c runtime: support legacy Python RPC auth 2026-05-30 20:37:08 -06:00
DeFiDude 7942aee235 tests: track Python artifact generator 2026-05-30 17:24:06 -06:00
DeFiDude cd58bbc0ac ratkey: satisfy clippy 2026-05-29 23:52:58 -06:00
DeFiDude 4ee47d40ac style: apply rustfmt 2026-05-29 23:49:09 -06:00
DeFiDude a8daa46958 ratkey: switch recoverable phrases to 12 words 2026-05-29 22:52:53 -06:00
DeFiDude eeb3e4589a ratkey: add PIV PIN recovery support 2026-05-29 22:38:34 -06:00
DeFiDude 132d7a2d79 runtime: route backend link signing 2026-05-29 20:28:47 -06:00
DeFiDude 27beef4564 ratkey: extract testable APDU response-chaining fn + unit tests 2026-05-29 19:24:41 -06:00
DeFiDude 6cd28f0337 ratkey: hardware-validate attestation chain (on-card ATTEST + F9 fetch, response chaining, hw attest) 2026-05-29 19:18:26 -06:00
DeFiDude 4f011314d4 ratkey: document recovery-phrase re-display (persisted, protection tracks the key) 2026-05-29 18:59:49 -06:00
DeFiDude 88677cef2f ratkey: implement TDES (3DES EDE3) management keys for pre-5.7 YubiKeys 2026-05-29 18:41:43 -06:00
DeFiDude 6181a18254 ratkey: document recoverable-identity model (seed-restore, mnemonic create, passcode vault) 2026-05-29 16:15:18 -06:00
DeFiDude dda2470987 ratkey: document desktop-only release scope + mobile/seed-restore plan 2026-05-29 14:52:35 -06:00
DeFiDude 6c9792846e ratkey: add backend lock() to drop the on-card PIN cache 2026-05-29 10:37:52 -06:00
DeFiDude cc8927f0f9 ratkey: provision_hardware_only + read_existing helpers
Shared finalize_provision builds the .hwid for all real flows; provision_hardware_only generates on-device, read_existing registers an already-provisioned token.
2026-05-29 00:26:17 -06:00
DeFiDude a4083bd4fe ratkey: PIV key import + recoverable provisioning/restore
IMPORT ASYMMETRIC KEY APDU (Ed25519 tag 0x07 / X25519 0x08) + PivSession import methods (mgmt-key gated). provision_recoverable derives from a fresh 24-word phrase and imports both keys; restore does the same from an existing phrase. Mirrors ratkey-py's import path.
2026-05-29 00:07:25 -06:00
DeFiDude ad279dfb67 ratkey: BIP-39 seed-phrase identity derivation
24-word mnemonic -> deterministic Reticulum identity (scheme v1: PBKDF2-SHA512 seed -> HKDF-SHA256), verified byte-for-byte against ratkey-py. Foundation for recoverable hardware-key backup.
2026-05-29 00:01:44 -06:00
DeFiDude 1c63de4e0f rns-runtime: optional link signing key for hardware identities
LinkManager::with_destination takes Option<Ed25519PrivateKey>; hardware identities pass None (link-mode packet proofs skip until routed through the backend, TODO). Software callers wrap Some(...). Opportunistic delivery is unaffected.
2026-05-28 23:19:38 -06:00
DeFiDude a475caf407 ratkey: Identity LocalKeyBackend seam + hardware-backed identity
Identity gains an optional LocalKeyBackend (Ed25519 sign + X25519 ECDH delegation, used only when the in-memory key is absent; None for software identities, so wire output is unchanged). rns-ratkey HardwareBackend runs the PIV session on a card-service thread (Send+Sync) and load_hardware_identity builds an Identity::from_backend. Backend-aware Identity::clone keeps both clone_identity sites working for hardware (Arc-shared) without extracting a private key.
2026-05-28 23:10:52 -06:00
DeFiDude f6afe585ce 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.
2026-05-28 23:10:52 -06:00
DeFiDude 4623436c93 ratkey: PIV management-key auth for on-device provisioning
Witness/challenge mutual auth on slot 9B (AES-128/192/256; 5.7 default is AES-192) gates GENERATE, so hw provision now creates keys on-device. TDES (pre-5.7) left as a TODO. Validated end-to-end on a YubiKey 5.7.4.
2026-05-28 22:20:56 -06:00
DeFiDude fac4dc870d ratkey: PivTransport seam; back HardwareIdentity by real PIV session
PivSession<T> is transport-agnostic (PC/SC behind `hardware`); HardwareIdentity holds Box<dyn IdentityBackend>, ending the mock-only runtime and leaving room for a mobile transport. hw provision still lacks PIV management-key auth.
2026-05-28 21:59:37 -06:00
dude.eth 4e427a7ad5 Merge pull request #7 from kujeger/bzip2_vers
update bzip2 depencency
2026-05-28 20:18:06 -06:00
Nikolai Vincent Vaags a65fd2097f update bzip2 depencency
bzip2 0.6 (latest) is also fully in rust, making it easier to cross-compile.
2026-05-28 15:28:49 +02:00
DeFiDude 26e4919ce1 transport: align announce replay with upstream 2026-05-26 19:45:10 -06:00
DeFiDude bfb4bb4e14 transport: stop shared client announce replay 2026-05-26 19:19:05 -06:00
DeFiDude 8263bfbf4a tests: cover shared instance lifecycle edges 2026-05-24 23:51:37 -06:00
DeFiDude da56d5559a runtime: harden shared instance lifecycle 2026-05-24 22:59:36 -06:00
dude.eth 6e11324b6b Merge pull request #5 from strijar/fix/rnsd_log
Disable ansi for log file
2026-05-24 12:20:20 -06:00
Belousov Oleg b89e434a00 Disable ansi for log file 2026-05-20 15:34:16 +03:00
40 changed files with 5782 additions and 931 deletions

No files matched your search

+1 -1
View File
@@ -6,4 +6,4 @@ __pycache__/
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
/tools/*
Generated
+256 -32
View File
@@ -69,6 +69,12 @@ version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "async-trait"
version = "0.1.89"
@@ -98,6 +104,17 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bip39"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"
dependencies = [
"bitcoin_hashes",
"serde",
"unicode-normalization",
]
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -113,6 +130,15 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitcoin_hashes"
version = "0.14.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9901a56e133a1fc86eeb1113e2591f45f4682451ca893bff494d2f88918e3f"
dependencies = [
"hex-conservative",
]
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -252,21 +278,11 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "bzip2"
version = "0.5.2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"bzip2-sys",
]
[[package]]
name = "bzip2-sys"
version = "0.1.13+1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
dependencies = [
"cc",
"pkg-config",
"libbz2-rs-sys",
]
[[package]]
@@ -278,16 +294,6 @@ dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.2.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e928d4b69e3077709075a938a05ffbedfa53a84c8f766efbf8220bb1ff60e1"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cesu8"
version = "1.1.0"
@@ -570,9 +576,32 @@ 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 = "des"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e"
dependencies = [
"cipher",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -580,6 +609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
@@ -655,10 +685,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "fnv"
@@ -839,6 +869,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hex-conservative"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"
dependencies = [
"arrayvec",
]
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -1004,6 +1043,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"
@@ -1011,6 +1053,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"
[[package]]
name = "libc"
version = "0.2.183"
@@ -1026,6 +1074,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"
@@ -1062,6 +1116,16 @@ dependencies = [
"libc",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.0"
@@ -1111,6 +1175,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"
@@ -1122,6 +1202,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"
@@ -1129,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@@ -1230,6 +1331,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"
@@ -1256,6 +1366,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"
@@ -1564,15 +1685,25 @@ dependencies = [
name = "rns-ratkey"
version = "0.9.4"
dependencies = [
"aes",
"bip39",
"const-oid",
"der",
"des",
"hex",
"hkdf",
"pcsc",
"rand 0.8.5",
"rns-crypto",
"rns-identity",
"rns-link",
"rsa",
"serde",
"sha2",
"thiserror 2.0.18",
"toml",
"tracing",
"x509-cert",
"zeroize",
]
@@ -1583,6 +1714,7 @@ dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1658,6 +1790,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"
@@ -1811,6 +1964,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"
@@ -1831,12 +1995,6 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -1853,6 +2011,7 @@ version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core 0.6.4",
]
@@ -1888,6 +2047,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"
@@ -2022,6 +2187,42 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tinyvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[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"
@@ -2200,6 +2401,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-normalization"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-xid"
version = "0.2.6"
@@ -2753,6 +2963,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"
+3 -1
View File
@@ -24,9 +24,11 @@ rust-version = "1.85"
x25519-dalek = { version = "2", features = ["static_secrets"] }
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
aes = "0.8"
des = "0.8"
cbc = { version = "0.1", features = ["alloc"] }
hkdf = "0.12"
hmac = "0.12"
md-5 = "0.10"
sha2 = "0.10"
subtle = "2"
zeroize = { version = "1", features = ["derive"] }
@@ -46,7 +48,7 @@ serde_json = "1"
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
bzip2 = "0.6"
# Serial
serialport = { version = "4", default-features = false }
+133 -4
View File
@@ -9,6 +9,7 @@ use zeroize::{Zeroize, Zeroizing};
use crate::persistence;
use std::path::Path;
use std::sync::Arc;
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
pub const DERIVED_KEY_LENGTH: usize = 64;
@@ -33,6 +34,20 @@ pub enum IdentityError {
Io(#[from] std::io::Error),
}
/// Delegate for an `Identity` whose private key is not in memory (e.g. a PIV
/// hardware token). Implemented outside this crate (see `rns-ratkey`). Both
/// operations must produce standard output — RFC 8032 Ed25519 / RFC 7748 X25519
/// — so the resulting identity is wire-identical to a software one.
pub trait LocalKeyBackend: Send + Sync {
/// Ed25519 signature over `message`, or `None` if currently unavailable.
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]>;
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
/// Drop any cached authentication so the next operation must re-authenticate
/// (e.g. a hardware token re-locks its PIN). No-op for software backends.
fn lock(&self) {}
}
/// A Reticulum identity: X25519 keypair for encryption + Ed25519 keypair for signing.
///
/// Wire representation:
@@ -45,6 +60,29 @@ pub struct Identity {
pub_key: X25519PublicKey,
sig_pub: Ed25519PublicKey,
pub hash: [u8; 16],
/// Set only for hardware-backed identities; `None` for all software ones.
backend: Option<Arc<dyn LocalKeyBackend>>,
}
impl Clone for Identity {
/// Software identities clone their key material; hardware-backed identities
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
fn clone(&self) -> Self {
Self {
prv: self
.prv
.as_ref()
.map(|k| X25519PrivateKey::from_bytes(&k.to_bytes())),
sig_prv: self
.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes())),
pub_key: self.pub_key.clone(),
sig_pub: self.sig_pub.clone(),
hash: self.hash,
backend: self.backend.clone(),
}
}
}
impl Default for Identity {
@@ -67,6 +105,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
}
}
@@ -91,6 +130,7 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
@@ -114,9 +154,22 @@ impl Identity {
pub_key,
sig_pub,
hash,
backend: None,
})
}
/// Construct an identity whose private operations are served by `backend`
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
/// delegate to the backend. Wire-identical to a software identity.
pub fn from_backend(
public_key: &[u8],
backend: Arc<dyn LocalKeyBackend>,
) -> Result<Self, IdentityError> {
let mut id = Self::from_public_key(public_key)?;
id.backend = Some(backend);
Ok(id)
}
/// Load an identity from file, accepting either the current msgpack envelope
/// or a legacy raw 64-byte private key.
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
@@ -167,15 +220,32 @@ impl Identity {
self.prv.is_some() && self.sig_prv.is_some()
}
/// True if private operations are served by a hardware backend.
pub fn has_backend(&self) -> bool {
self.backend.is_some()
}
/// Re-lock the hardware backend (drop its cached authentication). No-op for
/// software identities. The next private operation will fail until re-auth.
pub fn lock(&self) {
if let Some(b) = self.backend.as_ref() {
b.lock();
}
}
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
self.sig_prv
.as_ref()
.map(|k| Ed25519PrivateKey::from_bytes(&k.to_bytes()))
}
/// Sign `message` with the Ed25519 key; `None` if this is a public-only identity.
/// Sign `message` with the Ed25519 key, delegating to the hardware backend
/// when the in-memory key is absent; `None` if neither is available.
pub fn sign(&self, message: &[u8]) -> Option<[u8; 64]> {
self.sig_prv.as_ref().map(|key| key.sign(message))
match self.sig_prv.as_ref() {
Some(key) => Some(key.sign(message)),
None => self.backend.as_ref().and_then(|b| b.sign_ed25519(message)),
}
}
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
@@ -251,8 +321,16 @@ impl Identity {
return Err(IdentityError::DecryptionFailed);
}
let prv = self.prv.as_ref().ok_or(IdentityError::DecryptionFailed)?;
let mut shared = prv.exchange(&peer_pub);
// Identity-key ECDH: in-memory key if present, else the hardware backend.
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
prv.exchange(&peer_pub)
} else if let Some(backend) = self.backend.as_ref() {
backend
.ecdh(&peer_pub_bytes)
.ok_or(IdentityError::DecryptionFailed)?
} else {
return Err(IdentityError::DecryptionFailed);
};
let derived_result =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
@@ -483,4 +561,55 @@ mod tests {
let pub_id = Identity::from_public_key(&id.get_public_key()).unwrap();
assert!(pub_id.prove(b"test", true).is_err());
}
// A software-keyed backend, standing in for a hardware token in tests.
struct SoftwareBackend {
sig: rns_crypto::ed25519::Ed25519PrivateKey,
x: rns_crypto::x25519::X25519PrivateKey,
}
impl LocalKeyBackend for SoftwareBackend {
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
Some(self.sig.sign(message))
}
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub);
Some(self.x.exchange(&peer))
}
}
#[test]
fn test_backend_identity_is_wire_identical() {
use std::sync::Arc;
// Build a backend from a software identity's keys, then a separate
// backend-driven identity over the same public key.
let sw = Identity::new();
let prv = sw.get_private_key().unwrap();
let mut x_bytes = [0u8; 32];
x_bytes.copy_from_slice(&prv[..32]);
let mut ed_bytes = [0u8; 32];
ed_bytes.copy_from_slice(&prv[32..]);
let backend = Arc::new(SoftwareBackend {
sig: rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&ed_bytes),
x: rns_crypto::x25519::X25519PrivateKey::from_bytes(&x_bytes),
});
let hw = Identity::from_backend(&sw.get_public_key(), backend).unwrap();
// Same identity, but no extractable in-memory key.
assert_eq!(hw.hash, sw.hash);
assert!(!hw.has_private_key());
assert!(hw.get_private_key().is_none());
// sign() delegates and is byte-identical (Ed25519 is deterministic).
let msg = b"hardware parity";
assert_eq!(hw.sign(msg), sw.sign(msg));
assert!(hw.verify(msg, &hw.sign(msg).unwrap()));
// decrypt() delegates the ECDH to the backend; round-trips, and the
// software identity decrypts the same ciphertext (identical key material).
let ct = hw.encrypt(b"secret payload", None).unwrap();
assert_eq!(hw.decrypt(&ct, None, false).unwrap(), b"secret payload");
assert_eq!(sw.decrypt(&ct, None, false).unwrap(), b"secret payload");
}
}
File diff suppressed because it is too large. Load diff
+82 -12
View File
@@ -385,6 +385,49 @@ impl Link {
destination_hash: [u8; 16],
hops: u8,
) -> Result<(Self, Vec<u8>), HandshakeError> {
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
Self::new_responder_inner(
request_data,
&identity_ed25519_pub,
destination_hash,
hops,
Some(identity_signing_key),
|signed_data| Some(identity_signing_key.sign(signed_data)),
)
}
/// Create an inbound link proof using an external signer (e.g. YubiKey/PIV).
pub fn new_responder_with<F>(
request_data: &[u8],
identity_ed25519_pub: &[u8; 32],
destination_hash: [u8; 16],
hops: u8,
sign_fn: F,
) -> Result<(Self, Vec<u8>), HandshakeError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
Self::new_responder_inner(
request_data,
identity_ed25519_pub,
destination_hash,
hops,
None,
sign_fn,
)
}
fn new_responder_inner<F>(
request_data: &[u8],
identity_ed25519_pub: &[u8; 32],
destination_hash: [u8; 16],
hops: u8,
identity_signing_key: Option<&Ed25519PrivateKey>,
sign_fn: F,
) -> Result<(Self, Vec<u8>), HandshakeError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
let request = LinkRequestData::unpack(request_data)?;
let link_id = compute_link_id(&destination_hash, request_data);
@@ -404,16 +447,21 @@ impl Link {
// The proof binds the link to the responder's long-term identity key, not
// its ephemeral one — that's what lets the initiator authenticate us.
let identity_ed25519_pub = identity_signing_key.public_key().to_bytes();
let signalling =
SignallingData::new(request.signalling.mode, rns_wire::constants::MTU as u32);
let proof = LinkProofData::create(
identity_signing_key,
&responder_keys.x25519_pub.to_bytes(),
&identity_ed25519_pub,
&link_id,
let responder_x25519_pub = responder_keys.x25519_pub.to_bytes();
let sig_bytes = signalling.pack();
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + 3);
signed_data.extend_from_slice(&link_id);
signed_data.extend_from_slice(&responder_x25519_pub);
signed_data.extend_from_slice(identity_ed25519_pub);
signed_data.extend_from_slice(&sig_bytes);
let signature = sign_fn(&signed_data).ok_or(HandshakeError::InvalidSignature)?;
let proof = LinkProofData {
signature,
responder_x25519_pub,
signalling,
);
};
let proof_data = proof.pack();
let timeout_secs = ESTABLISHMENT_TIMEOUT_PER_HOP * (hops.max(1) as f64) + KEEPALIVE_DEFAULT;
@@ -429,9 +477,7 @@ impl Link {
ephemeral_keys: Some(responder_keys),
peer_x25519_pub: Some(request.peer_x25519_pub),
peer_ed25519_pub: Some(request.peer_ed25519_pub),
sig_prv: Some(Ed25519PrivateKey::from_bytes(
&identity_signing_key.to_bytes(),
)),
sig_prv: identity_signing_key.map(|key| Ed25519PrivateKey::from_bytes(&key.to_bytes())),
session_keys: Some(session_keys),
request_time: now,
rtt: None,
@@ -565,6 +611,18 @@ impl Link {
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> [u8; 64],
{
self.identify_with_fallible(identity_pub_key, |message| Some(sign_fn(message)))
}
/// Identify with an external signer that can be unavailable.
pub fn identify_with_fallible<F>(
&self,
identity_pub_key: &[u8; 64],
sign_fn: F,
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
if !self.is_initiator || self.state != LinkState::Active {
return Err(LinkCryptoError::EncryptionFailed);
@@ -574,7 +632,7 @@ impl Link {
signed_data.extend_from_slice(&self.link_id);
signed_data.extend_from_slice(identity_pub_key);
let signature = sign_fn(&signed_data);
let signature = sign_fn(&signed_data).ok_or(LinkCryptoError::EncryptionFailed)?;
let mut proof_data = Vec::with_capacity(128);
proof_data.extend_from_slice(identity_pub_key);
@@ -926,12 +984,24 @@ impl Link {
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> [u8; 64],
{
self.prove_packet_with_fallible(packet_hash, |hash| Some(sign_fn(hash)))
}
/// Variant of [`Link::prove_packet_with`] for signers that can be unavailable.
pub fn prove_packet_with_fallible<F>(
&self,
packet_hash: &[u8; 32],
sign_fn: F,
) -> Result<Vec<u8>, LinkCryptoError>
where
F: FnOnce(&[u8]) -> Option<[u8; 64]>,
{
if self.state != LinkState::Active && self.state != LinkState::Stale {
return Err(LinkCryptoError::EncryptionFailed);
}
let signature = sign_fn(packet_hash);
let signature = sign_fn(packet_hash).ok_or(LinkCryptoError::EncryptionFailed)?;
let mut proof = Vec::with_capacity(96);
proof.extend_from_slice(packet_hash);
+19
View File
@@ -14,12 +14,31 @@ thiserror = { workspace = true }
tracing = { workspace = true }
hex = { workspace = true }
zeroize = { workspace = true }
aes = { workspace = true }
des = { 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<Sha256/Sha512> build the DigestInfo prefix.
sha2 = { workspace = true, features = ["oid"] }
der = "0.7"
const-oid = "0.9"
# BIP-39 recoverable backup: 12-word mnemonic -> deterministic Reticulum identity.
bip39 = "2"
hkdf = "0.12"
[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 = []
+115 -14
View File
@@ -1,21 +1,122 @@
# RatKey Hardware Status
RatKey hardware identity support is intentionally not release-grade until it is
verified against real devices. The mock-backed tests cover public identity
shape, signing, ECDH, decrypt flow, and fail-closed key mismatch behavior, but
they do not prove PIV transport, touch/PIN policy, or X.509 chain verification.
RatKey hardware identity support is **desktop only** and experimental. The full
desktop path is validated on a real YubiKey (5.7.4): provision (recoverable /
hardware-only / import / restore), on-card sign + ECDH, in-app load into LXMF/RNS,
PIN-prompt unlock, auto-lock timeout, lock-on-quit, and **attestation-chain
verification against the device's real ATTEST output**. Pre-5.7 (TDES) management
keys are implemented and unit-tested but await validation on a pre-5.7 device.
Required before hardware RatKey is documented as supported:
## Release scope: desktop only
- Replace the mock-only `HardwareIdentity` session storage with a real PIV
backend abstraction and YubiKey/Nitrokey implementations.
- Verify signing and ECDH against physical YubiKeys, including disconnect,
wrong PIN, touch timeout, and slot mismatch cases.
- Implement cryptographic attestation certificate chain verification against
the bundled Yubico roots and intermediates.
- Decide and document the ratchet policy for hardware identities. PIV cannot
hold Reticulum ratchet private keys, so enforced-ratchet decrypt currently
fails closed.
Mobile is intentionally excluded from release. The `hardware` feature is off on
iOS/Android (pcsc is desktop-only), the `hw_*` commands are
`#[cfg(not(any(target_os = "android", target_os = "ios")))]`, and the frontend
hides every hardware entry point on mobile (`isMobile()` gate in setup.js +
identity.js).
## Mobile (deferred — needs a different model)
Desktop keeps the token plugged in and does every sign/ECDH on-card. That can't
work over transient NFC (iOS CoreNFC is modal ~60s; Android IsoDep only while the
tag is in-field; neither runs in the background). A messaging app used all day
needs a **wrapped software session**: tap the key to unlock (on-card ECDH unwraps
a software identity stored encrypted at rest, ideally in the Secure Enclave /
StrongBox), operate in software for a configurable window (mirrors the desktop
auto-lock setting), re-tap to refresh. This is a different security model than
"key never leaves the token" and should be an explicit mode alongside
hardware-only. The `PivTransport` seam is ready (`PivSession::new` takes any
transport); a mobile loader belongs in `ratspeak-runtime`. Android NFC (IsoDep)
is the tractable first transport.
### Recoverable software identities — DONE (2026-05-29, cross-platform)
The recoverable model generalized "hardware identity" → "recoverable identity,"
with the YubiKey as one optional backing. All on every platform (the derivation
+ vault are pure-Rust, gated behind a default `seed` feature in ratspeak-runtime
that pulls `rns-ratkey` without pcsc):
- **Software seed-restore** (`ratspeak_runtime::derive_identity_key_from_phrase`,
`restore_seed_identity` command): a 12-word phrase restores a software identity
on any platform — the practical mobile recovery path. Folded into the app's
**Import** flow (key *or* phrase), not a separate button.
- **Mnemonic-derived-by-default** (`generate_recoverable_key`): new software
identities are derived from a fresh BIP-39 mnemonic shown for backup at creation.
Both `api_create_identity` (settings) and `api_setup_complete` (first-setup)
produce them; legacy random identities keep raw-key export.
`LxmfManager::create_identity` (random) stays for internal/tests.
- **Recovery-phrase re-display** (`vault::store_plaintext_seed` /
`has_stored_mnemonic` / `reveal_mnemonic`, `reveal_identity_mnemonic` command,
software only): the phrase is persisted so it can be shown again. Its at-rest
protection tracks the key's — a plaintext `identity.seed` sidecar when the
identity is unprotected (crypto-equivalent to the already-plaintext `identity`
key file), folded into the vault as a `mnemonic_token` (same KEK) once a passcode
is set. The vault is authoritative when present, so reveal honors the passcode
even if a stale sidecar survives the verify-before-delete window. Captured at
create/import (both `api_create_identity`, `api_setup_complete`, and
`restore_seed_identity`); hardware identities never store a phrase.
- **Passcode at-rest encryption** (`vault.rs`): software identities can be sealed
with a passcode — Argon2id(passcode,salt) → HKDF(info=params‖salt) binds the KDF
params → 64-byte KEK → `rns_crypto::token` (AES-256-CBC + HMAC). Stored as
`identity.enc`; param-tamper/wrong-passcode → auth failure (unit-tested). The
launch unlock + auto-lock + lock-on-quit machinery is shared with the hardware
PIN path (one "protected identity" state, a `kind` discriminator selects PIN vs
passcode; the `hw_unlock`/`hardware_locked`/`hw_locked` wire names are retained).
Caveat documented to users: restore recovers the *identity*, not past message
history (forward secrecy).
## Architecture (done)
- `PivTransport` is the platform seam: APDU bytes in, response bytes out.
`PivSession<T>` builds every PIV operation on `apdu` over that seam and is
transport-agnostic (compiles with no features).
- `PcscTransport` (behind the `hardware` feature) is the desktop PC/SC
implementation; `PivSession::<PcscTransport>::connect()` is the entry point.
Mobile NFC/USB transports implement `PivTransport` from the application layer.
- `HardwareIdentity` holds a `Box<dyn IdentityBackend>`, implemented by both
`PivSession<T>` (real token, any transport) and `MockPivSession`.
- `PivSession::lock()` / `HardwareIdentity::lock()` re-select the PIV applet to
drop the on-card PIN cache (mechanism for app-side session timeout / lock-on-quit).
## Validated on hardware (YubiKey 5, firmware 5.7.4)
Full provision → verify → test loop with our own code, PIN-once + touch-never
Ed25519 (9A) / X25519 (9D):
- **Management-key authentication** (witness/challenge, AES-192) — `hw provision`
authenticates slot 9B and generates both keys on-device. Successful generate
is proof of auth.
- `parse_metadata_public_key` reads the correct pubkey from GET METADATA
(confirmed against ykman-exported ground truth — the layout assumption held).
- Ed25519 signing on slot 9A; signature verifies against the slot pubkey.
- X25519 ECDH on slot 9D; shared secret symmetric with a software peer.
- `HardwareIdentity` decrypt end-to-end (on-device ECDH → HKDF → AES token) — the
same Ed25519-sign + X25519-ECDH + token-AES primitives LXMF uses, so live LXMF
send/receive on a hardware identity routes through the card (serial 35284666).
- The pubkey our provision records matches ykman's independent export byte-for-byte.
- **Attestation chain verified against the device's real ATTEST output** (`hw
attest`): both slot-9A/9D per-key certs chain through the slot-F9 device
intermediate to a bundled, fingerprint-pinned new-PKI Yubico root. `hw provision`
now captures + verifies the chain into the `.hwid`. The captured 5.7.4 certs are
committed as a CI regression vector (`tests/fixtures/{9a_attest,f9_device}.der`).
## Still required before hardware RatKey is documented as supported
- **TDES management keys** are implemented (3DES EDE3 via the `des` crate, 8-byte
block; `mgmt.rs` dispatches on the algorithm byte). A FIPS-81 known-answer test
and a distinct-subkey round-trip cover the cipher. Pre-5.7 YubiKeys default to a
TDES management key; the witness/challenge auth flow already drives its block
size from `mgmt::block_len`, so it is ready — but not yet exercised against a
physical pre-5.7 device.
- A two-node **live LXMF message exchange** in the app on a hardware identity. The
on-card crypto primitives are validated (above) and the runtime delegates
sign/ECDH to the backend, but an end-to-end app round-trip between two peers is
still a manual check.
- 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
Reticulum ratchet private keys, so enforced-ratchet decrypt fails closed.
- Add hardware-gated tests that are skipped by default but run when a device is
explicitly selected by environment/config.
@@ -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-----
@@ -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-----
@@ -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-----
@@ -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-----
@@ -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-----
+386
View File
@@ -10,9 +10,11 @@ pub const PIV_AID: &[u8] = &[0xA0, 0x00, 0x00, 0x03, 0x08, 0x00, 0x00, 0x10, 0x0
pub const INS_SELECT: u8 = 0xA4;
pub const INS_VERIFY: u8 = 0x20;
pub const INS_CHANGE_REFERENCE: u8 = 0x24;
pub const INS_RESET_RETRY: u8 = 0x2C;
pub const INS_GENERAL_AUTHENTICATE: u8 = 0x87;
pub const INS_GENERATE_ASYMMETRIC: u8 = 0x47;
pub const INS_GET_DATA: u8 = 0xCB;
pub const INS_RESET_PIV: u8 = 0xFB;
pub const INS_GET_METADATA: u8 = 0xF7;
pub const INS_ATTEST: u8 = 0xF9;
pub const INS_IMPORT_KEY: u8 = 0xFE;
@@ -30,6 +32,13 @@ pub const SLOT_SIGNATURE: u8 = 0x9C;
pub const SLOT_KEY_MANAGEMENT: u8 = 0x9D;
pub const SLOT_CARD_AUTH: u8 = 0x9E;
pub const SLOT_ATTESTATION: u8 = 0xF9;
pub const SLOT_CARD_MANAGEMENT: u8 = 0x9B;
// Management-key algorithm (key reference 9B). AES-192 is the YubiKey 5.7 default.
pub const MGMT_ALG_TDES: u8 = 0x03;
pub const MGMT_ALG_AES128: u8 = 0x08;
pub const MGMT_ALG_AES192: u8 = 0x0A;
pub const MGMT_ALG_AES256: u8 = 0x0C;
pub const PIN_POLICY_NEVER: u8 = 0x01;
pub const PIN_POLICY_ONCE: u8 = 0x02;
@@ -42,26 +51,80 @@ pub const TOUCH_POLICY_CACHED: u8 = 0x03;
const TAG_DYNAMIC_AUTH: u8 = 0x7C;
const TAG_AUTH_RESPONSE: u8 = 0x82;
const TAG_AUTH_CHALLENGE: u8 = 0x81;
/// Management-key auth witness (same byte as `TAG_GEN_ALGORITHM`, different context).
const TAG_AUTH_WITNESS: u8 = 0x80;
const TAG_AUTH_EXPONENTIATION: u8 = 0x85;
const TAG_GEN_ALGORITHM: u8 = 0x80;
const TAG_PIN_POLICY: u8 = 0xAA;
const TAG_TOUCH_POLICY: u8 = 0xAB;
const TAG_OBJECT_ID: u8 = 0x5C;
const TAG_ECC_POINT: u8 = 0x86;
/// GET METADATA public-key field (Yubico).
const TAG_METADATA_PUBLIC_KEY: u8 = 0x04;
/// Cert object ID for slot 9A (Authentication).
pub const OBJ_ID_9A: &[u8] = &[0x5F, 0xC1, 0x05];
/// Cert object ID for slot 9D (Key Management).
pub const OBJ_ID_9D: &[u8] = &[0x5F, 0xC1, 0x0B];
/// Object ID for the device attestation (slot F9) intermediate certificate.
pub const OBJ_ID_F9: &[u8] = &[0x5F, 0xFF, 0x01];
pub fn slot_to_object_id(slot: u8) -> Option<&'static [u8]> {
match slot {
0x9A => Some(OBJ_ID_9A),
0x9D => Some(OBJ_ID_9D),
SLOT_ATTESTATION => Some(OBJ_ID_F9),
_ => None,
}
}
/// Extract the certificate DER from a PIV GET DATA cert object response, which
/// wraps the cert as `53 L { 70 L <certDER> 71 .. FE .. }`. Falls back to the raw
/// buffer if it already looks like a bare certificate (`30` SEQUENCE).
pub fn parse_certificate_object(resp: &[u8]) -> Option<Vec<u8>> {
let content = read_ber_tlv(resp, 0x53).unwrap_or(resp);
if let Some(cert) = read_ber_tlv(content, 0x70) {
return Some(cert.to_vec());
}
match resp.first() {
Some(0x30) => Some(resp.to_vec()),
_ => None,
}
}
/// First top-level BER-TLV with `tag` in `buf`, returning its value. Handles
/// short-form and 1-/2-byte long-form lengths; single-byte tags only.
fn read_ber_tlv(buf: &[u8], tag: u8) -> Option<&[u8]> {
let mut i = 0;
while i + 1 < buf.len() {
let t = buf[i];
let len_byte = buf[i + 1];
i += 2;
let len = if len_byte < 0x80 {
len_byte as usize
} else {
let n = (len_byte & 0x7f) as usize;
if n == 0 || n > 2 || i + n > buf.len() {
return None;
}
let mut l = 0usize;
for _ in 0..n {
l = (l << 8) | buf[i] as usize;
i += 1;
}
l
};
if i + len > buf.len() {
return None;
}
if t == tag {
return Some(&buf[i..i + len]);
}
i += len;
}
None
}
// ISO 7816-4 APDU: CLA INS P1 P2 [Lc] [Data]. CLA=0x00 (no chaining, no secure messaging).
fn build_apdu(ins: u8, p1: u8, p2: u8, data: &[u8]) -> Vec<u8> {
let mut apdu = Vec::with_capacity(5 + data.len());
@@ -129,6 +192,25 @@ pub fn change_pin(old_pin: &str, new_pin: &str) -> Vec<u8> {
build_apdu(INS_CHANGE_REFERENCE, 0x00, 0x80, &data)
}
/// RESET RETRY COUNTER: unblock a locked PIN with the PUK and set a new PIN.
pub fn reset_retry(puk: &str, new_pin: &str) -> Vec<u8> {
let mut data = [0xFFu8; 16];
let puk_bytes = puk.as_bytes();
let new_bytes = new_pin.as_bytes();
let puk_len = puk_bytes.len().min(8);
let new_len = new_bytes.len().min(8);
data[..puk_len].copy_from_slice(&puk_bytes[..puk_len]);
data[8..8 + new_len].copy_from_slice(&new_bytes[..new_len]);
build_apdu(INS_RESET_RETRY, 0x00, 0x80, &data)
}
/// RESET PIV: erase all PIV data and restore factory PIV secrets.
///
/// YubiKey only accepts this command after both the PIN and PUK are blocked.
pub fn reset_piv() -> Vec<u8> {
build_apdu(INS_RESET_PIV, 0x00, 0x00, &[])
}
// GENERATE ASYMMETRIC KEY PAIR (Ed25519/X25519).
pub fn generate_key(
slot: u8,
@@ -147,6 +229,63 @@ pub fn generate_key(
build_apdu(INS_GENERATE_ASYMMETRIC, 0x00, slot, &data)
}
// Yubico private-key import elements: Ed25519 = 0x07, X25519 = 0x08.
const TAG_IMPORT_ED25519: u8 = 0x07;
const TAG_IMPORT_X25519: u8 = 0x08;
/// IMPORT ASYMMETRIC KEY (Ed25519, slot). Requires management-key auth. For
/// recoverable provisioning — the key was derived off-device from a seed phrase.
pub fn import_ed25519(
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
import_key(
slot,
ALG_ED25519,
TAG_IMPORT_ED25519,
private_key,
pin_policy,
touch_policy,
)
}
/// IMPORT ASYMMETRIC KEY (X25519, slot). Requires management-key auth.
pub fn import_x25519(
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
import_key(
slot,
ALG_X25519,
TAG_IMPORT_X25519,
private_key,
pin_policy,
touch_policy,
)
}
fn import_key(
slot: u8,
alg: u8,
key_tag: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Vec<u8> {
let mut data = tlv(key_tag, private_key);
if let Some(pp) = pin_policy {
data.extend_from_slice(&tlv(TAG_PIN_POLICY, &[pp]));
}
if let Some(tp) = touch_policy {
data.extend_from_slice(&tlv(TAG_TOUCH_POLICY, &[tp]));
}
build_apdu(INS_IMPORT_KEY, alg, slot, &data)
}
/// GENERAL AUTHENTICATE Ed25519 sign. Send raw message — device does SHA-512 internally; no pre-hash.
pub fn sign_ed25519(slot: u8, message: &[u8]) -> Vec<u8> {
let challenge = tlv(TAG_AUTH_CHALLENGE, message);
@@ -194,6 +333,64 @@ pub fn attest_key(slot: u8) -> Vec<u8> {
build_apdu(INS_ATTEST, slot, 0x00, &[])
}
// --- Management-key authentication (slot 9B, witness/challenge mutual auth) ---
/// Step 1: request an encrypted witness from the card. `mgmt_alg` is the
/// management-key algorithm (P1).
pub fn auth_witness_request(mgmt_alg: u8) -> Vec<u8> {
let inner = tlv(TAG_AUTH_WITNESS, &[]);
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(
INS_GENERAL_AUTHENTICATE,
mgmt_alg,
SLOT_CARD_MANAGEMENT,
&data,
)
}
/// Step 3: return the decrypted witness plus our own challenge.
pub fn auth_witness_response(mgmt_alg: u8, decrypted_witness: &[u8], challenge: &[u8]) -> Vec<u8> {
let mut inner = tlv(TAG_AUTH_WITNESS, decrypted_witness);
inner.extend_from_slice(&tlv(TAG_AUTH_CHALLENGE, challenge));
let data = tlv(TAG_DYNAMIC_AUTH, &inner);
build_apdu(
INS_GENERAL_AUTHENTICATE,
mgmt_alg,
SLOT_CARD_MANAGEMENT,
&data,
)
}
/// Extract the witness (tag 0x80) from a witness-request response.
pub fn parse_auth_witness(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
find_tlv_value(data, TAG_AUTH_WITNESS)
.map(<[u8]>::to_vec)
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
/// Extract the card's encrypted challenge (tag 0x82) from a witness-response reply.
pub fn parse_auth_response(data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
find_tlv_value(data, TAG_AUTH_RESPONSE)
.map(<[u8]>::to_vec)
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
/// Algorithm byte (tag 0x01) from a GET METADATA response (e.g. slot 9B mgmt key).
pub fn parse_metadata_algorithm(metadata: &[u8]) -> Result<u8, RatkeyError> {
find_tlv_value(metadata, 0x01)
.and_then(|v| v.first().copied())
.ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})
}
pub fn check_response(response: &[u8]) -> Result<&[u8], RatkeyError> {
if response.len() < 2 {
return Err(RatkeyError::Apdu {
@@ -293,6 +490,31 @@ pub fn parse_ecdh_response(data: &[u8]) -> Result<[u8; 32], RatkeyError> {
Ok(out)
}
/// GET METADATA public key: field tag 0x04, then EC point tag 0x86 → 32 bytes.
/// `find_tlv_value` recurses into a `7F49` wrapper if present, so both the
/// bare (`86 20 ..`) and wrapped (`7F49 .. 86 20 ..`) encodings resolve.
/// Yubico 5.3+ extension; Nitrokey 3 does not implement GET METADATA.
pub fn parse_metadata_public_key(metadata: &[u8]) -> Result<[u8; 32], RatkeyError> {
let pubkey_field =
find_tlv_value(metadata, TAG_METADATA_PUBLIC_KEY).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
let point = find_tlv_value(pubkey_field, TAG_ECC_POINT).ok_or(RatkeyError::Apdu {
sw1: 0x6A,
sw2: 0x80,
})?;
if point.len() != 32 {
return Err(RatkeyError::InvalidHwid(format!(
"expected 32-byte public key in metadata, got {} bytes",
point.len()
)));
}
let mut out = [0u8; 32];
out.copy_from_slice(point);
Ok(out)
}
// Recurse into 7C / AC / 53 / any 2-byte tag (7F49 etc) to find a single-byte tag.
fn find_tlv_value(data: &[u8], target_tag: u8) -> Option<&[u8]> {
let mut pos = 0;
@@ -507,6 +729,34 @@ mod tests {
assert_eq!(apdu, vec![0x00, 0xF9, 0x9A, 0x00]);
}
#[test]
fn test_get_data_slot_f9_attestation() {
let apdu = get_data(SLOT_ATTESTATION).unwrap();
assert_eq!(
apdu,
vec![0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C, 0x03, 0x5F, 0xFF, 0x01]
);
}
#[test]
fn test_parse_certificate_object() {
// A 200-byte "cert" (DER SEQUENCE header) forces long-form lengths, wrapped
// as the PIV cert object: 53 L { 70 L <cert> 71 01 00 FE 00 }.
let mut cert = vec![0x30, 0x81, 0xC5];
cert.extend(std::iter::repeat_n(0xAB, 197));
let mut inner = vec![0x70, 0x81, cert.len() as u8];
inner.extend_from_slice(&cert);
inner.extend_from_slice(&[0x71, 0x01, 0x00, 0xFE, 0x00]);
let mut obj = vec![0x53, 0x81, inner.len() as u8];
obj.extend_from_slice(&inner);
assert_eq!(parse_certificate_object(&obj).unwrap(), cert);
// Bare DER (no PIV wrapper) is returned as-is.
assert_eq!(parse_certificate_object(&cert).unwrap(), cert);
// Non-cert payload yields nothing.
assert!(parse_certificate_object(&[0x00, 0x01, 0x02]).is_none());
}
#[test]
fn test_get_metadata() {
let apdu = get_metadata(SLOT_AUTHENTICATION);
@@ -571,6 +821,29 @@ mod tests {
);
}
#[test]
fn test_reset_retry() {
let apdu = reset_retry("12345678", "654321");
assert_eq!(apdu[0], 0x00); // CLA
assert_eq!(apdu[1], 0x2C); // INS = RESET RETRY
assert_eq!(apdu[2], 0x00); // P1
assert_eq!(apdu[3], 0x80); // P2 = PIN
assert_eq!(apdu[4], 0x10); // Lc = 16
assert_eq!(
&apdu[5..13],
&[0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]
);
assert_eq!(
&apdu[13..21],
&[0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0xFF, 0xFF]
);
}
#[test]
fn test_reset_piv() {
assert_eq!(reset_piv(), vec![0x00, 0xFB, 0x00, 0x00]);
}
#[test]
fn test_check_response_success() {
let response = vec![0xAA, 0xBB, 0x90, 0x00];
@@ -632,6 +905,119 @@ mod tests {
assert_eq!(secret, [0xCC; 32]);
}
#[test]
fn test_auth_witness_request() {
let apdu = auth_witness_request(MGMT_ALG_AES192);
assert_eq!(
apdu,
vec![0x00, 0x87, 0x0A, 0x9B, 0x04, 0x7C, 0x02, 0x80, 0x00]
);
}
#[test]
fn test_auth_witness_response_carries_witness() {
let witness = [0xAA; 16];
let challenge = [0xBB; 16];
let apdu = auth_witness_response(MGMT_ALG_AES192, &witness, &challenge);
assert_eq!(apdu[1], 0x87); // INS GENERAL AUTHENTICATE
assert_eq!(apdu[2], 0x0A); // P1 = AES-192
assert_eq!(apdu[3], 0x9B); // P2 = mgmt slot
assert_eq!(apdu[5], 0x7C); // dynamic auth template
assert_eq!(parse_auth_witness(&apdu[5..]).unwrap(), witness.to_vec());
}
#[test]
fn test_parse_auth_witness() {
let mut resp = vec![0x7C, 0x12, 0x80, 0x10];
resp.extend_from_slice(&[0xCC; 16]);
assert_eq!(parse_auth_witness(&resp).unwrap(), vec![0xCC; 16]);
}
#[test]
fn test_parse_auth_response() {
let mut resp = vec![0x7C, 0x12, 0x82, 0x10];
resp.extend_from_slice(&[0xDD; 16]);
assert_eq!(parse_auth_response(&resp).unwrap(), vec![0xDD; 16]);
}
#[test]
fn test_parse_metadata_algorithm() {
let meta = vec![0x01, 0x01, MGMT_ALG_AES192];
assert_eq!(parse_metadata_algorithm(&meta).unwrap(), MGMT_ALG_AES192);
}
#[test]
fn test_import_ed25519() {
let key = [0x11; 32];
let apdu = import_ed25519(
SLOT_AUTHENTICATION,
&key,
Some(PIN_POLICY_ONCE),
Some(TOUCH_POLICY_NEVER),
);
assert_eq!(apdu[1], 0xFE); // INS IMPORT KEY
assert_eq!(apdu[2], 0xE0); // P1 = Ed25519
assert_eq!(apdu[3], 0x9A); // P2 = slot
assert_eq!(apdu[5], 0x07); // Ed25519 private-key element tag
assert_eq!(apdu[6], 0x20); // 32-byte length
assert_eq!(&apdu[7..39], &key);
assert_eq!(
&apdu[39..45],
&[0xAA, 0x01, PIN_POLICY_ONCE, 0xAB, 0x01, TOUCH_POLICY_NEVER]
);
}
#[test]
fn test_import_x25519_tag() {
let apdu = import_x25519(SLOT_KEY_MANAGEMENT, &[0x22; 32], None, None);
assert_eq!(apdu[1], 0xFE);
assert_eq!(apdu[2], 0xE1); // X25519
assert_eq!(apdu[3], 0x9D);
assert_eq!(apdu[5], 0x08); // X25519 private-key element tag
assert_eq!(apdu[6], 0x20);
}
#[test]
fn test_parse_metadata_public_key_bare() {
// Slot metadata: 01(algo) 02(policy) 03(origin) 04(pubkey = 86 20 <32>).
// Layout pending confirmation against a real YubiKey GET METADATA response.
let mut meta = vec![
0x01,
0x01,
ALG_ED25519,
0x02,
0x02,
PIN_POLICY_ONCE,
TOUCH_POLICY_ALWAYS,
0x03,
0x01,
0x01,
0x04,
0x22,
0x86,
0x20,
];
meta.extend_from_slice(&[0xAB; 32]);
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xAB; 32]);
}
#[test]
fn test_parse_metadata_public_key_7f49_wrapped() {
// Same, but the point is wrapped in a 7F49 template (04 25 7F49 22 86 20 <32>).
let mut meta = vec![
0x01, 0x01, ALG_X25519, 0x04, 0x25, 0x7F, 0x49, 0x22, 0x86, 0x20,
];
meta.extend_from_slice(&[0xCD; 32]);
assert_eq!(parse_metadata_public_key(&meta).unwrap(), [0xCD; 32]);
}
#[test]
fn test_parse_metadata_public_key_missing_field() {
// No 0x04 field present.
let meta = vec![0x01, 0x01, ALG_ED25519, 0x03, 0x01, 0x01];
assert!(parse_metadata_public_key(&meta).is_err());
}
#[test]
fn test_parse_generate_response_wrong_size() {
let mut response = vec![0x7F, 0x49, 0x12, 0x86, 0x10];
+692 -31
View File
@@ -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 rsa::signature::Verifier;
use sha2::{Digest, Sha256, Sha512};
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,22 @@ 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 +90,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 +124,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,9 +137,8 @@ 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) {
if major > 5 || (major == 5 && (minor > 7 || (minor == 7 && patch >= 4))) {
"new".to_string()
} else {
"legacy".to_string()
@@ -93,17 +147,17 @@ 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 +169,268 @@ 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<TrustAnchor> {
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<Certificate> {
[
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,
&current.tbs_certificate.issuer,
) && verify_signature(&current, &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(
&current.tbs_certificate.subject,
&current.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,
&current.tbs_certificate.issuer,
) && verify_signature(&current, 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,
&current.tbs_certificate.issuer,
)
}) || searchable.iter().any(|c| {
names_match(&c.tbs_certificate.subject, &current.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::<Sha256>::new(pubkey)
.verify(&tbs, &sig)
.map_err(|_| ChainError::SignatureInvalid)
} else if alg == OID_SHA512_RSA {
VerifyingKey::<Sha512>::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 +690,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 +706,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 +714,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]
@@ -434,6 +741,25 @@ mod tests {
assert_eq!(result.root_ca, "new"); // 5.7.4 → new root CA
}
#[test]
fn test_verify_attestation_future_firmware_uses_new_root_label() {
let mut attest_der = Vec::new();
let mut inner = Vec::new();
inner.push(0x06);
inner.push(OID_FIRMWARE_VERSION.len() as u8);
inner.extend_from_slice(OID_FIRMWARE_VERSION);
inner.push(0x04);
inner.push(0x03);
inner.extend_from_slice(&[0x05, 0x08, 0x00]); // 5.8.0
attest_der.push(0x30);
attest_der.push(inner.len() as u8);
attest_der.extend_from_slice(&inner);
let result = verify_attestation(&attest_der, &[0x30, 0x00]).unwrap();
assert_eq!(result.root_ca, "new");
}
#[test]
fn test_verify_attestation_empty_cert() {
let result = verify_attestation(&[], &[]).unwrap();
@@ -442,4 +768,339 @@ mod tests {
assert!(!result.chain_verified);
assert_eq!(result.root_ca, "unknown");
}
// Real on-device vectors captured from a YubiKey 5.7.4 (serial 35284666) via
// `rnid-rs hw attest`: the slot-9A per-key attestation cert + the slot-F9
// device intermediate. Proves the verifier chains a real device's ATTEST
// output to a bundled, fingerprint-pinned Yubico root — the regression guard
// for the hardware validation, runnable in CI without a device.
// Both certs are notAfter=9999-12-31 (Yubico attestation certs do not expire),
// so the validity-window check in `verify_chain` will not rot this vector.
#[test]
fn test_real_yubikey_attestation_chain_verifies() {
let attest = include_bytes!("../tests/fixtures/9a_attest.der");
let device = include_bytes!("../tests/fixtures/f9_device.der");
let v = verify_attestation(attest, device).unwrap();
assert!(
v.chain_verified,
"real-device chain must verify: {}",
v.description
);
assert!(v.verified);
assert_eq!(v.root_ca, "new");
assert_eq!(v.info.firmware_version, Some((5, 7, 4)));
assert_eq!(v.info.serial_number, Some(35284666));
}
// ---------------------------------------------------------------------
// 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 std::str::FromStr;
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};
struct Node {
cert: Certificate,
der: Vec<u8>,
}
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::<Sha256>::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::<RsaSignature>().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)],
std::slice::from_ref(&sub.cert),
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)],
std::slice::from_ref(&sub.cert),
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)],
std::slice::from_ref(&sub.cert),
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:?}"
);
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Bridges a PIV token to an `rns_identity::Identity` via the `LocalKeyBackend`
//! seam. The PIV session runs on a dedicated thread — pcsc handles want serial
//! APDU access and are not `Sync` — so the backend handle holds only channel
//! senders and is therefore `Send + Sync`, usable directly from the async runtime.
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use rns_identity::identity::{Identity, LocalKeyBackend};
use crate::apdu::{SLOT_AUTHENTICATION, SLOT_KEY_MANAGEMENT};
use crate::error::RatkeyError;
use crate::hwid::HwidConfig;
use crate::session::PivSession;
use crate::transport::PcscTransport;
enum Cmd {
Sign {
message: Vec<u8>,
reply: Sender<Option<[u8; 64]>>,
},
Ecdh {
peer_pub: [u8; 32],
reply: Sender<Option<[u8; 32]>>,
},
/// Re-select the PIV applet to drop the on-card PIN cache. Acknowledged so
/// callers (lock-on-quit / timeout) can block until the card is re-locked.
Lock { reply: Sender<()> },
}
/// `LocalKeyBackend` over a PIV token. Each call round-trips a request to the
/// card-service thread and blocks for the device's reply (PIV ops are ~10-50ms).
pub struct HardwareBackend {
cmd_tx: Mutex<Sender<Cmd>>,
}
impl LocalKeyBackend for HardwareBackend {
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
let (reply, rx) = mpsc::channel();
self.cmd_tx
.lock()
.ok()?
.send(Cmd::Sign {
message: message.to_vec(),
reply,
})
.ok()?;
rx.recv().ok().flatten()
}
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
let (reply, rx) = mpsc::channel();
self.cmd_tx
.lock()
.ok()?
.send(Cmd::Ecdh {
peer_pub: *peer_pub,
reply,
})
.ok()?;
rx.recv().ok().flatten()
}
fn lock(&self) {
let (reply, rx) = mpsc::channel();
if let Ok(tx) = self.cmd_tx.lock()
&& tx.send(Cmd::Lock { reply }).is_ok()
{
let _ = rx.recv();
}
}
}
/// Connect to the token described by `hwid`, verify the on-device keys match it
/// (fail-closed), unlock with `pin`, and return an `Identity` whose private
/// operations run on the device. The PIV session lives on a worker thread that
/// exits when the returned identity (and its backend) is dropped.
pub fn load_hardware_identity(hwid: &HwidConfig, pin: &str) -> Result<Identity, RatkeyError> {
let ed_pub = hwid.ed25519_pub_bytes()?;
let x_pub = hwid.x25519_pub_bytes()?;
let pin = pin.to_string();
let (cmd_tx, cmd_rx) = mpsc::channel::<Cmd>();
let (ready_tx, ready_rx) = mpsc::channel::<Result<(), RatkeyError>>();
thread::Builder::new()
.name("ratkey-piv".to_string())
.spawn(move || {
let mut session = match PivSession::<PcscTransport>::connect() {
Ok(s) => s,
Err(e) => {
let _ = ready_tx.send(Err(e));
return;
}
};
// Fail closed: the device's slot keys must match the .hwid.
match (
session.read_public_key(SLOT_AUTHENTICATION),
session.read_public_key(SLOT_KEY_MANAGEMENT),
) {
(Ok(de), Ok(dx)) if de == ed_pub && dx == x_pub => {}
(Ok(_), Ok(_)) => {
let _ = ready_tx.send(Err(RatkeyError::KeyMismatch));
return;
}
(Err(e), _) | (_, Err(e)) => {
let _ = ready_tx.send(Err(e));
return;
}
}
if let Err(e) = session.verify_pin(&pin) {
let _ = ready_tx.send(Err(e));
return;
}
let _ = ready_tx.send(Ok(()));
// Serve sign/ECDH until the backend is dropped (sender closed).
while let Ok(cmd) = cmd_rx.recv() {
match cmd {
Cmd::Sign { message, reply } => {
let _ =
reply.send(session.sign_ed25519(SLOT_AUTHENTICATION, &message).ok());
}
Cmd::Ecdh { peer_pub, reply } => {
let _ =
reply.send(session.ecdh_x25519(SLOT_KEY_MANAGEMENT, &peer_pub).ok());
}
Cmd::Lock { reply } => {
let locked = session.lock().is_ok();
tracing::debug!(locked, "PIV applet re-selected (PIN cache dropped)");
let _ = reply.send(());
}
}
}
})
.map_err(|e| RatkeyError::Io(std::io::Error::other(e.to_string())))?;
// Wait for the worker to connect, match, and unlock before handing back.
ready_rx.recv().map_err(|_| RatkeyError::NoDevice)??;
let mut pub64 = [0u8; 64];
pub64[..32].copy_from_slice(&x_pub);
pub64[32..].copy_from_slice(&ed_pub);
Identity::from_backend(
&pub64,
Arc::new(HardwareBackend {
cmd_tx: Mutex::new(cmd_tx),
}),
)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot build identity: {e}")))
}
+12 -6
View File
@@ -1,9 +1,4 @@
//! PC/SC reader enumeration; filters to YubiKey 5 / Nitrokey 3 by reader name.
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, info, warn};
use crate::error::RatkeyError;
//! Device classification (always available) + PC/SC reader enumeration (behind `hardware`).
#[derive(Debug, Clone)]
pub struct DeviceInfo {
@@ -47,6 +42,14 @@ pub fn detect_device_type(reader_name: &str) -> DeviceType {
}
}
#[cfg(feature = "hardware")]
use crate::error::RatkeyError;
#[cfg(feature = "hardware")]
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
#[cfg(feature = "hardware")]
use tracing::{debug, info, warn};
#[cfg(feature = "hardware")]
pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
@@ -64,6 +67,7 @@ pub fn list_readers() -> Result<Vec<String>, RatkeyError> {
Ok(names)
}
#[cfg(feature = "hardware")]
pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
let readers = list_readers()?;
let mut devices = Vec::new();
@@ -101,6 +105,7 @@ pub fn detect_devices() -> Result<Vec<DeviceInfo>, RatkeyError> {
Ok(devices)
}
#[cfg(feature = "hardware")]
fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
use crate::apdu;
@@ -150,6 +155,7 @@ fn try_connect_piv(reader_name: &str) -> Result<DeviceInfo, RatkeyError> {
/// Best-effort serial/firmware read. Yubico proprietary INS — Nitrokey 3 returns (None, None).
/// APDU errors are tolerated; never fails a connection.
#[cfg(feature = "hardware")]
pub(crate) fn read_identity(card: &Card, device_type: DeviceType) -> (Option<u32>, Option<String>) {
use crate::apdu;
+15 -2
View File
@@ -11,10 +11,20 @@ pub enum RatkeyError {
#[error("PIN verification failed ({remaining} attempts remaining)")]
PinFailed { remaining: u8 },
/// PIN locked (retry counter exhausted); PUK required to unlock.
#[error("PIN locked — device requires PUK to unlock")]
/// PIN locked (retry counter exhausted); PIV reset or recovery-code unlock required.
#[error("PIN locked — reset the PIV application to recover")]
PinLocked,
#[error("PIV recovery code failed ({remaining} attempts remaining)")]
PukFailed { remaining: u8 },
/// Recovery counter exhausted; PIV reset is required.
#[error("PIV recovery counter locked — reset the PIV application to recover")]
PukLocked,
#[error("PIV reset requires both retry counters to be blocked")]
ResetRequiresBlockedPinAndPuk,
#[error("PIN required — call verify_pin() first")]
PinRequired,
@@ -36,6 +46,9 @@ pub enum RatkeyError {
#[error("key mismatch: hardware public key does not match .hwid file")]
KeyMismatch,
#[error("management key authentication failed")]
ManagementAuthFailed,
#[cfg(feature = "hardware")]
#[error("PC/SC error: {0}")]
Pcsc(#[from] pcsc::Error),
+367 -79
View File
@@ -1,5 +1,6 @@
//! `HardwareIdentity`: public-key-only `Identity` + PIV session for private ops.
//! Wire-compatible with software identities.
//! `HardwareIdentity`: a public-key-only `Identity` whose private ops are served
//! by an `IdentityBackend` (real PIV session or mock). Wire-compatible with
//! software identities.
use std::path::Path;
@@ -7,71 +8,128 @@ use rns_crypto::hkdf::derive_key_64;
use rns_crypto::token;
use rns_identity::identity::Identity;
use crate::apdu::{SLOT_AUTHENTICATION as SLOT_9A, SLOT_KEY_MANAGEMENT as SLOT_9D};
use crate::error::RatkeyError;
use crate::hwid::HwidConfig;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D};
use crate::mock::MockPivSession;
use crate::session::PivSession;
use crate::transport::PivTransport;
/// The private-key operations `HardwareIdentity` needs from a token. Implemented
/// by `PivSession<T>` (any transport) and `MockPivSession`, so the runtime
/// identity is backend-agnostic.
pub trait IdentityBackend {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError>;
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError>;
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError>;
fn is_connected(&self) -> bool;
/// Re-lock the session (require PIN again on the next op).
fn lock(&mut self) -> Result<(), RatkeyError>;
}
// Inherent methods take precedence over trait methods, so these delegate without recursing.
impl<T: PivTransport> IdentityBackend for PivSession<T> {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
self.sign_ed25519(slot, message)
}
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
self.ecdh_x25519(slot, peer_pub)
}
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.read_public_key(slot)
}
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
self.read_public_key(slot)
}
fn is_connected(&self) -> bool {
self.is_connected()
}
fn lock(&mut self) -> Result<(), RatkeyError> {
self.lock()
}
}
impl IdentityBackend for MockPivSession {
fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
self.sign_ed25519(slot, message)
}
fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
self.ecdh_x25519(slot, peer_pub)
}
fn read_ed25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
MockPivSession::read_ed25519_public(self, slot)
}
fn read_x25519_public(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
MockPivSession::read_x25519_public(self, slot)
}
fn is_connected(&self) -> bool {
self.is_connected()
}
fn lock(&mut self) -> Result<(), RatkeyError> {
self.lock();
Ok(())
}
}
pub struct HardwareIdentity {
pub identity: Identity,
pub config: HwidConfig,
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
// Mock session storage keeps the current API testable until the real PIV
// backend is wired. See crates/rns-ratkey/HARDWARE_STATUS.md.
mock_session: Option<MockPivSession>,
backend: Box<dyn IdentityBackend>,
}
impl HardwareIdentity {
pub fn from_hwid_mock(
/// Build from a `.hwid` config + a backend. Fail-closed: the device's slot
/// public keys must match the published identity.
pub fn from_hwid(
config: HwidConfig,
session: MockPivSession,
mut backend: Box<dyn IdentityBackend>,
) -> Result<Self, RatkeyError> {
let ed25519_pub = config.ed25519_pub_bytes()?;
let x25519_pub = config.x25519_pub_bytes()?;
// Fail closed: published identity hash must map to keys actually on the device.
let session_ed = session.read_ed25519_public(SLOT_9A)?;
let session_x = session.read_x25519_public(SLOT_9D)?;
let session_ed = backend.read_ed25519_public(SLOT_9A)?;
let session_x = backend.read_x25519_public(SLOT_9D)?;
if session_ed != ed25519_pub || session_x != x25519_pub {
return Err(RatkeyError::KeyMismatch);
}
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
backend,
})
}
pub fn from_file_mock(path: &Path, session: MockPivSession) -> Result<Self, RatkeyError> {
pub fn from_file(path: &Path, backend: Box<dyn IdentityBackend>) -> Result<Self, RatkeyError> {
let config = HwidConfig::from_file(path)?;
Self::from_hwid_mock(config, session)
Self::from_hwid(config, backend)
}
/// Test-only: build without `.hwid`; skips key-mismatch guard.
pub fn from_keys_mock(
/// Test / first-bring-up: build without a `.hwid` and skip the key-mismatch
/// guard, so sign/ECDH can be validated independently of metadata pubkey
/// readback.
pub fn from_keys(
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
session: MockPivSession,
backend: Box<dyn IdentityBackend>,
) -> Result<Self, RatkeyError> {
let identity = build_identity(&ed25519_pub, &x25519_pub)?;
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: String::new(),
hash: hex::encode(identity.hash),
nickname: "test".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: session.device_type.clone(),
serial: session.serial,
firmware: session.firmware.clone(),
device_type: "unknown".to_string(),
serial: 0,
firmware: "unknown".to_string(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
@@ -91,22 +149,12 @@ impl HardwareIdentity {
backup: Default::default(),
};
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(&x25519_pub);
pub_key_bytes[32..].copy_from_slice(&ed25519_pub);
let identity = Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))?;
let mut config = config;
// Hash is derived from the Identity so the .hwid stays consistent.
config.identity.hash = hex::encode(identity.hash);
Ok(Self {
identity,
config,
ed25519_pub,
x25519_pub,
mock_session: Some(session),
backend,
})
}
@@ -136,13 +184,11 @@ impl HardwareIdentity {
}
pub fn sign(&mut self, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.sign_ed25519(SLOT_9A, message)
self.backend.sign_ed25519(SLOT_9A, message)
}
pub fn ecdh(&mut self, peer_pub_bytes: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let session = self.mock_session.as_mut().ok_or(RatkeyError::NoDevice)?;
session.ecdh_x25519(SLOT_9D, peer_pub_bytes)
self.backend.ecdh_x25519(SLOT_9D, peer_pub_bytes)
}
/// Ciphertext = ephemeral_pub(32) || AES-256-CBC token. Mirrors `Identity::decrypt`
@@ -190,23 +236,38 @@ impl HardwareIdentity {
}
pub fn is_connected(&self) -> bool {
self.mock_session.as_ref().is_some_and(|s| s.is_connected())
self.backend.is_connected()
}
/// Re-lock the session; the next sign/ECDH will require the PIN again.
/// The app calls this on its session timeout and on quit.
pub fn lock(&mut self) -> Result<(), RatkeyError> {
self.backend.lock()
}
}
fn build_identity(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> Result<Identity, RatkeyError> {
let mut pub_key_bytes = [0u8; 64];
pub_key_bytes[..32].copy_from_slice(x25519_pub);
pub_key_bytes[32..].copy_from_slice(ed25519_pub);
Identity::from_public_key(&pub_key_bytes)
.map_err(|e| RatkeyError::InvalidHwid(format!("cannot create identity: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::{SLOT_9A as MOCK_9A, SLOT_9D as MOCK_9D};
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
use rns_identity::identity::Identity;
#[test]
fn test_from_keys_mock() {
fn test_from_keys() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert_eq!(hw.ed25519_public(), &ed_pub);
assert_eq!(hw.x25519_public(), &x_pub);
assert!(!hw.hash_hex().is_empty());
@@ -215,9 +276,9 @@ mod tests {
#[test]
fn test_sign_and_verify() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let message = b"ratkey hardware identity test";
let sig = hw.sign(message).unwrap();
@@ -231,9 +292,9 @@ mod tests {
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
@@ -256,9 +317,9 @@ mod tests {
#[test]
fn test_ecdh_with_software_peer() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let peer_prv = X25519PrivateKey::generate();
let peer_pub = peer_prv.public_key();
@@ -277,9 +338,9 @@ mod tests {
let ed_seed = [0x42u8; 32];
let x_secret = [0x43u8; 32];
let session = MockPivSession::with_key_bytes(&ed_seed, &x_secret);
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let mut prv_bytes = [0u8; 64];
prv_bytes[..32].copy_from_slice(&x_secret);
@@ -296,9 +357,9 @@ mod tests {
#[test]
fn test_encrypt_from_other_identity() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
let _sender = Identity::new();
@@ -310,27 +371,16 @@ mod tests {
#[test]
fn test_disconnect_fails_operations() {
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(SLOT_9A).unwrap();
let x_pub = session.read_x25519_public(SLOT_9D).unwrap();
let mut hw = HardwareIdentity::from_keys_mock(ed_pub, x_pub, session).unwrap();
let mut session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
session.disconnect();
assert!(hw.is_connected());
hw.mock_session.as_mut().unwrap().disconnect();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert!(!hw.is_connected());
assert!(matches!(hw.sign(b"test"), Err(RatkeyError::Disconnected)));
}
#[test]
fn test_key_mismatch_rejected() {
// from_keys_mock does not cross-check; the .hwid path does (test_hwid_key_mismatch).
let session = MockPivSession::with_keys();
let wrong_ed = [0xFFu8; 32];
let wrong_x = [0xFFu8; 32];
let _result = HardwareIdentity::from_keys_mock(wrong_ed, wrong_x, session);
}
#[test]
fn test_hwid_key_mismatch() {
let session = MockPivSession::with_keys();
@@ -363,7 +413,245 @@ mod tests {
backup: Default::default(),
};
let result = HardwareIdentity::from_hwid_mock(config, session);
let result = HardwareIdentity::from_hwid(config, Box::new(session));
assert!(matches!(result, Err(RatkeyError::KeyMismatch)));
}
// --- Real backend path over a canned-APDU transport ---------------------
// MockPivSession implements IdentityBackend directly and never touches
// PivSession. These exercise the production path (PivSession ops + its
// IdentityBackend impl + read_public_key→parse + slot routing) without a
// device. Caveat: the fake uses the *assumed* metadata layout, so it
// validates glue, not the real byte layout — that stays hardware-only.
use crate::detect::DeviceType;
use crate::session::DeviceMeta;
use crate::transport::PivTransport;
struct FakeTransport {
ed_pub: [u8; 32],
x_pub: [u8; 32],
sig: [u8; 64],
secret: [u8; 32],
}
impl FakeTransport {
fn metadata(key: &[u8; 32]) -> Vec<u8> {
// 01(algo) 04(pubkey = 86 20 <32>) + SW 90 00
let mut v = vec![0x01, 0x01, 0xE0, 0x04, 0x22, 0x86, 0x20];
v.extend_from_slice(key);
v.extend_from_slice(&[0x90, 0x00]);
v
}
}
impl PivTransport for FakeTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let (ins, p1, p2) = (apdu[1], apdu[2], apdu[3]);
match ins {
0xA4 => Ok(vec![0x90, 0x00]), // SELECT (applet / re-lock)
0x20 => Ok(vec![0x90, 0x00]), // VERIFY PIN
0x87 if p1 == 0xE0 => {
assert_eq!(p2, 0x9A, "sign must target slot 9A");
let mut v = vec![0x7C, 0x42, 0x82, 0x40];
v.extend_from_slice(&self.sig);
v.extend_from_slice(&[0x90, 0x00]);
Ok(v)
}
0x87 if p1 == 0xE1 => {
assert_eq!(p2, 0x9D, "ECDH must target slot 9D");
let mut v = vec![0x7C, 0x22, 0x82, 0x20];
v.extend_from_slice(&self.secret);
v.extend_from_slice(&[0x90, 0x00]);
Ok(v)
}
0xF7 => {
// GET METADATA: key keyed by requested slot, so a wrong-slot
// read returns the wrong key.
let key = match p2 {
0x9A => &self.ed_pub,
0x9D => &self.x_pub,
other => panic!("unexpected metadata slot 0x{other:02X}"),
};
Ok(Self::metadata(key))
}
other => panic!("unexpected INS 0x{other:02X}"),
}
}
fn is_connected(&self) -> bool {
true
}
}
fn fake_meta() -> DeviceMeta {
DeviceMeta {
device_type: DeviceType::YubiKey5,
serial: Some(1),
firmware: Some("5.7.4".to_string()),
}
}
#[test]
fn test_pivsession_ops_over_fake_transport() {
let ed_pub = [0x11u8; 32];
let x_pub = [0x22u8; 32];
let sig = [0x33u8; 64];
let secret = [0x44u8; 32];
let fake = FakeTransport {
ed_pub,
x_pub,
sig,
secret,
};
let mut session = PivSession::new(fake, fake_meta());
assert_eq!(session.sign_ed25519(SLOT_9A, b"msg").unwrap(), sig);
assert_eq!(session.ecdh_x25519(SLOT_9D, &[0u8; 32]).unwrap(), secret);
// read_public_key routes the slot and runs the metadata parser.
assert_eq!(session.read_public_key(SLOT_9A).unwrap(), ed_pub);
assert_eq!(session.read_public_key(SLOT_9D).unwrap(), x_pub);
// lock() re-selects the applet (SELECT APDU) without error.
session.lock().unwrap();
}
#[test]
fn test_lock_requires_pin_again() {
// End-to-end session lock on the mock path: sign works, lock, then the
// next op needs the PIN again.
let session = MockPivSession::with_keys();
let ed_pub = session.read_ed25519_public(MOCK_9A).unwrap();
let x_pub = session.read_x25519_public(MOCK_9D).unwrap();
let mut hw = HardwareIdentity::from_keys(ed_pub, x_pub, Box::new(session)).unwrap();
assert!(hw.sign(b"m").is_ok());
hw.lock().unwrap();
assert!(matches!(hw.sign(b"m"), Err(RatkeyError::PinRequired)));
}
#[test]
fn test_hardware_identity_from_hwid_over_real_backend() {
// Closest mock-free representation of the runtime path: HardwareIdentity
// over a real PivSession backend — guard reads pubkeys via metadata, then
// sign dispatches to slot 9A.
let ed_prv = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[0x42u8; 32]);
let ed_pub = ed_prv.public_key().to_bytes();
let x_prv = X25519PrivateKey::from_bytes(&[0x43u8; 32]);
let x_pub = x_prv.public_key().to_bytes();
let sig = [0x33u8; 64];
let fake = FakeTransport {
ed_pub,
x_pub,
sig,
secret: [0x44u8; 32],
};
let session = PivSession::new(fake, fake_meta());
let config = HwidConfig {
identity: crate::hwid::HwidIdentity {
hash: "test".to_string(),
nickname: "fake".to_string(),
created_at: 0,
},
device: crate::hwid::HwidDevice {
device_type: "yubikey5".to_string(),
serial: 1,
firmware: "5.7.4".to_string(),
},
keys: crate::hwid::HwidKeys {
ed25519_pub: hex::encode(ed_pub),
x25519_pub: hex::encode(x_pub),
},
slots: crate::hwid::HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: crate::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "always".to_string(),
touch_encryption: "cached".to_string(),
},
attestation: Default::default(),
app: Default::default(),
backup: Default::default(),
};
let mut hw = HardwareIdentity::from_hwid(config, Box::new(session)).unwrap();
assert_eq!(hw.sign(b"announce").unwrap(), sig);
}
// --- Management-key auth over a card-simulating transport ----------------
// Plays the card side of witness/challenge so the protocol direction (host
// must DECRYPT the witness, not encrypt it) is exercised without hardware.
struct MgmtFakeTransport {
alg: u8,
key: Vec<u8>,
witness: [u8; 16],
}
fn wrap_7c(tag: u8, payload: &[u8]) -> Vec<u8> {
let mut v = vec![0x7C, (payload.len() + 2) as u8, tag, payload.len() as u8];
v.extend_from_slice(payload);
v.extend_from_slice(&[0x90, 0x00]); // SW OK
v
}
impl PivTransport for MgmtFakeTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let (ins, p2) = (apdu[1], apdu[3]);
match (ins, p2) {
(0xF7, 0x9B) => Ok(vec![0x01, 0x01, self.alg, 0x90, 0x00]), // metadata: alg
(0x87, 0x9B) => {
let data = &apdu[5..];
let witness_field = crate::apdu::parse_auth_witness(data).unwrap();
if witness_field.is_empty() {
// witness request → return the witness encrypted with the key
let enc =
crate::mgmt::ecb_encrypt(self.alg, &self.key, &self.witness).unwrap();
Ok(wrap_7c(0x80, &enc))
} else if witness_field.as_slice() == self.witness {
// correct decrypted witness → encrypt the host's challenge
let challenge = &data[data.len() - 16..];
let enc = crate::mgmt::ecb_encrypt(self.alg, &self.key, challenge).unwrap();
Ok(wrap_7c(0x82, &enc))
} else {
// wrong witness → card rejects (security status not satisfied)
Ok(vec![0x69, 0x82])
}
}
_ => panic!("unexpected mgmt apdu ins=0x{ins:02X} p2=0x{p2:02X}"),
}
}
fn is_connected(&self) -> bool {
true
}
}
#[test]
fn test_authenticate_management_key_success() {
let key = vec![0x5Au8; 24]; // AES-192
let fake = MgmtFakeTransport {
alg: crate::apdu::MGMT_ALG_AES192,
key: key.clone(),
witness: [0x77; 16],
};
let mut session = PivSession::new(fake, fake_meta());
session.authenticate_management_key(&key).unwrap();
}
#[test]
fn test_authenticate_management_key_wrong_key() {
// Host's wrong key → decrypted witness mismatches → card rejects → mapped error.
let fake = MgmtFakeTransport {
alg: crate::apdu::MGMT_ALG_AES192,
key: vec![0x5Au8; 24],
witness: [0x77; 16],
};
let mut session = PivSession::new(fake, fake_meta());
let wrong = vec![0x00u8; 24];
assert!(matches!(
session.authenticate_management_key(&wrong),
Err(RatkeyError::ManagementAuthFailed)
));
}
}
+22 -6
View File
@@ -1,24 +1,40 @@
//! Hardware-backed identity (YubiKey 5, Nitrokey 3) via PIV. Ed25519 sign + X25519
//! ECDH keys live on-device; only public keys and results leave the token.
//! Wire-compatible with software identities. `hardware` feature enables real PIV via `pcsc`.
//! Wire-compatible with software identities.
//!
//! The PIV protocol logic (`PivSession`, `apdu`) is transport-agnostic; the
//! `PivTransport` seam isolates platform access. The `hardware` feature adds the
//! PC/SC transport (`PcscTransport`) and its `connect()` entry points. Mobile
//! NFC/USB transports implement `PivTransport` from the application layer.
pub mod apdu;
pub mod attestation;
#[cfg(feature = "hardware")]
pub mod backend;
pub mod detect;
pub mod error;
pub mod hardware;
pub mod hwid;
pub mod mgmt;
pub mod mock;
pub mod pin;
pub mod provision;
#[cfg(feature = "hardware")]
pub mod detect;
#[cfg(feature = "hardware")]
pub mod seed;
pub mod session;
pub mod transport;
pub use error::RatkeyError;
pub use hardware::HardwareIdentity;
pub use hardware::{HardwareIdentity, IdentityBackend};
pub use hwid::HwidConfig;
pub use mock::MockPivSession;
pub use pin::PinCache;
pub use provision::{ProvisionConfig, ProvisionResult};
pub use session::{DeviceMeta, PivSession};
pub use transport::PivTransport;
#[cfg(feature = "hardware")]
pub use backend::{HardwareBackend, load_hardware_identity};
#[cfg(feature = "hardware")]
pub use session::PcscPivSession;
#[cfg(feature = "hardware")]
pub use transport::PcscTransport;
+203
View File
@@ -0,0 +1,203 @@
//! PIV management-key crypto: ECB single/multi-block for the witness/challenge
//! mutual authentication. Dispatch is on the management-key *algorithm* byte, not
//! the key length — AES-192 and TDES both use 24-byte keys, but differ in block
//! size (AES 16, TDES 8). TDES (3DES EDE3) is the pre-5.7 YubiKey factory default.
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use aes::{Aes128, Aes192, Aes256};
use des::TdesEde3;
use crate::apdu;
use crate::error::RatkeyError;
const AES_BLOCK: usize = 16;
const DES_BLOCK: usize = 8;
/// Required key length for a management-key algorithm, or `None` if unsupported.
pub fn key_len(alg: u8) -> Option<usize> {
match alg {
apdu::MGMT_ALG_TDES => Some(24), // 3DES EDE3: three 8-byte DES subkeys
apdu::MGMT_ALG_AES128 => Some(16),
apdu::MGMT_ALG_AES192 => Some(24),
apdu::MGMT_ALG_AES256 => Some(32),
_ => None,
}
}
/// ECB block size (challenge length) for a supported algorithm.
pub fn block_len(alg: u8) -> Option<usize> {
match alg {
apdu::MGMT_ALG_TDES => Some(DES_BLOCK),
apdu::MGMT_ALG_AES128 | apdu::MGMT_ALG_AES192 | apdu::MGMT_ALG_AES256 => Some(AES_BLOCK),
_ => None,
}
}
fn check(alg: u8, key: &[u8], data: &[u8]) -> Result<(), RatkeyError> {
let n = key_len(alg).ok_or_else(|| {
RatkeyError::UnsupportedDevice(format!("unsupported management-key algorithm 0x{alg:02X}"))
})?;
if key.len() != n {
return Err(RatkeyError::InvalidHwid(format!(
"management key length {} does not match algorithm 0x{alg:02X} (expected {n})",
key.len()
)));
}
let block = block_len(alg).expect("supported alg has a block size");
if data.is_empty() || data.len() % block != 0 {
return Err(RatkeyError::InvalidHwid(format!(
"management-key ECB input not block-aligned: {} bytes (block {block})",
data.len()
)));
}
Ok(())
}
pub fn ecb_encrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
check(alg, key, data)?;
let mut out = data.to_vec();
process(alg, key, &mut out, false)?;
Ok(out)
}
pub fn ecb_decrypt(alg: u8, key: &[u8], data: &[u8]) -> Result<Vec<u8>, RatkeyError> {
check(alg, key, data)?;
let mut out = data.to_vec();
process(alg, key, &mut out, true)?;
Ok(out)
}
fn process(alg: u8, key: &[u8], buf: &mut [u8], decrypt: bool) -> Result<(), RatkeyError> {
macro_rules! run {
($cipher:ty, $block:expr) => {{
let cipher = <$cipher>::new_from_slice(key)
.map_err(|_| RatkeyError::InvalidHwid("invalid management key".to_string()))?;
for chunk in buf.chunks_mut($block) {
let block = GenericArray::from_mut_slice(chunk);
if decrypt {
cipher.decrypt_block(block);
} else {
cipher.encrypt_block(block);
}
}
}};
}
match alg {
apdu::MGMT_ALG_TDES => run!(TdesEde3, DES_BLOCK),
apdu::MGMT_ALG_AES128 => run!(Aes128, AES_BLOCK),
apdu::MGMT_ALG_AES192 => run!(Aes192, AES_BLOCK),
apdu::MGMT_ALG_AES256 => run!(Aes256, AES_BLOCK),
_ => {
return Err(RatkeyError::UnsupportedDevice(format!(
"unsupported management-key algorithm 0x{alg:02X}"
)));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
// FIPS-197 Appendix C.2 AES-192 known-answer vector.
const KAT_KEY: [u8; 24] = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
];
const KAT_PT: [u8; 16] = [
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
0xff,
];
const KAT_CT: [u8; 16] = [
0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71,
0x91,
];
#[test]
fn test_aes192_kat_encrypt() {
assert_eq!(
ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_PT).unwrap(),
KAT_CT.to_vec()
);
}
#[test]
fn test_aes192_kat_decrypt() {
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &KAT_CT).unwrap(),
KAT_PT.to_vec()
);
}
// 3DES EDE3 with three identical 8-byte subkeys reduces to single-DES, so the
// canonical FIPS-81 single-DES ECB vector is a known-answer for our EDE3 path:
// DES(0x0123456789ABCDEF, "Now is t") = 0x3FA40E8A984D4815.
const TDES_KAT_KEY: [u8; 24] = [
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD,
0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
];
const TDES_KAT_PT: [u8; 8] = [0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74];
const TDES_KAT_CT: [u8; 8] = [0x3F, 0xA4, 0x0E, 0x8A, 0x98, 0x4D, 0x48, 0x15];
#[test]
fn test_round_trip_all_aes() {
for (alg, klen) in [
(apdu::MGMT_ALG_AES128, 16usize),
(apdu::MGMT_ALG_AES192, 24),
(apdu::MGMT_ALG_AES256, 32),
] {
let key = vec![0x5Au8; klen];
let pt = [0x42u8; 16];
let ct = ecb_encrypt(alg, &key, &pt).unwrap();
assert_ne!(ct, pt.to_vec());
assert_eq!(ecb_decrypt(alg, &key, &ct).unwrap(), pt.to_vec());
}
}
#[test]
fn test_wrong_key_length_rejected() {
// AES-192 with a 16-byte key (would silently be AES-128 if not checked).
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &[0u8; 16], &[0u8; 16]).is_err());
}
#[test]
fn test_tdes_kat() {
assert_eq!(key_len(apdu::MGMT_ALG_TDES), Some(24));
assert_eq!(block_len(apdu::MGMT_ALG_TDES), Some(8));
assert_eq!(
ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_PT).unwrap(),
TDES_KAT_CT.to_vec()
);
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &TDES_KAT_CT).unwrap(),
TDES_KAT_PT.to_vec()
);
}
#[test]
fn test_tdes_round_trip_distinct_keys() {
// Three distinct subkeys exercise the real EDE3 / DED3 inverse, not the
// degenerate single-DES reduction.
let mut key = [0u8; 24];
for (i, b) in key.iter_mut().enumerate() {
*b = (i as u8).wrapping_mul(7).wrapping_add(1);
}
let pt = [0x42u8; 8];
let ct = ecb_encrypt(apdu::MGMT_ALG_TDES, &key, &pt).unwrap();
assert_ne!(ct, pt.to_vec());
assert_eq!(
ecb_decrypt(apdu::MGMT_ALG_TDES, &key, &ct).unwrap(),
pt.to_vec()
);
}
#[test]
fn test_non_block_aligned_rejected() {
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[0u8; 15]).is_err());
assert!(ecb_encrypt(apdu::MGMT_ALG_AES192, &KAT_KEY, &[]).is_err());
// TDES uses an 8-byte block: 8 is valid, 7 is not.
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 8]).is_ok());
assert!(ecb_encrypt(apdu::MGMT_ALG_TDES, &TDES_KAT_KEY, &[0u8; 7]).is_err());
}
}
+133
View File
@@ -46,6 +46,8 @@ impl SlotState {
#[derive(Debug, Clone)]
pub enum MockOperation {
PinVerify { success: bool },
PinUnblock { success: bool },
ResetPiv { success: bool },
GenerateEd25519 { slot: u8 },
GenerateX25519 { slot: u8 },
SignEd25519 { slot: u8, data_len: usize },
@@ -56,8 +58,10 @@ pub enum MockOperation {
pub struct MockPivSession {
slots: HashMap<u8, SlotState>,
pin: String,
puk: String,
pin_verified: bool,
pin_retries: u8,
puk_retries: u8,
max_retries: u8,
connected: bool,
/// True: `TouchPolicy::Always` slots reject ops. `simulate_touch()` clears.
@@ -77,8 +81,10 @@ impl MockPivSession {
Self {
slots,
pin: "123456".to_string(),
puk: "12345678".to_string(),
pin_verified: false,
pin_retries: 3,
puk_retries: 3,
max_retries: 3,
connected: true,
touch_required: true,
@@ -136,6 +142,10 @@ impl MockPivSession {
self.pin_verified = false;
}
pub fn set_puk(&mut self, puk: &str) {
self.puk = puk.to_string();
}
pub fn disconnect(&mut self) {
self.connected = false;
}
@@ -145,6 +155,12 @@ impl MockPivSession {
self.pin_verified = false;
}
/// Re-lock: clears PIN verification so the next op needs `verify_pin` again.
/// Mirrors `PivSession::lock` (which re-selects the applet on real hardware).
pub fn lock(&mut self) {
self.pin_verified = false;
}
pub fn simulate_touch(&mut self) {
self.touch_required = false;
}
@@ -211,6 +227,58 @@ impl MockPivSession {
}
}
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
self.check_connected()?;
if self.puk_retries == 0 {
self.operations
.push(MockOperation::PinUnblock { success: false });
return Err(RatkeyError::PukLocked);
}
if puk == self.puk {
self.pin = new_pin.to_string();
self.pin_verified = true;
self.pin_retries = self.max_retries;
self.puk_retries = self.max_retries;
self.operations
.push(MockOperation::PinUnblock { success: true });
Ok(())
} else {
self.puk_retries -= 1;
self.operations
.push(MockOperation::PinUnblock { success: false });
if self.puk_retries == 0 {
Err(RatkeyError::PukLocked)
} else {
Err(RatkeyError::PukFailed {
remaining: self.puk_retries,
})
}
}
}
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
self.check_connected()?;
if self.pin_retries != 0 || self.puk_retries != 0 {
self.operations
.push(MockOperation::ResetPiv { success: false });
return Err(RatkeyError::ResetRequiresBlockedPinAndPuk);
}
self.slots.insert(SLOT_9A, SlotState::empty());
self.slots.insert(SLOT_9D, SlotState::empty());
self.pin = "123456".to_string();
self.puk = "12345678".to_string();
self.pin_verified = false;
self.pin_retries = self.max_retries;
self.puk_retries = self.max_retries;
self.touch_required = true;
self.operations
.push(MockOperation::ResetPiv { success: true });
Ok(())
}
pub fn generate_ed25519(
&mut self,
slot: u8,
@@ -374,6 +442,7 @@ impl Default for MockPivSession {
impl Drop for MockPivSession {
fn drop(&mut self) {
self.pin.zeroize();
self.puk.zeroize();
}
}
@@ -412,6 +481,70 @@ mod tests {
assert!(matches!(err, RatkeyError::PinLocked));
}
#[test]
fn test_pin_unblock_with_puk() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
assert!(matches!(
session.verify_pin("123456"),
Err(RatkeyError::PinLocked)
));
session.unblock_pin("12345678", "654321").unwrap();
assert!(session.verify_pin("654321").is_ok());
assert!(matches!(
session.verify_pin("123456"),
Err(RatkeyError::PinFailed { .. })
));
}
#[test]
fn test_pin_unblock_wrong_puk_locks_puk() {
let mut session = MockPivSession::new();
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let _ = session.verify_pin("wrong");
let err = session.unblock_pin("bad", "654321").unwrap_err();
assert!(matches!(err, RatkeyError::PukFailed { remaining: 2 }));
let _ = session.unblock_pin("bad", "654321");
let err = session.unblock_pin("bad", "654321").unwrap_err();
assert!(matches!(err, RatkeyError::PukLocked));
assert!(matches!(
session.unblock_pin("12345678", "654321"),
Err(RatkeyError::PukLocked)
));
}
#[test]
fn test_reset_piv_requires_blocked_pin_and_puk() {
let mut session = MockPivSession::with_keys();
assert!(matches!(
session.reset_piv(),
Err(RatkeyError::ResetRequiresBlockedPinAndPuk)
));
}
#[test]
fn test_reset_piv_clears_keys_and_restores_defaults() {
let mut session = MockPivSession::with_keys();
let _ = session.verify_pin("badpin");
let _ = session.verify_pin("badpin");
let _ = session.verify_pin("badpin");
let _ = session.unblock_pin("badpuk", "654321");
let _ = session.unblock_pin("badpuk", "654321");
let _ = session.unblock_pin("badpuk", "654321");
session.reset_piv().unwrap();
session.verify_pin("123456").unwrap();
assert!(matches!(
session.sign_ed25519(SLOT_9A, b"test"),
Err(RatkeyError::EmptySlot { slot: SLOT_9A })
));
}
#[test]
fn test_pin_retry_reset() {
let mut session = MockPivSession::new();
+166 -1
View File
@@ -5,9 +5,13 @@ use std::time::{SystemTime, UNIX_EPOCH};
use rns_crypto::sha::truncated_hash;
use crate::apdu;
use crate::error::RatkeyError;
use crate::hwid::*;
use crate::mock::{MockPivSession, SLOT_9A, SLOT_9D, TouchPolicy};
use crate::seed;
use crate::session::PivSession;
use crate::transport::PivTransport;
#[derive(Debug, Clone)]
pub struct ProvisionResult {
@@ -132,6 +136,167 @@ pub fn compute_identity_hash(ed25519_pub: &[u8; 32], x25519_pub: &[u8; 32]) -> [
truncated_hash(&pub_key_bytes)
}
fn touch_byte(tp: TouchPolicy) -> u8 {
match tp {
TouchPolicy::Never => apdu::TOUCH_POLICY_NEVER,
TouchPolicy::Always => apdu::TOUCH_POLICY_ALWAYS,
TouchPolicy::Cached => apdu::TOUCH_POLICY_CACHED,
}
}
fn touch_str(tp: TouchPolicy) -> &'static str {
match tp {
TouchPolicy::Never => "never",
TouchPolicy::Always => "always",
TouchPolicy::Cached => "cached",
}
}
/// Recoverable provision / restore: derive the identity from `mnemonic`, import
/// both keys into the token (PIN-once + configured touch policy), and write the
/// `.hwid`. Requires the management key. The session must already be connected.
pub fn import_recoverable_identity<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
mnemonic: &str,
) -> Result<ProvisionResult, RatkeyError> {
let derived = seed::derive_identity(mnemonic)?;
session.authenticate_management_key(mgmt_key)?;
session.import_ed25519(
SLOT_9A,
&derived.ed25519_seed,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_signing)),
)?;
session.import_x25519(
SLOT_9D,
&derived.x25519_secret,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_encryption)),
)?;
finalize_provision(session, config, derived.ed25519_pub, derived.x25519_pub)
}
/// On-device provisioning (no seed backup): authenticate, generate both keys on
/// the token, and write the `.hwid`. Requires the management key.
pub fn provision_hardware_only<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
) -> Result<ProvisionResult, RatkeyError> {
session.authenticate_management_key(mgmt_key)?;
let ed_pub = session.generate_ed25519(
SLOT_9A,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_signing)),
)?;
let x_pub = session.generate_x25519(
SLOT_9D,
Some(apdu::PIN_POLICY_ONCE),
Some(touch_byte(config.touch_encryption)),
)?;
finalize_provision(session, config, ed_pub, x_pub)
}
/// Register an already-provisioned token: read its slot public keys and write a
/// `.hwid` for it (import-existing). No key material is created; no mgmt key needed.
pub fn read_existing<T: PivTransport>(
session: &mut PivSession<T>,
config: &ProvisionConfig,
) -> Result<ProvisionResult, RatkeyError> {
let ed_pub = session.read_public_key(SLOT_9A)?;
let x_pub = session.read_public_key(SLOT_9D)?;
finalize_provision(session, config, ed_pub, x_pub)
}
/// Build the `.hwid` from the provisioned public keys + device metadata, writing
/// it under `config.identities_dir` if set. Shared by all real-hardware flows.
fn finalize_provision<T: PivTransport>(
session: &PivSession<T>,
config: &ProvisionConfig,
ed25519_pub: [u8; 32],
x25519_pub: [u8; 32],
) -> Result<ProvisionResult, RatkeyError> {
let identity_hash = compute_identity_hash(&ed25519_pub, &x25519_pub);
let identity_hash_hex = hex::encode(identity_hash);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let hwid = HwidConfig {
identity: HwidIdentity {
hash: identity_hash_hex.clone(),
nickname: config.nickname.clone(),
created_at: now,
},
device: HwidDevice {
device_type: session.device_type().as_str().to_string(),
serial: session.serial().unwrap_or(0),
firmware: session.firmware().unwrap_or("unknown").to_string(),
},
keys: HwidKeys {
ed25519_pub: hex::encode(ed25519_pub),
x25519_pub: hex::encode(x25519_pub),
},
slots: HwidSlots {
signing: "9A".to_string(),
encryption: "9D".to_string(),
},
policy: HwidPolicy {
pin_cache_timeout: 300,
touch_signing: touch_str(config.touch_signing).to_string(),
touch_encryption: touch_str(config.touch_encryption).to_string(),
},
attestation: HwidAttestation::default(),
app: HwidApp::default(),
backup: HwidBackup::default(),
};
let hwid_path = if let Some(ref dir) = config.identities_dir {
let identity_dir = dir.join(&identity_hash_hex);
std::fs::create_dir_all(&identity_dir)?;
let path = identity_dir.join("identity.hwid");
hwid.to_file(&path)?;
Some(path)
} else {
None
};
Ok(ProvisionResult {
config: hwid,
ed25519_pub,
x25519_pub,
identity_hash,
identity_hash_hex,
hwid_path,
})
}
/// Recoverable provisioning: generate a fresh 12-word mnemonic, import the
/// derived identity, and return both the result and the mnemonic to show once.
pub fn provision_recoverable<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
) -> Result<(ProvisionResult, String), RatkeyError> {
let mnemonic = seed::generate_mnemonic()?;
let result = import_recoverable_identity(session, mgmt_key, config, &mnemonic)?;
Ok((result, mnemonic))
}
/// Restore a recoverable identity from an existing 12-word mnemonic onto a token.
pub fn restore<T: PivTransport>(
session: &mut PivSession<T>,
mgmt_key: &[u8],
config: &ProvisionConfig,
mnemonic: &str,
) -> Result<ProvisionResult, RatkeyError> {
import_recoverable_identity(session, mgmt_key, config, mnemonic)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -218,7 +383,7 @@ mod tests {
let result = provision_mock(&mut session, &config).unwrap();
let path = result.hwid_path.as_ref().unwrap();
let mut hw = crate::HardwareIdentity::from_file_mock(path, session).unwrap();
let mut hw = crate::HardwareIdentity::from_file(path, Box::new(session)).unwrap();
let message = b"provisioned and loaded";
let sig = hw.sign(message).unwrap();
+148
View File
@@ -0,0 +1,148 @@
//! BIP-39 recoverable backup: a deterministic Reticulum identity derived from a
//! 12-word mnemonic. Interop-compatible with ratkey-py (derivation scheme v1):
//!
//! ```text
//! mnemonic (12 words)
//! -> PBKDF2-SHA512 (BIP-39, passphrase="") -> 64-byte seed
//! -> HKDF-SHA256(seed, salt="ratkey-ed25519-v1", info) -> 32-byte Ed25519 seed
//! -> HKDF-SHA256(seed, salt="ratkey-x25519-v1", info) -> 32-byte X25519 secret
//! ```
//!
//! The seed phrase is a second attack surface (it reconstructs the private keys
//! and is not protected by the device PIN). Callers must surface that tradeoff.
use bip39::{Language, Mnemonic};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroize;
use rns_crypto::ed25519::Ed25519PrivateKey;
use rns_crypto::x25519::X25519PrivateKey;
use crate::error::RatkeyError;
const ED25519_SALT: &[u8] = b"ratkey-ed25519-v1";
const X25519_SALT: &[u8] = b"ratkey-x25519-v1";
const HKDF_INFO: &[u8] = b"ratkey identity key derivation";
const MNEMONIC_WORDS: usize = 12;
const MNEMONIC_ENTROPY_BYTES: usize = 16;
/// Key material derived from a mnemonic. The two secret fields are zeroized on drop.
pub struct DerivedIdentity {
pub ed25519_seed: [u8; 32],
pub x25519_secret: [u8; 32],
pub ed25519_pub: [u8; 32],
pub x25519_pub: [u8; 32],
}
impl Drop for DerivedIdentity {
fn drop(&mut self) {
self.ed25519_seed.zeroize();
self.x25519_secret.zeroize();
}
}
/// Generate a fresh 12-word (128-bit) BIP-39 English mnemonic.
pub fn generate_mnemonic() -> Result<String, RatkeyError> {
let mut entropy = [0u8; MNEMONIC_ENTROPY_BYTES];
entropy.copy_from_slice(&rns_crypto::random::random_bytes(MNEMONIC_ENTROPY_BYTES));
let result = Mnemonic::from_entropy_in(Language::English, &entropy)
.map(|m| m.to_string())
.map_err(|e| RatkeyError::InvalidHwid(format!("mnemonic generation failed: {e}")));
entropy.zeroize();
result
}
/// True for a valid 12-word BIP-39 English mnemonic (wordlist + checksum).
pub fn validate_mnemonic(words: &str) -> bool {
let w = words.trim();
w.split_whitespace().count() == MNEMONIC_WORDS
&& Mnemonic::parse_in_normalized(Language::English, w).is_ok()
}
/// Derive the Reticulum identity keys from a 12-word mnemonic (scheme v1).
pub fn derive_identity(words: &str) -> Result<DerivedIdentity, RatkeyError> {
if !validate_mnemonic(words) {
return Err(RatkeyError::InvalidHwid(
"invalid seed phrase: expected 12 valid BIP-39 English words".to_string(),
));
}
let mnemonic = Mnemonic::parse_in_normalized(Language::English, words.trim())
.map_err(|e| RatkeyError::InvalidHwid(format!("invalid seed phrase: {e}")))?;
let mut seed = mnemonic.to_seed("");
let ed25519_seed = hkdf32(&seed, ED25519_SALT)?;
let x25519_secret = hkdf32(&seed, X25519_SALT)?;
seed.zeroize();
let ed25519_pub = Ed25519PrivateKey::from_bytes(&ed25519_seed)
.public_key()
.to_bytes();
let x25519_pub = X25519PrivateKey::from_bytes(&x25519_secret)
.public_key()
.to_bytes();
Ok(DerivedIdentity {
ed25519_seed,
x25519_secret,
ed25519_pub,
x25519_pub,
})
}
fn hkdf32(ikm: &[u8], salt: &[u8]) -> Result<[u8; 32], RatkeyError> {
let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
let mut okm = [0u8; 32];
hk.expand(HKDF_INFO, &mut okm)
.map_err(|_| RatkeyError::InvalidHwid("HKDF expand failed".to_string()))?;
Ok(okm)
}
#[cfg(test)]
mod tests {
use super::*;
fn test_mnemonic() -> String {
// Standard BIP-39 all-zero-entropy vector (checksum word "about").
"abandon ".repeat(11) + "about"
}
#[test]
fn test_derive_matches_python_vector() {
// Cross-checked against ratkey-py's derivation (scheme v1).
let d = derive_identity(&test_mnemonic()).unwrap();
assert_eq!(
hex::encode(d.ed25519_seed),
"dfbf047515deef875db5884b7d1ec625f57641adb7265153a2c3b775ed04386f"
);
assert_eq!(
hex::encode(d.x25519_secret),
"20c92deea11650882a353b4e9928602d247b4ee689c1e0e10dc77637dbe3b33f"
);
}
#[test]
fn test_derive_is_deterministic() {
let a = derive_identity(&test_mnemonic()).unwrap();
let b = derive_identity(&test_mnemonic()).unwrap();
assert_eq!(a.ed25519_pub, b.ed25519_pub);
assert_eq!(a.x25519_pub, b.x25519_pub);
}
#[test]
fn test_validate_rejects_bad_input() {
assert!(!validate_mnemonic("not a real phrase"));
assert!(!validate_mnemonic(&"abandon ".repeat(12))); // 12 abandon = bad checksum
assert!(validate_mnemonic(&test_mnemonic()));
}
#[test]
fn test_generate_roundtrips() {
let m = generate_mnemonic().unwrap();
assert_eq!(m.split_whitespace().count(), MNEMONIC_WORDS);
assert!(validate_mnemonic(&m));
// A generated phrase derives a stable identity.
let d = derive_identity(&m).unwrap();
assert_ne!(d.ed25519_pub, [0u8; 32]);
}
}
+205 -95
View File
@@ -1,70 +1,43 @@
//! Real PIV session over PC/SC (YubiKey 5, Nitrokey 3).
//! Requires `hardware` feature + PC/SC daemon (macOS CryptoTokenKit / Linux pcscd / Windows WinSCard).
use pcsc::{Card, Context, Protocols, Scope, ShareMode};
use tracing::{debug, warn};
use zeroize::Zeroize;
//! Transport-agnostic PIV session. Every PIV operation is built on `apdu` plus a
//! `PivTransport`; the transport is the only platform-specific part (see `transport`).
//! `hardware` feature adds the PC/SC `connect()` entry points.
use crate::apdu;
use crate::detect::DeviceType;
use crate::error::RatkeyError;
use crate::pin::PinCache;
use crate::transport::PivTransport;
const MAX_RESPONSE: usize = 4096;
/// Device identity captured once at connect time; no per-operation cost.
pub struct DeviceMeta {
pub device_type: DeviceType,
pub serial: Option<u32>,
pub firmware: Option<String>,
}
pub struct PivSession {
card: Card,
pub struct PivSession<T: PivTransport> {
transport: T,
device_type: DeviceType,
reader_name: String,
serial: Option<u32>,
firmware: Option<String>,
pin_cache: PinCache,
}
impl PivSession {
pub fn connect() -> Result<Self, RatkeyError> {
let devices = crate::detect::detect_devices()?;
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
Self::connect_reader(&device.reader_name)
}
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let resp = transmit(&card, &apdu::select_piv())?;
apdu::check_response(&resp)?;
let device_type = crate::detect::detect_device_type(reader_name);
debug!(
"PIV session established with {} ({})",
reader_name,
device_type.as_str()
);
let (serial, firmware) = crate::detect::read_identity(&card, device_type);
Ok(Self {
card,
device_type,
reader_name: reader_name.to_string(),
serial,
firmware,
impl<T: PivTransport> PivSession<T> {
pub fn new(transport: T, meta: DeviceMeta) -> Self {
Self {
transport,
device_type: meta.device_type,
serial: meta.serial,
firmware: meta.firmware,
pin_cache: PinCache::default_timeout(),
})
}
}
pub fn device_type(&self) -> DeviceType {
self.device_type
}
pub fn reader_name(&self) -> &str {
&self.reader_name
}
pub fn serial(&self) -> Option<u32> {
self.serial
}
@@ -73,102 +46,239 @@ impl PivSession {
self.firmware.as_deref()
}
/// Probes the attestation slot (F9) — always present on provisioned tokens.
pub fn is_connected(&self) -> bool {
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
let mut buf = vec![0u8; 256];
self.card.transmit(&cmd, &mut buf).is_ok()
self.transport.is_connected()
}
/// Re-locks the card: re-selects the PIV applet (resetting the on-card PIN
/// verification) and clears the cached PIN, so the next private-key op needs
/// a fresh `verify_pin`. This is the mechanism behind the app-side session
/// timeout / lock-on-quit.
pub fn lock(&mut self) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::select_piv())?;
apdu::check_response(&resp)?;
self.pin_cache.clear();
Ok(())
}
pub fn verify_pin(&mut self, pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::verify_pin(pin);
let resp = transmit(&self.card, &cmd)?;
let resp = self.transport.transmit(&apdu::verify_pin(pin))?;
apdu::check_response(&resp)?;
self.pin_cache.cache(pin);
debug!("PIN verified");
Ok(())
}
pub fn change_pin(&mut self, old_pin: &str, new_pin: &str) -> Result<(), RatkeyError> {
let cmd = apdu::change_pin(old_pin, new_pin);
let resp = transmit(&self.card, &cmd)?;
let resp = self
.transport
.transmit(&apdu::change_pin(old_pin, new_pin))?;
apdu::check_response(&resp)?;
self.pin_cache.cache(new_pin);
debug!("PIN changed");
Ok(())
}
pub fn unblock_pin(&mut self, puk: &str, new_pin: &str) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::reset_retry(puk, new_pin))?;
match apdu::check_response(&resp) {
Ok(_) => {
self.pin_cache.cache(new_pin);
Ok(())
}
Err(RatkeyError::PinFailed { remaining }) => Err(RatkeyError::PukFailed { remaining }),
Err(RatkeyError::PinLocked) => Err(RatkeyError::PukLocked),
Err(other) => Err(other),
}
}
pub fn reset_piv(&mut self) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::reset_piv())?;
match apdu::check_response(&resp) {
Ok(_) => {
self.pin_cache.clear();
Ok(())
}
Err(RatkeyError::Apdu {
sw1: 0x69,
sw2: 0x85,
}) => Err(RatkeyError::ResetRequiresBlockedPinAndPuk),
Err(other) => Err(other),
}
}
pub fn generate_ed25519(
&self,
&mut self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_ED25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let resp = self.transport.transmit(&apdu::generate_key(
slot,
apdu::ALG_ED25519,
pin_policy,
touch_policy,
))?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn generate_x25519(
&self,
&mut self,
slot: u8,
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::generate_key(slot, apdu::ALG_X25519, pin_policy, touch_policy);
let resp = transmit(&self.card, &cmd)?;
let resp = self.transport.transmit(&apdu::generate_key(
slot,
apdu::ALG_X25519,
pin_policy,
touch_policy,
))?;
let data = apdu::check_response(&resp)?;
apdu::parse_generate_response(data)
}
pub fn sign_ed25519(&self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let cmd = apdu::sign_ed25519(slot, message);
let resp = transmit(&self.card, &cmd)?;
/// Import an off-device Ed25519 key (recoverable provisioning / restore).
/// Requires prior `authenticate_management_key`.
pub fn import_ed25519(
&mut self,
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::import_ed25519(
slot,
private_key,
pin_policy,
touch_policy,
))?;
apdu::check_response(&resp)?;
Ok(())
}
/// Import an off-device X25519 key. Requires prior `authenticate_management_key`.
pub fn import_x25519(
&mut self,
slot: u8,
private_key: &[u8; 32],
pin_policy: Option<u8>,
touch_policy: Option<u8>,
) -> Result<(), RatkeyError> {
let resp = self.transport.transmit(&apdu::import_x25519(
slot,
private_key,
pin_policy,
touch_policy,
))?;
apdu::check_response(&resp)?;
Ok(())
}
pub fn sign_ed25519(&mut self, slot: u8, message: &[u8]) -> Result<[u8; 64], RatkeyError> {
let resp = self
.transport
.transmit(&apdu::sign_ed25519(slot, message))?;
let data = apdu::check_response(&resp)?;
apdu::parse_sign_response(data)
}
pub fn ecdh_x25519(&self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let cmd = apdu::ecdh_x25519(slot, peer_pub);
let resp = transmit(&self.card, &cmd)?;
pub fn ecdh_x25519(&mut self, slot: u8, peer_pub: &[u8; 32]) -> Result<[u8; 32], RatkeyError> {
let resp = self
.transport
.transmit(&apdu::ecdh_x25519(slot, peer_pub))?;
let data = apdu::check_response(&resp)?;
let mut secret = apdu::parse_ecdh_response(data)?;
// Wipes local stack copy only. Caller must zeroize the returned bytes.
let result = secret;
secret.zeroize();
Ok(result)
apdu::parse_ecdh_response(data)
}
/// Returns DER-encoded X.509 attestation certificate.
pub fn attest_key(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::attest_key(slot);
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
pub fn attest_key(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(&apdu::attest_key(slot))?;
Ok(apdu::check_response(&resp)?.to_vec())
}
pub fn read_certificate(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
pub fn read_certificate(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_data(slot).ok_or(RatkeyError::EmptySlot { slot })?;
let resp = transmit(&self.card, &cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
let resp = self.transport.transmit(&cmd)?;
Ok(apdu::check_response(&resp)?.to_vec())
}
/// Returns raw metadata TLV bytes.
pub fn read_metadata(&self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_metadata(slot);
let resp = transmit(&self.card, &cmd)?;
/// Device attestation (slot F9) intermediate certificate, unwrapped to raw DER.
/// This is the issuer of the per-slot certs returned by [`Self::attest_key`].
pub fn read_attestation_cert(&mut self) -> Result<Vec<u8>, RatkeyError> {
let cmd = apdu::get_data(apdu::SLOT_ATTESTATION).ok_or(RatkeyError::EmptySlot {
slot: apdu::SLOT_ATTESTATION,
})?;
let resp = self.transport.transmit(&cmd)?;
let data = apdu::check_response(&resp)?;
Ok(data.to_vec())
apdu::parse_certificate_object(data).ok_or_else(|| {
RatkeyError::InvalidHwid("device attestation cert (F9) not found in response".into())
})
}
/// Returns raw GET METADATA TLV bytes.
pub fn read_metadata(&mut self, slot: u8) -> Result<Vec<u8>, RatkeyError> {
let resp = self.transport.transmit(&apdu::get_metadata(slot))?;
Ok(apdu::check_response(&resp)?.to_vec())
}
/// Reads the slot's 32-byte public key from GET METADATA. The metadata byte
/// layout is pending confirmation against a real device — see
/// `apdu::parse_metadata_public_key`. Yubico 5.3+ only (Nitrokey 3 has no
/// GET METADATA).
pub fn read_public_key(&mut self, slot: u8) -> Result<[u8; 32], RatkeyError> {
let metadata = self.read_metadata(slot)?;
apdu::parse_metadata_public_key(&metadata)
}
/// Authenticate the PIV management key (slot 9B) via witness/challenge mutual
/// auth — required before on-device key generation. The algorithm is read
/// from the card (YubiKey 5.7 default: AES-192).
pub fn authenticate_management_key(&mut self, key: &[u8]) -> Result<(), RatkeyError> {
let meta = self.read_metadata(apdu::SLOT_CARD_MANAGEMENT)?;
let alg = apdu::parse_metadata_algorithm(&meta)?;
let block = crate::mgmt::block_len(alg).ok_or_else(|| {
RatkeyError::UnsupportedDevice(format!(
"unsupported management-key algorithm 0x{alg:02X}"
))
})?;
// Step 1: get the card's encrypted witness, decrypt it with the key.
let resp = self.transport.transmit(&apdu::auth_witness_request(alg))?;
let witness = apdu::parse_auth_witness(apdu::check_response(&resp)?)?;
let decrypted = crate::mgmt::ecb_decrypt(alg, key, &witness)?;
// Step 2: prove the witness + send our own challenge. A wrong key is
// rejected here with an APDU status (not the mutual check below).
let challenge = rns_crypto::random::random_bytes(block);
let resp = self
.transport
.transmit(&apdu::auth_witness_response(alg, &decrypted, &challenge))?;
let data = apdu::check_response(&resp).map_err(|_| RatkeyError::ManagementAuthFailed)?;
let encrypted = apdu::parse_auth_response(data)?;
// Step 3: mutual check — the card must have encrypted our challenge.
if crate::mgmt::ecb_encrypt(alg, key, &challenge)? != encrypted {
return Err(RatkeyError::ManagementAuthFailed);
}
Ok(())
}
}
fn transmit(card: &Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
})?;
Ok(response.to_vec())
/// PC/SC convenience alias; `connect()` lives on this monomorphization.
#[cfg(feature = "hardware")]
pub type PcscPivSession = PivSession<crate::transport::PcscTransport>;
#[cfg(feature = "hardware")]
impl PivSession<crate::transport::PcscTransport> {
/// Connect to the first detected token over PC/SC.
pub fn connect() -> Result<Self, RatkeyError> {
let (transport, meta) = crate::transport::PcscTransport::connect()?;
Ok(Self::new(transport, meta))
}
/// Connect to a specific PC/SC reader by name.
pub fn connect_reader(reader_name: &str) -> Result<Self, RatkeyError> {
let (transport, meta) = crate::transport::PcscTransport::connect_reader(reader_name)?;
Ok(Self::new(transport, meta))
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Transport seam for PIV. The PIV protocol logic lives in `PivSession`; this
//! trait is the only platform-specific part: APDU bytes in, response bytes out.
//! Desktop PC/SC ships here behind the `hardware` feature. Mobile NFC/USB
//! transports live in the application layer and implement the same trait.
use crate::error::RatkeyError;
pub trait PivTransport {
/// Send one ISO 7816-4 APDU; return the full response including SW1/SW2.
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError>;
/// Cheap liveness probe — token still present and responding.
fn is_connected(&self) -> bool;
}
#[cfg(feature = "hardware")]
pub use pcsc_transport::PcscTransport;
#[cfg(feature = "hardware")]
mod pcsc_transport {
use pcsc::{Context, Protocols, Scope, ShareMode};
use tracing::{debug, warn};
use super::PivTransport;
use crate::apdu;
use crate::detect::{self, detect_device_type};
use crate::error::RatkeyError;
use crate::session::DeviceMeta;
const MAX_RESPONSE: usize = 4096;
/// Real PIV transport over PC/SC (YubiKey 5, Nitrokey 3). Requires a PC/SC
/// daemon: macOS CryptoTokenKit / Linux pcscd / Windows WinSCard.
pub struct PcscTransport {
card: pcsc::Card,
}
impl PcscTransport {
/// Connect to the first detected RATKEY token.
pub fn connect() -> Result<(Self, DeviceMeta), RatkeyError> {
let devices = detect::detect_devices()?;
let device = devices.first().ok_or(RatkeyError::NoDevice)?;
Self::connect_reader(&device.reader_name)
}
/// Connect to a specific PC/SC reader by name.
pub fn connect_reader(reader_name: &str) -> Result<(Self, DeviceMeta), RatkeyError> {
let ctx = Context::establish(Scope::User)?;
let reader = std::ffi::CString::new(reader_name)
.map_err(|_| RatkeyError::UnsupportedDevice(reader_name.to_string()))?;
let card = ctx.connect(&reader, ShareMode::Shared, Protocols::ANY)?;
let resp = transmit_card(&card, &apdu::select_piv())?;
apdu::check_response(&resp)?;
let device_type = detect_device_type(reader_name);
debug!(
"PIV session established with {} ({})",
reader_name,
device_type.as_str()
);
let (serial, firmware) = detect::read_identity(&card, device_type);
Ok((
Self { card },
DeviceMeta {
device_type,
serial,
firmware,
},
))
}
}
impl PivTransport for PcscTransport {
fn transmit(&mut self, apdu: &[u8]) -> Result<Vec<u8>, RatkeyError> {
transmit_card(&self.card, apdu)
}
fn is_connected(&self) -> bool {
// Attestation slot (F9) is present on any provisioned token.
let cmd = apdu::get_metadata(apdu::SLOT_ATTESTATION);
let mut buf = vec![0u8; 256];
self.card.transmit(&cmd, &mut buf).is_ok()
}
}
fn transmit_card(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let initial = transmit_once(card, command)?;
super::chain_response(command, initial, |apdu| transmit_once(card, apdu))
}
fn transmit_once(card: &pcsc::Card, command: &[u8]) -> Result<Vec<u8>, RatkeyError> {
let mut response_buf = vec![0u8; MAX_RESPONSE];
let response = card.transmit(command, &mut response_buf).map_err(|e| {
warn!("PC/SC transmit failed: {}", e);
RatkeyError::Disconnected
})?;
Ok(response.to_vec())
}
}
/// ISO 7816-4 response chaining, factored out of the PC/SC transport so it is
/// testable without a card. `initial` is the first response (data‖SW1‖SW2);
/// `transmit` sends a follow-up APDU and returns its raw response.
/// - `61 xx`: more data available — fetch it with GET RESPONSE and append.
/// - `6C xx`: wrong Le — resend `command` with the card's expected Le. Assumes
/// `command` carries no Le of its own (true for our case-3 reads); a command
/// that already has an Le would be malformed here.
///
/// Large reads (e.g. GET DATA on a ~1 KB attestation cert) arrive as `61 xx`;
/// without this every such read would be truncated to the first ≤256 bytes.
// Only the `hardware` transport calls this; the unit tests exercise it always.
#[cfg_attr(not(feature = "hardware"), allow(dead_code))]
pub(crate) fn chain_response(
command: &[u8],
initial: Vec<u8>,
mut transmit: impl FnMut(&[u8]) -> Result<Vec<u8>, RatkeyError>,
) -> Result<Vec<u8>, RatkeyError> {
let mut data = initial;
// Bounded against a misbehaving card that never returns a terminal SW.
for _ in 0..64 {
if data.len() < 2 {
break;
}
let (sw1, sw2) = (data[data.len() - 2], data[data.len() - 1]);
if sw1 == 0x61 {
data.truncate(data.len() - 2); // drop interim SW; keep the data
let get_response = [0x00, 0xC0, 0x00, 0x00, sw2]; // sw2 = bytes left (0 = 256)
data.extend_from_slice(&transmit(&get_response)?);
} else if sw1 == 0x6C {
let mut retry = command.to_vec();
retry.push(sw2);
data = transmit(&retry)?;
} else {
break;
}
}
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn passthrough_on_terminal_sw() {
let out = chain_response(&[], vec![0x01, 0x02, 0x90, 0x00], |_| {
panic!("no follow-up expected")
})
.unwrap();
assert_eq!(out, vec![0x01, 0x02, 0x90, 0x00]);
}
#[test]
fn appends_get_response_on_61() {
let mut calls = 0;
let out = chain_response(
&[0x00, 0xCB, 0x3F, 0xFF],
vec![0xAA, 0xBB, 0x61, 0x02],
|apdu| {
calls += 1;
assert_eq!(apdu, &[0x00, 0xC0, 0x00, 0x00, 0x02]); // GET RESPONSE, Le=2
Ok(vec![0xCC, 0xDD, 0x90, 0x00])
},
)
.unwrap();
assert_eq!(calls, 1);
assert_eq!(out, vec![0xAA, 0xBB, 0xCC, 0xDD, 0x90, 0x00]);
}
#[test]
fn chains_multiple_61() {
let mut step = 0;
let out = chain_response(&[0x00], vec![0x01, 0x61, 0x00], |_| {
step += 1;
if step == 1 {
Ok(vec![0x02, 0x61, 0x00]) // still more
} else {
Ok(vec![0x03, 0x90, 0x00]) // done
}
})
.unwrap();
assert_eq!(step, 2);
assert_eq!(out, vec![0x01, 0x02, 0x03, 0x90, 0x00]);
}
#[test]
fn resends_with_le_on_6c() {
let out = chain_response(&[0x00, 0xCB, 0x3F, 0xFF], vec![0x6C, 0x05], |apdu| {
assert_eq!(apdu, &[0x00, 0xCB, 0x3F, 0xFF, 0x05]); // original + Le=5
Ok(vec![0xDE, 0xAD, 0x90, 0x00])
})
.unwrap();
assert_eq!(out, vec![0xDE, 0xAD, 0x90, 0x00]);
}
}
Binary file not shown.
Binary file not shown.
+1
View File
@@ -24,6 +24,7 @@ tokio = { workspace = true }
bytes = { workspace = true }
tracing = { workspace = true }
hmac = { workspace = true }
md-5 = { workspace = true }
sha2 = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
+260 -29
View File
@@ -198,7 +198,8 @@ pub struct LinkManager {
transport_tx: mpsc::Sender<TransportMessage>,
event_rx: mpsc::Receiver<DestinationEvent>,
active_links: HashMap<[u8; 16], ActiveLink>,
/// `None` rejects all links.
/// Raw software signing key, when available. Hardware-backed identities sign
/// through `identity` instead.
identity_key: Option<Ed25519PrivateKey>,
pub destination_hash: [u8; 16],
destination: Option<Destination>,
@@ -280,7 +281,9 @@ impl LinkManager {
event_rx: mpsc::Receiver<DestinationEvent>,
identity: &Identity,
app_name: &str,
identity_key: Ed25519PrivateKey,
// `None` for hardware-backed identities (no extractable signing key);
// link proofs are routed through the backend-aware `Identity`.
identity_key: Option<Ed25519PrivateKey>,
) -> Self {
let dest = match Destination::new(Some(identity), Direction::In, DestType::Single, app_name)
{
@@ -298,7 +301,7 @@ impl LinkManager {
transport_tx,
event_rx,
active_links: HashMap::new(),
identity_key: Some(identity_key),
identity_key,
destination_hash,
destination: dest,
identity: manager_identity,
@@ -559,14 +562,6 @@ impl LinkManager {
}
fn handle_link_request(&mut self, raw: &[u8], interface_id: u64) {
let identity_key = match &self.identity_key {
Some(k) => k,
None => {
tracing::warn!("link request received but no identity key configured");
return;
}
};
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(raw) {
Ok(h) => h,
Err(_) => return,
@@ -587,14 +582,32 @@ impl LinkManager {
}
}
let (link, proof_data) =
match Link::new_responder(request_data, identity_key, self.destination_hash, hops) {
Ok(result) => result,
Err(e) => {
tracing::warn!(error = %e, "link handshake failed");
return;
}
};
let responder = match (&self.identity_key, &self.identity) {
(Some(identity_key), _) => {
Link::new_responder(request_data, identity_key, self.destination_hash, hops)
}
(None, Some(identity)) => {
let identity_ed25519_pub = identity_ed25519_public_key(identity);
Link::new_responder_with(
request_data,
&identity_ed25519_pub,
self.destination_hash,
hops,
|signed_data| identity.sign(signed_data),
)
}
(None, None) => {
tracing::warn!("link request received but no identity signer configured");
return;
}
};
let (link, proof_data) = match responder {
Ok(result) => result,
Err(e) => {
tracing::warn!(error = %e, "link handshake failed");
return;
}
};
let link_id = link.link_id;
@@ -1703,6 +1716,12 @@ impl LinkManager {
}
_ => {
// Application data on a link (LXMF DIRECT).
let identity_key_bytes = self.identity_key.as_ref().map(|key| key.to_bytes());
let identity_for_signing = if identity_key_bytes.is_none() {
self.identity.clone()
} else {
None
};
if let Some(active) = self.active_links.get_mut(&link_id) {
active.link.record_inbound();
active.link.record_rx(data.len());
@@ -1719,11 +1738,19 @@ impl LinkManager {
);
// Link proofs are unencrypted (Packet.py:198-200).
if let Some(ref signing_key) = self.identity_key {
let pkt_hash =
rns_wire::hash::packet_hash(raw, header.flags.header_type);
if let Ok(proof_data) = active.link.prove_packet(&pkt_hash, signing_key)
{
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
let proof = if let Some(key_bytes) = identity_key_bytes {
let signing_key = Ed25519PrivateKey::from_bytes(&key_bytes);
active.link.prove_packet(&pkt_hash, &signing_key)
} else if let Some(identity) = identity_for_signing.as_ref() {
active
.link
.prove_packet_with_fallible(&pkt_hash, |hash| identity.sign(hash))
} else {
Err(rns_link::encryption::LinkCryptoError::EncryptionFailed)
};
match proof {
Ok(proof_data) => {
let proof_header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
@@ -1751,6 +1778,12 @@ impl LinkManager {
"delivery proof sent for link data packet (unencrypted)"
);
}
Err(_) => {
tracing::warn!(
link_id = hex::encode(link_id),
"could not sign delivery proof for link data packet"
);
}
}
}
}
@@ -2537,8 +2570,20 @@ impl LinkManager {
}
fn clone_identity(identity: &Identity) -> Option<Identity> {
let private_key = identity.get_private_key()?;
Identity::from_private_key(&*private_key).ok()
// Clone preserves a hardware backend (shared Arc) — there is no extractable
// private key to copy; software identities clone their key material.
if identity.has_private_key() || identity.has_backend() {
Some(identity.clone())
} else {
None
}
}
fn identity_ed25519_public_key(identity: &Identity) -> [u8; 32] {
let public_key = identity.get_public_key();
let mut ed25519_pub = [0u8; 32];
ed25519_pub.copy_from_slice(&public_key[32..64]);
ed25519_pub
}
fn unix_now() -> f64 {
@@ -2568,9 +2613,31 @@ pub fn register_destination(
#[cfg(test)]
mod tests {
use super::*;
use rns_identity::identity::LocalKeyBackend;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
const TEST_CHANNEL_MSG_TYPE: u16 = 0x1234;
struct TestSigningBackend {
signing_key: Ed25519PrivateKey,
available: AtomicBool,
}
impl LocalKeyBackend for TestSigningBackend {
fn sign_ed25519(&self, message: &[u8]) -> Option<[u8; 64]> {
self.available
.load(Ordering::SeqCst)
.then(|| self.signing_key.sign(message))
}
fn ecdh(&self, _peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
None
}
}
struct TestChannelNoop;
impl rns_protocol::channel_message::MessageBase for TestChannelNoop {
@@ -2590,6 +2657,39 @@ mod tests {
}
}
fn link_request_raw(dest_hash: [u8; 16], request_data: &[u8]) -> Vec<u8> {
let flags = rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Single,
packet_type: rns_wire::flags::PacketType::LinkRequest,
};
let header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash: dest_hash,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(request_data);
raw
}
fn backend_identity(available: bool) -> (Identity, [u8; 32], [u8; 32]) {
let software = Identity::new();
let public_key = software.get_public_key();
let identity_ed25519_pub = identity_ed25519_public_key(&software);
let signing_seed = software.get_signing_key().unwrap().to_bytes();
let backend: Arc<dyn LocalKeyBackend> = Arc::new(TestSigningBackend {
signing_key: Ed25519PrivateKey::from_bytes(&signing_seed),
available: AtomicBool::new(available),
});
let backend_identity = Identity::from_backend(&public_key, backend).unwrap();
(backend_identity, identity_ed25519_pub, signing_seed)
}
#[test]
fn test_link_manager_creation() {
let (tx, _rx) = mpsc::channel(16);
@@ -2796,6 +2896,59 @@ mod tests {
assert_eq!(lm.active_link_count(), 0);
}
#[test]
fn backend_identity_accepts_link_request_without_raw_signing_key() {
let (tx, mut rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let (identity, identity_ed25519_pub, _signing_seed) = backend_identity(true);
let mut lm = LinkManager::with_destination(tx, event_rx, &identity, "test.hw", None);
let dest_hash = lm.destination_hash;
let (mut initiator, request_data) = Link::new_initiator(dest_hash, 1);
let raw = link_request_raw(dest_hash, &request_data);
lm.handle_link_request(&raw, 1);
assert_eq!(lm.active_link_count(), 1);
let outbound = rx.try_recv().expect("link proof should be queued");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound link proof");
};
let (proof_header, proof_offset) =
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(
proof_header.context,
rns_wire::context::PacketContext::Lrproof
);
let identity_pub =
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&identity_ed25519_pub).unwrap();
let rtt = initiator
.validate_proof(
&request.raw[proof_offset..],
&identity_pub,
&identity_ed25519_pub,
)
.expect("backend-signed proof validates");
assert!(!rtt.is_empty());
}
#[test]
fn backend_identity_link_request_fails_closed_when_signer_unavailable() {
let (tx, mut rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let (identity, _identity_ed25519_pub, _signing_seed) = backend_identity(false);
let mut lm = LinkManager::with_destination(tx, event_rx, &identity, "test.hw", None);
let dest_hash = lm.destination_hash;
let (_initiator, request_data) = Link::new_initiator(dest_hash, 1);
let raw = link_request_raw(dest_hash, &request_data);
lm.handle_link_request(&raw, 1);
assert_eq!(lm.active_link_count(), 0);
assert!(rx.try_recv().is_err());
}
#[test]
fn test_with_destination_constructor() {
let (tx, _rx) = mpsc::channel(16);
@@ -2804,7 +2957,8 @@ mod tests {
let identity = Identity::new();
let signing_key = identity.get_signing_key().unwrap();
let lm = LinkManager::with_destination(tx, event_rx, &identity, "test.app", signing_key);
let lm =
LinkManager::with_destination(tx, event_rx, &identity, "test.app", Some(signing_key));
assert!(lm.destination.is_some());
assert_eq!(lm.active_link_count(), 0);
@@ -2818,7 +2972,7 @@ mod tests {
let identity = Identity::new();
let signing_key = identity.get_signing_key().unwrap();
let mut lm =
LinkManager::with_destination(tx, event_rx, &identity, "test.app", signing_key);
LinkManager::with_destination(tx, event_rx, &identity, "test.app", Some(signing_key));
let tag = vec![0xA5; 16];
lm.handle_event(DestinationEvent::AnnounceRequested(AnnounceRequest {
@@ -3006,7 +3160,7 @@ mod tests {
let signing_key = identity.get_signing_key().unwrap();
let mut lm =
LinkManager::with_destination(tx, event_rx, &identity, "test.gate", signing_key);
LinkManager::with_destination(tx, event_rx, &identity, "test.gate", Some(signing_key));
if let Some(ref mut dest) = lm.destination {
dest.set_accepts_links(false);
@@ -3140,6 +3294,83 @@ mod tests {
assert!(sender_link.validate_packet_proof(&packet_hash, proof_data));
}
#[test]
fn backend_identity_signs_link_packet_delivery_proof() {
let (identity, identity_ed25519_pub, signing_seed) = backend_identity(true);
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm =
LinkManager::with_destination(transport_tx, event_rx, &identity, "test.hw", None);
let dest_hash = lm.destination_hash;
let identity_pub =
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&identity_ed25519_pub).unwrap();
let signing_key = Ed25519PrivateKey::from_bytes(&signing_seed);
let (mut sender_link, request_data) = Link::new_initiator(dest_hash, 1);
let (mut receiver_link, proof_data) =
Link::new_responder(&request_data, &signing_key, dest_hash, 1).unwrap();
let rtt_data = sender_link
.validate_proof(&proof_data, &identity_pub, &identity_ed25519_pub)
.unwrap();
receiver_link.receive_rtt_packet(&rtt_data).unwrap();
let link_id = receiver_link.link_id;
let encrypted = sender_link.encrypt(b"link payload").unwrap();
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
header_type: rns_wire::flags::HeaderType::Header1,
context_flag: false,
transport_type: rns_wire::flags::TransportType::Broadcast,
destination_type: rns_wire::flags::DestinationType::Link,
packet_type: rns_wire::flags::PacketType::Data,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::None,
};
let mut raw = header.pack();
raw.extend_from_slice(&encrypted);
let packet_hash = rns_wire::hash::packet_hash(&raw, header.flags.header_type);
lm.active_links.insert(
link_id,
ActiveLink {
link: receiver_link,
_interface_id: 1,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
lm.handle_inbound_packet(&raw, 1);
let outbound = transport_rx
.try_recv()
.expect("backend-signed delivery proof queued");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound proof");
};
let (proof_header, proof_offset) =
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(proof_header.destination_hash, link_id);
assert_eq!(
proof_header.flags.packet_type,
rns_wire::flags::PacketType::Proof
);
assert_eq!(
proof_header.context,
rns_wire::context::PacketContext::LinkProof
);
let proof_data = &request.raw[proof_offset..];
assert_eq!(&proof_data[..32], &packet_hash);
assert!(sender_link.validate_packet_proof(&packet_hash, proof_data));
}
#[test]
fn channel_packet_opens_channel_before_proof_and_dispatch() {
let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity();
+1 -1
View File
@@ -45,7 +45,7 @@ pub async fn start_remote_management(
event_rx,
identity,
app_name,
signing_key,
Some(signing_key),
);
let status_hash: [u8; 16] = truncated_hash(STATUS_PATH.as_bytes());
+184 -43
View File
@@ -1020,6 +1020,7 @@ pub async fn init(
{
Ok(client_handle) => {
let client_iface_id = client_handle.id;
let client_online = client_handle.online.clone();
register_interface_handle_with_role(
&transport_tx,
client_handle,
@@ -1027,11 +1028,12 @@ pub async fn init(
&interface_controls,
)
.await;
let _ = transport_tx
.send(TransportMessage::SharedConnectionRestored {
interface_id: client_iface_id,
})
.await;
spawn_shared_peer_monitor(
transport_tx.clone(),
client_iface_id,
client_online,
shutdown.clone(),
);
InstanceMode::Client
}
Err(_) => InstanceMode::Standalone,
@@ -1076,6 +1078,7 @@ pub async fn init(
{
Ok(client_handle) => {
let client_iface_id = client_handle.id;
let client_online = client_handle.online.clone();
register_interface_handle_with_role(
&transport_tx,
client_handle,
@@ -1083,11 +1086,12 @@ pub async fn init(
&interface_controls,
)
.await;
let _ = transport_tx
.send(TransportMessage::SharedConnectionRestored {
interface_id: client_iface_id,
})
.await;
spawn_shared_peer_monitor(
transport_tx.clone(),
client_iface_id,
client_online,
shutdown.clone(),
);
InstanceMode::Client
}
Err(_) => InstanceMode::Standalone,
@@ -1143,6 +1147,7 @@ pub async fn init(
{
Ok(client_handle) => {
let client_iface_id = client_handle.id;
let client_online = client_handle.online.clone();
register_interface_handle_with_role(
&transport_tx,
client_handle,
@@ -1150,11 +1155,12 @@ pub async fn init(
&interface_controls,
)
.await;
let _ = transport_tx
.send(TransportMessage::SharedConnectionRestored {
interface_id: client_iface_id,
})
.await;
spawn_shared_peer_monitor(
transport_tx.clone(),
client_iface_id,
client_online,
shutdown.clone(),
);
InstanceMode::Client
}
Err(_) => InstanceMode::Standalone,
@@ -1197,6 +1203,7 @@ pub async fn init(
{
Ok(client_handle) => {
let client_iface_id = client_handle.id;
let client_online = client_handle.online.clone();
register_interface_handle_with_role(
&transport_tx,
client_handle,
@@ -1204,11 +1211,12 @@ pub async fn init(
&interface_controls,
)
.await;
let _ = transport_tx
.send(TransportMessage::SharedConnectionRestored {
interface_id: client_iface_id,
})
.await;
spawn_shared_peer_monitor(
transport_tx.clone(),
client_iface_id,
client_online,
shutdown.clone(),
);
InstanceMode::Client
}
Err(_) => InstanceMode::Standalone,
@@ -1552,6 +1560,38 @@ fn next_id(id_gen: &Arc<AtomicU64>) -> u64 {
id_gen.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
fn spawn_shared_peer_monitor(
transport_tx: mpsc::Sender<TransportMessage>,
interface_id: u64,
online: Arc<AtomicBool>,
shutdown: ShutdownSignal,
) {
tokio::spawn(async move {
let mut was_online = false;
let mut interval = tokio::time::interval(Duration::from_millis(100));
loop {
tokio::select! {
_ = shutdown.wait() => break,
_ = interval.tick() => {
let is_online = online.load(std::sync::atomic::Ordering::SeqCst);
if is_online == was_online {
continue;
}
was_online = is_online;
let message = if is_online {
TransportMessage::SharedConnectionRestored { interface_id }
} else {
TransportMessage::SharedConnectionLost
};
if transport_tx.send(message).await.is_err() {
break;
}
}
}
}
});
}
fn ingress_for_role(
role: rns_transport::messages::InterfaceRole,
ingress_overrides: &rns_transport::ingress::IngressOverrides,
@@ -2387,7 +2427,7 @@ async fn start_blackhole_publisher(handle: &ReticulumHandle) -> Result<[u8; 16],
event_rx,
&identity,
app_name,
signing_key,
Some(signing_key),
);
let list_hash = rns_crypto::sha::truncated_hash(b"/list");
@@ -2513,8 +2553,12 @@ async fn start_blackhole_subscriber(handle: ReticulumHandle) {
}
fn clone_identity(identity: &Identity) -> Option<Identity> {
let private_key = identity.get_private_key()?;
Identity::from_private_key(&*private_key).ok()
// Preserve a hardware backend (shared Arc); software identities copy key material.
if identity.has_private_key() || identity.has_backend() {
Some(identity.clone())
} else {
None
}
}
fn send_announce_try(
@@ -2908,7 +2952,7 @@ pub async fn spawn_ble_peer_runtime(
identity_hash: Vec<u8>,
event_tx: Option<tokio::sync::mpsc::Sender<rns_interface::ble_peer::BlePeerEvent>>,
foreground_wake: std::sync::Arc<tokio::sync::Notify>,
seed_identities: Vec<String>,
seed_addresses: Vec<String>,
) -> Result<u64, String> {
let id = handle
.id_gen
@@ -2926,7 +2970,7 @@ pub async fn spawn_ble_peer_runtime(
handle.transport_tx.clone(),
handle.is_foreground.clone(),
foreground_wake,
seed_identities,
seed_addresses,
)
.await
.map_err(|e| {
@@ -3468,6 +3512,44 @@ mod tests {
bytes::Bytes::from(raw)
}
#[tokio::test]
async fn shared_peer_monitor_emits_connection_lifecycle_events() {
let (tx, mut rx) = mpsc::channel(4);
let online = Arc::new(AtomicBool::new(false));
let shutdown = ShutdownSignal::new();
spawn_shared_peer_monitor(tx, 7, online.clone(), shutdown.clone());
tokio::time::sleep(std::time::Duration::from_millis(120)).await;
assert!(
rx.try_recv().is_err(),
"offline initial state should not emit a lost event"
);
online.store(true, std::sync::atomic::Ordering::SeqCst);
let restored = tokio::time::timeout(std::time::Duration::from_millis(300), rx.recv())
.await
.expect("restored event timed out")
.expect("monitor channel closed");
match restored {
TransportMessage::SharedConnectionRestored { interface_id } => {
assert_eq!(interface_id, 7)
}
other => panic!("expected SharedConnectionRestored, got {other:?}"),
}
online.store(false, std::sync::atomic::Ordering::SeqCst);
let lost = tokio::time::timeout(std::time::Duration::from_millis(300), rx.recv())
.await
.expect("lost event timed out")
.expect("monitor channel closed");
match lost {
TransportMessage::SharedConnectionLost => {}
other => panic!("expected SharedConnectionLost, got {other:?}"),
}
shutdown.trigger();
}
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
std::fs::create_dir_all(storage_dir).unwrap();
@@ -4314,31 +4396,66 @@ enabled = yes
.unwrap();
assert_eq!(handle_c.instance_mode, InstanceMode::Client);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let (stats_tx, stats_rx) = tokio::sync::oneshot::channel();
handle_a
.transport_tx
.send(TransportMessage::Rpc {
query: rns_transport::messages::TransportQuery::GetInterfaceStats,
response_tx: stats_tx,
})
.await
.unwrap();
let server_stats = stats_rx.await.unwrap();
let roles: Vec<String> = match server_stats {
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => {
entries.into_iter().map(|entry| entry.role).collect()
let server_entries = {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
loop {
let (stats_tx, stats_rx) = tokio::sync::oneshot::channel();
handle_a
.transport_tx
.send(TransportMessage::Rpc {
query: rns_transport::messages::TransportQuery::GetInterfaceStats,
response_tx: stats_tx,
})
.await
.unwrap();
let server_stats = stats_rx.await.unwrap();
let entries = match server_stats {
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => {
entries
}
other => panic!("unexpected stats response: {other:?}"),
};
let local_clients: Vec<_> = entries
.iter()
.filter(|entry| entry.role == "local_client")
.collect();
if entries.iter().any(|entry| entry.role == "shared_server")
&& local_clients.len() == 2
&& local_clients.iter().all(|entry| entry.online)
&& local_clients.iter().all(|entry| entry.tx_drops == 0)
{
break entries;
}
if tokio::time::Instant::now() >= deadline {
break entries;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
other => panic!("unexpected stats response: {other:?}"),
};
let roles: Vec<String> = server_entries
.iter()
.map(|entry| entry.role.clone())
.collect();
assert!(
roles.iter().any(|role| role == "shared_server"),
"shared instance must mark the listener"
);
let local_clients: Vec<_> = server_entries
.iter()
.filter(|entry| entry.role == "local_client")
.collect();
assert_eq!(
local_clients.len(),
2,
"transient shared-instance detection sockets must not remain registered"
);
assert!(
roles.iter().filter(|role| *role == "local_client").count() >= 2,
"accepted shared clients must be marked for transport policy"
local_clients.iter().all(|entry| entry.online),
"accepted shared clients must be online"
);
assert!(
local_clients.iter().all(|entry| entry.tx_drops == 0),
"accepted shared clients must not accumulate TX drops"
);
let shared_control_stats = handle_b
@@ -4427,6 +4544,30 @@ enabled = yes
.expect("shared instance did not forward local-client plain packet");
assert_eq!(received.as_ref(), raw.as_ref());
let post_forward_stats = handle_b
.query_control(rns_transport::messages::TransportQuery::GetInterfaceStats)
.await
.expect("post-forward control query should reach shared instance");
let post_forward_entries = match post_forward_stats {
rns_transport::messages::TransportQueryResponse::InterfaceStats(entries) => entries,
other => panic!("unexpected post-forward stats response: {other:?}"),
};
let post_forward_local_clients: Vec<_> = post_forward_entries
.iter()
.filter(|entry| entry.role == "local_client")
.collect();
assert_eq!(
post_forward_local_clients.len(),
2,
"forwarding through shared instance must not retain stale local clients"
);
assert!(
post_forward_local_clients
.iter()
.all(|entry| entry.tx_drops == 0),
"forwarding through shared instance must not report TX drops"
);
shutdown_c.trigger();
shutdown_b.trigger();
shutdown_a.trigger();
+1 -1
View File
@@ -235,7 +235,7 @@ pub async fn spawn_rncp_listener(
dest_rx,
&cfg.identity,
&cfg.app_name,
signing_key,
Some(signing_key),
);
let (completion_tx, mut completion_rx) = mpsc::channel::<ResourceCompletion>(64);
+1 -1
View File
@@ -169,7 +169,7 @@ async fn run_rnsh_listener_inner(
event_rx,
&cfg.identity,
RNSH_APP_NAME,
signing_key,
Some(signing_key),
);
let announce_tx = transport_tx.clone();
+101 -5
View File
@@ -2,8 +2,9 @@
//!
//! Python Reticulum uses `multiprocessing.connection.Listener/Client` for the
//! local control port. Keep the Rust control socket wire-compatible with that:
//! framed auth challenge (`#CHALLENGE#` + `{sha256}` payload), framed pickle
//! request dictionaries, and framed pickle responses.
//! framed auth challenge (`#CHALLENGE#`), framed pickle request dictionaries,
//! and framed pickle responses. Python 3.12+ uses tagged SHA-256 auth
//! challenges, while Python 3.11 and older use raw MD5 HMAC responses.
use serde::{Deserialize, Serialize};
@@ -12,8 +13,23 @@ pub(crate) const MP_WELCOME: &[u8] = b"#WELCOME#";
pub(crate) const MP_FAILURE: &[u8] = b"#FAILURE#";
const MP_DIGEST_PREFIX: &[u8] = b"{sha256}";
const MP_CHALLENGE_RANDOM_LEN: usize = 40;
const MP_LEGACY_CHALLENGE_RANDOM_LEN: usize = 20;
const MAX_MP_FRAME_SIZE: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PythonAuthProtocol {
LegacyMd5,
Sha256,
}
pub(crate) fn detect_python_auth_protocol(challenge: &[u8]) -> PythonAuthProtocol {
if challenge.starts_with(MP_DIGEST_PREFIX) {
PythonAuthProtocol::Sha256
} else {
PythonAuthProtocol::LegacyMd5
}
}
#[derive(Debug, Clone, PartialEq)]
enum PyValue {
None,
@@ -213,6 +229,18 @@ pub fn compute_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 32] {
out
}
pub fn compute_legacy_auth_hmac(key: &[u8], challenge: &[u8]) -> [u8; 16] {
use hmac::{Hmac, Mac};
use md5::Md5;
let mut mac = Hmac::<Md5>::new_from_slice(key).expect("HMAC key can be any length");
mac.update(challenge);
let result = mac.finalize();
let mut out = [0u8; 16];
out.copy_from_slice(&result.into_bytes());
out
}
/// Constant-time comparison; handshake MUST NOT leak via timing.
pub fn verify_auth_hmac(key: &[u8], challenge: &[u8], provided: &[u8; 32]) -> bool {
use subtle::ConstantTimeEq;
@@ -1399,6 +1427,18 @@ fn read_u64_le(data: &[u8], index: &mut usize) -> Result<u64, RpcError> {
}
pub fn compute_python_auth_response(key: &[u8], message: &[u8]) -> Vec<u8> {
compute_python_auth_response_for(detect_python_auth_protocol(message), key, message)
}
pub(crate) fn compute_python_auth_response_for(
protocol: PythonAuthProtocol,
key: &[u8],
message: &[u8],
) -> Vec<u8> {
if protocol == PythonAuthProtocol::LegacyMd5 {
return compute_legacy_auth_hmac(key, message).to_vec();
}
let mut response = Vec::with_capacity(MP_DIGEST_PREFIX.len() + 32);
response.extend_from_slice(MP_DIGEST_PREFIX);
response.extend_from_slice(&compute_auth_hmac(key, message));
@@ -1406,7 +1446,26 @@ pub fn compute_python_auth_response(key: &[u8], message: &[u8]) -> Vec<u8> {
}
pub fn verify_python_auth_response(key: &[u8], message: &[u8], response: &[u8]) -> bool {
let protocol = if response.starts_with(MP_DIGEST_PREFIX) {
PythonAuthProtocol::Sha256
} else {
PythonAuthProtocol::LegacyMd5
};
verify_python_auth_response_for(protocol, key, message, response)
}
pub(crate) fn verify_python_auth_response_for(
protocol: PythonAuthProtocol,
key: &[u8],
message: &[u8],
response: &[u8],
) -> bool {
use subtle::ConstantTimeEq;
if protocol == PythonAuthProtocol::LegacyMd5 {
let expected = compute_legacy_auth_hmac(key, message);
return expected.as_slice().ct_eq(response).into();
}
if !response.starts_with(MP_DIGEST_PREFIX) {
return false;
}
@@ -1416,6 +1475,14 @@ pub fn verify_python_auth_response(key: &[u8], message: &[u8], response: &[u8])
}
pub fn new_python_challenge() -> Vec<u8> {
new_python_challenge_for(PythonAuthProtocol::Sha256)
}
pub(crate) fn new_python_challenge_for(protocol: PythonAuthProtocol) -> Vec<u8> {
if protocol == PythonAuthProtocol::LegacyMd5 {
return rns_crypto::random::random_bytes(MP_LEGACY_CHALLENGE_RANDOM_LEN);
}
let mut message = Vec::with_capacity(MP_DIGEST_PREFIX.len() + MP_CHALLENGE_RANDOM_LEN);
message.extend_from_slice(MP_DIGEST_PREFIX);
message.extend_from_slice(&rns_crypto::random::random_bytes(MP_CHALLENGE_RANDOM_LEN));
@@ -1580,8 +1647,9 @@ where
return Err(RpcError::AuthFailed);
}
let challenge = &challenge_frame[MP_CHALLENGE.len()..];
let protocol = detect_python_auth_protocol(challenge);
let response = compute_python_auth_response(rpc_key, challenge);
let response = compute_python_auth_response_for(protocol, rpc_key, challenge);
tokio::time::timeout(timeout, write_mp_frame(&mut stream, &response))
.await
.map_err(|_| {
@@ -1603,7 +1671,7 @@ where
return Err(RpcError::AuthFailed);
}
let client_challenge = new_python_challenge();
let client_challenge = new_python_challenge_for(protocol);
let mut client_challenge_frame =
Vec::with_capacity(MP_CHALLENGE.len() + client_challenge.len());
client_challenge_frame.extend_from_slice(MP_CHALLENGE);
@@ -1628,7 +1696,7 @@ where
"server auth response read timeout",
))
})??;
if verify_python_auth_response(rpc_key, &client_challenge, &server_response) {
if verify_python_auth_response_for(protocol, rpc_key, &client_challenge, &server_response) {
tokio::time::timeout(timeout, write_mp_frame(&mut stream, MP_WELCOME))
.await
.map_err(|_| {
@@ -1850,6 +1918,34 @@ mod tests {
assert!(!verify_auth_hmac(wrong_key, challenge, &hmac));
}
#[test]
fn test_python_legacy_md5_auth_response() {
let key = b"test_rpc_key";
let challenge = b"python311challenge";
let response = compute_python_auth_response(key, challenge);
assert_eq!(response.len(), 16);
assert!(verify_python_auth_response(key, challenge, &response));
assert!(!verify_python_auth_response(
b"wrong_key",
challenge,
&response
));
}
#[test]
fn test_python_sha256_auth_response() {
let key = b"test_rpc_key";
let challenge = b"{sha256}python312pluschallenge";
let response = compute_python_auth_response(key, challenge);
assert!(response.starts_with(MP_DIGEST_PREFIX));
assert!(verify_python_auth_response(key, challenge, &response));
assert!(!verify_python_auth_response(
b"wrong_key",
challenge,
&response
));
}
#[test]
fn test_derive_rpc_key() {
let private_key = [0x42u8; 64];
+5 -1
View File
@@ -198,7 +198,11 @@ async fn handle_rpc_client(
return Err(RpcError::AuthFailed);
}
let client_challenge = &client_challenge_frame[rpc::MP_CHALLENGE.len()..];
let client_response = rpc::compute_python_auth_response(rpc_key, client_challenge);
let client_response = rpc::compute_python_auth_response_for(
rpc::detect_python_auth_protocol(client_challenge),
rpc_key,
client_challenge,
);
rpc::write_mp_frame(&mut stream, &client_response).await?;
let client_welcome = rpc::read_mp_frame(&mut stream, 256).await?;
if client_welcome != rpc::MP_WELCOME {
+224 -23
View File
@@ -8,13 +8,77 @@ pub fn run(cmd: HwCommands) {
pin,
nickname,
output,
mgmt_key,
} => {
cmd_provision(pin, nickname, output);
cmd_provision(pin, nickname, output, mgmt_key);
}
HwCommands::List { dir } => cmd_list(dir),
HwCommands::Info { hwid } => cmd_info(hwid),
HwCommands::Verify { hwid } => cmd_verify(hwid),
HwCommands::Test { hwid } => cmd_test(hwid),
HwCommands::Test { hwid, pin } => cmd_test(hwid, pin),
HwCommands::Attest => cmd_attest(),
}
}
/// Fetch on-card attestation certs and verify the chain to a bundled Yubico root.
/// ATTEST + reading the F9 device cert are unauthenticated (no PIN).
fn cmd_attest() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error connecting to hardware token: {e}");
eprintln!("\nRun `rnid-rs hw detect` to check for connected devices.");
std::process::exit(1);
}
};
let device_cert = match session.read_attestation_cert() {
Ok(c) => c,
Err(e) => {
eprintln!("Error reading device attestation cert (slot F9): {e}");
std::process::exit(1);
}
};
println!(
"Attesting {} (serial {}, firmware {})...\n",
session.device_type().as_str(),
session.serial().unwrap_or(0),
session.firmware().unwrap_or("unknown"),
);
let mut all_ok = true;
for (label, slot) in [
("9A (signing)", rns_ratkey::apdu::SLOT_AUTHENTICATION),
("9D (encryption)", rns_ratkey::apdu::SLOT_KEY_MANAGEMENT),
] {
match session.attest_key(slot) {
Ok(cert) => match rns_ratkey::attestation::verify_attestation(&cert, &device_cert) {
Ok(v) => {
println!("Slot {label}:");
println!(" chain_verified: {}", v.chain_verified);
println!(" root CA: {}", v.root_ca);
println!(" {}", v.description);
all_ok &= v.chain_verified;
}
Err(e) => {
eprintln!("Slot {label}: verification error: {e}");
all_ok = false;
}
},
Err(e) => {
eprintln!("Slot {label}: attest error: {e}");
all_ok = false;
}
}
println!();
}
if all_ok {
println!("✓ Attestation chain cryptographically verified to a bundled Yubico root.");
} else {
eprintln!("✗ Attestation could not be fully verified.");
std::process::exit(1);
}
}
@@ -66,7 +130,42 @@ fn cmd_detect() {
}
}
fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<PathBuf>) {
/// Best-effort on-card attestation capture for the `.hwid`: the per-slot certs +
/// the chain-verified flag. Empty on devices without PIV attestation (e.g. Nitrokey).
fn capture_attestation(
session: &mut rns_ratkey::PcscPivSession,
) -> rns_ratkey::hwid::HwidAttestation {
let device = match session.read_attestation_cert() {
Ok(c) => c,
Err(_) => return Default::default(),
};
let ed = session
.attest_key(rns_ratkey::apdu::SLOT_AUTHENTICATION)
.ok();
let x = session
.attest_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT)
.ok();
let verified = ed
.as_ref()
.and_then(|c| rns_ratkey::attestation::verify_attestation(c, &device).ok())
.map(|v| v.chain_verified)
.unwrap_or(false);
rns_ratkey::hwid::HwidAttestation {
ed25519_cert: ed.map(hex::encode).unwrap_or_default(),
x25519_cert: x.map(hex::encode).unwrap_or_default(),
verified,
}
}
/// Factory-default PIV management key (24 bytes; AES-192 on YubiKey 5.7+).
const DEFAULT_MGMT_KEY: &str = "010203040506070801020304050607080102030405060708";
fn cmd_provision(
pin: Option<String>,
nickname: Option<String>,
output: Option<PathBuf>,
mgmt_key: Option<String>,
) {
let pin = match pin {
Some(p) => p,
None => {
@@ -81,7 +180,7 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
std::process::exit(1);
}
let mut session = match rns_ratkey::session::PivSession::connect() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error connecting to hardware token: {e}");
@@ -95,12 +194,29 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
std::process::exit(1);
}
// Slot 9A (PIV authentication), touch-always: prevents silent sign while PIN cache valid.
// Key generation is an administrative op gated by the management key, not the PIN.
let mgmt_key_hex = mgmt_key.unwrap_or_else(|| DEFAULT_MGMT_KEY.to_string());
let mgmt_key_bytes = match hex::decode(mgmt_key_hex.trim()) {
Ok(b) => b,
Err(e) => {
eprintln!("Error: invalid --mgmt-key hex: {e}");
std::process::exit(1);
}
};
if let Err(e) = session.authenticate_management_key(&mgmt_key_bytes) {
eprintln!("Management key authentication failed: {e}");
eprintln!("Pass --mgmt-key <hex> if the device uses a non-default management key.");
std::process::exit(1);
}
// Slot 9A (PIV authentication). PIN-once + touch-never: the PIN is the
// session unlock; the app re-locks on timeout / quit. (Policies are burned
// in permanently for a hardware-only identity.)
println!("Generating Ed25519 key in slot 9A...");
let ed_pub = match session.generate_ed25519(
rns_ratkey::apdu::SLOT_AUTHENTICATION,
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
Some(rns_ratkey::apdu::TOUCH_POLICY_ALWAYS),
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
) {
Ok(pub_key) => pub_key,
Err(e) => {
@@ -109,12 +225,13 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
}
};
// Slot 9D (PIV key management), touch-cached: one tap unlocks ECDH for a window (else every packet prompts).
// Slot 9D (PIV key management). PIN-once + touch-never: ECDH runs on every
// inbound packet, so per-op touch is impractical; the PIN gates the session.
println!("Generating X25519 key in slot 9D...");
let x_pub = match session.generate_x25519(
rns_ratkey::apdu::SLOT_KEY_MANAGEMENT,
Some(rns_ratkey::apdu::PIN_POLICY_ONCE),
Some(rns_ratkey::apdu::TOUCH_POLICY_CACHED),
Some(rns_ratkey::apdu::TOUCH_POLICY_NEVER),
) {
Ok(pub_key) => pub_key,
Err(e) => {
@@ -126,11 +243,15 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
let identity_hash = rns_ratkey::provision::compute_identity_hash(&ed_pub, &x_pub);
let hash_hex = hex::encode(identity_hash);
// Capture + verify the on-card attestation chain so the .hwid records it.
let attestation = capture_attestation(&mut session);
println!("\nHardware identity provisioned:");
println!(" Identity hash: {hash_hex}");
println!(" Ed25519 public: {}", hex::encode(ed_pub));
println!(" X25519 public: {}", hex::encode(x_pub));
println!(" Device: {}", session.device_type().as_str());
println!(" Attestation: chain_verified={}", attestation.verified);
if let Some(dir) = output {
let identity_dir = dir.join(&hash_hex);
@@ -164,10 +285,10 @@ fn cmd_provision(pin: Option<String>, nickname: Option<String>, output: Option<P
},
policy: rns_ratkey::hwid::HwidPolicy {
pin_cache_timeout: 300,
touch_signing: "always".to_string(),
touch_encryption: "cached".to_string(),
touch_signing: "never".to_string(),
touch_encryption: "never".to_string(),
},
attestation: Default::default(),
attestation: attestation.clone(),
app: Default::default(),
backup: Default::default(),
};
@@ -292,7 +413,22 @@ fn cmd_verify(hwid_path: PathBuf) {
println!("Verifying hardware identity {}...", config.identity.hash);
let session = match rns_ratkey::session::PivSession::connect() {
let expected_ed = match config.ed25519_pub_bytes() {
Ok(k) => k,
Err(e) => {
eprintln!("Error: .hwid has invalid Ed25519 key: {e}");
std::process::exit(1);
}
};
let expected_x = match config.x25519_pub_bytes() {
Ok(k) => k,
Err(e) => {
eprintln!("Error: .hwid has invalid X25519 key: {e}");
std::process::exit(1);
}
};
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error: cannot connect to hardware token: {e}");
@@ -300,20 +436,42 @@ fn cmd_verify(hwid_path: PathBuf) {
}
};
let metadata = match session.read_metadata(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
Ok(m) => m,
Err(e) => {
eprintln!("Error reading slot 9A: {e}");
std::process::exit(1);
// Reads the slot public keys from GET METADATA and compares against the .hwid.
// This is the on-device confirmation of the metadata parser before it gates
// HardwareIdentity construction.
let mut ok = true;
match session.read_public_key(rns_ratkey::apdu::SLOT_AUTHENTICATION) {
Ok(dev_ed) if dev_ed == expected_ed => println!(" Slot 9A (Ed25519): MATCH"),
Ok(_) => {
println!(" Slot 9A (Ed25519): MISMATCH");
ok = false;
}
};
Err(e) => {
println!(" Slot 9A (Ed25519): error reading key: {e}");
ok = false;
}
}
match session.read_public_key(rns_ratkey::apdu::SLOT_KEY_MANAGEMENT) {
Ok(dev_x) if dev_x == expected_x => println!(" Slot 9D (X25519): MATCH"),
Ok(_) => {
println!(" Slot 9D (X25519): MISMATCH");
ok = false;
}
Err(e) => {
println!(" Slot 9D (X25519): error reading key: {e}");
ok = false;
}
}
println!(" Slot 9A metadata: {} bytes", metadata.len());
println!(" Verification requires comparing public keys from device with .hwid file.");
println!(" (Full verification implemented when hardware is available for testing)");
if ok {
println!("\nVerified: connected token matches this .hwid.");
} else {
println!("\nVerification FAILED: token does not match this .hwid.");
std::process::exit(1);
}
}
fn cmd_test(hwid_path: PathBuf) {
fn cmd_test(hwid_path: PathBuf, pin: Option<String>) {
let config = match rns_ratkey::hwid::HwidConfig::from_file(&hwid_path) {
Ok(c) => c,
Err(e) => {
@@ -322,9 +480,18 @@ fn cmd_test(hwid_path: PathBuf) {
}
};
let pin = match pin {
Some(p) => p,
None => {
eprintln!("Error: --pin is required (PIN-once keys need one verification per session)");
eprintln!("Usage: rnid-rs hw test <hwid> --pin <PIN>");
std::process::exit(1);
}
};
println!("Testing hardware identity {}...\n", config.identity.hash);
let session = match rns_ratkey::session::PivSession::connect() {
let mut session = match rns_ratkey::PcscPivSession::connect() {
Ok(s) => s,
Err(e) => {
eprintln!("Error: cannot connect to hardware token: {e}");
@@ -332,6 +499,12 @@ fn cmd_test(hwid_path: PathBuf) {
}
};
// PIN_POLICY_ONCE: a fresh session must verify the PIN before any private-key op.
if let Err(e) = session.verify_pin(&pin) {
eprintln!("PIN verification failed: {e}");
std::process::exit(1);
}
println!("1. Testing Ed25519 signing in slot 9A...");
let test_msg = b"RATKEY hardware identity test message";
match session.sign_ed25519(rns_ratkey::apdu::SLOT_AUTHENTICATION, test_msg) {
@@ -373,5 +546,33 @@ fn cmd_test(hwid_path: PathBuf) {
}
}
println!("3. Testing HardwareIdentity decrypt (on-device ECDH + HKDF + AES) end-to-end...");
let mut hw = match rns_ratkey::HardwareIdentity::from_hwid(config.clone(), Box::new(session)) {
Ok(h) => h,
Err(e) => {
println!(" FAIL: cannot build HardwareIdentity: {e}");
std::process::exit(1);
}
};
let plaintext = b"RATKEY end-to-end decrypt test";
let ciphertext = match hw.as_identity().encrypt(plaintext, None) {
Ok(c) => c,
Err(e) => {
println!(" FAIL: encrypt to hardware identity failed: {e}");
std::process::exit(1);
}
};
match hw.decrypt(&ciphertext, None, false) {
Ok(pt) if pt == plaintext => println!(" PASS: round-trip decrypt via on-device ECDH"),
Ok(_) => {
println!(" FAIL: decrypted plaintext mismatch");
std::process::exit(1);
}
Err(e) => {
println!(" FAIL: {e}");
std::process::exit(1);
}
}
println!("\nAll tests passed.");
}
@@ -187,6 +187,9 @@ enum HwCommands {
nickname: Option<String>,
#[arg(short, long)]
output: Option<PathBuf>,
/// PIV management key (hex). Defaults to the factory key.
#[arg(long)]
mgmt_key: Option<String>,
},
List {
#[arg(short, long)]
@@ -200,7 +203,12 @@ enum HwCommands {
},
Test {
hwid: PathBuf,
#[arg(long)]
pin: Option<String>,
},
/// Fetch the on-card attestation (slots 9A/9D + device F9) and verify the
/// certificate chain to a bundled Yubico root. No PIN required.
Attest,
}
#[cfg(feature = "hardware")]
+1
View File
@@ -171,6 +171,7 @@ pub(crate) async fn main() {
tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(LogFileWriter { path: log_path })
.with_ansi(false)
.init();
} else {
tracing_subscriber::fmt().with_max_level(level).init();
+322 -49
View File
@@ -493,6 +493,15 @@ impl TransportActor {
let is_outbound = entry.direction.outbound;
let iface_name = entry.name.clone();
let role = entry.role;
if role == InterfaceRole::LocalClient && interface_marked_offline(&entry) {
tracing::info!(
id,
name = %iface_name,
role = role.as_str(),
"skipping registration for interface already marked offline"
);
return;
}
debug!(id, name = %iface_name, outbound = is_outbound, role = role.as_str(), "registering interface");
self.interfaces.insert(id, entry);
if !self.startup_complete && self.startup_time == 0.0 {
@@ -503,28 +512,10 @@ impl TransportActor {
// queries from other code (e.g. announce replay below) see
// the restored paths.
self.drain_pending_for_interface(id, &iface_name);
// Replay cached announces so a freshly connected peer learns
// the known destinations immediately. Important for relay
// topologies where announces arrived before any clients did.
if role == InterfaceRole::LocalClient && is_outbound {
self.replay_recent_announces_to_local_client(id);
} else if self.is_transport_enabled && is_outbound {
let announces: Vec<Vec<u8>> = self
.announce_table
.iter()
.map(|(_, entry)| entry.packet_raw.clone())
.collect();
if !announces.is_empty() {
debug!(
id,
count = announces.len(),
"replaying cached announces to new interface"
);
for raw in &announces {
self.send_to_interface(id, raw);
}
}
}
// Python interface registration does not trigger announce
// retransmission. Cached/path-response announces stay queued
// for the announce job, and local shared clients only receive
// live announces or request-driven responses after connect.
}
TransportMessage::DeregisterInterface { id } => {
debug!(id, "deregistering interface");
@@ -723,33 +714,6 @@ impl TransportActor {
}
}
fn replay_recent_announces_to_local_client(&mut self, interface_id: InterfaceId) {
let announces: Vec<Vec<u8>> = self
.recent_announces
.values()
.filter(|announce| !announce.raw_packet.is_empty())
.map(|announce| {
self.transport_announce_from_raw(
&announce.raw_packet,
announce.dest_hash,
announce.hops,
rns_wire::context::PacketContext::None,
)
})
.collect();
if !announces.is_empty() {
debug!(
interface_id,
count = announces.len(),
"replaying recent announces to local shared client"
);
}
for raw in announces {
self.send_to_interface(interface_id, &raw);
}
}
fn send_announce_to_local_clients(
&mut self,
cached_raw: &[u8],
@@ -980,6 +944,18 @@ impl TransportActor {
fields(interface_id = id, raw_len = raw.len()),
)]
fn send_to_interface(&mut self, id: InterfaceId, raw: &[u8]) {
let Some(entry) = self.interfaces.get(&id) else {
return;
};
if entry.role == InterfaceRole::LocalClient && interface_marked_offline(entry) {
tracing::info!(
interface_id = id,
interface_name = %entry.name,
"interface marked offline; auto-deregistering"
);
self.deregister_interface(id);
return;
}
let Some(entry) = self.interfaces.get(&id) else {
return;
};
@@ -1262,6 +1238,14 @@ impl TransportActor {
}
}
fn interface_marked_offline(entry: &InterfaceEntry) -> bool {
entry
.online
.as_ref()
.map(|online| !online.load(std::sync::atomic::Ordering::SeqCst))
.unwrap_or(false)
}
fn now_f64() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1659,6 +1643,266 @@ mod tests {
assert!(actor.interfaces.contains_key(&1));
}
#[test]
fn test_register_interface_skips_already_offline_child() {
let (mut actor, _tx) = TransportActor::new();
let (raw, dest_hash) = make_valid_announce("test.offline.local_client", 0);
actor.recent_announces.insert(
dest_hash,
RecentAnnounce {
dest_hash,
hops: 0,
app_data: None,
timestamp: now_f64(),
public_key: None,
ratchet: None,
raw_packet: raw.to_vec(),
retained: false,
name_hash: [0u8; 10],
},
);
let (mut entry, mut rx) = make_test_interface("SharedInstanceServer/client_4");
entry.role = InterfaceRole::LocalClient;
entry.online = Some(Arc::new(AtomicBool::new(false)));
let tx_drops = entry.tx_drops.clone();
actor.handle_message(TransportMessage::RegisterInterface { id: 4, entry });
assert!(
!actor.interfaces.contains_key(&4),
"offline child handles must not be registered after disconnect"
);
assert!(
rx.try_recv().is_err(),
"offline child must not receive cached announce replay"
);
assert_eq!(
tx_drops.load(std::sync::atomic::Ordering::Relaxed),
0,
"offline registration should not count as TX pressure"
);
}
#[test]
fn test_register_interface_allows_offline_shared_instance_peer() {
let (mut actor, _tx) = TransportActor::new();
let (mut entry, mut rx) = make_test_interface("SharedInstanceClient");
entry.role = InterfaceRole::SharedInstancePeer;
entry.online = Some(Arc::new(AtomicBool::new(false)));
actor.handle_message(TransportMessage::RegisterInterface { id: 44, entry });
assert!(
actor.interfaces.contains_key(&44),
"shared-instance peers must remain registered while reconnecting"
);
actor.send_to_interface(44, &[0xA5, 0x5A]);
assert_eq!(
rx.try_recv().unwrap(),
Bytes::from_static(&[0xA5, 0x5A]),
"offline shared peer should not use local-client stale-handle reaping"
);
assert!(
actor.interfaces.contains_key(&44),
"offline shared peer should not be auto-deregistered"
);
}
#[test]
fn test_register_local_client_does_not_replay_cached_announces() {
let (mut actor, _tx) = TransportActor::new();
let cached_announces = 1_200;
for i in 0..cached_announces {
let mut dest_hash = [0; 16];
dest_hash[8..].copy_from_slice(&(i as u64).to_be_bytes());
let mut raw_packet = vec![0x51];
raw_packet.extend_from_slice(&dest_hash);
actor.recent_announces.insert(
dest_hash,
RecentAnnounce {
dest_hash,
hops: 1,
app_data: None,
timestamp: i as f64,
public_key: None,
ratchet: None,
raw_packet,
retained: false,
name_hash: [0; 10],
},
);
}
assert!(
actor.recent_announces.len() > 1_000,
"fixture must model the large cache seen in contributor reports"
);
let (mut entry, mut rx) = make_test_interface("SharedInstanceServer/client_9");
entry.role = InterfaceRole::LocalClient;
let tx_drops = entry.tx_drops.clone();
actor.handle_message(TransportMessage::RegisterInterface { id: 9, entry });
assert_eq!(
rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty),
"registering a local shared client must not dump cached announces"
);
assert_eq!(
tx_drops.load(std::sync::atomic::Ordering::Relaxed),
0,
"registering a local shared client must not create TX pressure"
);
assert!(actor.interfaces.contains_key(&9));
}
#[test]
fn test_register_interface_does_not_replay_announce_table() {
let (mut actor, _tx) = TransportActor::new();
actor.is_transport_enabled = true;
let dest_hash = [0xA7; 16];
actor.announce_table.insert(
dest_hash,
crate::announce::AnnounceEntry {
timestamp: now_f64(),
retransmit_timeout: now_f64(),
retries: 0,
received_from: [0x22; 16],
hops: 2,
packet_raw: vec![0x51, 0x01, 0x02],
local_rebroadcasts: 0,
block_rebroadcast: false,
attached_interface: None,
source_interface: None,
},
);
let (entry, mut rx) = make_test_interface("tcp_backbone");
actor.handle_message(TransportMessage::RegisterInterface { id: 10, entry });
assert_eq!(
rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty),
"interface registration must not replay queued announces"
);
assert!(
actor.announce_table.get(&dest_hash).is_some(),
"announce job, not registration, owns queued announce processing"
);
}
#[test]
fn local_client_path_request_uses_cached_announce_without_startup_dump() {
let (mut actor, _tx) = TransportActor::new();
actor.is_transport_enabled = true;
actor.transport_identity_hash = Some([0x77; 16]);
let cached_announces = 1_200;
for i in 0..cached_announces {
let mut dest_hash = [0; 16];
dest_hash[8..].copy_from_slice(&(i as u64).to_be_bytes());
actor.recent_announces.insert(
dest_hash,
RecentAnnounce {
dest_hash,
hops: 1,
app_data: None,
timestamp: i as f64,
public_key: None,
ratchet: None,
raw_packet: vec![0x51, i as u8],
retained: false,
name_hash: [0; 10],
},
);
}
let (target_raw, target_dest) = make_valid_announce("test.shared.cached_path_response", 2);
actor.recent_announces.insert(
target_dest,
RecentAnnounce {
dest_hash: target_dest,
hops: 3,
app_data: None,
timestamp: cached_announces as f64,
public_key: None,
ratchet: None,
raw_packet: target_raw.to_vec(),
retained: false,
name_hash: [0; 10],
},
);
actor.path_table.insert(
target_dest,
crate::path_table::PathEntry::new(Some([0x22; 16]), 3, 2, InterfaceMode::Gateway),
);
assert!(
actor.recent_announces.len() > 1_000,
"fixture must keep a large cache while proving request-driven use"
);
let (mut local_client, mut local_rx) =
make_test_interface("SharedInstanceServer/client_10");
local_client.role = InterfaceRole::LocalClient;
actor.handle_message(TransportMessage::RegisterInterface {
id: 1,
entry: local_client,
});
assert_eq!(
local_rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty),
"local shared client must not receive cached announces on connect"
);
actor.handle_inbound_path_request(&make_path_request_payload(target_dest, None), 1);
assert_eq!(
local_rx.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty),
"path request should queue the cached response for the announce job"
);
actor.flush_pending_announces();
let response = local_rx
.try_recv()
.expect("cached announce should be returned after a local path request");
let (header, _) = rns_wire::header::PacketHeader::unpack(&response).unwrap();
assert_eq!(header.destination_hash, target_dest);
assert_eq!(header.hops, 3);
assert_eq!(header.transport_id, Some([0x77; 16]));
assert_eq!(
header.context,
rns_wire::context::PacketContext::PathResponse
);
}
#[test]
fn test_send_to_interface_auto_deregisters_offline_entry_before_queueing() {
let (mut actor, _tx) = TransportActor::new();
let (mut entry, mut rx) = make_test_interface("SharedInstanceServer/client_5");
entry.role = InterfaceRole::LocalClient;
entry.online = Some(Arc::new(AtomicBool::new(false)));
let tx_drops = entry.tx_drops.clone();
actor.interfaces.insert(5, entry);
actor.send_to_interface(5, &[0x01, 0x02, 0x03]);
assert!(
!actor.interfaces.contains_key(&5),
"offline interface should be reaped before enqueue"
);
assert!(
rx.try_recv().is_err(),
"offline interface should not receive outbound bytes"
);
assert_eq!(
tx_drops.load(std::sync::atomic::Ordering::Relaxed),
0,
"offline interface should not report queue drops"
);
}
#[test]
fn test_broadcast_on_interfaces() {
let (mut actor, _tx) = TransportActor::new();
@@ -7457,6 +7701,35 @@ mod tests {
assert_eq!(header.transport_id, Some([0x66; 16]));
}
#[test]
fn shared_connection_lost_clears_state_without_deregistering_peer() {
let (mut actor, _tx) = TransportActor::new();
actor.is_shared_instance = true;
let (mut shared_peer, _rx) = make_test_interface("SharedInstanceClient");
shared_peer.role = InterfaceRole::SharedInstancePeer;
shared_peer.online = Some(Arc::new(AtomicBool::new(false)));
actor.interfaces.insert(1, shared_peer);
actor.path_table.insert(
[0x11; 16],
crate::path_table::PathEntry::new(None, 1, 1, InterfaceMode::Gateway),
);
actor.reverse_table.insert([0x22; 16], 1, 1);
actor.pending_local_path_requests.insert([0x33; 16], 1);
actor.handle_message(TransportMessage::SharedConnectionLost);
assert!(!actor.is_shared_instance);
assert!(actor.shared_instance_client_mode);
assert!(
actor.interfaces.contains_key(&1),
"connection-loss events should suspend shared routing without deleting the peer"
);
assert!(actor.path_table.is_empty());
assert!(actor.reverse_table.is_empty());
assert!(actor.pending_local_path_requests.is_empty());
}
#[test]
fn shared_instance_peer_deregister_clears_shared_route_state() {
let (mut actor, _tx) = TransportActor::new();