Compare commits

...
100 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
DeFiDude 2f077af27b release: bump rsReticulum to 0.9.4 2026-05-24 00:11:36 -06:00
DeFiDude 05e2cdff83 interface: fix clippy hex grouping 2026-05-23 23:56:37 -06:00
DeFiDude 52c670e5fc tools: fix probe discovery and listener shutdown 2026-05-23 23:52:13 -06:00
DeFiDude 4cbb7d8b59 ble: smooth rnode pairing startup 2026-05-23 20:46:48 -06:00
DeFiDude 84bfd4871d rnode: detach serial transports on teardown 2026-05-23 17:43:24 -06:00
DeFiDude 4df2e6581f rnode: send detach sequence on BLE stop 2026-05-23 17:27:17 -06:00
DeFiDude 8328393a5f rnode: send radio off on BLE teardown 2026-05-23 16:46:41 -06:00
DeFiDude b45f6b10de tests: cover shared instance startup smoke 2026-05-23 15:33:19 -06:00
DeFiDude 55d2d34488 transport: load persisted state before actor startup 2026-05-23 15:19:34 -06:00
DeFiDude 73b250f36e Revert "ble-peer: add low-power advertising option"
This reverts commit f21f526b0a.
2026-05-23 02:38:05 -06:00
DeFiDude 1d4c1d6d7f Revert "ble-peer: restore balanced advertising default"
This reverts commit d30626a098.
2026-05-23 02:38:05 -06:00
DeFiDude d30626a098 ble-peer: restore balanced advertising default 2026-05-23 02:28:12 -06:00
DeFiDude f21f526b0a ble-peer: add low-power advertising option 2026-05-23 02:11:21 -06:00
DeFiDude 52cd1a0939 ble-peer: fix direct link request framing 2026-05-23 01:04:12 -06:00
DeFiDude d9af1beece runtime: satisfy ingress override clippy 2026-05-22 14:25:07 -06:00
DeFiDude 8b80ca88fd Merge remote-tracking branch 'origin/main' 2026-05-22 14:03:27 -06:00
DeFiDude a2c2a256d4 transport: harden shared instance client state 2026-05-22 13:57:45 -06:00
dude.eth 112dfc1d2c Update README.md
oops
2026-05-21 13:01:32 -06:00
dude.eth f9a8f89ffd Update README.md
Change target to 1.2.5 after the 1.2.4 -> 1.2.5 changes
2026-05-21 13:01:05 -06:00
DeFiDude 46449b21d3 runtime: normalize announce cap percent 2026-05-20 16:59:07 -06:00
DeFiDude 08848509b6 transport: add cache clear queries 2026-05-20 14:33:15 -06:00
DeFiDude 6a4e3af78a transport: mark path response announce entries 2026-05-20 12:02:57 -06:00
DeFiDude ffe641b3af transport: ignore stale paths for live routing 2026-05-20 10:27:47 -06:00
Belousov Oleg b89e434a00 Disable ansi for log file 2026-05-20 15:34:16 +03:00
DeFiDude 0013707496 resource: track outbound send progress 2026-05-19 23:59:38 -06:00
DeFiDude ade40c8283 interface: satisfy rnode tcp clippy 2026-05-19 22:34:25 -06:00
DeFiDude 20bee8bafd interface: split RNode TCP feature gate 2026-05-19 19:59:55 -06:00
DeFiDude f1042c0bb4 ci: use Node 24 action versions 2026-05-18 02:31:16 -06:00
DeFiDude 9d45c9a61f transport: suppress failed direct path interfaces 2026-05-17 22:24:14 -06:00
dude.eth a6c384f856 Merge pull request #2 from strijar/fix/ble
Fixed dependency on BLE
2026-05-17 15:48:38 -06:00
DeFiDude 84b0f0175a Update README.md 2026-05-17 15:38:54 -06:00
dude.eth 8e7d588faf Merge pull request #4 from strijar/fix/udevlib
Unnecessary dependency on udevlib has been removed
2026-05-17 15:35:55 -06:00
DeFiDude 83c63b463e interface: tune RNode TCP sockets 2026-05-17 15:23:12 -06:00
DeFiDude 8ac7f9a625 interface: clean up RNode TCP error wrapping 2026-05-17 15:11:42 -06:00
DeFiDude c7f048bac5 interface: reconnect RNode streams after disconnect 2026-05-17 15:02:06 -06:00
DeFiDude 7579873409 interface: harden RNode TCP endpoint parsing 2026-05-17 14:41:25 -06:00
DeFiDude a8df6d0b36 interface: note RNode TCP feature-gate cleanup 2026-05-17 14:20:41 -06:00
DeFiDude eb2972510c interface: bound RNode TCP connect attempts 2026-05-17 14:11:51 -06:00
DeFiDude 6d1b43bfc4 interface: treat RNode TCP EOF as disconnect 2026-05-17 14:10:51 -06:00
Belousov Oleg bebb9a8fca RNode cosmetic fixes 2026-05-17 14:09:02 -06:00
Belousov Oleg 497502596a RNode via TCP 2026-05-17 14:09:02 -06:00
DeFiDude 491664d24c interface: silence Android BLE build warnings 2026-05-15 20:37:13 -06:00
DeFiDude 3e85c74917 transport: satisfy strict ci lints 2026-05-15 19:32:47 -06:00
DeFiDude 68a83f83dc transport: finish upstream path reliability gaps 2026-05-15 15:45:27 -06:00
DeFiDude 1ad1a12388 transport: align path routing with upstream 2026-05-15 15:02:34 -06:00
DeFiDude 3758ae8bac transport: normalize inbound hop accounting 2026-05-15 14:34:33 -06:00
DeFiDude 15ae922535 runtime: choose packet or resource for link payloads 2026-05-15 03:25:02 -06:00
DeFiDude 5d0b6641cd runtime: add link app send commands 2026-05-15 03:22:52 -06:00
Belousov Oleg d651a4bcea Unnecessary dependency on udevlib has been removed 2026-05-15 09:29:42 +03:00
Belousov Oleg 51def9d622 Fixed dependency on BLE 2026-05-15 08:58:43 +03:00
DeFiDude 017b747eeb ci: avoid caching cargo shims 2026-05-14 23:34:50 -06:00
DeFiDude 863d723531 link: make keepalive jitter test platform-safe 2026-05-14 23:28:42 -06:00
DeFiDude 673a9715d5 tools: align utilities with Reticulum 1.2.5 2026-05-14 13:31:25 -06:00
DeFiDude 81672542ce runtime: group BLE RNode spawn args 2026-05-13 23:22:12 -06:00
DeFiDude c744831517 transport: satisfy strict clippy checks 2026-05-12 05:05:37 -06:00
DeFiDude 4cab54659c transport: implement Reticulum 1.2.5 routing controls 2026-05-11 20:15:21 -06:00
DeFiDude 4ddbf01a2a transport: expose announce aspect hashes 2026-05-11 16:05:05 -06:00
DeFiDude fe665b2216 release: prepare v0.9.3 2026-05-10 01:06:50 -06:00
DeFiDude e83fa8e208 interface: keep AutoInterface link-local addrs 2026-05-09 22:39:38 -06:00
DeFiDude bc232d65da release: prepare AutoInterface prerelease 2026-05-09 20:49:23 -06:00
DeFiDude 365bd02e75 interface: scope AutoInterface peers 2026-05-09 19:48:31 -06:00
91 changed files with 15375 additions and 1990 deletions

No files matched your search

+4 -2
View File
@@ -19,9 +19,11 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
@@ -36,7 +38,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
+7 -5
View File
@@ -39,11 +39,13 @@ jobs:
env:
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
ref: ${{ env.RELEASE_TAG }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
cache-bin: false
- name: Install system deps (Linux)
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
@@ -70,7 +72,7 @@ jobs:
if: runner.os == 'Windows'
shell: pwsh
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@v7
with:
name: ${{ env.ARCHIVE_NAME }}
path: |
@@ -85,15 +87,15 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/download-artifact@v4
- uses: actions/download-artifact@v7
with:
path: release-assets
merge-multiple: true
- name: Generate checksums
working-directory: release-assets
run: sha256sum * > SHA256SUMS
- uses: softprops/action-gh-release@v2
- uses: softprops/action-gh-release@v3
with:
tag_name: ${{ env.RELEASE_TAG }}
prerelease: true
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
files: release-assets/*
+1 -1
View File
@@ -6,4 +6,4 @@ __pycache__/
/interop_artifacts/
/rust_artifacts/
proptest-regressions/
/tools/
/tools/*
Generated
+263 -60
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"
@@ -1027,24 +1075,10 @@ dependencies = [
]
[[package]]
name = "libudev"
version = "0.3.0"
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0"
dependencies = [
"libc",
"libudev-sys",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
dependencies = [
"libc",
"pkg-config",
]
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "linux-raw-sys"
@@ -1082,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"
@@ -1131,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"
@@ -1142,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"
@@ -1149,6 +1229,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
@@ -1250,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"
@@ -1276,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"
@@ -1481,7 +1582,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"aes",
"cbc",
@@ -1502,7 +1603,7 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"hex",
"proptest",
@@ -1519,7 +1620,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"bluer",
"btleplug",
@@ -1549,7 +1650,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"hex",
"proptest",
@@ -1565,7 +1666,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"bzip2",
"hex",
@@ -1582,27 +1683,38 @@ dependencies = [
[[package]]
name = "rns-ratkey"
version = "0.9.2"
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",
]
[[package]]
name = "rns-runtime"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"bytes",
"hex",
"hmac",
"md-5",
"nix 0.29.0",
"rmp-serde",
"rmpv",
@@ -1623,7 +1735,7 @@ dependencies = [
[[package]]
name = "rns-tools"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"base64",
"bytes",
@@ -1650,7 +1762,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"bytes",
"hex",
@@ -1670,7 +1782,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "0.9.2"
version = "0.9.4"
dependencies = [
"proptest",
"rns-crypto",
@@ -1678,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"
@@ -1824,7 +1957,6 @@ dependencies = [
"core-foundation",
"core-foundation-sys",
"io-kit-sys",
"libudev",
"mach2",
"nix 0.26.4",
"scopeguard",
@@ -1832,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"
@@ -1852,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"
@@ -1874,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",
]
@@ -1909,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"
@@ -2043,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"
@@ -2221,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"
@@ -2774,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"
+8 -7
View File
@@ -14,7 +14,7 @@ members = [
]
[workspace.package]
version = "0.9.2"
version = "0.9.4"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.85"
@@ -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,16 +48,15 @@ serde_json = "1"
tokio = { version = "1", features = ["full"] }
# Compression
bzip2 = "0.5"
bzip2 = "0.6"
# Serial
serialport = "4"
# BLE
btleplug = "0.11"
serialport = { version = "4", default-features = false }
# Networking
if-addrs = "0.13"
# AutoInterface requires fe80::/10 discovery addresses. if-addrs filters them
# unless this feature is enabled, which leaves Linux/Windows with no adopted NICs.
if-addrs = { version = "0.13", features = ["link-local"] }
socket2 = { version = "0.5", features = ["all"] }
# CLI
+4 -4
View File
@@ -7,7 +7,7 @@
[![License: AGPL-3.0-or-later](https://img.shields.io/badge/license-AGPL--3.0--or--later-blue.svg)](LICENSE)
[![Rust 1.85+](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org)
[![Reticulum 1.2.4](https://img.shields.io/badge/target-Reticulum%201.2.4-success.svg)](https://reticulum.network/)
[![Reticulum 1.2.5](https://img.shields.io/badge/target-Reticulum%201.2.5-success.svg)](https://reticulum.network/)
[![Status](https://img.shields.io/badge/status-experimental-yellow.svg)](#feature-status)
[Reticulum Manual](https://reticulum.network/manual/) |
@@ -61,19 +61,19 @@ Debian, Ubuntu, and Raspberry Pi OS:
```bash
sudo apt update
sudo apt install -y build-essential pkg-config libudev-dev
sudo apt install -y build-essential pkg-config
```
Fedora:
```bash
sudo dnf install gcc make pkgconf-pkg-config systemd-devel
sudo dnf install gcc make pkgconf-pkg-config
```
Arch:
```bash
sudo pacman -S --needed base-devel pkgconf systemd
sudo pacman -S --needed base-devel pkgconf
```
##### Build the tools:
+25 -1
View File
@@ -198,6 +198,19 @@ impl AnnounceData {
packet_dest_hash: &[u8; 16],
known_public_key: Option<&[u8; 64]>,
) -> Result<Identity, AnnounceError> {
let identity = self.verify_signature(packet_dest_hash)?;
self.validate_destination_binding(packet_dest_hash, &identity, known_public_key)?;
Ok(identity)
}
/// Verify the announce signature without checking destination-hash
/// binding or first-seen key continuity.
///
/// Reticulum transport performs this lightweight precheck before announce
/// ingress limiting, then runs full binding validation before learning the
/// path. Keeping this as a distinct step lets transport match that order
/// without duplicating announce wire-format logic.
pub fn verify_signature(&self, packet_dest_hash: &[u8; 16]) -> Result<Identity, AnnounceError> {
let identity = Identity::from_public_key(&self.public_key)
.map_err(|_| AnnounceError::InvalidPublicKey)?;
@@ -224,6 +237,17 @@ impl AnnounceData {
return Err(AnnounceError::SignatureInvalid);
}
Ok(identity)
}
/// Validate destination-hash binding and first-seen public-key continuity
/// after [`verify_signature`] has succeeded.
pub fn validate_destination_binding(
&self,
packet_dest_hash: &[u8; 16],
identity: &Identity,
known_public_key: Option<&[u8; 64]>,
) -> Result<(), AnnounceError> {
// Destination hash = SHA-256(name_hash || identity_hash) truncated to 16 bytes.
let expected_hash = {
let mut material = Vec::with_capacity(26);
@@ -256,7 +280,7 @@ impl AnnounceData {
}
}
Ok(identity)
Ok(())
}
}
+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");
}
}
+4 -3
View File
@@ -8,7 +8,8 @@ license.workspace = true
[features]
default = []
serial = ["dep:serialport"]
ble = ["dep:btleplug", "dep:futures", "dep:uuid"]
rnode-tcp = []
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
ble_peer = ["ble"]
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
# and reverse-peering probes slow down in the background; BLE peer scan
@@ -26,7 +27,7 @@ tracing = { workspace = true }
socket2 = { workspace = true }
if-addrs = { workspace = true }
serialport = { workspace = true, optional = true }
btleplug = { workspace = true, optional = true }
btleplug = { version = "0.11", optional = true }
futures = { version = "0.3", optional = true }
uuid = { version = "1", optional = true }
rand = { workspace = true }
@@ -56,7 +57,7 @@ jni = "0.19"
# Linux-only target dep so non-Linux builds don't pull in BlueZ. The
# linux_peripheral module is gated by both `ble` feature and target_os.
[target.'cfg(target_os = "linux")'.dependencies]
bluer = { version = "0.17", features = ["bluetoothd"] }
bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
# Windows BLE Peripheral via WinRT GattServiceProvider (MSIX-packaged apps).
# Windows-only target dep so cross-platform builds don't pull in WinRT
+81 -10
View File
@@ -1,7 +1,8 @@
//! USB serial RNode over Android USB-C OTG via JNI to `UsbManager`. 115200 8N1.
use std::sync::Arc;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use bytes::Bytes;
use tokio::sync::mpsc;
@@ -27,6 +28,60 @@ pub const KNOWN_VIDS: &[(u16, &str)] = &[
(0x1915, "Nordic Semiconductor NRF52840"),
];
type AndroidUsbRNodeStopRegistry = Mutex<HashMap<InterfaceId, mpsc::Sender<()>>>;
fn android_usb_rnode_stop_registry() -> &'static AndroidUsbRNodeStopRegistry {
static REGISTRY: OnceLock<AndroidUsbRNodeStopRegistry> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}
struct AndroidUsbRNodeStopRegistryGuard {
id: InterfaceId,
}
impl Drop for AndroidUsbRNodeStopRegistryGuard {
fn drop(&mut self) {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.remove(&self.id);
}
}
fn register_android_usb_rnode_stop(
id: InterfaceId,
stop_tx: mpsc::Sender<()>,
) -> AndroidUsbRNodeStopRegistryGuard {
android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.insert(id, stop_tx);
AndroidUsbRNodeStopRegistryGuard { id }
}
/// Ask an Android USB RNode interface to send upstream's detach sequence before
/// runtime teardown aborts the task. Idempotent; unknown ids are ignored.
pub fn stop_android_usb_rnode_interface(id: InterfaceId) {
let stop_tx = android_usb_rnode_stop_registry()
.lock()
.expect("android_usb_rnode_stop_registry mutex poisoned")
.get(&id)
.cloned();
let Some(stop_tx) = stop_tx else {
tracing::debug!(id, "Android USB RNode stop requested for unknown interface");
return;
};
match stop_tx.try_send(()) {
Ok(()) => tracing::info!(id, "Android USB RNode stop signal sent"),
Err(mpsc::error::TrySendError::Full(_)) => {
tracing::debug!(id, "Android USB RNode stop signal already pending")
}
Err(mpsc::error::TrySendError::Closed(_)) => {
tracing::debug!(id, "Android USB RNode stop signal receiver already closed")
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UsbSerialDevice {
pub device_name: String,
@@ -68,7 +123,6 @@ impl AndroidUsbConfig {
use jni::JavaVM;
use jni::objects::{GlobalRef, JObject, JValue};
use std::sync::OnceLock;
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
static APP_CONTEXT: OnceLock<GlobalRef> = OnceLock::new();
@@ -453,7 +507,7 @@ async fn open_usb_serial(
let cw = connected.clone();
let vm = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB write loop".into()),
};
let cr_w = conn_ref.clone();
@@ -487,7 +541,7 @@ async fn open_usb_serial(
let cr = connected.clone();
let vm2 = match JAVA_VM.get() {
Some(v) => v.clone(),
Some(v) => v,
None => return Err("JavaVM not initialized for USB read loop".into()),
};
tokio::task::spawn_blocking(move || {
@@ -572,17 +626,32 @@ pub async fn spawn_android_usb_rnode_interface(
let shared_rxb = Arc::new(AtomicU64::new(0));
let (tx, mut app_rx) = mpsc::channel::<Bytes>(64);
let (stop_tx, mut stop_rx) = mpsc::channel::<()>(1);
let stop_guard = register_android_usb_rnode_stop(id, stop_tx);
let txb = shared_txb.clone();
let wtx = raw_write_tx.clone();
let write_name = name.clone();
tokio::spawn(async move {
while let Some(payload) = app_rx.recv().await {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
loop {
tokio::select! {
Some(payload) = app_rx.recv() => {
let frame = kiss::frame(&payload);
txb.fetch_add(frame.len() as u64, Ordering::Relaxed);
if wtx.send(frame).await.is_err() {
tracing::warn!(name = %write_name, "USB write channel closed");
break;
}
}
Some(_) = stop_rx.recv() => {
if wtx.send(rnode::build_detach_sequence()).await.is_err() {
tracing::warn!(name = %write_name, "USB detach sequence could not be queued");
} else {
tracing::info!(name = %write_name, "USB detach sequence queued");
}
break;
}
else => break,
}
}
});
@@ -593,6 +662,7 @@ pub async fn spawn_android_usb_rnode_interface(
let rxb = shared_rxb.clone();
let online = connected.clone();
let read_task = tokio::spawn(async move {
let _stop_guard = stop_guard;
let mut deframer = kiss::KissDeframer::new();
let mut last_rssi: Option<f32> = None;
let mut last_snr: Option<f32> = None;
@@ -625,6 +695,7 @@ pub async fn spawn_android_usb_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: config.mode,
direction: InterfaceDirection {
+410 -66
View File
@@ -237,14 +237,38 @@ impl Default for AutoInterfaceConfig {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PeerKey {
ip: Ipv6Addr,
scope_id: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PeerScopeSource {
Received,
LocalCandidate,
UnscopedNonLinkLocal,
}
#[derive(Debug, Clone)]
struct PeerScopeCandidate {
ifname: String,
scope_id: u32,
source: PeerScopeSource,
}
#[derive(Debug, Clone)]
struct Peer {
ip: Ipv6Addr,
ifname: String,
scope_id: u32,
scope_source: PeerScopeSource,
addr: SocketAddrV6,
last_seen: Instant,
last_reverse: Instant,
}
type PeerTable = Arc<Mutex<HashMap<Ipv6Addr, Peer>>>;
type PeerTable = Arc<Mutex<HashMap<PeerKey, Peer>>>;
#[derive(Debug, Clone)]
struct DeduplicateEntry {
@@ -334,6 +358,111 @@ fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
)
}
fn is_link_local_v6(addr: Ipv6Addr) -> bool {
(addr.segments()[0] & 0xffc0) == 0xfe80
}
fn peer_scope_candidates(
peer_ip: Ipv6Addr,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
) -> Vec<PeerScopeCandidate> {
// Python Reticulum associates AutoInterface peers with the receiving
// ifname and sends to fe80::peer%ifindex. Some platforms report scope 0
// from a wildcard-bound socket, so expand link-local peers to scoped local
// candidates instead of storing an unusable fe80::peer%0 address.
if received_scope != 0 {
let ifname = link_locals
.iter()
.find(|(_, _, scope_id)| *scope_id == received_scope)
.map(|(name, _, _)| name.clone())
.unwrap_or_else(|| format!("ifindex:{received_scope}"));
return vec![PeerScopeCandidate {
ifname,
scope_id: received_scope,
source: PeerScopeSource::Received,
}];
}
if !is_link_local_v6(peer_ip) {
return vec![PeerScopeCandidate {
ifname: String::new(),
scope_id: 0,
source: PeerScopeSource::UnscopedNonLinkLocal,
}];
}
let mut candidates = Vec::new();
for (ifname, _, scope_id) in link_locals {
if *scope_id == 0
|| candidates
.iter()
.any(|c: &PeerScopeCandidate| c.scope_id == *scope_id)
{
continue;
}
candidates.push(PeerScopeCandidate {
ifname: ifname.clone(),
scope_id: *scope_id,
source: PeerScopeSource::LocalCandidate,
});
}
candidates
}
fn upsert_peer_candidates(
table: &mut HashMap<PeerKey, Peer>,
peer_ip: Ipv6Addr,
data_port: u16,
received_scope: u32,
link_locals: &[(String, Ipv6Addr, u32)],
now: Instant,
source: &'static str,
) -> usize {
let candidates = peer_scope_candidates(peer_ip, received_scope, link_locals);
if candidates.is_empty() {
tracing::warn!(
peer = %peer_ip,
received_scope,
local_candidates = link_locals.len(),
source,
"auto: discovered link-local peer but no usable scope candidates are available"
);
return 0;
}
let mut inserted = 0usize;
for candidate in candidates {
let key = PeerKey {
ip: peer_ip,
scope_id: candidate.scope_id,
};
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, candidate.scope_id);
table
.entry(key)
.and_modify(|p| {
p.ifname = candidate.ifname.clone();
p.scope_id = candidate.scope_id;
p.scope_source = candidate.source;
p.addr = data_addr;
p.last_seen = now;
})
.or_insert_with(|| {
inserted += 1;
Peer {
ip: peer_ip,
ifname: candidate.ifname,
scope_id: candidate.scope_id,
scope_source: candidate.source,
addr: data_addr,
last_seen: now,
last_reverse: now,
}
});
}
inserted
}
/// Derive `ff_T_S_:0:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX` from address-type nibble,
/// scope nibble, and bytes 2..14 of `SHA-256(group_id)`.
pub fn derive_multicast_address(
@@ -779,9 +908,19 @@ fn get_link_local_addrs_android(
}
fn iface_scope_id(iface: &if_addrs::Interface) -> u32 {
iface
.index
.unwrap_or_else(|| iface_name_to_scope_id(&iface.name))
if let Some(index) = iface.index {
return index;
}
#[cfg(windows)]
{
let adapter_index = iface_name_to_scope_id(&iface.adapter_name);
if adapter_index != 0 {
return adapter_index;
}
}
iface_name_to_scope_id(&iface.name)
}
/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`.
@@ -841,6 +980,11 @@ fn bind_one(port: u16) -> std::io::Result<UdpSocket> {
UdpSocket::from_std(sock.into())
}
fn set_multicast_if_v6(sock: &UdpSocket, scope_id: u32) -> std::io::Result<()> {
let sock_ref = socket2::SockRef::from(sock);
sock_ref.set_multicast_if_v6(scope_id)
}
/// Diagnostic: probe alternate ports to localize bind failures.
#[cfg(target_os = "android")]
fn probe_alternate_ports(base: u16) {
@@ -927,6 +1071,15 @@ pub async fn spawn_auto_interface(
tracing::info!(name = %config.name, port = config.discovery_port, "auto discovery socket bound");
for (iface_name, _ll_addr, scope_id) in &initial_link_locals {
if let Err(e) = set_multicast_if_v6(disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %iface_name,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"failed to set IPv6 multicast outbound interface"
);
}
if let Err(e) = disc_sock.join_multicast_v6(&mcast_group, *scope_id) {
// EPERM/EACCES on Apple is the canonical signal that the
// multicast networking entitlement isn't provisioned (e.g. iOS
@@ -1001,16 +1154,38 @@ pub async fn spawn_auto_interface(
for (_name, ll_addr, scope_id) in &snapshot {
let beacon = make_beacon(&group_id, ll_addr);
let dest = SocketAddrV6::new(mcast_group, disc_port, 0, *scope_id);
if let Err(e) = set_multicast_if_v6(disc_sock_send.as_ref(), *scope_id) {
tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: failed to select multicast outbound interface"
);
}
let res = disc_sock_send.send_to(&beacon, dest).await;
tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent = res.is_ok(),
"auto-instr beacon TX"
);
match res {
Ok(n) => tracing::debug!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
sent_bytes = n,
"auto-instr beacon TX"
),
Err(e) => tracing::warn!(
iface = %_name,
ll = %ll_addr,
scope_id,
dst = %dest,
hash = %hex32(&beacon),
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: beacon TX failed"
),
}
}
}
});
@@ -1037,8 +1212,8 @@ pub async fn spawn_auto_interface(
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
// Match source LL against ours — non-empty means self-echo.
let snapshot = { disc_link_locals.lock().await.clone() };
let self_iface = {
let snapshot = disc_link_locals.lock().await;
snapshot
.iter()
.find(|(_, ll, _)| *ll == peer_ip)
@@ -1068,19 +1243,25 @@ pub async fn spawn_auto_interface(
if !match_ok {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = peers_disc.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: peer discovered/refreshed");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"multicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: peer discovered/refreshed"
);
} else {
tracing::debug!(src = %src, "auto-instr mcast RX non-v6 source");
}
@@ -1099,16 +1280,19 @@ pub async fn spawn_auto_interface(
let unicast_group_id = config.group_id.clone();
let unicast_link_locals = link_locals.clone();
let unicast_disc_port = config.discovery_port + 1;
if let Ok(unicast_sock) = UdpSocket::bind(SocketAddrV6::new(
Ipv6Addr::UNSPECIFIED,
unicast_disc_port,
0,
0,
))
.await
{
let unicast_sock = Arc::new(unicast_sock);
let unicast_sock = match bind_reusable_udp_v6(unicast_disc_port) {
Ok(sock) => Some(Arc::new(sock)),
Err(e) => {
tracing::debug!(
port = unicast_disc_port,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: could not bind unicast discovery port"
);
None
}
};
if let Some(unicast_sock) = unicast_sock {
let urecv_sock = unicast_sock.clone();
let urecv_peers = peers_unicast.clone();
let urecv_online = online_u.clone();
@@ -1127,29 +1311,33 @@ pub async fn spawn_auto_interface(
}
if let SocketAddr::V6(src_v6) = src {
let peer_ip = *src_v6.ip();
let is_self = {
let snapshot = urecv_link_locals.lock().await;
snapshot.iter().any(|(_, ll, _)| *ll == peer_ip)
};
let snapshot = { urecv_link_locals.lock().await.clone() };
let is_self = { snapshot.iter().any(|(_, ll, _)| *ll == peer_ip) };
if is_self {
continue;
}
if !verify_beacon(&buf[..n], &urecv_group_id, &peer_ip) {
continue;
}
let scope = src_v6.scope_id();
let data_addr = SocketAddrV6::new(peer_ip, data_port, 0, scope);
let received_scope = src_v6.scope_id();
let now = Instant::now();
let mut table = urecv_peers.lock().await;
table
.entry(peer_ip)
.and_modify(|p| p.last_seen = now)
.or_insert(Peer {
addr: data_addr,
last_seen: now,
last_reverse: now,
});
tracing::debug!(peer = %peer_ip, "auto: unicast peer discovered");
let inserted = upsert_peer_candidates(
&mut table,
peer_ip,
data_port,
received_scope,
&snapshot,
now,
"unicast",
);
tracing::debug!(
peer = %peer_ip,
received_scope,
inserted,
peer_records = table.len(),
"auto: unicast peer discovered"
);
}
}
Err(e) => {
@@ -1194,26 +1382,42 @@ pub async fn spawn_auto_interface(
let snapshot = { rev_link_locals.lock().await.clone() };
let now = Instant::now();
let mut table = rev_peers.lock().await;
for (_ip, peer) in table.iter_mut() {
for (_key, peer) in table.iter_mut() {
if now.duration_since(peer.last_reverse).as_secs_f64()
>= REVERSE_PEERING_INTERVAL
{
for (_name, ll_addr, scope_id) in &snapshot {
let mut targets: Vec<_> = snapshot
.iter()
.filter(|(_, _, scope_id)| {
peer.scope_id == 0 || *scope_id == peer.scope_id
})
.collect();
if targets.is_empty() {
targets = snapshot.iter().collect();
}
for (_name, ll_addr, scope_id) in targets {
let beacon = make_beacon(&rev_group_id, ll_addr);
let dest =
SocketAddrV6::new(*peer.addr.ip(), unicast_disc_port, 0, *scope_id);
let _ = unicast_sock.send_to(&beacon, dest).await;
if let Err(e) = unicast_sock.send_to(&beacon, dest).await {
tracing::debug!(
peer = %peer.ip,
peer_ifname = %peer.ifname,
peer_scope_id = peer.scope_id,
local_iface = %_name,
local_scope_id = scope_id,
dst = %dest,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: reverse peering TX failed"
);
}
}
peer.last_reverse = now;
}
}
}
});
} else {
tracing::debug!(
"auto: could not bind unicast discovery port {}",
unicast_disc_port
);
}
// Periodic jobs: NIC re-enum, peer aging, carrier detection (every PEER_JOB_INTERVAL).
@@ -1273,6 +1477,17 @@ pub async fn spawn_auto_interface(
);
}
for (ifname, addr, scope_id) in &added {
if let Err(e) = set_multicast_if_v6(jobs_disc_sock.as_ref(), *scope_id) {
tracing::warn!(
iface = %jobs_iface_name,
nic = %ifname,
addr = %addr,
scope_id,
error = %e,
raw_os_error = ?e.raw_os_error(),
"AutoInterface failed to set multicast interface for new NIC"
);
}
match jobs_disc_sock.join_multicast_v6(&jobs_mcast, *scope_id) {
Ok(()) => tracing::info!(
iface = %jobs_iface_name,
@@ -1360,18 +1575,46 @@ pub async fn spawn_auto_interface(
let prefix = hex_prefix(&data, 16);
let table = peers_write.lock().await;
let peer_count = table.len();
for (_ip, peer) in table.iter() {
let res = data_sock_w.send_to(&data, peer.addr).await;
if peer_count == 0 {
tracing::debug!(
dst = %peer.addr,
len,
prefix = %prefix,
peer_count,
sent = res.is_ok(),
"auto-instr data TX"
"auto-instr data TX skipped: no discovered peers"
);
if res.is_ok() {
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
for (_key, peer) in table.iter() {
let res = data_sock_w.send_to(&data, peer.addr).await;
match res {
Ok(n) => {
tracing::debug!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
sent_bytes = n,
prefix = %prefix,
peer_count,
"auto-instr data TX"
);
task_txb.fetch_add(len as u64, Ordering::Relaxed);
}
Err(e) => {
tracing::warn!(
peer = %peer.ip,
ifname = %peer.ifname,
scope_id = peer.scope_id,
scope_source = ?peer.scope_source,
dst = %peer.addr,
len,
prefix = %prefix,
peer_count,
error = %e,
raw_os_error = ?e.raw_os_error(),
"auto: data TX failed"
);
}
}
}
}
@@ -1427,6 +1670,7 @@ pub async fn spawn_auto_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1559,6 +1803,83 @@ mod tests {
assert!(!verify_beacon(&beacon[..16], "reticulum", &addr));
}
#[test]
fn peer_scope_candidates_preserves_received_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 22, &locals);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].ifname, "eth0");
assert_eq!(candidates[0].scope_id, 22);
assert_eq!(candidates[0].source, PeerScopeSource::Received);
}
#[test]
fn peer_scope_candidates_expands_zero_scope_for_link_local() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
("duplicate".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let candidates = peer_scope_candidates(peer, 0, &locals);
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0].ifname, "en0");
assert_eq!(candidates[0].scope_id, 11);
assert_eq!(candidates[0].source, PeerScopeSource::LocalCandidate);
assert_eq!(candidates[1].ifname, "eth0");
assert_eq!(candidates[1].scope_id, 22);
}
#[test]
fn upsert_peer_candidates_keys_same_ip_by_scope() {
let peer = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let locals = vec![
("en0".to_string(), Ipv6Addr::LOCALHOST, 11),
("eth0".to_string(), Ipv6Addr::LOCALHOST, 22),
];
let mut table = HashMap::new();
let inserted = upsert_peer_candidates(
&mut table,
peer,
DATA_PORT,
0,
&locals,
Instant::now(),
"test",
);
assert_eq!(inserted, 2);
assert_eq!(table.len(), 2);
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 11,
}));
assert!(table.contains_key(&PeerKey {
ip: peer,
scope_id: 22,
}));
assert_eq!(
table
.get(&PeerKey {
ip: peer,
scope_id: 11,
})
.unwrap()
.addr
.scope_id(),
11
);
}
#[test]
fn test_scope_id_prefers_enumerated_interface_index() {
let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
@@ -1566,6 +1887,29 @@ mod tests {
assert_eq!(iface_scope_id(&iface), 1234);
}
#[cfg(target_os = "linux")]
#[test]
fn if_addrs_link_local_feature_is_enabled() {
let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
let host_has_link_local = proc_addrs.lines().any(|line| {
line.split_whitespace()
.nth(3)
.is_some_and(|scope| scope.eq_ignore_ascii_case("20"))
});
if !host_has_link_local {
return;
}
let addrs = if_addrs::get_if_addrs().expect("list network interfaces");
assert!(
addrs.iter().any(|iface| {
matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local())
}),
"Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \
keep the workspace if-addrs dependency feature `link-local` enabled"
);
}
fn test_interface(name: &str, ip: Ipv6Addr, index: Option<u32>) -> if_addrs::Interface {
let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr {
ip,
+1
View File
@@ -411,6 +411,7 @@ pub async fn spawn_ax25kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+3
View File
@@ -291,6 +291,7 @@ pub async fn spawn_backbone_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(id),
name: client_name,
mode,
direction: InterfaceDirection {
@@ -323,6 +324,7 @@ pub async fn spawn_backbone_server(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -490,6 +492,7 @@ pub async fn spawn_backbone_client(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
File diff suppressed because it is too large. Load diff
+147 -57
View File
@@ -46,9 +46,12 @@ const RECONNECT_WAIT_MAX: u64 = 120;
/// `None` retries forever; teardown goes via `stop_ble_rnode_interface`.
const MAX_RECONNECT_TRIES: Option<usize> = None;
const SCAN_TIMEOUT: u64 = 3;
const CONNECT_TIMEOUT: u64 = 5;
/// Bounds disable-while-offline teardown latency to ~1s.
const RUNNING_POLL: Duration = Duration::from_secs(1);
#[cfg(target_os = "linux")]
const RNODE_POST_BOND_SETTLE: Duration = Duration::from_millis(2600);
const RNODE_NATIVE_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(6);
const RNODE_NATIVE_HANDSHAKE_PROBE: Duration = Duration::from_millis(650);
/// `stop_ble_rnode_interface` flips false; the read_task removes the entry
/// on its way out.
@@ -117,38 +120,77 @@ async fn wait_or_shutdown(total: Duration, flag: &AtomicBool) -> bool {
!flag.load(Ordering::SeqCst)
}
/// RNode can pack multiple frames in one read, so use the raw deframer for
/// full-command extended KISS framing.
async fn wait_for_rnode_handshake(
fn is_rnode_handshake_frame(cmd: u8, frame: &[u8]) -> bool {
(cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP))
|| (cmd == rnode::CMD_FW_VERSION && !frame.is_empty())
}
fn is_pairing_transition_error(error: &InterfaceError) -> bool {
matches!(
error,
InterfaceError::SendFailed(message) if message.starts_with("BLE pairing in progress:")
)
}
/// Android's native bridge can come up immediately after SMP completes, while
/// rsCardputer's RNode BLE stack is still settling. Probe detect a few times
/// inside one connection attempt so a single dropped early frame does not cost
/// a full reconnect backoff.
async fn probe_native_rnode_handshake(
tcp_read: &mut tokio::net::tcp::OwnedReadHalf,
tcp_write: &mut tokio::net::tcp::OwnedWriteHalf,
timeout: Duration,
probe_interval: Duration,
running_task: &AtomicBool,
) -> bool {
use tokio::io::AsyncReadExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let detect_seq = rnode::build_detect_sequence();
let mut deframer = kiss::RawKissDeframer::new();
let mut buf = [0u8; 1024];
let deadline = std::time::Instant::now() + timeout;
let mut next_probe = std::time::Instant::now();
while std::time::Instant::now() < deadline {
if !running_task.load(Ordering::SeqCst) {
return false;
}
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let read = tokio::time::timeout(remaining.min(RUNNING_POLL), tcp_read.read(&mut buf)).await;
let now = std::time::Instant::now();
if now >= next_probe {
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect probe write failed");
return false;
}
let _ = tcp_write.flush().await;
next_probe = std::time::Instant::now() + probe_interval;
}
let now = std::time::Instant::now();
let read_budget = next_probe
.min(deadline)
.saturating_duration_since(now)
.min(RUNNING_POLL);
if read_budget.is_zero() {
tokio::task::yield_now().await;
continue;
}
let read = tokio::time::timeout(read_budget, tcp_read.read(&mut buf)).await;
let n = match read {
Ok(Ok(0)) => return false,
Ok(Ok(n)) => n,
Ok(Err(_)) => return false,
Err(_) => continue,
};
for (cmd, frame) in deframer.feed(&buf[..n]) {
if cmd == rnode::CMD_DETECT && frame.first().copied() == Some(rnode::DETECT_RESP) {
return true;
}
if cmd == rnode::CMD_FW_VERSION && !frame.is_empty() {
if is_rnode_handshake_frame(cmd, &frame) {
return true;
}
}
}
false
}
@@ -584,6 +626,11 @@ struct BleRNodeConnection {
write_mtu: usize,
}
enum NativeBridgeWrite {
Packet(Bytes),
Raw(Vec<u8>),
}
async fn connect_rnode(
adapter: &Adapter,
ble_uri: &str,
@@ -592,6 +639,18 @@ async fn connect_rnode(
let peripheral = resolve_ble_target(adapter, ble_uri).await?;
ble_diag(format!("[ble] resolved peripheral id={}", peripheral.id()));
#[cfg(target_os = "linux")]
{
// BlueZ needs explicit pairing before we open a btleplug GATT
// connection. If this creates a fresh bond, RNode intentionally
// disconnects shortly afterwards; wait through that before connect().
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
if linux_trigger_pairing(bluer_addr).await? {
ble_diag("[pair][linux] fresh bond complete — waiting for RNode post-pair disconnect");
tokio::time::sleep(RNODE_POST_BOND_SETTLE).await;
}
}
let mut last_err = String::new();
for attempt in 1..=3 {
match peripheral.connect().await {
@@ -657,18 +716,10 @@ async fn connect_rnode(
// SMP must run BEFORE subscribe on desktop / Apple platforms — reading
// the encrypted TX char kicks off SMP and drops L2CAP, which kills any
// pending subscribe. iOS/macOS share CoreBluetooth; Windows uses WinRT
// GATT (auto-prompt on encrypted-char reads). Same trigger shape works
// for all three. Linux uses bluer's explicit `Device::pair()` instead —
// BlueZ does not auto-prompt SMP from an encrypted-char read.
// GATT (auto-prompt on encrypted-char reads). Linux used explicit BlueZ
// pairing before `connect()`, above.
#[cfg(any(target_os = "ios", target_os = "macos", target_os = "windows"))]
desktop_trigger_pairing(&peripheral, &tx_char).await?;
#[cfg(target_os = "linux")]
{
// peripheral.address() returns a BDAddr → MAC string; the helper
// also accepts BlueZ D-Bus paths for callers that pass `id()`.
let bluer_addr = parse_linux_ble_address(&peripheral.address().to_string())?;
linux_trigger_pairing(bluer_addr).await?;
}
ble_diag("[ble] subscribe TX start");
peripheral.subscribe(&tx_char).await.map_err(|e| {
@@ -896,7 +947,7 @@ fn parse_linux_ble_address(addr: &str) -> Result<bluer::Address, InterfaceError>
/// daemon stops retrying SMP instead of re-invoking `request_passkey`
/// every ~60s.
#[cfg(target_os = "linux")]
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), InterfaceError> {
async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<bool, InterfaceError> {
let overall_start = std::time::Instant::now();
// Reuse the cached session so the second-and-subsequent attempts skip
@@ -927,7 +978,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
"[pair][linux] already bonded with {bluer_addr} (is_paired check {:.2}s)",
t_paired.elapsed().as_secs_f32()
));
return Ok(());
return Ok(false);
}
ble_diag(format!(
"[pair][linux] is_paired=false in {:.2}s",
@@ -1049,7 +1100,7 @@ async fn linux_trigger_pairing(bluer_addr: bluer::Address) -> Result<(), Interfa
}
}
let _ = linux_pairing_finished_sender().send(LinuxPairingFinished { attempt_id, status });
outcome
outcome.map(|()| true)
}
/// WithoutResponse is fire-and-forget at the ATT layer; the radio still
@@ -1069,6 +1120,14 @@ pub(crate) async fn ble_write(
Ok(())
}
async fn ble_send_radio_off(conn: &BleRNodeConnection) {
let seq = rnode::build_detach_sequence();
match ble_write(&conn.peripheral, &conn.rx_char, &seq, conn.write_mtu).await {
Ok(()) => ble_diag("[ble] detach sent before disconnect"),
Err(e) => ble_diag(format!("[ble] detach before disconnect failed: {e}")),
}
}
/// Auto-reconnect across drops; resolve_ble_target re-runs every retry so
/// iOS RPA rotation heals automatically.
pub async fn spawn_ble_rnode_interface(
@@ -1154,9 +1213,11 @@ pub async fn spawn_ble_rnode_interface(
let conn = match connect_rnode(&adapter, &ble_uri).await {
Ok(c) => c,
Err(e) => {
let pairing_transition = is_pairing_transition_error(&e);
let retry_wait = if pairing_transition { 1 } else { backoff };
tracing::warn!(name = %log_name, error = %e, "BLE RNode connect failed");
ble_diag(format!(
"[ble] connect_rnode err: {e} — retrying in {backoff}s (attempt {})",
"[ble] connect_rnode err: {e} — retrying in {retry_wait}s (attempt {})",
tries + 1
));
if reconnect_try_exhausted(&mut tries) {
@@ -1164,10 +1225,14 @@ pub async fn spawn_ble_rnode_interface(
ble_diag("[ble] max reconnect tries reached — giving up");
return;
}
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
if wait_or_shutdown(Duration::from_secs(retry_wait), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
if pairing_transition {
backoff = RECONNECT_WAIT;
} else {
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
}
continue;
}
};
@@ -1286,16 +1351,21 @@ pub async fn spawn_ble_rnode_interface(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
let notification = tokio::select! {
n = notification_stream.next() => n,
_ = tokio::time::sleep(Duration::from_secs(CONNECT_TIMEOUT)) => {
_ = tokio::time::sleep(RUNNING_POLL) => {
// Polling slice — bounds disable-while-connected
// teardown latency.
if !running_task.load(Ordering::SeqCst) {
ble_send_radio_off(&conn).await;
break 'read;
}
if conn.peripheral.is_connected().await.unwrap_or(false) {
@@ -1368,6 +1438,7 @@ pub async fn spawn_ble_rnode_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -1471,22 +1542,17 @@ pub async fn spawn_ble_rnode_interface_native(
let (mut tcp_read, mut tcp_write) = stream.into_split();
let detect_seq = rnode::build_detect_sequence();
if let Err(e) = tcp_write.write_all(&detect_seq).await {
tracing::warn!(error = %e, "BLE RNode native detect write failed");
if wait_or_shutdown(Duration::from_secs(backoff), &running_task).await {
return;
}
backoff = (backoff * 2).min(RECONNECT_WAIT_MAX);
continue;
}
// Without gating on DETECT_RESP + firmware version we'd flag
// "online" while the radio is asleep or the BLE-NUS bridge
// dropped a frame.
let detected =
wait_for_rnode_handshake(&mut tcp_read, Duration::from_secs(5), &running_task)
.await;
let detected = probe_native_rnode_handshake(
&mut tcp_read,
&mut tcp_write,
RNODE_NATIVE_HANDSHAKE_TIMEOUT,
RNODE_NATIVE_HANDSHAKE_PROBE,
&running_task,
)
.await;
if !detected {
tracing::warn!(
name = %log_name,
@@ -1524,26 +1590,38 @@ pub async fn spawn_ble_rnode_interface_native(
let ready = Arc::new(AtomicBool::new(true));
let (conn_tx, mut conn_rx) = mpsc::channel::<Bytes>(256);
let (conn_tx, mut conn_rx) = mpsc::channel::<NativeBridgeWrite>(256);
let conn_tx_for_stop = conn_tx.clone();
let online_w = online_handle.clone();
let ready_w = ready.clone();
let txb_w = task_txb.clone();
let write_handle = tokio::spawn(async move {
while let Some(data) = conn_rx.recv().await {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
while let Some(msg) = conn_rx.recv().await {
match msg {
NativeBridgeWrite::Packet(data) => {
txb_w.fetch_add(data.len() as u64, Ordering::Relaxed);
if flow_control {
while !ready_w.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
if !online_w.load(Ordering::SeqCst) {
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
}
}
}
let framed = kiss::frame(&data);
if let Err(e) = tcp_write.write_all(&framed).await {
tracing::warn!(error = %e, "BLE RNode native write error");
online_w.store(false, Ordering::SeqCst);
return;
NativeBridgeWrite::Raw(data) => {
if let Err(e) = tcp_write.write_all(&data).await {
tracing::warn!(error = %e, "BLE RNode native raw write error");
}
let _ = tcp_write.flush().await;
return;
}
}
}
});
@@ -1554,7 +1632,7 @@ pub async fn spawn_ble_rnode_interface_native(
let fwd_handle = tokio::spawn(async move {
let mut guard = rx_ref.lock().await;
while let Some(data) = guard.recv().await {
if conn_tx.send(data).await.is_err() {
if conn_tx.send(NativeBridgeWrite::Packet(data)).await.is_err() {
break;
}
}
@@ -1567,7 +1645,14 @@ pub async fn spawn_ble_rnode_interface_native(
let mut transport_closed = false;
'read: loop {
if !online_handle.load(Ordering::SeqCst) || !running_task.load(Ordering::SeqCst) {
if !online_handle.load(Ordering::SeqCst) {
break 'read;
}
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
@@ -1589,6 +1674,10 @@ pub async fn spawn_ble_rnode_interface_native(
// Idle LoRa silence is normal — only break if
// shutdown flag cleared.
if !running_task.load(Ordering::SeqCst) {
let _ = conn_tx_for_stop
.send(NativeBridgeWrite::Raw(rnode::build_detach_sequence()))
.await;
tokio::time::sleep(Duration::from_millis(100)).await;
break 'read;
}
continue;
@@ -1648,6 +1737,7 @@ pub async fn spawn_ble_rnode_interface_native(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+3
View File
@@ -545,6 +545,7 @@ pub async fn spawn_i2p_client(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -738,6 +739,7 @@ pub async fn spawn_i2p_server(
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: config.mode,
direction: InterfaceDirection {
@@ -774,6 +776,7 @@ pub async fn spawn_i2p_server(
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+1
View File
@@ -233,6 +233,7 @@ pub async fn spawn_kiss_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+6
View File
@@ -265,6 +265,7 @@ mod platform {
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -300,6 +301,7 @@ mod platform {
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -345,6 +347,7 @@ mod platform {
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -431,6 +434,7 @@ mod platform {
let handle = InterfaceHandle {
id: client_id,
parent_id: Some(0),
name: client_name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -466,6 +470,7 @@ mod platform {
Ok(InterfaceHandle {
id: 0,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
@@ -512,6 +517,7 @@ mod platform {
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode: InterfaceMode::Full,
direction: InterfaceDirection {
+1
View File
@@ -189,6 +189,7 @@ pub async fn spawn_pipe_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
File diff suppressed because it is too large. Load diff
+1
View File
@@ -423,6 +423,7 @@ pub async fn spawn_rnode_multi_interface(
handles.push(InterfaceHandle {
id: ids[i],
parent_id: None,
name: sub_name,
mode: sub_cfg.mode,
direction: InterfaceDirection {
+1
View File
@@ -171,6 +171,7 @@ pub async fn spawn_serial_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+97
View File
@@ -29,6 +29,25 @@ pub fn set_keepalive(stream: &TcpStream) -> std::io::Result<()> {
Ok(())
}
/// Enable portable `SO_KEEPALIVE` on a blocking std TCP stream.
#[cfg(unix)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
sock.set_keepalive(true)?;
Ok(())
}
#[cfg(windows)]
pub fn set_keepalive_std(stream: &std::net::TcpStream) -> std::io::Result<()> {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
sock.set_keepalive(true)?;
Ok(())
}
/// Tuned keepalive: idle/interval/retries + Linux TCP_USER_TIMEOUT. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned(
@@ -58,6 +77,35 @@ pub fn set_keepalive_tuned(
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
/// Tuned keepalive for blocking std TCP streams. Best-effort.
#[cfg(unix)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
#[cfg(windows)]
pub fn set_keepalive_tuned_std(
stream: &std::net::TcpStream,
idle: Duration,
intvl: Duration,
retries: u32,
user_timeout: Duration,
) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
apply_tuned_keepalive(&sock, idle, intvl, retries, user_timeout);
}
fn apply_tuned_keepalive(
sock: &socket2::Socket,
idle: Duration,
@@ -107,6 +155,25 @@ pub fn set_socket_buffers(stream: &TcpStream, size: usize) {
let _ = sock.set_send_buffer_size(size);
}
/// Raise TCP send/recv buffers on a blocking std TCP stream; best-effort.
#[cfg(unix)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::fd::{AsRawFd, FromRawFd};
let raw_fd = stream.as_raw_fd();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_fd(raw_fd) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
#[cfg(windows)]
pub fn set_socket_buffers_std(stream: &std::net::TcpStream, size: usize) {
use std::os::windows::io::{AsRawSocket, FromRawSocket};
let raw = stream.as_raw_socket();
let sock = std::mem::ManuallyDrop::new(unsafe { socket2::Socket::from_raw_socket(raw) });
let _ = sock.set_recv_buffer_size(size);
let _ = sock.set_send_buffer_size(size);
}
/// Resolve interface name to `IpAddr`; `None` if missing. Caller falls back
/// to wildcard bind.
pub fn iface_addr_for(name: &str, prefer_ipv6: bool) -> Option<IpAddr> {
@@ -177,6 +244,36 @@ mod tests {
set_socket_buffers(&client, 131_072);
}
#[test]
fn std_keepalive_and_buffers_apply_without_panic() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let accept = std::thread::spawn(move || listener.accept().unwrap().0);
let client = std::net::TcpStream::connect(addr).unwrap();
let server = accept.join().unwrap();
set_keepalive_std(&server).expect("server set_keepalive_std");
set_keepalive_std(&client).expect("client set_keepalive_std");
set_keepalive_tuned_std(
&server,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_keepalive_tuned_std(
&client,
Duration::from_secs(5),
Duration::from_secs(2),
12,
Duration::from_secs(24),
);
set_socket_buffers_std(&server, 131_072);
set_socket_buffers_std(&client, 131_072);
}
#[test]
fn iface_addr_for_loopback_resolves() {
// Loopback name varies by OS; iterate candidates.
+5
View File
@@ -391,6 +391,7 @@ pub async fn spawn_tcp_client(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
@@ -419,6 +420,7 @@ pub async fn spawn_tcp_client(
async fn spawn_tcp_accepted(
stream: TcpStream,
id: InterfaceId,
parent_id: InterfaceId,
name: String,
transport_tx: mpsc::Sender<TransportMessage>,
kiss_framing: bool,
@@ -459,6 +461,7 @@ async fn spawn_tcp_accepted(
let bitrate: u64 = 10_000_000;
InterfaceHandle {
id,
parent_id: Some(parent_id),
name,
mode,
direction: InterfaceDirection {
@@ -510,6 +513,7 @@ pub async fn spawn_tcp_server(
let handle = spawn_tcp_accepted(
stream,
client_id,
id,
client_name,
transport_tx.clone(),
kiss_framing,
@@ -533,6 +537,7 @@ pub async fn spawn_tcp_server(
let bitrate: u64 = 10_000_000;
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+45 -12
View File
@@ -9,6 +9,9 @@ pub type InterfaceId = u64;
/// Handle returned by every `spawn_*`: write channel, status flag, and read task.
pub struct InterfaceHandle {
pub id: InterfaceId,
/// Parent interface for dynamically spawned children such as accepted TCP,
/// Backbone or I2P peers.
pub parent_id: Option<InterfaceId>,
pub name: String,
pub mode: InterfaceMode,
pub direction: InterfaceDirection,
@@ -154,21 +157,39 @@ pub fn optimise_mtu(bitrate: u64) -> Option<u32> {
pub const NAME_HASH_LENGTH: usize = 10;
// Ingress control constants — must match Reticulum reference.
pub const IA_FREQ_SAMPLES: usize = 128;
pub const OA_FREQ_SAMPLES: usize = 128;
pub const IA_FREQ_SAMPLES: usize = 48;
pub const OA_FREQ_SAMPLES: usize = 48;
pub const IP_FREQ_SAMPLES: usize = 48;
pub const OP_FREQ_SAMPLES: usize = 48;
pub const AR_MINFREQ_HZ: f64 = 0.1;
pub const PR_MINFREQ_HZ: f64 = 0.1;
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Duration a new interface stays in "new" state (seconds).
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
pub const IC_BURST_FREQ: f64 = 35.0;
pub const IC_BURST_FREQ: f64 = 10.0;
/// Burst threshold for new interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (path requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection window duration (seconds).
pub const IC_BURST_HOLD: f64 = 60.0;
pub const IC_BURST_HOLD: f64 = 15.0;
/// Penalty duration after a detected burst (seconds).
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Interval between released held announces (seconds).
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Minimum samples required before incoming frequency is considered defined.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst clearing / PR egress limiting.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
#[derive(Debug, thiserror::Error)]
pub enum InterfaceError {
@@ -239,13 +260,25 @@ mod tests {
#[test]
fn test_ingress_control_constants() {
assert_eq!(IA_FREQ_SAMPLES, 128);
assert_eq!(OA_FREQ_SAMPLES, 128);
assert_eq!(IC_BURST_FREQ, 35.0);
assert_eq!(IC_BURST_FREQ_NEW, 6.0);
assert_eq!(IC_BURST_HOLD, 60.0);
assert_eq!(IA_FREQ_SAMPLES, 48);
assert_eq!(OA_FREQ_SAMPLES, 48);
assert_eq!(IP_FREQ_SAMPLES, 48);
assert_eq!(OP_FREQ_SAMPLES, 48);
assert_eq!(AR_MINFREQ_HZ, 0.1);
assert_eq!(PR_MINFREQ_HZ, 0.1);
assert_eq!(AR_FREQ_DECAY, 10.0);
assert_eq!(PR_FREQ_DECAY, 10.0);
assert_eq!(IC_BURST_FREQ, 10.0);
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_PR_BURST_FREQ, 8.0);
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_BURST_HOLD, 15.0);
assert_eq!(IC_BURST_PENALTY, 15.0);
assert_eq!(IC_NEW_TIME, 7200.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 2.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
}
+1
View File
@@ -145,6 +145,7 @@ pub async fn spawn_udp_interface(
Ok(InterfaceHandle {
id,
parent_id: None,
name,
mode,
direction: InterfaceDirection {
+21 -6
View File
@@ -149,6 +149,17 @@ mod tests {
use super::*;
use std::thread;
fn instant_before_now(elapsed: Duration) -> Instant {
if let Some(instant) = Instant::now().checked_sub(elapsed) {
instant
} else {
thread::sleep(elapsed);
Instant::now()
.checked_sub(elapsed)
.expect("elapsed duration should be representable after waiting")
}
}
#[test]
fn test_rtt_scaling() {
let mut ks = KeepaliveState::new(true);
@@ -225,11 +236,13 @@ mod tests {
#[test]
fn test_jitter_desynchronizes_keepalives() {
let links: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
// Push last_inbound just past the interval boundary.
ks.last_inbound = Instant::now() - ks.keepalive_interval;
ks.last_inbound = instant_before_now(ks.keepalive_interval);
ks
})
.collect();
@@ -237,10 +250,12 @@ mod tests {
let firing: usize = links.iter().filter(|ks| ks.should_send_keepalive()).count();
let links_past: Vec<KeepaliveState> = (0..20)
.map(|_| {
.map(|i| {
let mut ks = KeepaliveState::new(true);
ks.update_from_rtt(Duration::from_millis(500));
ks.last_inbound = Instant::now() - ks.keepalive_interval * 2;
ks.keepalive_interval = Duration::from_secs_f64(KEEPALIVE_MIN);
ks.jitter_offset = Duration::from_millis(500);
ks.jitter_negative = i % 2 == 0;
ks.last_inbound = instant_before_now(Duration::from_secs(6));
ks
})
.collect();
+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);
+63 -3
View File
@@ -1253,6 +1253,7 @@ pub struct OutboundTransfer {
/// Scopes the search range when servicing RESOURCE_REQ lookups.
pub receiver_min_consecutive_height: usize,
pub sent_parts: usize,
sent_part_indices: HashSet<usize>,
req_hashlist: HashSet<[u8; 32]>,
}
@@ -1301,6 +1302,7 @@ impl OutboundTransfer {
window_max_sent: 0,
receiver_min_consecutive_height: 0,
sent_parts: 0,
sent_part_indices: HashSet::new(),
req_hashlist: HashSet::new(),
}
}
@@ -1351,6 +1353,9 @@ impl OutboundTransfer {
if let Some(part_data) = part_data {
self.last_part_sent = Some(Instant::now());
self.resource.state = ResourceState::Transferring;
if self.sent_part_indices.insert(part_idx) {
self.sent_parts += 1;
}
if self.window_cursor >= window_end {
// Last part in the window is now in flight; stop
@@ -1548,6 +1553,9 @@ impl OutboundTransfer {
{
if let Some(part_data) = self.resource.get_part(i) {
actions.push(TransferAction::SendPart(i, part_data.to_vec()));
if self.sent_part_indices.insert(i) {
self.sent_parts += 1;
}
sent_count += 1;
}
}
@@ -1736,13 +1744,16 @@ impl OutboundTransfer {
buf
}
/// Fraction of parts confirmed, in `0.0..=1.0`.
/// Fraction of unique parts transmitted, in `0.0..=1.0`.
///
/// Upstream Reticulum reports initiator-side progress from `sent_parts`,
/// while receiver HMUs/proofs still decide completion. This keeps UI
/// progress useful on large resources before a full segment proof arrives.
pub fn progress(&self) -> f64 {
let confirmed = self.confirmed_parts.iter().filter(|&&c| c).count();
if self.resource.num_parts() == 0 {
return 1.0;
}
confirmed as f64 / self.resource.num_parts() as f64
self.sent_parts.min(self.resource.num_parts()) as f64 / self.resource.num_parts() as f64
}
}
@@ -2821,6 +2832,55 @@ mod tests {
assert_eq!(transfer.progress(), 0.0);
}
#[test]
fn test_transfer_progress_tracks_unique_sent_parts() {
let data = vec![0x55; SDU * 2 + 100];
let mut sender =
OutboundTransfer::new(data.clone(), false, Duration::from_millis(50)).unwrap();
assert!(sender.resource.num_parts() > 1);
assert!(matches!(
sender.tick(),
TransferAction::SendAdvertisement(_)
));
let first_progress = match sender.tick() {
TransferAction::SendPart(_, _) => sender.progress(),
other => panic!("expected first part, got {other:?}"),
};
assert!(first_progress > 0.0);
assert!(first_progress < 1.0);
let mut receiver = InboundTransfer::from_advertisement(
sender.resource.num_parts(),
sender.resource.total_size,
data.len(),
sender.resource.random_hash,
sender.resource.resource_hash,
ResourceFlags {
compressed: false,
..Default::default()
},
sender.resource.map_hashes.clone(),
Duration::from_millis(50),
)
.unwrap();
let TransferAction::SendRequest(request) = receiver.request_next() else {
panic!("expected receiver request");
};
let first_count = sender.sent_parts;
let _ = sender.handle_request(&request);
let after_request = sender.sent_parts;
let _ = sender.handle_request(&request);
assert!(after_request >= first_count);
assert_eq!(
sender.sent_parts, after_request,
"duplicate requests must not inflate visible send progress"
);
}
#[test]
fn test_full_transfer_roundtrip() {
// Simulate a complete transfer: sender → receiver
+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.
+2
View File
@@ -8,6 +8,7 @@ license.workspace = true
[features]
default = []
serial = ["rns-interface/serial"]
rnode-tcp = ["rns-interface/rnode-tcp"]
ble = ["rns-interface/ble"]
[dependencies]
@@ -23,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"] }
+6 -3
View File
@@ -12,9 +12,12 @@ pub const RESOURCE_CACHE: u64 = 86400;
pub const MAX_QUEUED_ANNOUNCES: usize = 16384;
pub const QUEUED_ANNOUNCE_LIFE: u64 = 86400;
/// Percentage matching Python `Reticulum.ANNOUNCE_CAP = 2`; transport actor
/// divides by 100 before applying to bitrate math.
pub const ANNOUNCE_CAP: f64 = 2.0;
/// Announce bandwidth cap as a fraction of interface bitrate (2%).
///
/// Python exposes/configures this as `2` percent, then stores `0.02` on live
/// interfaces. Runtime registration must hand the transport actor the stored
/// fraction, because queue spacing is calculated as `tx_time / announce_cap`.
pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MINIMUM_BITRATE: u64 = 5;
pub const IFAC_MIN_SIZE: usize = 1;
+91 -14
View File
@@ -30,7 +30,7 @@ pub enum InterfaceConfig {
#[cfg(feature = "serial")]
KissSerial(KissSerialConfig),
Auto(AutoInterfaceConfig),
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
RNode(RNodeInterfaceConfig),
Local(LocalInterfaceConfig),
I2P(I2PInterfaceConfig),
@@ -79,7 +79,7 @@ pub struct AutoInterfaceConfig {
pub mode: InterfaceMode,
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[derive(Debug, Clone)]
pub struct RNodeInterfaceConfig {
pub name: String,
@@ -254,7 +254,12 @@ pub fn synthesize_interface(
"KISSInterface" => synthesize_kiss_serial(name, section, mode),
"AutoInterface" => synthesize_auto(name, section, mode),
"RNodeInterface" => {
let port = section.get("port").unwrap_or("");
let port = section
.get("port")
.ok_or_else(|| InterfaceFactoryError::MissingField {
name: name.to_string(),
field: "port".to_string(),
})?;
if port.starts_with("ble://") {
#[cfg(feature = "ble")]
{
@@ -274,14 +279,23 @@ pub fn synthesize_interface(
"RNodeInterface '{name}' is an Android USB-OTG entry — skipped at startup; re-add from the UI after plugging the device in"
)));
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
{
synthesize_rnode(name, section, mode)
let is_tcp = port
.get(.."tcp://".len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("tcp://"));
if is_tcp || cfg!(feature = "serial") {
synthesize_rnode(name, section, mode)
} else {
Err(InterfaceFactoryError::Disabled(format!(
"RNodeInterface '{name}' requires 'serial' feature for non-TCP ports"
)))
}
}
#[cfg(not(feature = "serial"))]
#[cfg(not(any(feature = "serial", feature = "rnode-tcp")))]
{
Err(InterfaceFactoryError::Disabled(format!(
"RNodeInterface '{name}' requires 'serial' feature for serial ports"
"RNodeInterface '{name}' requires 'serial' or 'rnode-tcp' feature"
)))
}
}
@@ -524,7 +538,7 @@ fn synthesize_auto(
}))
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
fn synthesize_rnode(
name: &str,
section: &ConfigSection,
@@ -1003,6 +1017,8 @@ impl InterfacePostInit {
enabled: if ingress_control { None } else { Some(false) },
burst_freq_new: section.get_float("ic_burst_freq_new"),
burst_freq: section.get_float("ic_burst_freq"),
pr_burst_freq_new: section.get_float("ic_pr_burst_freq_new"),
pr_burst_freq: section.get_float("ic_pr_burst_freq"),
new_time: section.get_float("ic_new_time"),
burst_hold: section.get_float("ic_burst_hold"),
burst_penalty: section.get_float("ic_burst_penalty"),
@@ -1010,11 +1026,15 @@ impl InterfacePostInit {
.get_uint("ic_max_held_announces")
.map(|v| v as usize),
held_release_interval: section.get_float("ic_held_release_interval"),
ec_pr_freq: section.get_float("ec_pr_freq"),
egress_control: section.get_bool("egress_control"),
};
Self {
outgoing: section.get_bool("outgoing").unwrap_or(true),
bitrate: section.get_uint("bitrate"),
announce_cap: section.get_float("announce_cap"),
announce_cap: section
.get_float("announce_cap")
.and_then(normalize_announce_cap_percent),
announce_rate_target,
announce_rate_grace: section
.get_uint("announce_rate_grace")
@@ -1044,6 +1064,14 @@ impl InterfacePostInit {
}
}
fn normalize_announce_cap_percent(value: f64) -> Option<f64> {
if value > 0.0 && value <= 100.0 {
Some(value / 100.0)
} else {
None
}
}
/// Python `DEFAULT_IFAC_SIZE`: network interfaces 16 bytes, serial/packet-radio 8.
pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
match config {
@@ -1056,9 +1084,10 @@ pub fn default_ifac_size_for(config: &InterfaceConfig) -> usize {
#[cfg(feature = "serial")]
InterfaceConfig::Serial(_)
| InterfaceConfig::KissSerial(_)
| InterfaceConfig::RNode(_)
| InterfaceConfig::RNodeMulti(_)
| InterfaceConfig::AX25KISS(_) => 8,
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
InterfaceConfig::RNode(_) => 8,
InterfaceConfig::Local(_) | InterfaceConfig::Pipe(_) => 8,
#[cfg(feature = "ble")]
InterfaceConfig::BleRNode(_) => 8,
@@ -1451,7 +1480,26 @@ mod tests {
}
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_tcp() {
let mut section = ConfigSection::new();
section.set("type", "RNodeInterface");
section.set("port", "tcp://rnode.local");
section.set("frequency", "915000000");
let config = synthesize_interface("rnode_tcp", &section).unwrap();
match config {
InterfaceConfig::RNode(c) => {
assert_eq!(c.name, "rnode_tcp");
assert_eq!(c.port, "tcp://rnode.local");
assert_eq!(c.frequency, 915000000);
}
_ => panic!("expected RNode"),
}
}
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_missing_port() {
let mut section = ConfigSection::new();
@@ -1466,12 +1514,12 @@ mod tests {
}
}
#[cfg(feature = "serial")]
#[cfg(any(feature = "serial", feature = "rnode-tcp"))]
#[test]
fn test_synthesize_rnode_missing_frequency() {
let mut section = ConfigSection::new();
section.set("type", "RNodeInterface");
section.set("port", "/dev/ttyACM0");
section.set("port", "tcp://rnode.local");
match synthesize_interface("rnode_no_freq", &section) {
Err(InterfaceFactoryError::MissingField { field, .. }) => {
@@ -1572,6 +1620,10 @@ mod tests {
section.set("ifac_size", "16");
section.set("ingress_control", "false");
section.set("announce_cap", "5.0");
section.set("ic_pr_burst_freq_new", "4.5");
section.set("ic_pr_burst_freq", "9.5");
section.set("ec_pr_freq", "6.5");
section.set("egress_control", "Yes");
let pi = InterfacePostInit::from_section(&section);
assert!(!pi.outgoing);
@@ -1580,7 +1632,32 @@ mod tests {
assert_eq!(pi.ifac_passphrase.as_deref(), Some("secret"));
assert_eq!(pi.ifac_size, Some(16));
assert!(!pi.ingress_control);
assert!((pi.announce_cap.unwrap() - 5.0).abs() < f64::EPSILON);
assert!((pi.announce_cap.unwrap() - 0.05).abs() < f64::EPSILON);
assert_eq!(pi.ingress_overrides.enabled, Some(false));
assert_eq!(pi.ingress_overrides.pr_burst_freq_new, Some(4.5));
assert_eq!(pi.ingress_overrides.pr_burst_freq, Some(9.5));
assert_eq!(pi.ingress_overrides.ec_pr_freq, Some(6.5));
assert_eq!(pi.ingress_overrides.egress_control, Some(true));
}
#[test]
fn announce_cap_config_uses_python_percent_shape() {
let mut section = ConfigSection::new();
section.set("announce_cap", "2");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, Some(0.02));
section.set("announce_cap", "100");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, Some(1.0));
section.set("announce_cap", "0");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, None);
section.set("announce_cap", "101");
let pi = InterfacePostInit::from_section(&section);
assert_eq!(pi.announce_cap, None);
}
#[test]
+635 -29
View File
@@ -64,6 +64,36 @@ pub struct ChannelSendReceipt {
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkPacketSendReceipt {
pub link_id: [u8; 16],
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkResourceSendReceipt {
pub link_id: [u8; 16],
pub resource_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkPacketProof {
pub link_id: [u8; 16],
pub packet_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub struct LinkResourceProof {
pub link_id: [u8; 16],
pub resource_hash: [u8; 32],
}
#[derive(Debug, Clone)]
pub enum LinkPayloadSendReceipt {
Packet(LinkPacketSendReceipt),
Resource(LinkResourceSendReceipt),
}
#[derive(Debug, thiserror::Error)]
pub enum ChannelSendError {
#[error("link not found")]
@@ -78,12 +108,43 @@ pub enum ChannelSendError {
TransportUnavailable,
}
#[derive(Debug, thiserror::Error)]
pub enum LinkSendError {
#[error("link not found")]
LinkNotFound,
#[error("link is not active")]
LinkNotActive,
#[error("link session keys are unavailable")]
NoSessionKeys,
#[error("transport channel is full or closed")]
TransportUnavailable,
#[error("resource transfer could not be started")]
ResourceStartFailed,
}
pub enum LinkManagerCommand {
SendChannelMessage {
link_id: [u8; 16],
message: Box<dyn MessageBase>,
result_tx: Option<oneshot::Sender<Result<ChannelSendReceipt, ChannelSendError>>>,
},
SendLinkPacket {
link_id: [u8; 16],
payload: Vec<u8>,
result_tx: Option<oneshot::Sender<Result<LinkPacketSendReceipt, LinkSendError>>>,
},
SendLinkResource {
link_id: [u8; 16],
payload: Vec<u8>,
auto_compress: bool,
result_tx: Option<oneshot::Sender<Result<LinkResourceSendReceipt, LinkSendError>>>,
},
SendLinkPayload {
link_id: [u8; 16],
payload: Vec<u8>,
auto_compress: bool,
result_tx: Option<oneshot::Sender<Result<LinkPayloadSendReceipt, LinkSendError>>>,
},
CloseLink {
link_id: [u8; 16],
reason: CloseReason,
@@ -137,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>,
@@ -162,6 +224,10 @@ pub struct LinkManager {
link_identity_gate: Option<LinkIdentityGate>,
/// Decrypted link-packet stream (LXMF DIRECT).
link_packet_tx: Option<mpsc::Sender<(Vec<u8>, [u8; 16])>>,
/// Valid proof for an application link packet sent through this manager.
link_packet_proof_tx: Option<mpsc::Sender<LinkPacketProof>>,
/// Valid proof for an application resource sent through this manager.
outbound_resource_proof_tx: Option<mpsc::Sender<LinkResourceProof>>,
/// Decrypted channel envelopes as `(link_id, msg_type, payload)`.
channel_message_tx: Option<mpsc::Sender<LinkChannelMessage>>,
/// Fires when an active link is closed or torn down.
@@ -199,6 +265,8 @@ impl LinkManager {
link_identified_tx: None,
link_identity_gate: None,
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
channel_message_tx: None,
link_closed_tx: None,
inbound_raw_tx: None,
@@ -213,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)
{
@@ -231,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,
@@ -245,6 +315,8 @@ impl LinkManager {
link_identified_tx: None,
link_identity_gate: None,
link_packet_tx: None,
link_packet_proof_tx: None,
outbound_resource_proof_tx: None,
channel_message_tx: None,
link_closed_tx: None,
inbound_raw_tx: None,
@@ -342,6 +414,41 @@ impl LinkManager {
}
true
}
LinkManagerCommand::SendLinkPacket {
link_id,
payload,
result_tx,
} => {
let result = self.send_link_packet(&link_id, &payload);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::SendLinkResource {
link_id,
payload,
auto_compress,
result_tx,
} => {
let result = self.send_link_resource(&link_id, payload, auto_compress);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::SendLinkPayload {
link_id,
payload,
auto_compress,
result_tx,
} => {
let result = self.send_link_payload(&link_id, payload, auto_compress);
if let Some(tx) = result_tx {
let _ = tx.send(result);
}
true
}
LinkManagerCommand::CloseLink {
link_id,
reason,
@@ -455,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,
@@ -483,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;
@@ -1418,6 +1535,8 @@ impl LinkManager {
.is_some_and(|transfer| transfer.handle_proof(data));
if complete {
active.outbound_resources.remove(&rh);
let mut started_next_segment = false;
let completed_resource_hash = queue_key.unwrap_or(rh);
if let Some(key) = queue_key {
let (next, empty) = if let Some(queue) =
active.outbound_split_queues.get_mut(&key)
@@ -1437,8 +1556,17 @@ impl LinkManager {
&link_id,
next,
);
started_next_segment = true;
}
}
if !started_next_segment
&& let Some(ref tx) = self.outbound_resource_proof_tx
{
let _ = tx.try_send(LinkResourceProof {
link_id,
resource_hash: completed_resource_hash,
});
}
}
}
}
@@ -1588,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());
@@ -1604,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,
@@ -1636,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"
);
}
}
}
}
@@ -1933,8 +2081,10 @@ impl LinkManager {
}
let rtt = active.link.rtt_secs();
let mut matched_channel_sequence = false;
if let Some(channel) = active.channel.as_mut() {
if let Some(sequence) = channel.delivered_by_packet_hash(&packet_hash, rtt) {
matched_channel_sequence = true;
active.link.keepalive.record_proof();
tracing::debug!(
link_id = hex::encode(link_id),
@@ -1944,6 +2094,12 @@ impl LinkManager {
);
}
}
if !matched_channel_sequence && let Some(ref tx) = self.link_packet_proof_tx {
let _ = tx.try_send(LinkPacketProof {
link_id,
packet_hash,
});
}
}
pub fn set_request_handler<F>(&mut self, handler: F)
@@ -2002,6 +2158,14 @@ impl LinkManager {
self.link_packet_tx = Some(tx);
}
pub fn set_link_packet_proof_channel(&mut self, tx: mpsc::Sender<LinkPacketProof>) {
self.link_packet_proof_tx = Some(tx);
}
pub fn set_outbound_resource_proof_channel(&mut self, tx: mpsc::Sender<LinkResourceProof>) {
self.outbound_resource_proof_tx = Some(tx);
}
pub fn set_channel_message_channel(&mut self, tx: mpsc::Sender<LinkChannelMessage>) {
self.channel_message_tx = Some(tx);
}
@@ -2092,6 +2256,111 @@ impl LinkManager {
})
}
pub fn send_link_packet(
&mut self,
link_id: &[u8; 16],
payload: &[u8],
) -> Result<LinkPacketSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
let encrypted = active
.link
.encrypt(payload)
.map_err(|_| LinkSendError::NoSessionKeys)?;
let transport_tx = self.transport_tx.clone();
let permit = transport_tx
.try_reserve()
.map_err(|_| LinkSendError::TransportUnavailable)?;
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);
let active = self
.active_links
.get_mut(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
active.link.record_tx(raw.len());
permit.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: *link_id,
}));
Ok(LinkPacketSendReceipt {
link_id: *link_id,
packet_hash,
})
}
pub fn send_link_resource(
&mut self,
link_id: &[u8; 16],
payload: Vec<u8>,
auto_compress: bool,
) -> Result<LinkResourceSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
if active.link.session_keys().is_none() {
return Err(LinkSendError::NoSessionKeys);
}
let resource_hash = self
.start_resource_transfer(link_id, payload, auto_compress)
.ok_or(LinkSendError::ResourceStartFailed)?;
Ok(LinkResourceSendReceipt {
link_id: *link_id,
resource_hash,
})
}
pub fn send_link_payload(
&mut self,
link_id: &[u8; 16],
payload: Vec<u8>,
auto_compress: bool,
) -> Result<LinkPayloadSendReceipt, LinkSendError> {
let active = self
.active_links
.get(link_id)
.ok_or(LinkSendError::LinkNotFound)?;
if active.link.state != LinkState::Active {
return Err(LinkSendError::LinkNotActive);
}
if payload.len() <= active.link.mdu {
self.send_link_packet(link_id, &payload)
.map(LinkPayloadSendReceipt::Packet)
} else {
self.send_link_resource(link_id, payload, auto_compress)
.map(LinkPayloadSendReceipt::Resource)
}
}
pub fn process_destination_packet(&self, raw: &[u8], identity: &Identity) -> Option<Vec<u8>> {
let dest = self.destination.as_ref()?;
let (header, data_offset) = rns_wire::header::PacketHeader::unpack(raw).ok()?;
@@ -2301,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 {
@@ -2332,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 {
@@ -2354,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);
@@ -2560,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);
@@ -2568,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);
@@ -2582,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 {
@@ -2770,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);
@@ -2904,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();
@@ -3105,6 +3572,145 @@ mod tests {
assert!(lm.get_channel(&link_id).unwrap().is_ready_to_send());
}
#[test]
fn send_link_packet_emits_plain_link_data_and_proof_event() {
let (initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
let link_id = responder_link.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC1; 16], None);
let (proof_tx, mut proof_rx) = mpsc::channel(4);
lm.set_link_packet_proof_channel(proof_tx);
lm.active_links.insert(
link_id,
ActiveLink {
link: responder_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(),
},
);
let receipt = lm
.send_link_packet(&link_id, b"backchannel payload")
.expect("link packet queued");
let outbound = transport_rx.try_recv().expect("link packet outbound");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound link packet");
};
let (sent_header, sent_offset) =
rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(sent_header.context, rns_wire::context::PacketContext::None);
assert_eq!(sent_header.destination_hash, link_id);
assert_eq!(
receipt.packet_hash,
rns_wire::hash::packet_hash(&request.raw, sent_header.flags.header_type)
);
assert_eq!(
initiator_link.decrypt(&request.raw[sent_offset..]).unwrap(),
b"backchannel payload"
);
let proof_data = initiator_link
.prove_packet_with_link_key(&receipt.packet_hash)
.unwrap();
let proof_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::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::None,
};
let mut proof_raw = proof_header.pack();
proof_raw.extend_from_slice(&proof_data);
lm.handle_inbound_packet(&proof_raw, 1);
let proof = proof_rx.try_recv().expect("link packet proof event");
assert_eq!(proof.link_id, link_id);
assert_eq!(proof.packet_hash, receipt.packet_hash);
}
#[test]
fn send_link_resource_emits_resource_proof_event() {
let (_initiator_link, responder_link, _identity_key) = handshaken_link_pair_with_identity();
let link_id = responder_link.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(transport_tx, event_rx, [0xC2; 16], None);
let (proof_tx, mut proof_rx) = mpsc::channel(4);
lm.set_outbound_resource_proof_channel(proof_tx);
lm.active_links.insert(
link_id,
ActiveLink {
link: responder_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(),
},
);
let receipt = lm
.send_link_resource(&link_id, b"resource payload".to_vec(), false)
.expect("resource started");
let outbound = transport_rx.try_recv().expect("resource ADV outbound");
let TransportMessage::Outbound(request) = outbound else {
panic!("expected outbound resource ADV");
};
let (adv_header, _) = rns_wire::header::PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(
adv_header.context,
rns_wire::context::PacketContext::ResourceAdv
);
let proof_data = {
let active = lm.active_links.get(&link_id).unwrap();
let transfer = active
.outbound_resources
.get(&receipt.resource_hash)
.expect("outbound resource tracked");
let mut proof = Vec::new();
proof.extend_from_slice(&transfer.resource.resource_hash);
proof.extend_from_slice(&transfer.resource.expected_proof);
proof
};
let proof_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::Proof,
},
hops: 0,
transport_id: None,
destination_hash: link_id,
context: rns_wire::context::PacketContext::ResourcePrf,
};
let mut proof_raw = proof_header.pack();
proof_raw.extend_from_slice(&proof_data);
lm.handle_inbound_packet(&proof_raw, 1);
let proof = proof_rx.try_recv().expect("resource proof event");
assert_eq!(proof.link_id, link_id);
assert_eq!(proof.resource_hash, receipt.resource_hash);
}
#[test]
fn unmatched_valid_link_packet_proof_does_not_record_keepalive_proof() {
let (sender_link, receiver_link, _identity_key) = handshaken_link_pair_with_identity();
+121 -10
View File
@@ -75,13 +75,52 @@ pub async fn spawn_probe_responder(
.map_err(|_| ProbeError::TransportClosed)?;
let identity = Arc::new(identity);
let mut destination = dest;
// Implicit proof is Python's default (`use_implicit_proof = Yes`).
let implicit = true;
tokio::spawn(async move {
while let Some(event) = event_rx.recv().await {
let DestinationEvent::InboundPacket { raw, .. } = event else {
continue;
let (raw, interface_id) = match event {
DestinationEvent::InboundPacket { raw, interface_id } => (raw, interface_id),
DestinationEvent::AnnounceRequested(request) => {
let raw = match destination.announce_packet(
identity.as_ref(),
None,
None,
request.path_response,
request.tag.as_deref(),
unix_now(),
) {
Ok(raw) => raw,
Err(e) => {
tracing::warn!(
error = %e,
path_response = request.path_response,
"probe responder: failed to build requested announce"
);
continue;
}
};
let outbound = OutboundRequest {
raw: Bytes::from(raw),
destination_hash: dest_hash,
};
let message = if let Some(interface_id) = request.attached_interface {
TransportMessage::OutboundAttached {
request: outbound,
interface_id,
}
} else {
TransportMessage::Outbound(outbound)
};
if transport_tx.send(message).await.is_err() {
tracing::debug!("probe responder: transport closed, exiting");
break;
}
continue;
}
_ => continue,
};
let (header, _) = match PacketHeader::unpack(&raw) {
Ok(h) => h,
@@ -122,10 +161,13 @@ pub async fn spawn_probe_responder(
proof_raw.extend_from_slice(&proof_payload);
if transport_tx
.send(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: trunc_hash,
}))
.send(TransportMessage::OutboundAttached {
request: OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: trunc_hash,
},
interface_id,
})
.await
.is_err()
{
@@ -413,6 +455,13 @@ fn find_public_key(announces: &[AnnounceRpcEntry], dest_hash: &[u8; 16]) -> Opti
.and_then(|a| a.public_key)
}
fn unix_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -455,6 +504,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x11; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
AnnounceRpcEntry {
@@ -464,6 +515,8 @@ mod tests {
timestamp: 0.0,
public_key: Some([0x22; 64]),
ratchet: None,
name_hash: [0; 10],
is_path_response: false,
retained: false,
},
];
@@ -524,15 +577,20 @@ mod tests {
.await
.expect("timed out waiting for proof")
.expect("channel closed");
let (request, interface_id) = match outbound {
TransportMessage::OutboundAttached {
request,
interface_id,
} => (request, interface_id),
other => panic!("expected OutboundAttached, got {other:?}"),
};
let OutboundRequest {
raw: proof_raw,
destination_hash,
} = match outbound {
TransportMessage::Outbound(r) => r,
other => panic!("expected Outbound, got {other:?}"),
};
} = request;
assert_eq!(destination_hash, expected_trunc);
assert_eq!(interface_id, 0);
let (proof_header, data_offset) = PacketHeader::unpack(&proof_raw).unwrap();
assert_eq!(proof_header.flags.packet_type, PacketType::Proof);
@@ -552,6 +610,59 @@ mod tests {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responder_sends_attached_path_response_announce() {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
let identity = Identity::new();
let spawn_tx = tx.clone();
let spawn_handle = tokio::spawn(async move {
spawn_probe_responder(spawn_tx, identity, default_probe_app_name()).await
});
let first = rx.recv().await.expect("RegisterDestination");
let delivery_tx = match first {
TransportMessage::RegisterDestination {
delivery_tx: Some(dt),
..
} => dt,
other => panic!("expected RegisterDestination, got {other:?}"),
};
let dest_hash = spawn_handle.await.unwrap().unwrap();
delivery_tx
.send(DestinationEvent::AnnounceRequested(
rns_transport::link_messages::AnnounceRequest {
app_name: default_probe_app_name().to_string(),
path_response: true,
tag: Some(vec![0xA5; 16]),
attached_interface: Some(7),
},
))
.await
.unwrap();
let outbound = tokio::time::timeout(Duration::from_secs(2), rx.recv())
.await
.expect("timed out waiting for path response")
.expect("channel closed");
let (request, interface_id) = match outbound {
TransportMessage::OutboundAttached {
request,
interface_id,
} => (request, interface_id),
other => panic!("expected OutboundAttached, got {other:?}"),
};
assert_eq!(interface_id, 7);
assert_eq!(request.destination_hash, dest_hash);
let (header, _offset) = PacketHeader::unpack(&request.raw).unwrap();
assert_eq!(header.flags.packet_type, PacketType::Announce);
assert_eq!(header.flags.destination_type, DestinationType::Single);
assert_eq!(header.destination_hash, dest_hash);
assert_eq!(header.context, PacketContext::PathResponse);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responder_ignores_non_data_packets() {
let (tx, mut rx) = mpsc::channel::<TransportMessage>(16);
+51 -2
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());
@@ -252,7 +252,13 @@ fn interface_stats_from_rpc(e: InterfaceStatRpcEntry) -> schema::InterfaceStats
txb: e.tx_bytes,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
held_announces: e.held_announces,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
status: e.online,
mode,
bitrate: Some(e.bitrate),
@@ -330,7 +336,13 @@ mod tests {
txb: 7,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 0.0,
outgoing_pr_frequency: 0.0,
held_announces: 0,
burst_active: false,
burst_activated: 0.0,
pr_burst_active: false,
pr_burst_activated: 0.0,
status: true,
mode: 0x01,
bitrate: Some(1_000_000),
@@ -465,11 +477,17 @@ mod tests {
held_announces: 1,
incoming_announce_frequency: 0.5,
outgoing_announce_frequency: 0.25,
incoming_pr_frequency: 3.0,
outgoing_pr_frequency: 1.5,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 2.0,
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 0,
}];
@@ -484,6 +502,9 @@ mod tests {
hops: 2,
expires: 1_700_100_000.0,
interface: "MockIf".to_string(),
interface_id: 1,
interface_mode: rns_transport::constants::InterfaceMode::Full,
interface_role: rns_transport::messages::InterfaceRole::Normal,
}];
TransportQueryResponse::PathTable(entries)
}
@@ -562,6 +583,34 @@ mod tests {
Some(0x06),
"Gateway mode maps to Python MODE_GATEWAY=0x06"
);
let incoming_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("incoming_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(incoming_pr, Some(3.0));
let outgoing_pr = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("outgoing_pr_frequency"))
.unwrap()
.1
.as_f64();
assert_eq!(outgoing_pr, Some(1.5));
let burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(burst_active, Some(true));
let pr_burst_active = iface_map
.iter()
.find(|(k, _)| k.as_str() == Some("pr_burst_active"))
.unwrap()
.1
.as_bool();
assert_eq!(pr_burst_active, Some(true));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -34,7 +34,13 @@ pub struct InterfaceStats {
pub txb: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub held_announces: u64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
/// Python field name (not `online`).
pub status: bool,
/// Matches Python `Interface.MODE_*` integers.
File diff suppressed because it is too large. Load diff
+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);
+27 -1
View File
@@ -32,6 +32,7 @@ use rns_transport::messages::{
AnnounceRpcEntry, OutboundRequest, TransportMessage, TransportQuery, TransportQueryResponse,
};
use crate::lifecycle::ShutdownSignal;
use crate::link_manager::{
ChannelSendError, LinkChannelMessage, LinkManager, LinkManagerCommand, register_destination,
};
@@ -132,6 +133,22 @@ pub struct RnshListenerConfig {
pub async fn run_rnsh_listener(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
) -> Result<(), RnshError> {
run_rnsh_listener_inner(transport_tx, cfg, None).await
}
pub async fn run_rnsh_listener_with_shutdown(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
shutdown: ShutdownSignal,
) -> Result<(), RnshError> {
run_rnsh_listener_inner(transport_tx, cfg, Some(shutdown)).await
}
async fn run_rnsh_listener_inner(
transport_tx: mpsc::Sender<TransportMessage>,
cfg: RnshListenerConfig,
shutdown: Option<ShutdownSignal>,
) -> Result<(), RnshError> {
let signing_key = cfg
.identity
@@ -152,7 +169,7 @@ pub async fn run_rnsh_listener(
event_rx,
&cfg.identity,
RNSH_APP_NAME,
signing_key,
Some(signing_key),
);
let announce_tx = transport_tx.clone();
@@ -237,6 +254,15 @@ pub async fn run_rnsh_listener(
} => {
send_announce(&transport_tx, &cfg.identity, RNSH_APP_NAME).await?;
}
_ = async {
if let Some(shutdown) = shutdown.as_ref() {
shutdown.wait().await;
} else {
std::future::pending::<()>().await;
}
} => {
break;
}
}
}
+279 -8
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,
@@ -45,6 +61,10 @@ pub enum RpcRequest {
GetNextHop {
destination_hash: Vec<u8>,
},
RequestPath {
destination_hash: Vec<u8>,
timeout_secs: Option<f64>,
},
GetFirstHopTimeout {
destination_hash: Vec<u8>,
},
@@ -65,6 +85,8 @@ pub enum RpcRequest {
DropAllVia {
transport_hash: Vec<u8>,
},
DropPathTable,
DropRecentAnnounces,
DropAnnounceQueues,
BlackholeIdentity {
identity_hash: Vec<u8>,
@@ -130,6 +152,18 @@ pub struct InterfaceStatEntry {
pub held_announces: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
#[serde(default)]
pub incoming_pr_frequency: f64,
#[serde(default)]
pub outgoing_pr_frequency: f64,
#[serde(default)]
pub burst_active: bool,
#[serde(default)]
pub burst_activated: f64,
#[serde(default)]
pub pr_burst_active: bool,
#[serde(default)]
pub pr_burst_activated: f64,
pub clients: Option<u64>,
pub announce_rate_target: Option<f64>,
pub announce_rate_grace: Option<u32>,
@@ -195,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;
@@ -229,6 +275,17 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
("get", PyValue::String("next_hop".to_string())),
("destination_hash", PyValue::Bytes(destination_hash.clone())),
]),
RpcRequest::RequestPath {
destination_hash,
timeout_secs,
} => py_dict(vec![
("request", PyValue::String("path".to_string())),
("destination_hash", PyValue::Bytes(destination_hash.clone())),
(
"timeout",
timeout_secs.map(PyValue::Float).unwrap_or(PyValue::None),
),
]),
RpcRequest::GetFirstHopTimeout { destination_hash } => py_dict(vec![
("get", PyValue::String("first_hop_timeout".to_string())),
("destination_hash", PyValue::Bytes(destination_hash.clone())),
@@ -255,6 +312,13 @@ fn request_to_py_value(req: &RpcRequest) -> PyValue {
("drop", PyValue::String("all_via".to_string())),
("destination_hash", PyValue::Bytes(transport_hash.clone())),
]),
RpcRequest::DropPathTable => {
py_dict(vec![("drop", PyValue::String("path_table".to_string()))])
}
RpcRequest::DropRecentAnnounces => py_dict(vec![(
"drop",
PyValue::String("recent_announces".to_string()),
)]),
RpcRequest::DropAnnounceQueues => py_dict(vec![(
"drop",
PyValue::String("announce_queues".to_string()),
@@ -350,6 +414,8 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
"all_via" => Ok(RpcRequest::DropAllVia {
transport_hash: dict_bytes(entries, "destination_hash")?,
}),
"path_table" => Ok(RpcRequest::DropPathTable),
"recent_announces" => Ok(RpcRequest::DropRecentAnnounces),
"announce_queues" => Ok(RpcRequest::DropAnnounceQueues),
other => Err(RpcError::Deserialize(format!(
"unknown Python RPC drop path: {other}"
@@ -357,6 +423,18 @@ fn py_value_to_request(value: &PyValue) -> Result<RpcRequest, RpcError> {
};
}
if let Some(PyValue::String(path)) = dict_get(entries, "request") {
return match path.as_str() {
"path" => Ok(RpcRequest::RequestPath {
destination_hash: dict_bytes(entries, "destination_hash")?,
timeout_secs: dict_get(entries, "timeout").and_then(py_f64),
}),
other => Err(RpcError::Deserialize(format!(
"unknown Python RPC request path: {other}"
))),
};
}
if let Some(PyValue::Bytes(identity_hash)) = dict_get(entries, "blackhole_identity") {
return Ok(RpcRequest::BlackholeIdentity {
identity_hash: identity_hash.clone(),
@@ -454,6 +532,18 @@ fn response_to_py_value(resp: &RpcResponse) -> PyValue {
"outgoing_announce_frequency",
PyValue::Float(e.outgoing_announce_frequency),
),
(
"incoming_pr_frequency",
PyValue::Float(e.incoming_pr_frequency),
),
(
"outgoing_pr_frequency",
PyValue::Float(e.outgoing_pr_frequency),
),
("burst_active", PyValue::Bool(e.burst_active)),
("burst_activated", PyValue::Float(e.burst_activated)),
("pr_burst_active", PyValue::Bool(e.pr_burst_active)),
("pr_burst_activated", PyValue::Float(e.pr_burst_activated)),
(
"clients",
e.clients
@@ -577,13 +667,19 @@ fn py_value_to_response_for_request(
Ok(RpcResponse::StringResult(py_optional_string(value)?))
}
RpcRequest::GetNextHop { .. } => Ok(RpcResponse::HashResult(py_optional_bytes(value)?)),
RpcRequest::RequestPath { .. } => Ok(RpcResponse::BoolResult(match value {
PyValue::Bool(v) => *v,
PyValue::None => false,
_ => py_required_int(value)? != 0,
})),
RpcRequest::GetFirstHopTimeout { .. }
| RpcRequest::GetPacketRssi { .. }
| RpcRequest::GetPacketSnr { .. }
| RpcRequest::GetPacketQ { .. } => Ok(RpcResponse::FloatResult(py_optional_float(value)?)),
RpcRequest::GetLinkCount | RpcRequest::DropAllVia { .. } => {
Ok(RpcResponse::IntResult(py_required_int(value)?))
}
RpcRequest::GetLinkCount
| RpcRequest::DropAllVia { .. }
| RpcRequest::DropPathTable
| RpcRequest::DropRecentAnnounces => Ok(RpcResponse::IntResult(py_required_int(value)?)),
RpcRequest::GetBlackholedIdentities => {
Ok(RpcResponse::BlackholeList(parse_blackhole_list(value)?))
}
@@ -704,6 +800,24 @@ fn parse_interface_stats(value: &PyValue) -> Result<Vec<InterfaceStatEntry>, Rpc
outgoing_announce_frequency: dict_get(m, "outgoing_announce_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
incoming_pr_frequency: dict_get(m, "incoming_pr_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
outgoing_pr_frequency: dict_get(m, "outgoing_pr_frequency")
.and_then(py_f64)
.unwrap_or(0.0),
burst_active: dict_get(m, "burst_active")
.and_then(py_bool)
.unwrap_or(false),
burst_activated: dict_get(m, "burst_activated")
.and_then(py_f64)
.unwrap_or(0.0),
pr_burst_active: dict_get(m, "pr_burst_active")
.and_then(py_bool)
.unwrap_or(false),
pr_burst_activated: dict_get(m, "pr_burst_activated")
.and_then(py_f64)
.unwrap_or(0.0),
clients: match dict_get(m, "clients") {
Some(PyValue::None) | None => None,
Some(value) => py_u64(value),
@@ -1313,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));
@@ -1320,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;
}
@@ -1330,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));
@@ -1494,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(|_| {
@@ -1517,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);
@@ -1542,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(|_| {
@@ -1640,6 +1794,89 @@ mod tests {
}
}
fn interface_stat_entry() -> InterfaceStatEntry {
InterfaceStatEntry {
id: 7,
name: "TestIf".to_string(),
rx_bytes: 100,
tx_bytes: 200,
rx_rate: 10,
tx_rate: 20,
online: true,
bitrate: 115_200,
mtu: 500,
mode: "Gateway".to_string(),
role: "normal".to_string(),
announce_queue: Some(2),
held_announces: 3,
incoming_announce_frequency: 4.0,
outgoing_announce_frequency: 5.0,
incoming_pr_frequency: 6.0,
outgoing_pr_frequency: 7.0,
burst_active: true,
burst_activated: 1_700_000_001.0,
pr_burst_active: true,
pr_burst_activated: 1_700_000_002.0,
clients: Some(4),
announce_rate_target: Some(3600.0),
announce_rate_grace: Some(5),
announce_rate_penalty: Some(30.0),
announce_cap: 0.02,
ifac_size: 0,
tx_drops: 1,
}
}
#[test]
fn test_interface_stats_response_roundtrip_includes_125_fields() {
let resp = RpcResponse::InterfaceStats(vec![interface_stat_entry()]);
let encoded = encode_response(&resp).unwrap();
let decoded =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
match decoded {
RpcResponse::InterfaceStats(entries) => {
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.incoming_pr_frequency, 6.0);
assert_eq!(entry.outgoing_pr_frequency, 7.0);
assert!(entry.burst_active);
assert_eq!(entry.burst_activated, 1_700_000_001.0);
assert!(entry.pr_burst_active);
assert_eq!(entry.pr_burst_activated, 1_700_000_002.0);
}
_ => panic!("wrong variant"),
}
}
#[test]
fn test_interface_stats_parser_defaults_missing_125_fields() {
let legacy = py_dict(vec![(
"interfaces",
PyValue::List(vec![py_dict(vec![
("name", PyValue::String("LegacyIf".to_string())),
("rxb", PyValue::Int(1)),
("txb", PyValue::Int(2)),
("status", PyValue::Bool(true)),
])]),
)]);
let encoded = encode_python_pickle(&legacy).unwrap();
let decoded =
decode_response_for_request(&encoded, &RpcRequest::GetInterfaceStats).unwrap();
match decoded {
RpcResponse::InterfaceStats(entries) => {
assert_eq!(entries.len(), 1);
let entry = &entries[0];
assert_eq!(entry.incoming_pr_frequency, 0.0);
assert_eq!(entry.outgoing_pr_frequency, 0.0);
assert!(!entry.burst_active);
assert_eq!(entry.burst_activated, 0.0);
assert!(!entry.pr_burst_active);
assert_eq!(entry.pr_burst_activated, 0.0);
}
_ => panic!("wrong variant"),
}
}
#[test]
fn test_python_blackhole_dict_response_shape() {
let identity_hash = vec![0x42; 16];
@@ -1681,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];
@@ -1699,10 +1964,16 @@ mod tests {
RpcRequest::GetNextHopIfName {
destination_hash: vec![0; 16],
},
RpcRequest::RequestPath {
destination_hash: vec![0; 16],
timeout_secs: Some(0.01),
},
RpcRequest::GetLinkCount,
RpcRequest::DropPath {
destination_hash: vec![0; 16],
},
RpcRequest::DropPathTable,
RpcRequest::DropRecentAnnounces,
RpcRequest::DropAnnounceQueues,
RpcRequest::BlackholeIdentity {
identity_hash: vec![0; 16],
+128 -9
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 {
@@ -222,20 +226,58 @@ async fn query_transport(
query: rns_transport::messages::TransportQuery,
) -> Option<rns_transport::messages::TransportQueryResponse> {
let (tx, rx) = tokio::sync::oneshot::channel();
if transport_tx
.send(TransportMessage::Rpc {
let budget = std::time::Duration::from_secs(5);
let started = std::time::Instant::now();
match tokio::time::timeout(
budget,
transport_tx.send(TransportMessage::Rpc {
query,
response_tx: tx,
}),
)
.await
{
Ok(Ok(())) => {}
Ok(Err(_)) => return None,
Err(_) => return None,
}
let remaining = budget.checked_sub(started.elapsed())?;
tokio::time::timeout(remaining, rx)
.await
.ok()
.and_then(|r| r.ok())
}
async fn request_path(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
timeout_secs: Option<f64>,
) -> bool {
let wait = std::time::Duration::from_secs_f64(timeout_secs.unwrap_or(5.0).max(0.1));
if transport_tx
.send(TransportMessage::RequestPath { destination_hash })
.await
.is_err()
{
return false;
}
let (reply, rx) = tokio::sync::oneshot::channel();
if transport_tx
.send(TransportMessage::AwaitPath {
dest: destination_hash,
reply,
})
.await
.is_err()
{
return None;
return false;
}
match tokio::time::timeout(wait, rx).await {
Ok(Ok(found)) => found,
_ => false,
}
tokio::time::timeout(std::time::Duration::from_secs(5), rx)
.await
.ok()
.and_then(|r| r.ok())
}
async fn process_rpc_request(
@@ -286,6 +328,12 @@ async fn process_rpc_request(
held_announces: e.held_announces,
incoming_announce_frequency: e.incoming_announce_frequency,
outgoing_announce_frequency: e.outgoing_announce_frequency,
incoming_pr_frequency: e.incoming_pr_frequency,
outgoing_pr_frequency: e.outgoing_pr_frequency,
burst_active: e.burst_active,
burst_activated: e.burst_activated,
pr_burst_active: e.pr_burst_active,
pr_burst_activated: e.pr_burst_activated,
clients: e.clients,
announce_rate_target: e.announce_rate_target,
announce_rate_grace: e.announce_rate_grace,
@@ -297,7 +345,9 @@ async fn process_rpc_request(
.collect();
RpcResponse::InterfaceStats(rpc_entries)
}
_ => RpcResponse::InterfaceStats(Vec::new()),
_ => RpcResponse::Error(
"transport actor did not answer interface stats query".to_string(),
),
}
}
RpcRequest::GetRateTable => {
@@ -360,6 +410,15 @@ async fn process_rpc_request(
None => RpcResponse::HashResult(None),
}
}
RpcRequest::RequestPath {
destination_hash,
timeout_secs,
} => match hash_to_array(&destination_hash) {
Some(dest) => {
RpcResponse::BoolResult(request_path(transport_tx, dest, timeout_secs).await)
}
None => RpcResponse::BoolResult(false),
},
RpcRequest::DropPath { destination_hash } => {
let dest = hash_to_array(&destination_hash);
if let Some(d) = dest {
@@ -367,6 +426,22 @@ async fn process_rpc_request(
}
RpcResponse::Ok
}
RpcRequest::DropPathTable => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropPathTable).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropRecentAnnounces => {
if let Some(TransportQueryResponse::IntResult(n)) =
query_transport(transport_tx, TransportQuery::DropRecentAnnounces).await
{
return RpcResponse::IntResult(n);
}
RpcResponse::IntResult(0)
}
RpcRequest::DropAnnounceQueues => {
let _ = query_transport(transport_tx, TransportQuery::DropAnnounceQueues).await;
RpcResponse::Ok
@@ -827,6 +902,10 @@ listener.close()
RpcRequest::GetNextHop {
destination_hash: vec![0; 16],
},
RpcRequest::RequestPath {
destination_hash: vec![0; 16],
timeout_secs: Some(0.01),
},
RpcRequest::GetFirstHopTimeout {
destination_hash: vec![0; 16],
},
@@ -847,6 +926,8 @@ listener.close()
RpcRequest::DropAllVia {
transport_hash: vec![0; 16],
},
RpcRequest::DropPathTable,
RpcRequest::DropRecentAnnounces,
RpcRequest::DropAnnounceQueues,
RpcRequest::BlackholeIdentity {
identity_hash: vec![0; 16],
@@ -878,6 +959,44 @@ listener.close()
let _ = tx.send(TransportMessage::Shutdown).await;
}
#[tokio::test]
async fn request_path_rpc_sends_transport_request_and_awaits_result() {
let (tx, mut rx) = mpsc::channel(4);
let dest = [0x42; 16];
let handle = tokio::spawn(async move {
process_rpc_request(
RpcRequest::RequestPath {
destination_hash: dest.to_vec(),
timeout_secs: Some(1.0),
},
&tx,
)
.await
});
match rx.recv().await.expect("RequestPath message") {
TransportMessage::RequestPath { destination_hash } => {
assert_eq!(destination_hash, dest)
}
other => panic!("expected RequestPath, got {other:?}"),
}
match rx.recv().await.expect("AwaitPath message") {
TransportMessage::AwaitPath {
dest: awaited,
reply,
} => {
assert_eq!(awaited, dest);
reply.send(true).unwrap();
}
other => panic!("expected AwaitPath, got {other:?}"),
}
assert!(matches!(
handle.await.unwrap(),
RpcResponse::BoolResult(true)
));
}
fn portpicker_ephemeral() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap().port()
+5 -1
View File
@@ -42,7 +42,7 @@ use rns_runtime::rncp::{
};
const DEFAULT_TIMEOUT_SECS: f64 = 15.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
@@ -695,6 +695,9 @@ async fn run_listen(args: Args) -> ! {
}
}
}
_ = handle.shutdown.wait() => {
break;
}
}
}
@@ -702,6 +705,7 @@ async fn run_listen(args: Args) -> ! {
task.abort();
let _ = task.await;
}
listener.shutdown().await;
process::exit(0);
}
+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.");
}
+81 -17
View File
@@ -1,6 +1,6 @@
//! rnid-rs - identity create/inspect/sign/verify/encrypt/decrypt.
//!
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.4.
//! Python reference: `RNS/Utilities/rnid.py` from Reticulum 1.2.5.
mod rsg;
@@ -26,7 +26,7 @@ use rns_transport::messages::{
#[cfg(feature = "hardware")]
mod hw_commands;
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
const DEFAULT_ASPECTS: &str = "rns.id";
const PUB_EXT: &str = "pub";
const SIG_EXT: &str = "rsg";
@@ -159,6 +159,10 @@ struct Args {
#[arg(short = 'B', long)]
base32: bool,
/// Use hex-encoded input and output.
#[arg(long)]
hex: bool,
/// Print version and exit.
#[arg(long)]
version: bool,
@@ -183,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)]
@@ -196,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")]
@@ -271,8 +283,12 @@ async fn run(mut args: Args) -> ExitCode {
eprintln!("The -i, -g, -m and -M args are mutually exclusive");
return ExitCode::from(1);
}
if args.base64 && args.base32 {
eprintln!("The -b and -B args are mutually exclusive");
let encoding_count = [args.base64, args.base32, args.hex]
.into_iter()
.filter(|flag| *flag)
.count();
if encoding_count > 1 {
eprintln!("The -b, -B and --hex args are mutually exclusive");
return ExitCode::from(1);
}
@@ -858,19 +874,6 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
return ExitCode::from(6);
}
};
let Some(output_path) = args
.write
.clone()
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
else {
eprintln!("Signing requested, but no output specified");
return ExitCode::from(253);
};
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
eprintln!("{e}");
return ExitCode::from(11);
}
let signature = if args.raw {
match rsg::create_raw_signature(identity, input) {
Ok(signature) => signature.to_vec(),
@@ -888,6 +891,37 @@ fn sign_file(identity: &Identity, args: &Args) -> ExitCode {
}
}
};
if !args.raw && (args.base64 || args.base32 || args.hex) {
let encoded = if args.base64 {
URL_SAFE.encode(&signature)
} else if args.base32 {
encode_base32(&signature)
} else {
hex::encode(&signature)
};
println!("\n{}\n", wrap_rsg(encoded.as_bytes()));
println!(
"Signed file {} with {}",
input_path.display(),
pretty_hash(&identity.hash)
);
return ExitCode::SUCCESS;
}
let Some(output_path) = args
.write
.clone()
.or_else(|| Some(append_extension(input_path, SIG_EXT)))
else {
eprintln!("Signing requested, but no output specified");
return ExitCode::from(253);
};
if let Err(e) = ensure_output_allowed(&output_path, args.force) {
eprintln!("{e}");
return ExitCode::from(11);
}
if let Err(e) = write_output(&output_path, &signature, args.stdout) {
eprintln!("{e}");
return ExitCode::from(253);
@@ -1301,6 +1335,36 @@ fn encode_key_text(bytes: &[u8], args: &Args) -> String {
}
}
fn wrap_rsg(rsg: &[u8]) -> String {
const HEADER: &[u8] = b"#### Start of rsg data ";
const FOOTER: &[u8] = b" End of rsg data ####";
const ROW_WIDTH: usize = 64;
let mut header = String::from_utf8_lossy(HEADER).into_owned();
while header.len() < ROW_WIDTH {
header.push('#');
}
let mut footer = String::new();
while footer.len() + FOOTER.len() < ROW_WIDTH {
footer.push('#');
}
footer.push_str(&String::from_utf8_lossy(FOOTER));
let mut wrapped = String::new();
wrapped.push_str(&header);
wrapped.push('\n');
for chunk in rsg.chunks(ROW_WIDTH) {
wrapped.push_str(&String::from_utf8_lossy(chunk));
for _ in chunk.len()..ROW_WIDTH {
wrapped.push('=');
}
wrapped.push('\n');
}
wrapped.push_str(&footer);
wrapped
}
fn encode_base32(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let mut out = String::new();
+1 -1
View File
@@ -291,7 +291,7 @@ mod tests {
use super::*;
fn message() -> &'static [u8] {
b"Reticulum 1.2.4 rsg test payload"
b"Reticulum 1.2.5 rsg test payload"
}
fn pack_value(value: Value) -> Vec<u8> {
+73 -7
View File
@@ -27,7 +27,7 @@ const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const BLACKHOLE_APP: &str = "rnstransport.info.blackhole";
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
@@ -270,12 +270,20 @@ struct ClientCtx {
}
async fn request(ctx: &ClientCtx, req: &RpcRequest) -> Result<RpcResponse, LocalRpcFailure> {
request_with_timeout(ctx, req, ctx.timeout).await
}
async fn request_with_timeout(
ctx: &ClientCtx,
req: &RpcRequest,
timeout: std::time::Duration,
) -> Result<RpcResponse, LocalRpcFailure> {
let result = match &ctx.endpoint {
SharedInstanceRpcEndpoint::Tcp(port) => {
rpc::connect_and_request(*port, &ctx.rpc_key, req, ctx.timeout).await
rpc::connect_and_request(*port, &ctx.rpc_key, req, timeout).await
}
SharedInstanceRpcEndpoint::Unix(socket_path) => {
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, ctx.timeout).await
rpc::connect_unix_and_request(socket_path, &ctx.rpc_key, req, timeout).await
}
};
result.map_err(|source| LocalRpcFailure {
@@ -754,13 +762,73 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
_ => None,
};
let path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
let mut path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
Ok(RpcResponse::PathTable(entries)) => entries
.into_iter()
.find(|entry| entry.hash.as_slice() == dest),
_ => None,
};
let mut next_hop = next_hop;
let mut iface = iface;
if next_hop.is_none() && path_entry.is_none() {
let timeout_secs = ctx.timeout.as_secs_f64().max(0.1);
let req = RpcRequest::RequestPath {
destination_hash: dest.to_vec(),
timeout_secs: Some(timeout_secs),
};
let rpc_timeout = ctx.timeout + std::time::Duration::from_secs(1);
let found = match request_with_timeout(ctx, &req, rpc_timeout).await {
Ok(RpcResponse::BoolResult(found)) => found,
Ok(other) => {
eprintln!("rnpath-rs: unexpected response: {other:?}");
return ExitCode::from(1);
}
Err(e) => {
eprintln!("rnpath-rs: {e}");
return ExitCode::from(1);
}
};
if found {
next_hop = match request(
ctx,
&RpcRequest::GetNextHop {
destination_hash: dest.to_vec(),
},
)
.await
{
Ok(RpcResponse::HashResult(h)) => h,
Ok(other) => {
eprintln!("rnpath-rs: unexpected response: {other:?}");
return ExitCode::from(1);
}
Err(e) => {
eprintln!("rnpath-rs: {e}");
return ExitCode::from(1);
}
};
iface = match request(
ctx,
&RpcRequest::GetNextHopIfName {
destination_hash: dest.to_vec(),
},
)
.await
{
Ok(RpcResponse::StringResult(s)) => s,
_ => None,
};
path_entry = match request(ctx, &RpcRequest::GetPathTable { max_hops: None }).await {
Ok(RpcResponse::PathTable(entries)) => entries
.into_iter()
.find(|entry| entry.hash.as_slice() == dest),
_ => None,
};
}
}
println!("Destination: {}", hex::encode(dest));
match next_hop.as_ref() {
Some(h) => println!(" Next hop : {}", hex::encode(h)),
@@ -775,9 +843,7 @@ async fn query_path(ctx: &ClientCtx, dest_hex: &str) -> ExitCode {
}
if next_hop.is_none() && path_entry.is_none() {
println!(
" Note : no cached local path was found; active path requests are not implemented in rnpath yet"
);
println!(" Note : path request timed out or no path was found");
ExitCode::from(1)
} else {
ExitCode::SUCCESS
+1 -1
View File
@@ -13,7 +13,7 @@ use rns_runtime::probe::{
const DEFAULT_PROBE_SIZE: usize = 16;
const DEFAULT_TIMEOUT_SECS: f64 = 12.0;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
+2 -1
View File
@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
use clap::Parser;
use tracing_subscriber::fmt::MakeWriter;
const RETICULUM_COMPAT_VERSION: &str = "1.2.2";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
const LOG_ROTATE_BYTES: u64 = 5 * 1024 * 1024;
const RNSD_EXAMPLE_CONFIG: &str = r#"# This is an example Reticulum config 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();
+6 -4
View File
@@ -19,11 +19,11 @@ use rns_runtime::lifecycle::{ShutdownSignal, install_signal_handlers};
use rns_runtime::platform::{StoragePaths, resolve_config_dir};
use rns_runtime::rnsh::{
RnshClientConfig, RnshError, RnshListenerConfig, RnshWindowSize, rnsh_client_execute,
run_rnsh_listener,
run_rnsh_listener_with_shutdown,
};
use tokio::sync::mpsc;
const RNS_VERSION: &str = "1.2.2";
const RNS_VERSION: &str = "1.2.5";
const RNSH_PROTOCOL_VERSION: &str = "0.2.0";
const APP_NAME: &str = "rnsh";
const DEFAULT_SERVICE_NAME: &str = "default";
@@ -160,7 +160,9 @@ async fn run_listener(args: Args) -> ExitCode {
announce_period: args.announce,
};
match run_rnsh_listener(handle.transport_tx.clone(), cfg).await {
match run_rnsh_listener_with_shutdown(handle.transport_tx.clone(), cfg, handle.shutdown.clone())
.await
{
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("rnsh-rs: {e}");
@@ -872,7 +874,7 @@ mod tests {
fn version_string_uses_rust_command_name() {
assert_eq!(
format!("rnsh-rs {RNS_VERSION} (protocol {RNSH_PROTOCOL_VERSION})"),
"rnsh-rs 1.2.2 (protocol 0.2.0)"
"rnsh-rs 1.2.5 (protocol 0.2.0)"
);
}
+261 -8
View File
@@ -27,7 +27,7 @@ const DEFAULT_TIMEOUT_SECS: u64 = 5;
const REMOTE_TIMEOUT_SECS: u64 = 30;
const REMOTE_HOPS: u8 = 8;
const MGMT_APP: &str = "rnstransport.remote.management";
const RETICULUM_COMPAT_VERSION: &str = "1.2.4";
const RETICULUM_COMPAT_VERSION: &str = "1.2.5";
#[derive(Parser)]
#[command(
@@ -44,15 +44,23 @@ struct Args {
#[arg(short = 'A', long)]
announce_stats: bool,
/// Show path request frequency stats.
#[arg(short = 'P', long = "pr-stats")]
pr_stats: bool,
/// Show link table entry count.
#[arg(short, long)]
link_stats: bool,
/// Only show interfaces with active announce or path request bursts.
#[arg(short = 'B', long)]
burst: bool,
/// Display traffic totals.
#[arg(short, long)]
totals: bool,
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held.
/// Sort interfaces by rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held.
#[arg(short, long)]
sort: Option<String>,
@@ -200,6 +208,10 @@ async fn run_local_once(args: &Args) -> ExitCode {
match local_rpc_request(&endpoint, &rpc_key, &RpcRequest::GetInterfaceStats, timeout).await
{
Ok(RpcResponse::InterfaceStats(v)) => v,
Ok(RpcResponse::Error(e)) => {
eprintln!("rnstatus-rs: {e}");
return ExitCode::from(1);
}
Ok(other) => {
eprintln!("rnstatus-rs: unexpected response: {other:?}");
return ExitCode::from(1);
@@ -323,6 +335,8 @@ enum SortKey {
Announces,
AnnounceRx,
AnnounceTx,
PathRequestRx,
PathRequestTx,
Held,
}
@@ -353,10 +367,12 @@ fn parse_sort_key(value: Option<&str>) -> Result<Option<SortKey>, String> {
"announces" | "announce" => SortKey::Announces,
"arx" => SortKey::AnnounceRx,
"atx" => SortKey::AnnounceTx,
"prx" => SortKey::PathRequestRx,
"ptx" => SortKey::PathRequestTx,
"held" => SortKey::Held,
_ => {
return Err(format!(
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx or held; got {value}"
"--sort must be one of rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx or held; got {value}"
));
}
};
@@ -374,6 +390,8 @@ fn local_stat_sort_value(e: &rpc::InterfaceStatEntry, key: SortKey) -> f64 {
SortKey::Announces => e.incoming_announce_frequency + e.outgoing_announce_frequency,
SortKey::AnnounceRx => e.incoming_announce_frequency,
SortKey::AnnounceTx => e.outgoing_announce_frequency,
SortKey::PathRequestRx => e.incoming_pr_frequency,
SortKey::PathRequestTx => e.outgoing_pr_frequency,
SortKey::Held => e.held_announces as f64,
}
}
@@ -394,6 +412,24 @@ fn interface_matches_filter(name: &str, filter: Option<&str>) -> bool {
})
}
fn interface_matches_burst_filter(
name: &str,
burst_active: bool,
pr_burst_active: bool,
args: &Args,
) -> bool {
if !args.burst {
return interface_matches_filter(name, args.filter.as_deref());
}
burst_active
|| pr_burst_active
|| args.filter.as_deref().is_some_and(|filter| {
name.to_ascii_lowercase()
.contains(&filter.to_ascii_lowercase())
})
}
fn filtered_local_stats<'a>(
stats: &'a [rpc::InterfaceStatEntry],
args: &Args,
@@ -401,7 +437,14 @@ fn filtered_local_stats<'a>(
let mut entries: Vec<_> = stats
.iter()
.filter(|entry| args.all || visible_by_default(&entry.name))
.filter(|entry| interface_matches_filter(&entry.name, args.filter.as_deref()))
.filter(|entry| {
interface_matches_burst_filter(
&entry.name,
entry.burst_active,
entry.pr_burst_active,
args,
)
})
.collect();
if let Ok(Some(key)) = parse_sort_key(args.sort.as_deref()) {
entries.sort_by(|a, b| {
@@ -457,6 +500,7 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
}
if entry.incoming_announce_frequency > 0.0
|| entry.outgoing_announce_frequency > 0.0
|| entry.burst_active
{
print_announce_frequency(
entry.incoming_announce_frequency,
@@ -465,9 +509,18 @@ fn print_local_human(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
entry.announce_rate_target,
entry.announce_rate_penalty,
entry.announce_rate_grace,
burst_status_text(entry.burst_active, entry.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
entry.incoming_pr_frequency,
entry.outgoing_pr_frequency,
entry.clients,
burst_status_text(entry.pr_burst_active, entry.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(entry.rx_bytes),
@@ -514,7 +567,7 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"role\":{},\"bitrate\":{},\"mtu\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{},\"tx_drops\":{}}}",
json_str(&e.name),
e.online,
json_str(&e.mode),
@@ -531,6 +584,12 @@ fn print_local_json(stats: &[rpc::InterfaceStatEntry], link_count: Option<i64>,
e.held_announces,
e.incoming_announce_frequency,
e.outgoing_announce_frequency,
e.incoming_pr_frequency,
e.outgoing_pr_frequency,
e.burst_active,
e.burst_activated,
e.pr_burst_active,
e.pr_burst_activated,
opt_u64_json(e.clients),
opt_f64_json(e.announce_rate_target),
opt_u32_json(e.announce_rate_grace),
@@ -902,6 +961,12 @@ struct RemoteInterface {
held_announces: u64,
incoming_announce_frequency: f64,
outgoing_announce_frequency: f64,
incoming_pr_frequency: f64,
outgoing_pr_frequency: f64,
burst_active: bool,
burst_activated: f64,
pr_burst_active: bool,
pr_burst_activated: f64,
clients: Option<u64>,
announce_rate_target: Option<f64>,
announce_rate_grace: Option<u32>,
@@ -922,6 +987,8 @@ impl RemoteInterface {
}
SortKey::AnnounceRx => self.incoming_announce_frequency,
SortKey::AnnounceTx => self.outgoing_announce_frequency,
SortKey::PathRequestRx => self.incoming_pr_frequency,
SortKey::PathRequestTx => self.outgoing_pr_frequency,
SortKey::Held => self.held_announces as f64,
}
}
@@ -972,7 +1039,14 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
ifs.iter()
.filter_map(|iface| iface.as_map().map(|m| remote_interface_from_map(m)))
.filter(|iface| args.all || visible_by_default(&iface.name))
.filter(|iface| interface_matches_filter(&iface.name, args.filter.as_deref()))
.filter(|iface| {
interface_matches_burst_filter(
&iface.name,
iface.burst_active,
iface.pr_burst_active,
args,
)
})
.collect::<Vec<_>>()
})
.unwrap_or_default();
@@ -994,7 +1068,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
print!(",");
}
print!(
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
"{{\"name\":{},\"online\":{},\"mode\":{},\"bitrate\":{},\"rxb\":{},\"txb\":{},\"rxs\":{},\"txs\":{},\"announce_queue\":{},\"held_announces\":{},\"incoming_announce_frequency\":{},\"outgoing_announce_frequency\":{},\"incoming_pr_frequency\":{},\"outgoing_pr_frequency\":{},\"burst_active\":{},\"burst_activated\":{},\"pr_burst_active\":{},\"pr_burst_activated\":{},\"clients\":{},\"announce_rate_target\":{},\"announce_rate_grace\":{},\"announce_rate_penalty\":{}}}",
json_str(&iface.name),
iface.online,
iface.mode,
@@ -1010,6 +1084,12 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.held_announces,
iface.incoming_announce_frequency,
iface.outgoing_announce_frequency,
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.burst_active,
iface.burst_activated,
iface.pr_burst_active,
iface.pr_burst_activated,
opt_u64_json(iface.clients),
opt_f64_json(iface.announce_rate_target),
opt_u32_json(iface.announce_rate_grace),
@@ -1058,6 +1138,7 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
}
if iface.incoming_announce_frequency > 0.0
|| iface.outgoing_announce_frequency > 0.0
|| iface.burst_active
{
print_announce_frequency(
iface.incoming_announce_frequency,
@@ -1066,9 +1147,18 @@ fn print_remote_status(bytes: &[u8], args: &Args) -> ExitCode {
iface.announce_rate_target,
iface.announce_rate_penalty,
iface.announce_rate_grace,
burst_status_text(iface.burst_active, iface.burst_activated),
);
}
}
if args.pr_stats {
print_path_request_frequency(
iface.incoming_pr_frequency,
iface.outgoing_pr_frequency,
iface.clients,
burst_status_text(iface.pr_burst_active, iface.pr_burst_activated),
);
}
println!(
" Traffic : {} rx / {} tx",
format::pretty_size(iface.rxb),
@@ -1118,6 +1208,12 @@ fn remote_interface_from_map(m: &[(rmpv::Value, rmpv::Value)]) -> RemoteInterfac
.unwrap_or(0.0),
outgoing_announce_frequency: map_f64_or_u64(m, "outgoing_announce_frequency")
.unwrap_or(0.0),
incoming_pr_frequency: map_f64_or_u64(m, "incoming_pr_frequency").unwrap_or(0.0),
outgoing_pr_frequency: map_f64_or_u64(m, "outgoing_pr_frequency").unwrap_or(0.0),
burst_active: map_bool(m, "burst_active").unwrap_or(false),
burst_activated: map_f64_or_u64(m, "burst_activated").unwrap_or(0.0),
pr_burst_active: map_bool(m, "pr_burst_active").unwrap_or(false),
pr_burst_activated: map_f64_or_u64(m, "pr_burst_activated").unwrap_or(0.0),
clients: map_u64(m, "clients"),
announce_rate_target: map_f64_or_u64(m, "announce_rate_target"),
announce_rate_grace: map_u64(m, "announce_rate_grace")
@@ -1157,6 +1253,7 @@ fn print_announce_frequency(
target: Option<f64>,
penalty: Option<f64>,
grace: Option<u32>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
@@ -1166,7 +1263,38 @@ fn print_announce_frequency(
.unwrap_or_default();
let limits = announce_rate_limits_text(target, penalty, grace);
println!(" Announces: {outgoing_text}{per_client}");
println!(" {incoming_text} {limits}");
println!(" {incoming_text} {limits}{burst_text}");
}
fn print_path_request_frequency(
incoming: f64,
outgoing: f64,
clients: Option<u64>,
burst_text: String,
) {
let outgoing_text = format!("{}↑", format::pretty_frequency(outgoing));
let incoming_text = format!("{}↓", format::pretty_frequency(incoming));
let per_client = clients
.filter(|clients| *clients > 0)
.map(|clients| format!(" {}/c", format::pretty_frequency(outgoing / clients as f64)))
.unwrap_or_default();
println!(" Path Rqs.: {outgoing_text}{per_client}");
println!(" {incoming_text} {burst_text}");
}
fn burst_status_text(active: bool, activated: f64) -> String {
if !active || activated <= 0.0 {
return String::new();
}
let age = (unix_now() - activated).max(0.0);
format!(" burst for {}", format::pretty_time(age))
}
fn unix_now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64()
}
fn announce_rate_limits_text(
@@ -1246,6 +1374,131 @@ fn json_str(s: &str) -> String {
mod tests {
use super::*;
fn test_args() -> Args {
Args {
all: true,
announce_stats: false,
pr_stats: false,
link_stats: false,
burst: false,
totals: false,
sort: None,
reverse: false,
json: false,
config: None,
remote: None,
identity: None,
timeout: None,
discovered: false,
discovered_details: false,
monitor: false,
monitor_interval: 1.0,
version: false,
verbose: 0,
quiet: 0,
filter: None,
}
}
fn local_entry(
name: &str,
burst_active: bool,
pr_burst_active: bool,
) -> rpc::InterfaceStatEntry {
rpc::InterfaceStatEntry {
id: 1,
name: name.to_string(),
rx_bytes: 0,
tx_bytes: 0,
rx_rate: 0,
tx_rate: 0,
online: true,
bitrate: 1,
mtu: 500,
mode: "Full".to_string(),
role: "normal".to_string(),
announce_queue: None,
held_announces: 0,
incoming_announce_frequency: 0.0,
outgoing_announce_frequency: 0.0,
incoming_pr_frequency: 2.0,
outgoing_pr_frequency: 3.0,
burst_active,
burst_activated: if burst_active { 1_700_000_000.0 } else { 0.0 },
pr_burst_active,
pr_burst_activated: if pr_burst_active {
1_700_000_001.0
} else {
0.0
},
clients: None,
announce_rate_target: None,
announce_rate_grace: None,
announce_rate_penalty: None,
announce_cap: 0.0,
ifac_size: 0,
tx_drops: 0,
}
}
#[test]
fn sort_key_accepts_path_request_rates() {
assert_eq!(
parse_sort_key(Some("prx")).unwrap(),
Some(SortKey::PathRequestRx)
);
assert_eq!(
parse_sort_key(Some("ptx")).unwrap(),
Some(SortKey::PathRequestTx)
);
let entry = local_entry("SortIf", false, false);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestRx), 2.0);
assert_eq!(local_stat_sort_value(&entry, SortKey::PathRequestTx), 3.0);
}
#[test]
fn pr_and_burst_flags_parse() {
let args = Args::try_parse_from(["rnstatus-rs", "-P", "-B"]).unwrap();
assert!(args.pr_stats);
assert!(args.burst);
}
#[test]
fn burst_filter_includes_active_bursts_or_name_matches() {
let stats = vec![
local_entry("InactiveIf", false, false),
local_entry("AnnounceBurstIf", true, false),
local_entry("PrBurstIf", false, true),
local_entry("ManualMatchIf", false, false),
];
let mut args = test_args();
args.burst = true;
args.filter = Some("manual".to_string());
let names: Vec<_> = filtered_local_stats(&stats, &args)
.into_iter()
.map(|entry| entry.name.as_str())
.collect();
assert_eq!(names, vec!["AnnounceBurstIf", "PrBurstIf", "ManualMatchIf"]);
}
#[test]
fn remote_status_parser_defaults_missing_125_fields() {
let iface = remote_interface_from_map(&[
(rmpv::Value::from("name"), rmpv::Value::from("LegacyIf")),
(rmpv::Value::from("status"), rmpv::Value::from(true)),
]);
assert_eq!(iface.incoming_pr_frequency, 0.0);
assert_eq!(iface.outgoing_pr_frequency, 0.0);
assert!(!iface.burst_active);
assert_eq!(iface.burst_activated, 0.0);
assert!(!iface.pr_burst_active);
assert_eq!(iface.pr_burst_activated, 0.0);
}
#[test]
fn local_rpc_auth_failure_explains_config_mismatch_and_port_owner() {
let endpoint = SharedInstanceRpcEndpoint::Tcp(37429);
@@ -0,0 +1,145 @@
#[cfg(unix)]
use std::fs;
#[cfg(unix)]
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::process::{Child, Command, Stdio};
#[cfg(unix)]
use std::thread;
#[cfg(unix)]
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[cfg(unix)]
struct TempDir {
path: PathBuf,
}
#[cfg(unix)]
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
#[cfg(unix)]
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[cfg(unix)]
fn write_config(tmp: &TempDir) {
fs::write(
tmp.path().join("config"),
"[reticulum]\nshare_instance = No\nenable_transport = No\n\n[interfaces]\n",
)
.expect("write config");
}
#[cfg(unix)]
fn wait_until_running(child: &mut Child) -> bool {
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
if child.try_wait().expect("poll child").is_some() {
return false;
}
thread::sleep(Duration::from_millis(50));
}
true
}
#[cfg(unix)]
fn assert_sigint_exits(mut child: Child, name: &str) {
if !wait_until_running(&mut child) {
let output = child.wait_with_output().expect("collect child output");
panic!(
"{name} exited before SIGINT\nstatus: {}\nstdout:\n{}\nstderr:\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
let status = Command::new("kill")
.arg("-INT")
.arg(child.id().to_string())
.status()
.expect("send SIGINT");
assert!(status.success(), "kill -INT failed with {status}");
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if let Some(status) = child.try_wait().expect("poll child after SIGINT") {
let output = child.wait_with_output().expect("collect child output");
assert!(
status.success(),
"{name} exited unsuccessfully after SIGINT: {status}\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let output = child
.wait_with_output()
.expect("collect killed child output");
panic!(
"{name} did not exit after SIGINT\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
#[cfg(unix)]
#[test]
fn rncp_listener_exits_on_sigint() {
let tmp = TempDir::new("rncp-sigint");
write_config(&tmp);
let child = Command::new(env!("CARGO_BIN_EXE_rncp-rs"))
.arg("--config")
.arg(tmp.path())
.arg("-l")
.arg("-n")
.arg("-S")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn rncp-rs listener");
assert_sigint_exits(child, "rncp-rs");
}
#[cfg(unix)]
#[test]
fn rnsh_listener_exits_on_sigint() {
let tmp = TempDir::new("rnsh-sigint");
write_config(&tmp);
let child = Command::new(env!("CARGO_BIN_EXE_rnsh-rs"))
.arg("--config")
.arg(tmp.path())
.arg("-l")
.arg("-n")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn rnsh-rs listener");
assert_sigint_exits(child, "rnsh-rs");
}
+6 -1
View File
@@ -135,7 +135,12 @@ fn rnid_flag_conflicts_are_rejected() {
let tmp = TempDir::new("rnid-flag-conflicts");
let output = rnid(&tmp, ["-b", "-B"]);
assert_failure(&output, Some(1), "-b and -B", "base64/base32 conflict");
assert_failure(
&output,
Some(1),
"-b, -B and --hex",
"base64/base32 conflict",
);
let generated = tmp.join("identity");
let output = rnid(
@@ -0,0 +1,480 @@
use std::ffi::OsStr;
use std::fs;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use rns_identity::destination::Destination;
use rns_identity::identity::Identity;
const PROBE_APP: &str = "rnstransport.probe";
const COMMAND_TIMEOUT_SECS: &str = "4";
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
self.path.join(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct ChildGuard {
label: &'static str,
child: Option<Child>,
}
impl ChildGuard {
fn spawn<I, S>(label: &'static str, program: &str, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn child process");
Self {
label,
child: Some(child),
}
}
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
self.child
.as_mut()
.and_then(|child| child.try_wait().expect("poll child status"))
}
fn terminate_and_output_text(&mut self) -> (String, String) {
let Some(mut child) = self.child.take() else {
return ("<not started>\n".to_string(), String::new());
};
let _ = child.kill();
let output = child.wait_with_output().expect("collect child output");
output_text(&output)
}
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
fn free_tcp_ports(count: usize) -> Vec<u16> {
let listeners: Vec<TcpListener> = (0..count)
.map(|_| TcpListener::bind("127.0.0.1:0").expect("bind free tcp port"))
.collect();
listeners
.iter()
.map(|listener| listener.local_addr().expect("local addr").port())
.collect()
}
fn write_responder_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = 5151515151515151515151515151515151515151515151515151515151515151\n\
enable_transport = No\n\
respond_to_probes = Yes\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Matrix TCP Server]]\n\
type = TCPServerInterface\n\
enabled = Yes\n\
listen_ip = 127.0.0.1\n\
listen_port = {link_port}\n"
);
fs::write(tmp.join("config"), config).expect("write responder config");
}
fn write_origin_config(tmp: &TempDir, shared_port: u16, control_port: u16, link_port: u16) {
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = 5252525252525252525252525252525252525252525252525252525252525252\n\
enable_transport = No\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Matrix TCP Client]]\n\
type = TCPClientInterface\n\
enabled = Yes\n\
target_host = 127.0.0.1\n\
target_port = {link_port}\n"
);
fs::write(tmp.join("config"), config).expect("write origin config");
}
fn output_text(output: &Output) -> (String, String) {
(
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn rnstatus_json(tmp: &TempDir) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
.arg("--config")
.arg(tmp.path())
.arg("--json")
.arg("--all")
.arg("--timeout")
.arg("1")
.output()
.expect("run rnstatus-rs")
}
fn poll_shared_server(
daemon: &mut ChildGuard,
tmp: &TempDir,
deadline_after: Duration,
) -> Result<(), String> {
let deadline = Instant::now() + deadline_after;
let mut last_status = None;
let mut last_stdout = String::new();
let mut last_stderr = String::new();
while Instant::now() < deadline {
if let Some(status) = daemon.try_wait() {
return Err(format!(
"{} exited before shared server was ready: {status}",
daemon.label
));
}
let output = rnstatus_json(tmp);
last_status = output.status.code();
(last_stdout, last_stderr) = output_text(&output);
if output.status.success() {
let value: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
let ready = value
.get("interfaces")
.and_then(|v| v.as_array())
.is_some_and(|interfaces| {
interfaces.iter().any(|entry| {
entry.get("role").and_then(|v| v.as_str()) == Some("shared_server")
})
});
if ready {
return Ok(());
}
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"rnstatus-rs did not report {} shared server before the deadline\n\
last rnstatus status: {last_status:?}\n\
--- last rnstatus stdout ---\n{last_stdout}\n\
--- last rnstatus stderr ---\n{last_stderr}",
daemon.label
))
}
fn read_probe_hash(responder: &mut ChildGuard, tmp: &TempDir) -> Result<[u8; 16], String> {
let path = tmp.join("storage").join("probe_identity");
let deadline = Instant::now() + Duration::from_secs(5);
let mut last_error = String::new();
while Instant::now() < deadline {
if let Some(status) = responder.try_wait() {
return Err(format!(
"{} exited before probe identity was ready: {status}",
responder.label
));
}
match Identity::from_file(&path) {
Ok(identity) => {
return Ok(Destination::hash_from_name_and_identity(
PROBE_APP,
Some(&identity.hash),
));
}
Err(e) => last_error = e.to_string(),
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"probe identity was not readable at {}\nlast error: {last_error}",
path.display()
))
}
fn run_rnpath(origin: &TempDir, probe_hash_hex: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnpath-rs"))
.arg("--config")
.arg(origin.path())
.arg("-w")
.arg(COMMAND_TIMEOUT_SECS)
.arg(probe_hash_hex)
.output()
.expect("run rnpath-rs")
}
fn run_rnprobe(origin: &TempDir, probe_hash_hex: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnprobe-rs"))
.arg("--config")
.arg(origin.path())
.arg("--json")
.arg("-t")
.arg(COMMAND_TIMEOUT_SECS)
.arg(PROBE_APP)
.arg(probe_hash_hex)
.output()
.expect("run rnprobe-rs")
}
fn poll_command_success<F>(
label: &str,
deadline_after: Duration,
mut run: F,
) -> Result<Output, String>
where
F: FnMut() -> Output,
{
let deadline = Instant::now() + deadline_after;
let mut last_output = None;
while Instant::now() < deadline {
let output = run();
if output.status.success() {
return Ok(output);
}
last_output = Some(output);
thread::sleep(Duration::from_millis(200));
}
let Some(output) = last_output else {
return Err(format!("{label} was not run"));
};
let (stdout, stderr) = output_text(&output);
Err(format!(
"{label} did not succeed before the deadline\n\
last status: {}\n\
--- last stdout ---\n{stdout}\n\
--- last stderr ---\n{stderr}",
output.status
))
}
fn panic_with_daemon_outputs(
message: String,
responder: &mut ChildGuard,
path_origin: &mut ChildGuard,
cold_origin: &mut ChildGuard,
) -> ! {
let (responder_stdout, responder_stderr) = responder.terminate_and_output_text();
let (path_stdout, path_stderr) = path_origin.terminate_and_output_text();
let (cold_stdout, cold_stderr) = cold_origin.terminate_and_output_text();
panic!(
"{message}\n\
--- responder stdout ---\n{responder_stdout}\n\
--- responder stderr ---\n{responder_stderr}\n\
--- path origin stdout ---\n{path_stdout}\n\
--- path origin stderr ---\n{path_stderr}\n\
--- cold origin stdout ---\n{cold_stdout}\n\
--- cold origin stderr ---\n{cold_stderr}"
);
}
#[test]
fn rust_probe_destination_supports_active_path_and_probe_matrix() {
let responder_tmp = TempDir::new("rnprobe-rnpath-responder");
let path_origin_tmp = TempDir::new("rnprobe-rnpath-path-origin");
let cold_origin_tmp = TempDir::new("rnprobe-rnpath-cold-origin");
let ports = free_tcp_ports(7);
let link_port = ports[0];
write_responder_config(&responder_tmp, ports[1], ports[2], link_port);
write_origin_config(&path_origin_tmp, ports[3], ports[4], link_port);
write_origin_config(&cold_origin_tmp, ports[5], ports[6], link_port);
let mut responder = ChildGuard::spawn(
"responder rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), responder_tmp.path().as_os_str()],
);
if let Err(message) = poll_shared_server(&mut responder, &responder_tmp, Duration::from_secs(5))
{
let mut placeholder = ChildGuard {
label: "path origin rnsd-rs",
child: None,
};
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut placeholder,
&mut cold_placeholder,
);
}
let probe_hash = match read_probe_hash(&mut responder, &responder_tmp) {
Ok(hash) => hash,
Err(message) => {
let mut placeholder = ChildGuard {
label: "path origin rnsd-rs",
child: None,
};
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut placeholder,
&mut cold_placeholder,
);
}
};
let probe_hash_hex = hex::encode(probe_hash);
let mut path_origin = ChildGuard::spawn(
"path origin rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), path_origin_tmp.path().as_os_str()],
);
if let Err(message) =
poll_shared_server(&mut path_origin, &path_origin_tmp, Duration::from_secs(5))
{
let mut cold_placeholder = ChildGuard {
label: "cold origin rnsd-rs",
child: None,
};
panic_with_daemon_outputs(
message,
&mut responder,
&mut path_origin,
&mut cold_placeholder,
);
}
let mut cold_origin = ChildGuard::spawn(
"cold origin rnsd-rs",
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), cold_origin_tmp.path().as_os_str()],
);
if let Err(message) =
poll_shared_server(&mut cold_origin, &cold_origin_tmp, Duration::from_secs(5))
{
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin);
}
let rnpath = poll_command_success(
"rnpath-rs active path request",
Duration::from_secs(16),
|| run_rnpath(&path_origin_tmp, &probe_hash_hex),
);
let rnpath = match rnpath {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
let (rnpath_stdout, _rnpath_stderr) = output_text(&rnpath);
assert!(
rnpath_stdout.contains(&format!("Destination: {probe_hash_hex}")),
"rnpath-rs output did not include the requested destination\n{rnpath_stdout}"
);
assert!(
!rnpath_stdout.contains("(no known path)"),
"rnpath-rs reported no known path after active request\n{rnpath_stdout}"
);
let known_path_probe = poll_command_success(
"rnprobe-rs with rnpath-populated path",
Duration::from_secs(16),
|| run_rnprobe(&path_origin_tmp, &probe_hash_hex),
);
let known_path_probe = match known_path_probe {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
assert_probe_json_ok(&known_path_probe, &probe_hash_hex);
let cold_probe = poll_command_success(
"rnprobe-rs cold active-path probe",
Duration::from_secs(16),
|| run_rnprobe(&cold_origin_tmp, &probe_hash_hex),
);
let cold_probe = match cold_probe {
Ok(output) => output,
Err(message) => {
panic_with_daemon_outputs(message, &mut responder, &mut path_origin, &mut cold_origin)
}
};
assert_probe_json_ok(&cold_probe, &probe_hash_hex);
}
fn assert_probe_json_ok(output: &Output, expected_hash: &str) {
let (stdout, stderr) = output_text(output);
let value: serde_json::Value =
serde_json::from_str(stdout.trim()).expect("rnprobe-rs JSON output");
assert_eq!(
value.get("status").and_then(|v| v.as_str()),
Some("ok"),
"rnprobe-rs did not report ok\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert_eq!(
value.get("destination").and_then(|v| v.as_str()),
Some(expected_hash),
"rnprobe-rs returned the wrong destination\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert!(
value.get("rtt_ms").and_then(|v| v.as_f64()).is_some(),
"rnprobe-rs JSON did not include an RTT\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
}
+307
View File
@@ -0,0 +1,307 @@
use std::ffi::OsStr;
use std::fs;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_nanos();
let path = std::env::temp_dir().join(format!(
"rsreticulum-{prefix}-{}-{nonce}",
std::process::id()
));
fs::create_dir_all(&path).expect("create tempdir");
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
self.path.join(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
struct ChildGuard {
child: Option<Child>,
}
impl ChildGuard {
fn spawn<I, S>(program: &str, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn child process");
Self { child: Some(child) }
}
fn try_wait(&mut self) -> Option<std::process::ExitStatus> {
self.child
.as_mut()
.and_then(|child| child.try_wait().expect("poll child status"))
}
fn terminate_and_output(mut self) -> Output {
let mut child = self.child.take().expect("child already taken");
let _ = child.kill();
child.wait_with_output().expect("collect child output")
}
}
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
fn free_tcp_port_pair() -> (u16, u16) {
let first = TcpListener::bind("127.0.0.1:0").expect("bind first free tcp port");
let second = TcpListener::bind("127.0.0.1:0").expect("bind second free tcp port");
let first_port = first.local_addr().expect("first local addr").port();
let second_port = second.local_addr().expect("second local addr").port();
(first_port, second_port)
}
fn write_stale_python_destination_table(storage_dir: &Path, entries: usize) {
fs::create_dir_all(storage_dir).expect("create storage dir");
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock before unix epoch")
.as_secs_f64();
let mut table = rns_transport::path_table::PathTable::new();
for i in 0..entries {
let mut dest = [0u8; 16];
dest[..8].copy_from_slice(&(i as u64).to_be_bytes());
dest[8..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut packet_hash = [0u8; 32];
packet_hash[..8].copy_from_slice(&(i as u64).to_be_bytes());
packet_hash[8..16].copy_from_slice(&(entries as u64).to_be_bytes());
packet_hash[16..24].copy_from_slice(&(0xA5A5_A5A5_A5A5_A5A5u64).to_be_bytes());
packet_hash[24..].copy_from_slice(&(!i as u64).to_be_bytes());
let mut entry = rns_transport::path_table::PathEntry::new(
None,
1,
7,
rns_transport::constants::InterfaceMode::Gateway,
);
entry.timestamp = now;
entry.expires = now + 3600.0;
entry.packet_hash = Some(packet_hash);
table.insert(dest, entry);
}
let mut names = std::collections::HashMap::new();
names.insert(7u64, "Border_TCP".to_string());
rns_transport::persistence::save_python_destination_table(
&table,
&names,
&storage_dir.join("destination_table"),
)
.expect("write Python destination_table");
}
fn output_text(output: &Output) -> (String, String) {
(
String::from_utf8_lossy(&output.stdout).into_owned(),
String::from_utf8_lossy(&output.stderr).into_owned(),
)
}
fn rnstatus_json(tmp: &TempDir, timeout_secs: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_rnstatus-rs"))
.arg("--config")
.arg(tmp.path())
.arg("--json")
.arg("--all")
.arg("--timeout")
.arg(timeout_secs)
.output()
.expect("run rnstatus-rs")
}
fn poll_rnstatus_until<F>(
daemon: &mut ChildGuard,
tmp: &TempDir,
deadline_after: Duration,
timeout_secs: &str,
predicate: F,
) -> Result<(), String>
where
F: Fn(&[serde_json::Value]) -> bool,
{
let deadline = Instant::now() + deadline_after;
let mut last_status = None;
let mut last_stdout = String::new();
let mut last_stderr = String::new();
while Instant::now() < deadline {
if let Some(status) = daemon.try_wait() {
return Err(format!(
"rnsd-rs exited before rnstatus-rs succeeded: {status}"
));
}
let output = rnstatus_json(tmp, timeout_secs);
last_status = output.status.code();
(last_stdout, last_stderr) = output_text(&output);
if output.status.success() {
let value: serde_json::Value =
serde_json::from_slice(&output.stdout).expect("rnstatus-rs JSON output");
let interfaces = value
.get("interfaces")
.and_then(|v| v.as_array())
.expect("interfaces array");
if predicate(interfaces) {
return Ok(());
}
}
thread::sleep(Duration::from_millis(100));
}
Err(format!(
"rnstatus-rs did not report the expected interface before the deadline\n\
last rnstatus status: {last_status:?}\n\
--- last rnstatus stdout ---\n{last_stdout}\n\
--- last rnstatus stderr ---\n{last_stderr}"
))
}
fn panic_with_daemon_output(message: String, daemon: ChildGuard) -> ! {
let daemon_output = daemon.terminate_and_output();
let (daemon_stdout, daemon_stderr) = output_text(&daemon_output);
panic!(
"{message}\n\
--- daemon stdout ---\n{daemon_stdout}\n\
--- daemon stderr ---\n{daemon_stderr}"
);
}
#[test]
fn rnsd_rnstatus_cli_survives_stale_python_destination_table() {
let tmp = TempDir::new("rnsd-rnstatus-stale-python-table");
let (shared_port, control_port) = free_tcp_port_pair();
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = Yes\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n"
);
fs::write(tmp.join("config"), config).expect("write config");
write_stale_python_destination_table(&tmp.join("storage"), 512);
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(5),
"1",
|interfaces| {
interfaces
.iter()
.any(|entry| entry.get("role").and_then(|v| v.as_str()) == Some("shared_server"))
},
) {
panic_with_daemon_output(message, daemon);
}
}
#[test]
#[ignore = "requires network access to a public Reticulum TCP peer"]
fn rnsd_rnstatus_cli_public_tcp_testnet_smoke() {
let tmp = TempDir::new("rnsd-rnstatus-public-tcp-testnet");
let (shared_port, control_port) = free_tcp_port_pair();
let host = std::env::var("RSRETICULUM_LIVE_TCP_HOST")
.unwrap_or_else(|_| "rns.ratspeak.org".to_string());
let port = std::env::var("RSRETICULUM_LIVE_TCP_PORT")
.ok()
.and_then(|value| value.parse::<u16>().ok())
.unwrap_or(4242);
let rpc_key_hex = "5353535353535353535353535353535353535353535353535353535353535353";
let config = format!(
"[reticulum]\n\
share_instance = Yes\n\
shared_instance_type = tcp\n\
shared_instance_port = {shared_port}\n\
instance_control_port = {control_port}\n\
rpc_key = {rpc_key_hex}\n\
enable_transport = No\n\
\n\
[logging]\n\
loglevel = 1\n\
\n\
[interfaces]\n\
\n\
[[Public TCP]]\n\
type = TCPClientInterface\n\
enabled = Yes\n\
target_host = {host}\n\
target_port = {port}\n"
);
fs::write(tmp.join("config"), config).expect("write config");
let mut daemon = ChildGuard::spawn(
env!("CARGO_BIN_EXE_rnsd-rs"),
["--config".as_ref(), tmp.path().as_os_str()],
);
if let Err(message) = poll_rnstatus_until(
&mut daemon,
&tmp,
Duration::from_secs(10),
"2",
|interfaces| {
interfaces.iter().any(|entry| {
entry.get("name").and_then(|v| v.as_str()) == Some("Public TCP")
&& entry.get("online").and_then(|v| v.as_bool()) == Some(true)
})
},
) {
panic_with_daemon_output(
format!("{message}\nexpected Public TCP to come online for {host}:{port}"),
daemon,
);
}
}
+453 -189
View File
@@ -34,7 +34,7 @@ impl TransportActor {
packet.raw.clone()
};
let (parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
let (mut parsed, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok((header, offset)) => (header, offset),
Err(e) => {
tracing::warn!(
@@ -89,6 +89,8 @@ impl TransportActor {
}
}
parsed.hops = self.adjusted_inbound_hops(parsed.hops, packet.interface_id);
tracing::debug!(
pkt_type = ?parsed.flags.packet_type,
dest = %hex::encode(parsed.destination_hash),
@@ -133,13 +135,73 @@ impl TransportActor {
return;
}
// Per-interface ingress control. Record the announce and, if the
// interface is burst-limiting, hold it for later release by the
// maintenance tick rather than processing now.
//
// Bypass the hold when the announce answers an outstanding path
// request: the announce *is* the resolution, and delaying it there
// would stall the requester for no gain.
let (announce_data, validated_identity) = {
if data_offset >= raw.len() {
tracing::warn!(
dest = hex::encode(header.destination_hash),
"announce missing payload, dropping"
);
return;
}
let payload = &raw[data_offset..];
let has_ratchet = header.flags.context_flag;
tracing::debug!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
header_type = ?header.flags.header_type,
"announce payload received"
);
match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) {
Ok(announce_data) => {
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_len = announce_data.app_data.as_ref().map(|d| d.len()),
has_ratchet_key = announce_data.ratchet.is_some(),
"announce unpacked"
);
match announce_data.verify_signature(&header.destination_hash) {
Ok(validated_identity) => {
if self.blackhole_table.is_blackholed(&validated_identity.hash) {
trace!(
identity = hex::encode(validated_identity.hash),
dest = hex::encode(header.destination_hash),
"announce from blackholed identity, dropping"
);
return;
}
(announce_data, validated_identity)
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
error = %e,
"announce validation failed, dropping"
);
return;
}
}
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
error = %e,
"announce unpack failed, dropping"
);
return;
}
}
};
// Python validates the announce signature before ingress accounting,
// and only holds still-unknown destinations. Known re-announces and
// path responses for paths we already know must continue refreshing
// route state during an ingress burst.
let announced_destination_known = self.path_table.get(&header.destination_hash).is_some();
let answers_path_request = self.path_requests.contains_key(&header.destination_hash)
|| self
.discovery_path_requests
@@ -147,6 +209,7 @@ impl TransportActor {
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.received_announce();
if !is_from_local_client
&& !announced_destination_known
&& !answers_path_request
&& entry.ingress.should_ingress_limit()
{
@@ -165,6 +228,36 @@ impl TransportActor {
}
}
let known_public_key = self
.recent_announces
.get(&header.destination_hash)
.and_then(|entry| entry.public_key);
if let Err(e) = announce_data.validate_destination_binding(
&header.destination_hash,
&validated_identity,
known_public_key.as_ref(),
) {
tracing::warn!(
dest = hex::encode(header.destination_hash),
error = %e,
"announce validation failed, dropping"
);
return;
}
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_present = announce_data.app_data.is_some(),
"announce validated"
);
let announce_app_data = announce_data.app_data.clone();
let announce_public_key = Some(validated_identity.get_public_key());
let announce_ratchet = announce_data.ratchet;
let announce_name_hash = announce_data.name_hash;
let announce_identity_hash = Some(validated_identity.hash);
let announce_random_hash = announce_data.random_hash;
let mut rate_blocked = false;
// Per-interface rate limiting is opt-in and suppresses rebroadcast
@@ -206,95 +299,6 @@ impl TransportActor {
self.rate_table.record(header.destination_hash);
}
let (
announce_app_data,
announce_public_key,
announce_ratchet,
announce_name_hash,
announce_identity_hash,
announce_random_hash,
) = {
if data_offset >= raw.len() {
tracing::warn!(
dest = hex::encode(header.destination_hash),
"announce missing payload, dropping"
);
return;
}
let payload = &raw[data_offset..];
let has_ratchet = header.flags.context_flag;
tracing::debug!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
header_type = ?header.flags.header_type,
"announce payload received"
);
match rns_identity::announce::AnnounceData::unpack(payload, has_ratchet) {
Ok(announce_data) => {
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_len = announce_data.app_data.as_ref().map(|d| d.len()),
has_ratchet_key = announce_data.ratchet.is_some(),
"announce unpacked"
);
let known_public_key = self
.recent_announces
.get(&header.destination_hash)
.and_then(|entry| entry.public_key);
match announce_data.validate_with_known_key(
&header.destination_hash,
known_public_key.as_ref(),
) {
Ok(validated_identity) => {
if self.blackhole_table.is_blackholed(&validated_identity.hash) {
trace!(
identity = hex::encode(validated_identity.hash),
dest = hex::encode(header.destination_hash),
"announce from blackholed identity, dropping"
);
return;
}
tracing::debug!(
dest = hex::encode(header.destination_hash),
app_data_present = announce_data.app_data.is_some(),
"announce validated"
);
(
announce_data.app_data.clone(),
Some(validated_identity.get_public_key()),
announce_data.ratchet,
announce_data.name_hash,
Some(validated_identity.hash),
announce_data.random_hash,
)
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
error = %e,
"announce validation failed, dropping"
);
return;
}
}
}
Err(e) => {
tracing::warn!(
dest = hex::encode(header.destination_hash),
payload_len = payload.len(),
has_ratchet = has_ratchet,
error = %e,
"announce unpack failed, dropping"
);
return;
}
}
};
let iface_mode = self
.interfaces
.get(&interface_id)
@@ -342,7 +346,11 @@ impl TransportActor {
.get(&header.destination_hash)
.map(|entry| entry.random_blobs.clone())
.unwrap_or_default();
let should_add = if let Some(existing) = self.path_table.get(&header.destination_hash) {
let suppressed =
self.is_path_interface_suppressed(header.destination_hash, interface_id, now_f64());
let should_add = if suppressed {
false
} else if let Some(existing) = self.path_table.get(&header.destination_hash) {
let random_seen = existing.has_random_blob(&announce_random_hash);
let path_timebase = path_timebase_from_random_blobs(existing.random_blobs.iter());
if header.hops <= existing.hops {
@@ -369,10 +377,12 @@ impl TransportActor {
&& header.hops < PATHFINDER_M
{
let now = now_f64();
let mut rebroadcast_raw = raw.to_vec();
if rebroadcast_raw.len() >= 2 {
rebroadcast_raw[1] = header.hops.saturating_add(1);
}
let rebroadcast_raw = self.transport_announce_from_raw(
raw,
header.destination_hash,
header.hops,
rns_wire::context::PacketContext::None,
);
let announce_entry = crate::announce::AnnounceEntry {
timestamp: now,
retransmit_timeout: if is_from_local_client {
@@ -380,7 +390,11 @@ impl TransportActor {
} else {
now + rand_window()
},
retries: 0,
retries: if is_from_local_client {
PATHFINDER_R
} else {
0
},
received_from: header.transport_id.unwrap_or(header.destination_hash),
hops: header.hops,
packet_raw: rebroadcast_raw,
@@ -411,8 +425,23 @@ impl TransportActor {
entry.random_blobs = random_blobs;
// Store the announce packet hash so a later CacheRequest for this
// destination can replay the exact announce bytes.
entry.packet_hash = Some(rns_wire::hash::packet_hash(raw, header.flags.header_type));
let announce_packet_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
entry.packet_hash = Some(announce_packet_hash);
let tunnel_path = crate::tunnel::TunnelPath {
timestamp: entry.timestamp,
next_hop: entry.next_hop,
hops: entry.hops,
expires: entry.expires,
random_blobs: entry.random_blobs.iter().copied().collect(),
packet_hash: entry.packet_hash,
};
self.path_table.insert(header.destination_hash, entry);
if let Some(tunnel) = self.tunnel_table.get_mut_by_interface(interface_id) {
tunnel
.tunnel_paths
.insert(header.destination_hash, tunnel_path);
tunnel.expires = now_f64() + TUNNEL_TIMEOUT as f64;
}
self.state_dirty = true;
// Wake any callers waiting on a path for this destination.
self.fire_path_waiters(&header.destination_hash);
@@ -441,8 +470,11 @@ impl TransportActor {
dest = hex::encode(header.destination_hash),
hops = header.hops,
announce_emitted,
interface_id,
suppressed,
"ignoring replayed or stale announce"
);
return;
}
// Diagnostics + identity cache. `retained` pins survive re-announce so
@@ -568,7 +600,7 @@ impl TransportActor {
let from_local_client = self.is_local_client_interface(interface_id);
let for_local_client = self
.path_table
.get(&header.destination_hash)
.get_live(&header.destination_hash)
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
let path_request_dest = Self::path_request_dest_hash();
@@ -589,15 +621,6 @@ impl TransportActor {
}
}
// Reverse entries only exist to route proofs back through us, so a
// non-transport node has no reason to keep one unless it is acting for
// a local shared client.
if self.is_transport_enabled || from_local_client {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table
.insert(pkt_hash, interface_id, header.hops);
}
if self.route_link_packet_via_link_table(raw, header, interface_id, "data") {
return;
}
@@ -669,28 +692,6 @@ impl TransportActor {
return;
}
if header.context == rns_wire::context::PacketContext::PathResponse {
let iface_mode = self
.interfaces
.get(&interface_id)
.map(|e| e.mode)
.unwrap_or(InterfaceMode::Gateway);
let entry = crate::path_table::PathEntry::new(
Some(header.destination_hash),
header.hops,
interface_id,
iface_mode,
);
self.path_table.insert(header.destination_hash, entry);
self.state_dirty = true;
self.fire_path_waiters(&header.destination_hash);
debug!(
dest = hex::encode(header.destination_hash),
"path learned from PathResponse"
);
return;
}
if header.context == rns_wire::context::PacketContext::CacheRequest {
self.handle_cache_request(raw, header, interface_id);
return;
@@ -717,20 +718,29 @@ impl TransportActor {
return;
}
if self.is_transport_enabled || from_local_client || for_local_client {
if let Some(path) = self.path_table.get(&header.destination_hash) {
let target_interface = path.interface_id;
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
"data packet forwarded"
);
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
raw,
header,
interface_id,
from_local_client,
for_local_client,
) {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table.insert_with_outbound(
pkt_hash,
interface_id,
header.hops,
Some(target_interface),
);
self.send_to_interface(target_interface, &forwarded);
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
path.touch();
}
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
"data packet forwarded"
);
}
}
@@ -743,16 +753,20 @@ impl TransportActor {
let from_local_client = self.is_local_client_interface(interface_id);
let for_local_client = self
.path_table
.get(&header.destination_hash)
.get_live(&header.destination_hash)
.is_some_and(|path| self.is_local_client_interface(path.interface_id));
if self.is_transport_enabled || from_local_client {
let pkt_hash = rns_wire::hash::truncated_packet_hash(raw, header.flags.header_type);
self.reverse_table
.insert(pkt_hash, interface_id, header.hops);
}
let link_request_for_this_instance = header.transport_id.is_none()
|| header
.transport_id
.zip(self.transport_identity_hash)
.is_some_and(|(packet_transport_id, our_transport_id)| {
packet_transport_id == our_transport_id
});
if self.local_destinations.contains(&header.destination_hash) {
if self.local_destinations.contains(&header.destination_hash)
&& link_request_for_this_instance
{
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::LinkRequest {
raw: raw.clone(),
@@ -766,18 +780,22 @@ impl TransportActor {
return;
}
if let Some(path) = (self.is_transport_enabled || from_local_client || for_local_client)
.then(|| self.path_table.get(&header.destination_hash))
.flatten()
{
let target_interface = path.interface_id;
if let Some((target_interface, forwarded)) = self.transport_forward_candidate(
raw,
header,
interface_id,
from_local_client,
for_local_client,
) {
let Some(path) = self.path_table.get_live(&header.destination_hash) else {
return;
};
let remaining_hops = path.hops;
let next_hop = path.next_hop;
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
}
self.send_to_interface(target_interface, &forwarded);
if let Some(path) = self.path_table.get_live_mut(&header.destination_hash) {
path.touch();
}
// Cache the relay so the matching LRPROOF can be routed back to
// the initiator without a fresh path lookup. Proof timeout scales
@@ -824,6 +842,92 @@ impl TransportActor {
}
}
fn transport_forward_candidate(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
interface_id: InterfaceId,
from_local_client: bool,
for_local_client: bool,
) -> Option<(InterfaceId, Vec<u8>)> {
let path = self.path_table.get_live(&header.destination_hash)?;
if path.interface_id == interface_id && !for_local_client {
return None;
}
let may_forward_for_shared_client = from_local_client || for_local_client;
let addressed_to_us = header
.transport_id
.zip(self.transport_identity_hash)
.is_some_and(|(packet_transport_id, our_transport_id)| {
packet_transport_id == our_transport_id
});
// Upstream Transport only relays in-transport packets when the Header2
// transport id names this instance. Shared-instance local-client edges
// are the exception: they are allowed to use the local path cache even
// when packets arrive without normal transport wrapping.
if may_forward_for_shared_client && header.transport_id.is_some() && !addressed_to_us {
return None;
}
if !may_forward_for_shared_client && (!self.is_transport_enabled || !addressed_to_us) {
return None;
}
let forwarded = self.rewrite_forwarded_transport_packet(raw, header, path)?;
Some((path.interface_id, forwarded))
}
fn rewrite_forwarded_transport_packet(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
path: &crate::path_table::PathEntry,
) -> Option<Vec<u8>> {
let payload_offset = header.size();
if raw.len() < payload_offset {
return None;
}
if path.hops > 1 {
let next_hop = path.next_hop?;
let mut flags = header.flags;
flags.header_type = rns_wire::flags::HeaderType::Header2;
flags.transport_type = rns_wire::flags::TransportType::Transport;
let new_header = rns_wire::header::PacketHeader {
flags,
hops: header.hops,
transport_id: Some(next_hop),
destination_hash: header.destination_hash,
context: header.context,
};
let mut forwarded = new_header.pack();
forwarded.extend_from_slice(&raw[payload_offset..]);
Some(forwarded)
} else if path.hops == 1 {
let mut flags = header.flags;
flags.header_type = rns_wire::flags::HeaderType::Header1;
flags.transport_type = rns_wire::flags::TransportType::Broadcast;
let new_header = rns_wire::header::PacketHeader {
flags,
hops: header.hops,
transport_id: None,
destination_hash: header.destination_hash,
context: header.context,
};
let mut forwarded = new_header.pack();
forwarded.extend_from_slice(&raw[payload_offset..]);
Some(forwarded)
} else {
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
Some(forwarded)
}
}
fn process_proof(
&mut self,
raw: &bytes::Bytes,
@@ -843,7 +947,9 @@ impl TransportActor {
.get(&header.destination_hash)
.is_some_and(|entry| self.is_local_client_interface(entry.receiving_interface));
if let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash) {
if header.context != rns_wire::context::PacketContext::Lrproof
&& let Some(receipt) = self.receipt_table.get_mut(&header.destination_hash)
{
let rtt = receipt
.get_rtt()
.or_else(|| Some(receipt.sent_at.elapsed()));
@@ -878,38 +984,49 @@ impl TransportActor {
// Link-request proofs route back via the link_table to the interface
// the original request arrived on.
//
// Hop-count note: proofs start at hops=0 at the destination. Python
// auto-increments hops on receipt; we do not, so the equivalence is
// `hops+1 == remaining_hops` here and we bump hops on forward so the
// next relay sees the expected value.
// Proofs start at hops=0 at the destination. We normalise inbound
// hops before dispatch, matching Python Transport's increment-on-
// receive rule, so the proof must equal the remaining hops recorded
// when the request was forwarded.
if header.context == rns_wire::context::PacketContext::Lrproof {
if self.is_transport_enabled || from_local_client || for_local_client_link {
if let Some(link_entry) = self.link_table.get(&header.destination_hash) {
let expected_hops = link_entry.remaining_hops;
let outbound_interface = link_entry.interface_id;
let target_interface = link_entry.receiving_interface;
let destination_hash = link_entry.destination_hash;
// Require that the proof arrived on the same interface we
// forwarded the request to; a mismatch is either a routing
// change or a spoof and must not be relayed.
let hops_match = if expected_hops == 0 {
header.hops == 0
} else {
header.hops.saturating_add(1) == expected_hops
};
let hops_match = header.hops == expected_hops;
if hops_match && _interface_id == outbound_interface {
if !self.validate_transit_lrproof(raw, header, link_entry) {
return;
}
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
if !self.packet_hashlist.insert(pkt_hash) {
trace!(
link_id = hex::encode(header.destination_hash),
"duplicate LRPROOF dropped after link-table claim"
);
return;
}
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
forwarded[1] = header.hops;
}
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
entry.validated = true;
}
self.send_to_interface(target_interface, &forwarded);
if !self.is_shared_instance {
self.use_destination(&destination_hash);
}
debug!(
link_id = hex::encode(header.destination_hash),
via_interface = target_interface,
hops = header.hops + 1,
hops = header.hops,
"link proof (LRPROOF) routed via link table"
);
return;
@@ -918,7 +1035,7 @@ impl TransportActor {
link_id = hex::encode(header.destination_hash),
expected_hops,
actual_hops = header.hops,
"link proof hop mismatch, not transporting (expected hops+1 == remaining_hops)"
"link proof hop mismatch, not transporting"
);
} else {
warn!(
@@ -934,13 +1051,18 @@ impl TransportActor {
// Fall through to local-pending-link delivery when link_table
// didn't claim the proof.
if let Some(tx) = self.destination_channels.get(&header.destination_hash) {
if let Err(e) = tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
raw: raw.clone(),
interface_id: _interface_id,
}) {
let delivered =
tx.try_send(crate::link_messages::DestinationEvent::InboundPacket {
raw: raw.clone(),
interface_id: _interface_id,
});
if let Err(e) = delivered {
self.channel_drops += 1;
warn!(dest = hex::encode(header.destination_hash), drops = self.channel_drops, err = %e,
"failed to deliver LRPROOF to local pending link (channel full)");
} else {
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
self.packet_hashlist.insert(pkt_hash);
}
}
return;
@@ -966,7 +1088,11 @@ impl TransportActor {
);
} else {
let target_interface = reverse_entry.receiving_interface;
self.send_to_interface(target_interface, raw);
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
@@ -976,7 +1102,11 @@ impl TransportActor {
}
} else {
let target_interface = reverse_entry.receiving_interface;
self.send_to_interface(target_interface, raw);
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops;
}
self.send_to_interface(target_interface, &forwarded);
trace!(
dest = hex::encode(header.destination_hash),
via_interface = target_interface,
@@ -1023,10 +1153,43 @@ impl TransportActor {
return false;
}
let target_interface = if interface_id == entry.receiving_interface {
entry.interface_id
let target_interface = if entry.interface_id == entry.receiving_interface {
if header.hops == entry.remaining_hops || header.hops == entry.taken_hops {
entry.interface_id
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
remaining_hops = entry.remaining_hops,
taken_hops = entry.taken_hops,
"link packet hop mismatch, not transporting"
);
return true;
}
} else if interface_id == entry.receiving_interface {
if header.hops == entry.taken_hops {
entry.interface_id
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
expected_hops = entry.taken_hops,
"link packet initiator-side hop mismatch, not transporting"
);
return true;
}
} else if interface_id == entry.interface_id {
entry.receiving_interface
if header.hops == entry.remaining_hops {
entry.receiving_interface
} else {
trace!(
link_id = hex::encode(header.destination_hash),
actual_hops = header.hops,
expected_hops = entry.remaining_hops,
"link packet destination-side hop mismatch, not transporting"
);
return true;
}
} else {
warn!(
link_id = hex::encode(header.destination_hash),
@@ -1040,7 +1203,26 @@ impl TransportActor {
let mut forwarded = raw.to_vec();
if forwarded.len() >= 2 {
forwarded[1] = header.hops.saturating_add(1);
forwarded[1] = header.hops;
}
let skip_hashlist = matches!(
header.context,
rns_wire::context::PacketContext::Keepalive
| rns_wire::context::PacketContext::Resource
| rns_wire::context::PacketContext::ResourceReq
| rns_wire::context::PacketContext::ResourcePrf
| rns_wire::context::PacketContext::CacheRequest
| rns_wire::context::PacketContext::Channel
);
if !skip_hashlist {
let pkt_hash = rns_wire::hash::packet_hash(raw, header.flags.header_type);
if !self.packet_hashlist.insert(pkt_hash) {
trace!(
link_id = hex::encode(header.destination_hash),
packet_kind, "duplicate link-table packet dropped after claim"
);
return true;
}
}
if let Some(entry) = self.link_table.get_mut(&header.destination_hash) {
entry.timestamp = now_f64();
@@ -1049,10 +1231,92 @@ impl TransportActor {
trace!(
link_id = hex::encode(header.destination_hash),
via_interface = target_interface,
hops = header.hops.saturating_add(1),
hops = header.hops,
packet_kind,
"link packet routed via link table"
);
true
}
fn validate_transit_lrproof(
&self,
raw: &[u8],
header: &rns_wire::header::PacketHeader,
link_entry: &crate::link_table::LinkEntry,
) -> bool {
let payload_offset = header.size();
if raw.len() < payload_offset {
warn!(
link_id = hex::encode(header.destination_hash),
raw_len = raw.len(),
"link proof missing payload, not transporting"
);
return false;
}
let proof_data = &raw[payload_offset..];
if proof_data.len() != 96 && proof_data.len() != 99 {
warn!(
link_id = hex::encode(header.destination_hash),
proof_len = proof_data.len(),
"malformed link request proof length, not transporting"
);
return false;
}
let mut signature = [0u8; 64];
signature.copy_from_slice(&proof_data[..64]);
let responder_x25519_pub = &proof_data[64..96];
let signalling = if proof_data.len() == 99 {
&proof_data[96..99]
} else {
&[]
};
let Some(destination_public_key) = self
.recent_announces
.get(&link_entry.destination_hash)
.and_then(|announce| announce.public_key)
else {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
"link request proof has no known destination identity, not transporting"
);
return false;
};
let mut destination_ed25519 = [0u8; 32];
destination_ed25519.copy_from_slice(&destination_public_key[32..64]);
let verify_key =
match rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&destination_ed25519) {
Ok(key) => key,
Err(err) => {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
error = %err,
"link request proof destination identity is invalid, not transporting"
);
return false;
}
};
let mut signed_data = Vec::with_capacity(16 + 32 + 32 + signalling.len());
signed_data.extend_from_slice(&header.destination_hash);
signed_data.extend_from_slice(responder_x25519_pub);
signed_data.extend_from_slice(&destination_ed25519);
signed_data.extend_from_slice(signalling);
if verify_key.verify(&signed_data, &signature).is_ok() {
true
} else {
warn!(
link_id = hex::encode(header.destination_hash),
destination = hex::encode(link_entry.destination_hash),
"invalid link request proof signature, not transporting"
);
false
}
}
}
+210 -14
View File
@@ -30,6 +30,8 @@ impl TransportActor {
self.path_table.cull_expired_batch(100);
self.reverse_table.cull_expired_batch(100);
self.tunnel_table.cull_expired_batch(50);
self.cull_stale_tunnel_paths(now);
self.cull_path_interface_suppressions(now);
// Drop entries pointing to interfaces that have gone away —
// those routes could never be used anyway.
@@ -38,17 +40,22 @@ impl TransportActor {
self.reverse_table.cull_dead_interfaces(&active_interfaces);
self.link_table.cull_dead_interfaces(&active_interfaces);
// An unvalidated link whose proof window elapsed means the
// cached path is probably stale — expire it and re-resolve so
// the next attempt doesn't hammer a dead route.
let (_, expired_dests) = self.link_table.cull_stale(LINK_TIMEOUT);
for dest_hash in expired_dests {
self.path_table.expire(&dest_hash);
self.on_path_request(dest_hash);
debug!(
dest = hex::encode(dest_hash),
"unvalidated link expired -- path expired and re-discovery triggered"
);
// Failed link establishment can mean either a stale path or a
// topology change. Queue rediscovery so automated path requests
// are bounded and throttled like upstream Reticulum 1.2.5.
let (_, expired_links) = self.link_table.cull_stale(LINK_TIMEOUT);
let mut queued_dests = HashSet::new();
for expired_link in expired_links {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now)
{
if queued_dests.insert(request.destination_hash) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
}
// Cull may have removed path/tunnel entries — flag for save so
@@ -151,17 +158,170 @@ impl TransportActor {
self.expire_path_waiters(now);
// Drop pending path-request markers older than 30 s so a retried
// request isn't treated as "still in flight".
self.path_requests.retain(|_, last| now - *last < 30.0);
// Drop pending path-request markers after the upstream gate timeout.
self.path_requests
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
self.discovery_path_requests
.retain(|_, request| now < request.timeout);
self.discovery_pr_tags
.retain(|_, last| now - *last < PATH_REQUEST_GATE_TIMEOUT);
self.process_pending_discovery_path_requests(now);
self.process_announce_queues(now);
}
pub(super) fn queue_discovery_path_request(
&mut self,
destination_hash: [u8; 16],
blocked_interface: Option<InterfaceId>,
now: f64,
) -> bool {
if self.pending_discovery_prs.len() >= MAX_QUEUED_DISCOVERY_PRS {
trace!(
dest = hex::encode(destination_hash),
"dropping queued discovery path request because queue is full"
);
return false;
}
let was_empty = self.pending_discovery_prs.is_empty();
self.pending_discovery_prs
.push_back(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
});
if was_empty {
self.last_discovery_pr_tx = now;
}
true
}
pub(super) fn process_pending_discovery_path_requests(&mut self, now: f64) {
if self.pending_discovery_prs.is_empty() {
return;
}
if now - self.last_discovery_pr_tx < DISCOVERY_PR_TX_THROTTLE {
return;
}
let Some(request) = self.pending_discovery_prs.pop_front() else {
return;
};
self.last_discovery_pr_tx = now;
if let Some(blocked_interface) = request.blocked_interface {
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| {
if id == blocked_interface || !entry.direction.outbound {
None
} else {
Some(id)
}
})
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, None, false);
}
} else {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let ids: Vec<InterfaceId> = self
.interfaces
.iter()
.filter_map(|(&id, entry)| entry.direction.outbound.then_some(id))
.collect();
for id in ids {
self.send_path_request(request.destination_hash, id, Some(&request_tag), false);
}
}
}
#[cfg(test)]
pub(super) fn handle_expired_unvalidated_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) {
if let Some(request) = self.rediscovery_request_for_expired_link(expired_link, now) {
self.queue_discovery_path_request(
request.destination_hash,
request.blocked_interface,
now,
);
}
}
fn rediscovery_request_for_expired_link(
&mut self,
expired_link: crate::link_table::ExpiredLink,
now: f64,
) -> Option<PendingDiscoveryPathRequest> {
let destination_hash = expired_link.destination_hash;
let last_path_request = self
.path_requests
.get(&destination_hash)
.copied()
.unwrap_or(0.0);
let path_request_throttle = now - last_path_request < PATH_REQUEST_MI;
let mut blocked_interface = None;
let mut should_request = false;
if !self.path_table.has_path(&destination_hash) {
should_request = true;
} else if !path_request_throttle {
if expired_link.taken_hops == 0 {
should_request = true;
} else if self.path_table.hops_to(&destination_hash) == Some(1)
|| expired_link.taken_hops == 1
{
should_request = true;
blocked_interface = Some(expired_link.receiving_interface);
self.mark_failed_link_path_unresponsive(&expired_link);
}
}
if !should_request {
return None;
}
if !self.is_transport_enabled {
self.path_table.expire(&destination_hash);
}
debug!(
dest = hex::encode(destination_hash),
blocked_interface, "unvalidated link expired -- queued re-discovery"
);
Some(PendingDiscoveryPathRequest {
destination_hash,
blocked_interface,
})
}
fn mark_failed_link_path_unresponsive(
&mut self,
expired_link: &crate::link_table::ExpiredLink,
) {
if !self.is_transport_enabled {
return;
}
let receiving_is_boundary = self
.interfaces
.get(&expired_link.receiving_interface)
.is_some_and(|entry| entry.mode == InterfaceMode::Boundary);
if !receiving_is_boundary {
self.path_table
.set_state(expired_link.destination_hash, PathState::Unresponsive);
}
}
/// Called on background → foreground. Resets every `last_*_check` so the
/// next `on_tick` runs all maintenance paths in one go.
pub(super) fn on_resume(&mut self) {
@@ -271,6 +431,42 @@ impl TransportActor {
}
}
pub(super) fn cull_stale_tunnel_paths(&mut self, now: f64) {
let mut removed = 0usize;
for (tunnel_id, tunnel) in self.tunnel_table.iter_mut() {
let stale: Vec<[u8; 16]> = tunnel
.tunnel_paths
.iter()
.filter_map(|(dest_hash, tunnel_path)| {
if now > tunnel_path.timestamp + TUNNEL_PATH_TIMEOUT as f64 {
return Some(*dest_hash);
}
let active = self.path_table.get_live(dest_hash)?;
let current_timebase =
path_timebase_from_random_blobs(active.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
(current_timebase > tunnel_timebase).then_some(*dest_hash)
})
.collect();
for dest_hash in stale {
tunnel.tunnel_paths.remove(&dest_hash);
removed += 1;
debug!(
dest = hex::encode(dest_hash),
tunnel = hex::encode(&tunnel_id[..16]),
"removed stale tunnel path"
);
}
}
if removed > 0 {
self.state_dirty = true;
}
}
/// Sweep `recent_announces`. Keep retained + pathed entries; reap the
/// rest past `DESTINATION_TIMEOUT` (7 days). No count cap.
pub(super) fn cleanup_known_destinations(&mut self, now: f64) {
File diff suppressed because it is too large. Load diff
+117 -79
View File
@@ -57,7 +57,7 @@ impl TransportActor {
self.broadcast_on_interfaces(&request.raw, None);
}
rns_wire::flags::DestinationType::Single | rns_wire::flags::DestinationType::Link => {
if let Some(path) = self.path_table.get(&request.destination_hash) {
if let Some(path) = self.path_table.get_live(&request.destination_hash) {
let target_interface = path.interface_id;
let path_hops = path.hops;
let path_next_hop = path.next_hop;
@@ -112,8 +112,8 @@ impl TransportActor {
// Touch the path so an actively-used route isn't culled
// for staleness while traffic is still flowing on it.
if let Some(path) = self.path_table.get_mut(&request.destination_hash) {
path.timestamp = now_f64();
if let Some(path) = self.path_table.get_live_mut(&request.destination_hash) {
path.touch();
}
} else {
let iface_names: Vec<&str> = self
@@ -128,7 +128,7 @@ impl TransportActor {
"outbound: no path, broadcasting"
);
self.broadcast_on_interfaces(&request.raw, None);
self.on_path_request(request.destination_hash);
self.on_automatic_path_request(request.destination_hash);
}
}
}
@@ -283,6 +283,10 @@ impl TransportActor {
return;
};
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.received_path_request();
}
let now = now_f64();
let mut unique_tag = Vec::with_capacity(32);
unique_tag.extend_from_slice(&requested_dest);
@@ -321,7 +325,7 @@ impl TransportActor {
}
if !is_from_local_client {
if let Some(path) = self.path_table.get(&requested_dest) {
if let Some(path) = self.path_table.get_live(&requested_dest) {
if self.is_local_client_interface(path.interface_id) {
self.pending_local_path_requests
.insert(requested_dest, interface_id);
@@ -333,7 +337,7 @@ impl TransportActor {
// shared instance's path cache even when the instance is not a transport
// node. Ordinary peers still require transport mode.
if let Some(path) = (self.is_transport_enabled || is_from_local_client)
.then(|| self.path_table.get(&requested_dest))
.then(|| self.path_table.get_live(&requested_dest))
.flatten()
{
let requestor_is_next_hop =
@@ -424,29 +428,39 @@ impl TransportActor {
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, false);
} else if self.is_transport_enabled && should_search_unknown {
let should_forward = match self.discovery_path_requests.entry(requested_dest) {
std::collections::hash_map::Entry::Occupied(_) => {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
false
}
std::collections::hash_map::Entry::Vacant(entry) => {
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
entry.insert(DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
});
true
}
};
if should_forward {
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
if self.discovery_path_requests.contains_key(&requested_dest) {
debug!(
dest = %hex::encode(requested_dest),
"not forwarding path request — discovery request is already waiting"
);
return;
}
let ingress_limited = self
.interfaces
.get_mut(&interface_id)
.is_some_and(|iface| iface.ingress.should_ingress_limit_pr());
if ingress_limited {
debug!(
dest = %hex::encode(requested_dest),
interface_id,
"not forwarding recursive path request — ingress PR burst active"
);
return;
}
debug!(
dest = %hex::encode(requested_dest),
"forwarding path request on other interfaces"
);
self.discovery_path_requests.insert(
requested_dest,
DiscoveryPathRequest {
requesting_interface: interface_id,
timeout: now + PATH_REQUEST_TIMEOUT,
},
);
self.forward_path_request(requested_dest, Some(interface_id), tag_bytes, true);
} else if self.has_local_client_interfaces() {
debug!(
dest = %hex::encode(requested_dest),
@@ -501,16 +515,61 @@ impl TransportActor {
raw
}
fn send_path_request(
pub(super) fn send_path_request(
&mut self,
destination_hash: [u8; 16],
interface_id: InterfaceId,
tag: Option<&[u8]>,
_recursive: bool,
recursive: bool,
) {
let raw = self.build_path_request_packet(destination_hash, tag);
let now = now_f64();
{
let Some(entry) = self.interfaces.get_mut(&interface_id) else {
return;
};
if !entry.direction.outbound {
return;
}
if recursive {
if entry.ingress.should_egress_limit_pr() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — egress PR limit active"
);
return;
}
if !entry.announce_queue.is_empty() {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce queue is not empty"
);
return;
}
if now < entry.announce_allowed_at {
trace!(
dest = %hex::encode(destination_hash),
interface_id,
"skipping recursive path request — announce cap window active"
);
return;
}
let bitrate = entry.bitrate.max(1) as f64;
let tx_time = (raw.len() as f64 * 8.0) / bitrate;
let wait_time = tx_time / entry.announce_cap.max(0.001);
entry.announce_allowed_at = now + wait_time;
}
}
self.send_to_interface(interface_id, &raw);
self.path_requests.insert(destination_hash, now_f64());
if let Some(entry) = self.interfaces.get_mut(&interface_id) {
entry.ingress.sent_path_request();
}
self.path_requests.insert(destination_hash, now);
}
fn forward_path_request(
@@ -537,60 +596,29 @@ impl TransportActor {
}
pub(super) fn on_path_request(&mut self, destination_hash: [u8; 16]) {
let now = now_f64();
if let Some(last) = self.path_requests.get(&destination_hash) {
if now - last < PATH_REQUEST_MI {
return;
}
}
self.path_requests.insert(destination_hash, now);
self.broadcast_path_request(destination_hash);
}
pub(super) fn on_automatic_path_request(&mut self, destination_hash: [u8; 16]) {
if self.path_table.has_path(&destination_hash) {
return;
}
if let Some(last) = self.path_requests.get(&destination_hash) {
if now_f64() - last < PATH_REQUEST_MI {
return;
}
}
self.broadcast_path_request(destination_hash);
}
// Python Transport.request_path sends a PLAIN packet to the
// rnstransport.path.request destination. The payload is the requested
// destination hash, optionally followed by the transport identity hash,
// and a random tag used for request deduplication.
fn broadcast_path_request(&mut self, destination_hash: [u8; 16]) {
let mut request_tag = [0u8; 16];
{
use rand::RngCore;
rand::thread_rng().fill_bytes(&mut request_tag);
}
let mut request_data = Vec::with_capacity(48);
request_data.extend_from_slice(&destination_hash);
if self.is_transport_enabled {
if let Some(identity_hash) = self.transport_identity_hash {
request_data.extend_from_slice(&identity_hash);
}
}
request_data.extend_from_slice(&request_tag);
let path_request_dest = rns_identity::destination::Destination::hash_from_name_and_identity(
"rnstransport.path.request",
None,
);
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::Plain,
packet_type: rns_wire::flags::PacketType::Data,
};
let path_request_header = rns_wire::header::PacketHeader {
flags,
hops: 0,
transport_id: None,
destination_hash: path_request_dest,
context: rns_wire::context::PacketContext::None,
};
let mut request_raw = path_request_header.pack();
request_raw.extend_from_slice(&request_data);
self.broadcast_on_interfaces(&request_raw, None);
self.forward_path_request(destination_hash, None, Some(&request_tag), false);
debug!(
dest = hex::encode(destination_hash),
@@ -622,10 +650,19 @@ impl TransportActor {
if let Some(existing) = self.path_table.get(dest_hash) {
let old_hops = existing.hops;
let old_expires = existing.expires;
// Only overwrite a live path if the tunnel copy is at least
// as short, or the live entry is already stale.
if tunnel_path.hops <= old_hops || now > old_expires {
should_add = true;
let current_timebase =
path_timebase_from_random_blobs(existing.random_blobs.iter());
let tunnel_timebase =
path_timebase_from_random_blobs(tunnel_path.random_blobs.iter());
if tunnel_timebase >= current_timebase {
should_add = true;
} else {
debug!(
dest = hex::encode(dest_hash),
"did not restore tunnel path: existing path is more recent"
);
}
} else {
debug!(
dest = hex::encode(dest_hash),
@@ -644,12 +681,12 @@ impl TransportActor {
if should_add {
let entry = crate::path_table::PathEntry {
timestamp: now,
next_hop: None,
next_hop: tunnel_path.next_hop,
hops: tunnel_path.hops,
expires: tunnel_path.expires,
random_blobs: tunnel_path.random_blobs.iter().copied().collect(),
interface_id,
packet_hash: None,
packet_hash: tunnel_path.packet_hash,
};
self.path_table.insert(*dest_hash, entry);
self.state_dirty = true;
@@ -675,6 +712,7 @@ impl TransportActor {
);
}
}
self.state_dirty = true;
}
}
}
+269 -18
View File
@@ -10,6 +10,81 @@ fn now() -> f64 {
.unwrap_or(0.0)
}
fn recent_announce_from_cached_packet(
dest_hash: [u8; 16],
hops: u8,
timestamp: f64,
raw_packet: Vec<u8>,
) -> RecentAnnounce {
let mut recent = RecentAnnounce {
dest_hash,
hops,
app_data: None,
timestamp,
public_key: None,
ratchet: None,
raw_packet,
retained: false,
name_hash: [0u8; 10],
};
if let Ok((header, offset)) = rns_wire::header::PacketHeader::unpack(&recent.raw_packet)
&& header.flags.packet_type == rns_wire::flags::PacketType::Announce
&& header.destination_hash == dest_hash
&& recent.raw_packet.len() >= offset
&& let Ok(announce) = rns_identity::announce::AnnounceData::unpack(
&recent.raw_packet[offset..],
header.flags.context_flag,
)
{
recent.app_data = announce.app_data;
recent.public_key = Some(announce.public_key);
recent.ratchet = announce.ratchet;
recent.name_hash = announce.name_hash;
}
recent
}
fn python_announce_cache_index(
announce_cache_dir: &std::path::Path,
) -> Option<std::collections::HashSet<String>> {
match std::fs::read_dir(announce_cache_dir) {
Ok(entries) => {
let mut names = std::collections::HashSet::new();
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str()
&& name.len() == 64
&& name.as_bytes().iter().all(u8::is_ascii_hexdigit)
{
names.insert(name.to_ascii_lowercase());
}
}
Some(names)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Some(std::collections::HashSet::new())
}
Err(_) => None,
}
}
fn load_indexed_python_cached_announce(
announce_cache_dir: &std::path::Path,
cache_index: Option<&std::collections::HashSet<String>>,
packet_hash: &[u8; 32],
) -> Result<Option<crate::persistence::PythonCachedAnnounce>, crate::persistence::PersistenceError>
{
if let Some(index) = cache_index {
let name = hex::encode(packet_hash);
if !index.contains(&name) {
return Ok(None);
}
}
crate::persistence::load_python_cached_announce(announce_cache_dir, packet_hash)
}
impl TransportActor {
/// Flush the small/critical routing-state files: path_table,
/// announce_cache, blackhole_table, tunnel_table. Hashlist is excluded —
@@ -20,6 +95,13 @@ impl TransportActor {
/// `state_dirty` and bumps `last_state_save` so the periodic trigger
/// doesn't double-fire.
pub(super) fn save_routing_state(&mut self) {
if self.shared_instance_client_mode {
trace!("skipping routing-state save in shared-instance client mode");
self.state_dirty = false;
self.last_state_save = now();
return;
}
if let Some(ref dir) = self.storage_dir {
let interface_names: std::collections::HashMap<u64, String> = self
.interfaces
@@ -84,8 +166,9 @@ impl TransportActor {
}
let announce_cache_dir = dir.join("cache").join("announces");
if let Err(e) = crate::persistence::save_python_announce_cache_for_paths(
if let Err(e) = crate::persistence::save_python_announce_cache_for_paths_and_tunnels(
&self.path_table,
Some(&self.tunnel_table),
self.recent_announces.values(),
&interface_names,
&announce_cache_dir,
@@ -104,6 +187,15 @@ impl TransportActor {
debug!("saved tunnel table ({} entries)", self.tunnel_table.len());
}
let python_tunnels_path = dir.join("tunnels");
if let Err(e) = crate::persistence::save_python_tunnel_table(
&self.tunnel_table,
&interface_names,
&python_tunnels_path,
) {
trace!("failed to save Python tunnels table: {}", e);
}
// Single-line summary for diagnosing periodic routing-state saves
// without surfacing normal flushes at default log levels.
debug!(
@@ -124,6 +216,9 @@ impl TransportActor {
pub(super) fn save_state(&mut self) {
// Routing state first so the order matches the periodic-save shape.
self.save_routing_state();
if self.shared_instance_client_mode {
return;
}
if let Some(ref dir) = self.storage_dir {
let hashlist_path = dir.join("packet_hashlist");
@@ -186,13 +281,15 @@ impl TransportActor {
let mut missing_cache = 0usize;
let mut pending = 0usize;
let announce_cache_dir = dir.join("cache").join("announces");
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
for pe in entries {
if pe.expires <= now_ts {
expired += 1;
continue;
}
let cached = match crate::persistence::load_python_cached_announce(
let cached = match load_indexed_python_cached_announce(
&announce_cache_dir,
announce_cache_index.as_ref(),
&pe.packet_hash,
) {
Ok(Some(cached)) => cached,
@@ -229,16 +326,13 @@ impl TransportActor {
});
self.recent_announces
.entry(pe.destination_hash)
.or_insert_with(|| RecentAnnounce {
dest_hash: pe.destination_hash,
hops: pe.hops,
app_data: None,
timestamp: pe.timestamp,
public_key: None,
ratchet: None,
raw_packet: cached.raw_packet,
retained: false,
name_hash: [0u8; 10],
.or_insert_with(|| {
recent_announce_from_cached_packet(
pe.destination_hash,
pe.hops,
pe.timestamp,
cached.raw_packet,
)
});
pending += 1;
}
@@ -323,9 +417,121 @@ impl TransportActor {
}
self.load_python_blackhole_if_ready();
// tunnel_table — defer remap.
// Python tunnels — canonical interop shape. Each path is only staged
// when its cached announce packet is present, mirroring upstream's
// dependency between tunnel paths and the announce cache.
let python_tunnels_path = dir.join("tunnels");
let loaded_python_tunnel_table = if python_tunnels_path.exists() {
match crate::persistence::load_python_tunnel_table(&python_tunnels_path) {
Ok(entries) => {
let total = entries.len();
let mut expired = 0usize;
let mut missing_cache = 0usize;
let mut legacy = 0usize;
let mut pending = 0usize;
let announce_cache_dir = dir.join("cache").join("announces");
let announce_cache_index = python_announce_cache_index(&announce_cache_dir);
for te in entries {
if te.expires <= now_ts {
expired += 1;
continue;
}
let mut paths = Vec::new();
let mut interface_name = None;
let mut interface_hash =
te.interface_hash.as_ref().map(|hash| hash.to_vec());
for tp in te.paths {
if tp.expires <= now_ts {
expired += 1;
continue;
}
if interface_hash.is_none() {
interface_hash =
tp.interface_hash.as_ref().map(|hash| hash.to_vec());
}
let cached = match load_indexed_python_cached_announce(
&announce_cache_dir,
announce_cache_index.as_ref(),
&tp.packet_hash,
) {
Ok(Some(cached)) => cached,
Ok(None) | Err(_) => {
missing_cache += 1;
continue;
}
};
if interface_name.is_none() {
interface_name = cached.interface_reference.clone();
}
let next_hop = if tp.received_from == tp.destination_hash {
None
} else {
Some(tp.received_from.to_vec())
};
paths.push(crate::persistence::PersistedTunnelPath {
destination_hash: tp.destination_hash.to_vec(),
next_hop,
hops: tp.hops,
expires: tp.expires,
timestamp: tp.timestamp,
random_blobs: tp
.random_blobs
.iter()
.map(|blob| blob.to_vec())
.collect(),
packet_hash: Some(tp.packet_hash.to_vec()),
});
self.recent_announces
.entry(tp.destination_hash)
.or_insert_with(|| {
recent_announce_from_cached_packet(
tp.destination_hash,
tp.hops,
tp.timestamp,
cached.raw_packet,
)
});
}
if paths.is_empty() {
continue;
}
if interface_name.is_none() && interface_hash.is_none() {
legacy += 1;
continue;
}
self.pending_tunnel_entries.push(
crate::persistence::PersistedTunnelEntry {
tunnel_id: te.tunnel_id.to_vec(),
interface_id: 0,
expires: te.expires,
paths,
interface_name,
interface_hash,
},
);
pending += 1;
}
debug!(
total,
pending, expired, missing_cache, legacy, "staged Python tunnel entries"
);
pending > 0
}
Err(e) => {
trace!("failed to load Python tunnels table: {}", e);
false
}
}
} else {
false
};
// tunnel_table — legacy Rust sidecar fallback, defer remap.
let tunnel_path = dir.join("tunnel_table.msgpack");
if tunnel_path.exists() {
if !loaded_python_tunnel_table && tunnel_path.exists() {
match crate::persistence::load_tunnel_table(&tunnel_path) {
Ok(entries) => {
let total = entries.len();
@@ -340,7 +546,7 @@ impl TransportActor {
expired += 1;
continue;
}
if te.interface_name.is_none() {
if te.interface_name.is_none() && te.interface_hash.is_none() {
legacy += 1;
continue;
}
@@ -364,10 +570,18 @@ impl TransportActor {
match crate::persistence::load_announce_cache(&announce_path) {
Ok(entries) => {
let count = entries.len();
let mut expired = 0usize;
for ae in entries {
if ae.destination_hash.len() == 16 {
let mut hash = [0u8; 16];
hash.copy_from_slice(&ae.destination_hash);
let stale_pathless = !ae.retained
&& !self.recent_announces.contains_key(&hash)
&& now_ts - ae.timestamp > DESTINATION_TIMEOUT as f64;
if stale_pathless {
expired += 1;
continue;
}
let public_key = ae.public_key.and_then(|k| {
if k.len() == 64 {
let mut arr = [0u8; 64];
@@ -408,7 +622,7 @@ impl TransportActor {
});
}
}
debug!("loaded {} announce cache entries from disk", count);
debug!(count, expired, "loaded announce cache entries from disk");
}
Err(e) => {
trace!("failed to load announce cache: {}", e);
@@ -535,7 +749,11 @@ impl TransportActor {
if !self.pending_tunnel_entries.is_empty() {
let mut promoted = 0usize;
self.pending_tunnel_entries.retain(|te| {
if te.interface_name.as_deref() != Some(name) {
let name_matches = te.interface_name.as_deref() == Some(name);
let hash_matches = te.interface_hash.as_deref().is_some_and(|hash| {
hash == crate::persistence::interface_hash_from_name(name).as_slice()
});
if !name_matches && !hash_matches {
return true;
}
if te.tunnel_id.len() != 32 {
@@ -548,13 +766,46 @@ impl TransportActor {
if tp.destination_hash.len() == 16 {
let mut dest = [0u8; 16];
dest.copy_from_slice(&tp.destination_hash);
let next_hop = tp.next_hop.as_ref().and_then(|next_hop| {
if next_hop.len() == 16 {
let mut arr = [0u8; 16];
arr.copy_from_slice(next_hop);
Some(arr)
} else {
None
}
});
let packet_hash = tp.packet_hash.as_ref().and_then(|packet_hash| {
if packet_hash.len() == 32 {
let mut arr = [0u8; 32];
arr.copy_from_slice(packet_hash);
Some(arr)
} else {
None
}
});
let random_blobs = tp
.random_blobs
.iter()
.filter_map(|blob| {
if blob.len() == 10 {
let mut arr = [0u8; 10];
arr.copy_from_slice(blob);
Some(arr)
} else {
None
}
})
.collect();
tunnel_paths.insert(
dest,
crate::tunnel::TunnelPath {
timestamp: tp.timestamp,
next_hop,
hops: tp.hops,
expires: tp.expires,
random_blobs: vec![],
random_blobs,
packet_hash,
},
);
}
+100 -15
View File
@@ -10,7 +10,7 @@ impl TransportActor {
TransportQuery::GetPathTable => {
let entries: Vec<PathTableRpcEntry> = self
.path_table
.iter()
.iter_live()
.map(|(hash, entry)| {
let iface_name = self
.interfaces
@@ -24,12 +24,24 @@ impl TransportActor {
hops: entry.hops,
expires: entry.expires,
interface: iface_name,
interface_id: entry.interface_id,
interface_mode: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.mode)
.unwrap_or(crate::constants::InterfaceMode::Full),
interface_role: self
.interfaces
.get(&entry.interface_id)
.map(|e| e.role)
.unwrap_or_default(),
}
})
.collect();
TransportQueryResponse::PathTable(entries)
}
TransportQuery::GetInterfaceStats => {
let now = now_f64();
let stats: Vec<InterfaceStatRpcEntry> = self
.interfaces
.iter()
@@ -66,7 +78,23 @@ impl TransportActor {
incoming_announce_frequency: entry
.ingress
.incoming_announce_frequency(),
outgoing_announce_frequency: 0.0,
outgoing_announce_frequency: entry
.ingress
.outgoing_announce_frequency(),
incoming_pr_frequency: entry.ingress.incoming_pr_frequency(),
outgoing_pr_frequency: entry.ingress.outgoing_pr_frequency(),
burst_active: entry.ingress.is_burst_active(),
burst_activated: activation_epoch(
now,
entry.ingress.is_burst_active(),
entry.ingress.burst_activated(),
),
pr_burst_active: entry.ingress.is_pr_burst_active(),
pr_burst_activated: activation_epoch(
now,
entry.ingress.is_pr_burst_active(),
entry.ingress.pr_burst_activated(),
),
clients: None,
announce_rate_target: entry.announce_rate_target,
announce_rate_grace: entry.announce_rate_grace,
@@ -101,14 +129,24 @@ impl TransportActor {
let mut entries: Vec<AnnounceRpcEntry> = self
.recent_announces
.values()
.map(|a| AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
retained: a.retained,
.map(|a| {
let is_path_response =
rns_wire::header::PacketHeader::unpack(&a.raw_packet)
.ok()
.is_some_and(|(header, _)| {
header.context == rns_wire::context::PacketContext::PathResponse
});
AnnounceRpcEntry {
dest_hash: a.dest_hash,
hops: a.hops,
app_data: a.app_data.clone(),
timestamp: a.timestamp,
public_key: a.public_key,
ratchet: a.ratchet,
name_hash: a.name_hash,
is_path_response,
retained: a.retained,
}
})
.collect();
// HashMap iteration order is unspecified; sort newest-first
@@ -122,13 +160,13 @@ impl TransportActor {
TransportQueryResponse::Announces(entries)
}
TransportQuery::GetNextHop { dest } => {
let next_hop = self.path_table.get(&dest).and_then(|e| e.next_hop);
let next_hop = self.path_table.get_live(&dest).and_then(|e| e.next_hop);
TransportQueryResponse::HashResult(next_hop)
}
TransportQuery::GetNextHopIfName { dest } => {
let name = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id).map(|i| i.name.clone()));
TransportQueryResponse::StringResult(name)
}
@@ -157,12 +195,48 @@ impl TransportActor {
self.state_dirty = true;
TransportQueryResponse::Ok
}
TransportQuery::SuppressPathInterface {
dest,
interface_id,
duration,
} => TransportQueryResponse::BoolResult(self.suppress_path_interface(
dest,
interface_id,
duration,
)),
TransportQuery::SuppressCurrentPathInterface { dest, duration } => {
let interface_id = self
.path_table
.get_live(&dest)
.map(|entry| entry.interface_id);
TransportQueryResponse::BoolResult(interface_id.is_some_and(|interface_id| {
self.suppress_path_interface(dest, interface_id, duration)
}))
}
TransportQuery::DropAnnounceQueues => {
for entry in self.interfaces.values_mut() {
entry.announce_queue.clear();
}
TransportQueryResponse::Ok
}
TransportQuery::DropPathTable => {
let cleared = self.path_table.len();
self.path_table = crate::path_table::PathTable::new();
self.pending_path_entries.clear();
self.discovery_path_requests.clear();
self.pending_local_path_requests.clear();
self.pending_discovery_prs.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::DropRecentAnnounces => {
let cleared = self.recent_announces.len();
self.recent_announces.clear();
self.state_dirty = true;
self.save_routing_state();
TransportQueryResponse::IntResult(cleared as i64)
}
TransportQuery::GetBlackholedIdentities => {
// Snapshot of identity hashes we have a current announce for —
// used to decorate each entry with `verified`.
@@ -386,19 +460,22 @@ impl TransportActor {
TransportQuery::GetNextHopBitrate { dest } => {
let bitrate = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.map(|iface| iface.bitrate as f64);
TransportQueryResponse::FloatResult(bitrate)
}
TransportQuery::GetNextHopInterfaceId { dest } => {
let id = self.path_table.get(&dest).map(|e| e.interface_id as i64);
let id = self
.path_table
.get_live(&dest)
.map(|e| e.interface_id as i64);
TransportQueryResponse::IntResult(id.unwrap_or(-1))
}
TransportQuery::FirstHopTimeout { dest } => {
let timeout = self
.path_table
.get(&dest)
.get_live(&dest)
.and_then(|e| self.interfaces.get(&e.interface_id))
.map(|iface| {
let per_byte_latency = 8.0 / iface.bitrate as f64;
@@ -521,3 +598,11 @@ impl TransportActor {
}
}
}
fn activation_epoch(now: f64, active: bool, activated: std::time::Instant) -> f64 {
if active {
now - activated.elapsed().as_secs_f64()
} else {
0.0
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ pub struct AnnounceEntry {
pub received_from: [u8; 16],
/// Hop count as observed on receipt.
pub hops: u8,
/// Outbound packet bytes with the hop count already incremented.
/// Outbound packet bytes with the Python-parity inbound-adjusted hop count.
pub packet_raw: Vec<u8>,
/// Count of duplicate rebroadcasts heard from neighbours — used to suppress flooding.
pub local_rebroadcasts: u32,
+2 -1
View File
@@ -2,7 +2,8 @@
//!
//! Mirrors Python `Transport.await_path(destination_hash, timeout=None)`
//! (RNS/Transport.py:2524). The helper sends an [`AwaitPath`] actor
//! message and races the oneshot reply against a caller-supplied timeout.
//! message and races the oneshot reply against a caller-supplied timeout. The
//! actor emits the upstream-compatible path request before parking the waiter.
//!
//! [`AwaitPath`]: crate::messages::TransportMessage::AwaitPath
+57 -15
View File
@@ -53,6 +53,12 @@ pub const PATH_REQUEST_TIMEOUT: f64 = 15.0;
/// Duplicate inbound path request tag retention (seconds).
pub const PATH_REQUEST_GATE_TIMEOUT: f64 = 120.0;
/// Maximum queued automatic discovery path requests after failed link setup.
pub const MAX_QUEUED_DISCOVERY_PRS: usize = 32;
/// Minimum spacing between queued discovery path-request transmissions.
pub const DISCOVERY_PR_TX_THROTTLE: f64 = 0.5;
/// Grace before path response (seconds).
pub const PATH_REQUEST_GRACE: f64 = 0.4;
@@ -116,41 +122,77 @@ pub const ANNOUNCE_CAP: f64 = 0.02;
pub const MAX_HELD_ANNOUNCES: usize = 256;
/// Held announce release interval (seconds).
/// Matches Python 1.2.4 `Interface.IC_HELD_RELEASE_INTERVAL = 2`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 2.0;
/// Matches Python 1.2.5 `Interface.IC_HELD_RELEASE_INTERVAL = 5`.
pub const IC_HELD_RELEASE_INTERVAL: f64 = 5.0;
/// Incoming announce frequency window samples.
/// Matches Python 1.2.4 `Interface.IA_FREQ_SAMPLES = 128`.
pub const IA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.IA_FREQ_SAMPLES = 48`.
pub const IA_FREQ_SAMPLES: usize = 48;
/// Outgoing announce frequency window samples.
/// Matches Python 1.2.4 `Interface.OA_FREQ_SAMPLES = 128`.
pub const OA_FREQ_SAMPLES: usize = 128;
/// Matches Python 1.2.5 `Interface.OA_FREQ_SAMPLES = 48`.
pub const OA_FREQ_SAMPLES: usize = 48;
/// Incoming path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.IP_FREQ_SAMPLES = 48`.
pub const IP_FREQ_SAMPLES: usize = 48;
/// Outgoing path-request frequency window samples.
/// Matches Python 1.2.5 `Interface.OP_FREQ_SAMPLES = 48`.
pub const OP_FREQ_SAMPLES: usize = 48;
/// Minimum non-zero announce frequency represented by the decay window.
pub const AR_MINFREQ_HZ: f64 = 0.1;
/// Minimum non-zero path-request frequency represented by the decay window.
pub const PR_MINFREQ_HZ: f64 = 0.1;
/// Frequency decay window for announces (seconds).
pub const AR_FREQ_DECAY: f64 = 1.0 / AR_MINFREQ_HZ;
/// Frequency decay window for path requests (seconds).
pub const PR_FREQ_DECAY: f64 = 1.0 / PR_MINFREQ_HZ;
/// Minimum samples required before frequency is considered defined.
/// Matches Python 1.2.4 `Interface.IC_DEQUE_MIN_SAMPLE = 32`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 32;
/// Matches Python 1.2.5 `Interface.IC_DEQUE_MIN_SAMPLE = 2`.
pub const IC_DEQUE_MIN_SAMPLE: usize = 2;
/// Minimum samples required for burst state clearing / egress PR limiting.
/// Matches Python 1.2.5 `Interface.IC_BURST_MIN_SAMPLES = 6`.
pub const IC_BURST_MIN_SAMPLES: usize = 6;
/// Duration interface is treated as "new" (seconds).
/// Matches Python `Interface.IC_NEW_TIME = 2*60*60`.
pub const IC_NEW_TIME: f64 = 7200.0;
/// Burst threshold for new interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ_NEW = 6`.
pub const IC_BURST_FREQ_NEW: f64 = 6.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ_NEW = 3`.
pub const IC_BURST_FREQ_NEW: f64 = 3.0;
/// Burst threshold for established interfaces (announces/sec).
/// Matches Python 1.2.4 `Interface.IC_BURST_FREQ = 35`.
pub const IC_BURST_FREQ: f64 = 35.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_FREQ = 10`.
pub const IC_BURST_FREQ: f64 = 10.0;
/// Path-request burst threshold for new interfaces (requests/sec).
pub const IC_PR_BURST_FREQ_NEW: f64 = 3.0;
/// Path-request burst threshold for established interfaces (requests/sec).
pub const IC_PR_BURST_FREQ: f64 = 8.0;
/// Burst detection active duration (seconds).
/// Matches Python `Interface.IC_BURST_HOLD = 1*60`.
pub const IC_BURST_HOLD: f64 = 60.0;
/// Matches Python 1.2.5 `Interface.IC_BURST_HOLD = 15`.
pub const IC_BURST_HOLD: f64 = 15.0;
/// Burst penalty delay (seconds).
/// Matches Python 1.2.4 `Interface.IC_BURST_PENALTY = 15`.
/// Matches Python 1.2.5 `Interface.IC_BURST_PENALTY = 15`.
pub const IC_BURST_PENALTY: f64 = 15.0;
/// Optional outgoing path-request limiter threshold (requests/sec).
pub const EC_PR_FREQ: f64 = 5.0;
/// Whether outgoing path-request limiting is active by default.
pub const EGRESS_CONTROL: bool = false;
/// Tunnel timeout (8 hours, in seconds).
/// Matches Python 1.1.6 `Transport.TUNNEL_TIMEOUT = 60*60*8`.
pub const TUNNEL_TIMEOUT: u64 = 28_800;
+443 -30
View File
@@ -1,4 +1,4 @@
//! Per-interface ingress control: announce flood protection.
//! Per-interface ingress/egress control for announce and path-request floods.
//!
//! Each interface owns one `IngressController`. The inbound path consults it
//! on every announce — when the incoming rate crosses the burst threshold the
@@ -15,9 +15,10 @@ use std::time::{Duration, Instant};
use bytes::Bytes;
use crate::constants::{
IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW, IC_BURST_HOLD, IC_BURST_PENALTY,
IC_DEQUE_MIN_SAMPLE, IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, MAX_HELD_ANNOUNCES,
OA_FREQ_SAMPLES,
AR_FREQ_DECAY, EC_PR_FREQ, EGRESS_CONTROL, IA_FREQ_SAMPLES, IC_BURST_FREQ, IC_BURST_FREQ_NEW,
IC_BURST_HOLD, IC_BURST_MIN_SAMPLES, IC_BURST_PENALTY, IC_DEQUE_MIN_SAMPLE,
IC_HELD_RELEASE_INTERVAL, IC_NEW_TIME, IC_PR_BURST_FREQ, IC_PR_BURST_FREQ_NEW, IP_FREQ_SAMPLES,
MAX_HELD_ANNOUNCES, OA_FREQ_SAMPLES, OP_FREQ_SAMPLES, PR_FREQ_DECAY,
};
/// Per-interface ingress overrides parsed from `[interface.<name>] ic_*` keys.
@@ -27,11 +28,15 @@ pub struct IngressOverrides {
pub enabled: Option<bool>,
pub burst_freq_new: Option<f64>,
pub burst_freq: Option<f64>,
pub pr_burst_freq_new: Option<f64>,
pub pr_burst_freq: Option<f64>,
pub new_time: Option<f64>,
pub burst_hold: Option<f64>,
pub burst_penalty: Option<f64>,
pub max_held: Option<usize>,
pub held_release_interval: Option<f64>,
pub ec_pr_freq: Option<f64>,
pub egress_control: Option<bool>,
}
impl IngressOverrides {
@@ -39,11 +44,15 @@ impl IngressOverrides {
self.enabled.is_none()
&& self.burst_freq_new.is_none()
&& self.burst_freq.is_none()
&& self.pr_burst_freq_new.is_none()
&& self.pr_burst_freq.is_none()
&& self.new_time.is_none()
&& self.burst_hold.is_none()
&& self.burst_penalty.is_none()
&& self.max_held.is_none()
&& self.held_release_interval.is_none()
&& self.ec_pr_freq.is_none()
&& self.egress_control.is_none()
}
}
@@ -65,19 +74,29 @@ pub struct IngressController {
ia_freq_deque: VecDeque<Instant>,
/// Outgoing announce timestamps; capped at `OA_FREQ_SAMPLES`.
oa_freq_deque: VecDeque<Instant>,
/// Incoming path-request timestamps; capped at `IP_FREQ_SAMPLES`.
ip_freq_deque: VecDeque<Instant>,
/// Outgoing path-request timestamps; capped at `OP_FREQ_SAMPLES`.
op_freq_deque: VecDeque<Instant>,
burst_active: bool,
burst_activated: Instant,
pr_burst_active: bool,
pr_burst_activated: Instant,
/// Earliest instant at which the next held announce may be released.
held_release: Instant,
held_announces: HashMap<[u8; 16], HeldAnnounce>,
burst_freq_new: f64,
burst_freq: f64,
pr_burst_freq_new: f64,
pr_burst_freq: f64,
new_time: f64,
burst_hold: f64,
burst_penalty: f64,
max_held: usize,
held_release_interval: f64,
ec_pr_freq: f64,
egress_control: bool,
}
impl IngressController {
@@ -88,17 +107,25 @@ impl IngressController {
enabled: true,
ia_freq_deque: VecDeque::with_capacity(IA_FREQ_SAMPLES),
oa_freq_deque: VecDeque::with_capacity(OA_FREQ_SAMPLES),
ip_freq_deque: VecDeque::with_capacity(IP_FREQ_SAMPLES),
op_freq_deque: VecDeque::with_capacity(OP_FREQ_SAMPLES),
burst_active: false,
burst_activated: now,
pr_burst_active: false,
pr_burst_activated: now,
held_release: now,
held_announces: HashMap::new(),
burst_freq_new: IC_BURST_FREQ_NEW,
burst_freq: IC_BURST_FREQ,
pr_burst_freq_new: IC_PR_BURST_FREQ_NEW,
pr_burst_freq: IC_PR_BURST_FREQ,
new_time: IC_NEW_TIME,
burst_hold: IC_BURST_HOLD,
burst_penalty: IC_BURST_PENALTY,
max_held: MAX_HELD_ANNOUNCES,
held_release_interval: IC_HELD_RELEASE_INTERVAL,
ec_pr_freq: EC_PR_FREQ,
egress_control: EGRESS_CONTROL,
}
}
@@ -125,6 +152,12 @@ impl IngressController {
if let Some(v) = overrides.burst_freq {
ctrl.burst_freq = v;
}
if let Some(v) = overrides.pr_burst_freq_new {
ctrl.pr_burst_freq_new = v;
}
if let Some(v) = overrides.pr_burst_freq {
ctrl.pr_burst_freq = v;
}
if let Some(v) = overrides.new_time {
ctrl.new_time = v;
}
@@ -140,6 +173,12 @@ impl IngressController {
if let Some(v) = overrides.held_release_interval {
ctrl.held_release_interval = v;
}
if let Some(v) = overrides.ec_pr_freq {
ctrl.ec_pr_freq = v;
}
if let Some(v) = overrides.egress_control {
ctrl.egress_control = v;
}
ctrl
}
@@ -151,6 +190,22 @@ impl IngressController {
self.burst_freq_new
}
pub fn pr_burst_freq(&self) -> f64 {
self.pr_burst_freq
}
pub fn pr_burst_freq_new(&self) -> f64 {
self.pr_burst_freq_new
}
pub fn ec_pr_freq(&self) -> f64 {
self.ec_pr_freq
}
pub fn is_egress_control_enabled(&self) -> bool {
self.egress_control
}
pub fn held_release_interval(&self) -> f64 {
self.held_release_interval
}
@@ -171,27 +226,51 @@ impl IngressController {
}
pub fn received_announce(&mut self) {
let now = Instant::now();
if self.ia_freq_deque.len() >= IA_FREQ_SAMPLES {
self.ia_freq_deque.pop_front();
}
self.ia_freq_deque.push_back(now);
push_sample(&mut self.ia_freq_deque, IA_FREQ_SAMPLES, Instant::now());
}
pub fn sent_announce(&mut self) {
let now = Instant::now();
if self.oa_freq_deque.len() >= OA_FREQ_SAMPLES {
self.oa_freq_deque.pop_front();
}
self.oa_freq_deque.push_back(now);
push_sample(&mut self.oa_freq_deque, OA_FREQ_SAMPLES, Instant::now());
}
pub fn received_path_request(&mut self) {
push_sample(&mut self.ip_freq_deque, IP_FREQ_SAMPLES, Instant::now());
}
pub fn sent_path_request(&mut self) {
push_sample(&mut self.op_freq_deque, OP_FREQ_SAMPLES, Instant::now());
}
pub fn incoming_announce_frequency(&self) -> f64 {
frequency_from_deque(&self.ia_freq_deque)
frequency_from_deque(
&self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
)
}
pub fn outgoing_announce_frequency(&self) -> f64 {
frequency_from_deque(&self.oa_freq_deque)
frequency_from_deque(
&self.oa_freq_deque,
1,
Duration::from_secs_f64(AR_FREQ_DECAY),
)
}
pub fn incoming_pr_frequency(&self) -> f64 {
frequency_from_deque(
&self.ip_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(PR_FREQ_DECAY),
)
}
pub fn outgoing_pr_frequency(&self) -> f64 {
frequency_from_deque(
&self.op_freq_deque,
1,
Duration::from_secs_f64(PR_FREQ_DECAY),
)
}
/// Whether inbound announces should currently be held. Also updates the
@@ -209,13 +288,18 @@ impl IngressController {
self.burst_freq
};
let ia_freq = self.incoming_announce_frequency();
let ia_freq = frequency_from_deque_mut(
&mut self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
);
let now = Instant::now();
if self.burst_active {
if ia_freq < freq_threshold
&& now.duration_since(self.burst_activated)
> Duration::from_secs_f64(self.burst_hold)
&& self.ia_freq_deque.len() >= IC_BURST_MIN_SAMPLES
{
self.burst_active = false;
}
@@ -230,6 +314,58 @@ impl IngressController {
}
}
/// Whether unknown recursive path-request discovery should be suppressed
/// on this ingress interface.
pub fn should_ingress_limit_pr(&mut self) -> bool {
if !self.enabled {
return false;
}
let freq_threshold = if self.age() < self.new_time {
self.pr_burst_freq_new
} else {
self.pr_burst_freq
};
let ip_freq = frequency_from_deque_mut(
&mut self.ip_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(PR_FREQ_DECAY),
);
let now = Instant::now();
if self.pr_burst_active {
if ip_freq < freq_threshold
&& now.duration_since(self.pr_burst_activated)
> Duration::from_secs_f64(self.burst_hold)
{
self.pr_burst_active = false;
}
true
} else if ip_freq > freq_threshold {
self.pr_burst_active = true;
self.pr_burst_activated = now;
true
} else {
false
}
}
/// Whether outgoing path-request transmission should be skipped on this
/// interface. This limiter is off by default in Reticulum 1.2.5.
pub fn should_egress_limit_pr(&mut self) -> bool {
if !self.egress_control {
return false;
}
let op_freq = frequency_from_deque_mut(
&mut self.op_freq_deque,
1,
Duration::from_secs_f64(PR_FREQ_DECAY),
);
op_freq > self.ec_pr_freq && self.op_freq_deque.len() >= IC_BURST_MIN_SAMPLES
}
pub fn hold_announce(&mut self, announce: HeldAnnounce) {
if self.held_announces.contains_key(&announce.destination_hash)
|| self.held_announces.len() < self.max_held
@@ -240,11 +376,12 @@ impl IngressController {
}
/// Release at most one held announce per call — the one with the lowest
/// hop count, so short-path announces win priority. `None` means either
/// the burst is still active, the release cooldown has not elapsed, or
/// the buffer is empty.
/// hop count, so short-path announces win priority. This intentionally
/// does not consult `should_ingress_limit()`: upstream releases held
/// announces based on release time and current announce frequency, even if
/// the displayed burst state has not cleared yet.
pub fn try_release_held(&mut self) -> Option<HeldAnnounce> {
if self.should_ingress_limit() || self.held_announces.is_empty() {
if self.held_announces.is_empty() {
return None;
}
@@ -259,7 +396,12 @@ impl IngressController {
self.burst_freq
};
if self.incoming_announce_frequency() >= freq_threshold {
let ia_freq = frequency_from_deque_mut(
&mut self.ia_freq_deque,
IC_DEQUE_MIN_SAMPLE,
Duration::from_secs_f64(AR_FREQ_DECAY),
);
if ia_freq >= freq_threshold {
return None;
}
@@ -281,6 +423,18 @@ impl IngressController {
pub fn is_burst_active(&self) -> bool {
self.burst_active
}
pub fn burst_activated(&self) -> Instant {
self.burst_activated
}
pub fn is_pr_burst_active(&self) -> bool {
self.pr_burst_active
}
pub fn pr_burst_activated(&self) -> Instant {
self.pr_burst_activated
}
}
impl Default for IngressController {
@@ -289,32 +443,118 @@ impl Default for IngressController {
}
}
/// Announces-per-second estimate over a timestamp deque. Returns 0 until
/// enough samples have accumulated (`IC_DEQUE_MIN_SAMPLE`) so the first few
/// entries on a new interface cannot trip the limiter by themselves.
fn frequency_from_deque(deque: &VecDeque<Instant>) -> f64 {
fn push_sample(deque: &mut VecDeque<Instant>, cap: usize, now: Instant) {
if deque.len() >= cap {
deque.pop_front();
}
deque.push_back(now);
}
/// Snapshot frequency over a timestamp deque. Stale samples are ignored for
/// observability without mutating the controller from read-only status paths.
fn frequency_from_deque(deque: &VecDeque<Instant>, min_samples: usize, decay: Duration) -> f64 {
let now = Instant::now();
let oldest = deque
.iter()
.find(|sample| sample_age(now, **sample) <= decay);
let Some(oldest) = oldest else {
return 0.0;
};
let n = deque
.iter()
.filter(|sample| sample_age(now, **sample) <= decay)
.count();
frequency_from_parts(n, now, *oldest, min_samples)
}
/// Mutable limiter frequency. Mirrors upstream's decay side effect by dropping
/// one stale oldest sample when the observed window is older than the decay
/// horizon, then calculating from the current sample count and oldest span.
fn frequency_from_deque_mut(
deque: &mut VecDeque<Instant>,
min_samples: usize,
decay: Duration,
) -> f64 {
let n = deque.len();
if n <= IC_DEQUE_MIN_SAMPLE {
if n <= min_samples {
return 0.0;
}
let span = match deque.front() {
Some(oldest) => oldest.elapsed().as_secs_f64(),
None => return 0.0,
let now = Instant::now();
let Some(oldest) = deque.front().copied() else {
return 0.0;
};
if sample_age(now, oldest) > decay {
deque.pop_front();
}
frequency_from_parts(n, now, oldest, min_samples)
}
fn frequency_from_parts(n: usize, now: Instant, oldest: Instant, min_samples: usize) -> f64 {
if n <= min_samples {
return 0.0;
}
let span = sample_age(now, oldest).as_secs_f64();
if span <= 0.0 { 0.0 } else { n as f64 / span }
}
fn sample_age(now: Instant, sample: Instant) -> Duration {
now.checked_duration_since(sample)
.unwrap_or_else(|| Duration::from_secs(0))
}
#[cfg(test)]
mod tests {
use super::*;
fn push_samples(
deque: &mut VecDeque<Instant>,
cap: usize,
count: usize,
oldest_age: f64,
spacing: f64,
) {
let now = Instant::now();
for i in 0..count {
let age = oldest_age - (i as f64 * spacing);
push_sample(deque, cap, now - Duration::from_secs_f64(age.max(0.0)));
}
}
#[test]
fn reticulum_125_control_constants_are_pinned() {
assert_eq!(IA_FREQ_SAMPLES, 48);
assert_eq!(OA_FREQ_SAMPLES, 48);
assert_eq!(IP_FREQ_SAMPLES, 48);
assert_eq!(OP_FREQ_SAMPLES, 48);
assert_eq!(AR_FREQ_DECAY, 10.0);
assert_eq!(PR_FREQ_DECAY, 10.0);
assert_eq!(IC_DEQUE_MIN_SAMPLE, 2);
assert_eq!(IC_BURST_MIN_SAMPLES, 6);
assert_eq!(IC_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_BURST_FREQ, 10.0);
assert_eq!(IC_PR_BURST_FREQ_NEW, 3.0);
assert_eq!(IC_PR_BURST_FREQ, 8.0);
assert_eq!(IC_BURST_HOLD, 15.0);
assert_eq!(IC_BURST_PENALTY, 15.0);
assert_eq!(IC_HELD_RELEASE_INTERVAL, 5.0);
assert_eq!(EC_PR_FREQ, 5.0);
const { assert!(!EGRESS_CONTROL) };
}
#[test]
fn ingress_controller_default_state() {
let ctrl = IngressController::new();
assert!(ctrl.is_enabled());
assert!(!ctrl.is_burst_active());
assert!(!ctrl.is_pr_burst_active());
assert!(!ctrl.is_egress_control_enabled());
assert_eq!(ctrl.pr_burst_freq_new(), IC_PR_BURST_FREQ_NEW);
assert_eq!(ctrl.pr_burst_freq(), IC_PR_BURST_FREQ);
assert_eq!(ctrl.ec_pr_freq(), EC_PR_FREQ);
assert_eq!(ctrl.held_count(), 0);
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
assert_eq!(ctrl.outgoing_pr_frequency(), 0.0);
}
#[test]
@@ -326,6 +566,179 @@ mod tests {
assert!(!ctrl.should_ingress_limit());
}
#[test]
fn disabled_ingress_control_keeps_frequency_stats() {
let mut ctrl = IngressController::disabled();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.2);
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.2);
assert!(!ctrl.should_ingress_limit());
assert!(!ctrl.should_ingress_limit_pr());
assert!(ctrl.incoming_announce_frequency() > 0.0);
assert!(ctrl.incoming_pr_frequency() > 0.0);
}
#[test]
fn announce_frequency_ignores_decayed_samples_for_stats() {
let mut ctrl = IngressController::new();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 2,
AR_FREQ_DECAY + 2.0,
0.1,
);
assert_eq!(ctrl.incoming_announce_frequency(), 0.0);
}
#[test]
fn pr_frequency_ignores_decayed_samples_for_stats() {
let mut ctrl = IngressController::new();
push_samples(
&mut ctrl.ip_freq_deque,
IP_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 2,
PR_FREQ_DECAY + 2.0,
0.1,
);
assert_eq!(ctrl.incoming_pr_frequency(), 0.0);
}
#[test]
fn announce_burst_clears_only_with_minimum_remaining_samples() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES + 1,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(!ctrl.is_burst_active());
}
#[test]
fn held_release_poll_does_not_activate_burst_when_nothing_is_held() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.try_release_held().is_none());
assert!(!ctrl.is_burst_active());
}
#[test]
fn held_announces_release_even_if_burst_state_is_waiting_for_clear_samples() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ia_freq_deque, IA_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ia_freq_deque.clear();
push_samples(
&mut ctrl.ia_freq_deque,
IA_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
AR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit());
assert!(ctrl.is_burst_active());
ctrl.held_release = Instant::now() - Duration::from_secs(1);
ctrl.hold_announce(HeldAnnounce {
raw: Bytes::from_static(&[1, 2, 3]),
destination_hash: [0xA5; 16],
hops: 1,
receiving_interface_id: 1,
});
let released = ctrl.try_release_held();
assert!(released.is_some());
assert!(ctrl.is_burst_active());
}
#[test]
fn pr_ingress_burst_activates_and_clears() {
let mut ctrl = IngressController::new();
push_samples(&mut ctrl.ip_freq_deque, IP_FREQ_SAMPLES, 4, 1.0, 0.1);
assert!(ctrl.should_ingress_limit_pr());
assert!(ctrl.is_pr_burst_active());
ctrl.pr_burst_activated = Instant::now() - Duration::from_secs_f64(IC_BURST_HOLD + 1.0);
ctrl.ip_freq_deque.clear();
push_samples(
&mut ctrl.ip_freq_deque,
IP_FREQ_SAMPLES,
IC_DEQUE_MIN_SAMPLE + 1,
PR_FREQ_DECAY + 1.0,
0.1,
);
assert!(ctrl.should_ingress_limit_pr());
assert!(!ctrl.is_pr_burst_active());
assert!(!ctrl.should_ingress_limit_pr());
}
#[test]
fn pr_egress_limiting_is_optional_and_requires_six_samples() {
let mut disabled = IngressController::new();
push_samples(
&mut disabled.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES + 2,
1.0,
0.1,
);
assert!(!disabled.should_egress_limit_pr());
let mut ctrl = IngressController::with_overrides(&IngressOverrides {
egress_control: Some(true),
ec_pr_freq: Some(EC_PR_FREQ),
..Default::default()
});
push_samples(
&mut ctrl.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES - 1,
1.0,
0.1,
);
assert!(!ctrl.should_egress_limit_pr());
ctrl.op_freq_deque.clear();
push_samples(
&mut ctrl.op_freq_deque,
OP_FREQ_SAMPLES,
IC_BURST_MIN_SAMPLES,
1.0,
0.1,
);
assert!(ctrl.should_egress_limit_pr());
}
#[test]
fn hold_announce_dedups_by_destination() {
let mut ctrl = IngressController::new();
+32 -6
View File
@@ -25,6 +25,30 @@ pub struct LinkEntry {
pub taken_hops: u8,
}
/// Metadata retained when an unvalidated link expires before proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpiredLink {
pub next_hop: Option<[u8; 16]>,
pub interface_id: InterfaceId,
pub remaining_hops: u8,
pub destination_hash: [u8; 16],
pub receiving_interface: InterfaceId,
pub taken_hops: u8,
}
impl From<&LinkEntry> for ExpiredLink {
fn from(entry: &LinkEntry) -> Self {
Self {
next_hop: entry.next_hop,
interface_id: entry.interface_id,
remaining_hops: entry.remaining_hops,
destination_hash: entry.destination_hash,
receiving_interface: entry.receiving_interface,
taken_hops: entry.taken_hops,
}
}
}
pub struct LinkTable {
entries: HashMap<LinkId, LinkEntry>,
}
@@ -73,9 +97,9 @@ impl LinkTable {
/// - Unvalidated links drop once their own `proof_timeout` elapses, since
/// proof never arrived during the establishment window.
///
/// Returns `(total_culled, destinations_that_expired_unvalidated)` — the
/// caller can re-issue path discovery for those destinations.
pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<[u8; 16]>) {
/// Returns `(total_culled, expired_unvalidated_links)` — the caller can
/// apply failed-link rediscovery rules using the retained route metadata.
pub fn cull_stale(&mut self, timeout: f64) -> (usize, Vec<ExpiredLink>) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
@@ -89,7 +113,7 @@ impl LinkTable {
if entry.validated {
entry.timestamp > cutoff
} else if now > entry.proof_timeout {
unvalidated_expired.push(entry.destination_hash);
unvalidated_expired.push(ExpiredLink::from(&*entry));
false
} else {
true
@@ -196,7 +220,9 @@ mod tests {
let (culled, expired_dests) = table.cull_stale(900.0);
assert_eq!(culled, 1);
assert_eq!(expired_dests.len(), 1);
assert_eq!(expired_dests[0], dest_hash);
assert_eq!(expired_dests[0].destination_hash, dest_hash);
assert_eq!(expired_dests[0].receiving_interface, 2);
assert_eq!(expired_dests[0].taken_hops, 0);
assert_eq!(table.len(), 0);
}
@@ -278,7 +304,7 @@ mod tests {
assert_eq!(culled, 2);
assert_eq!(table.len(), 2);
assert_eq!(expired_dests.len(), 1);
assert_eq!(expired_dests[0], [0xA4; 16]);
assert_eq!(expired_dests[0].destination_hash, [0xA4; 16]);
}
#[test]
+35
View File
@@ -397,6 +397,21 @@ pub enum TransportQuery {
DropPath {
dest: [u8; 16],
},
/// Temporarily reject path-table installs for `dest` learned through
/// `interface_id`. Used after link establishment failure so rediscovery can
/// consider alternate interfaces instead of immediately reselecting the
/// path that just failed.
SuppressPathInterface {
dest: [u8; 16],
interface_id: InterfaceId,
duration: f64,
},
/// Temporarily reject path-table installs for `dest` learned through the
/// interface that currently owns the path.
SuppressCurrentPathInterface {
dest: [u8; 16],
duration: f64,
},
DropAnnounceQueues,
GetBlackholedIdentities,
BlackholeIdentity {
@@ -435,6 +450,12 @@ pub enum TransportQuery {
DropAllVia {
next_hop: [u8; 16],
},
/// Drop every cached route from the path table and persist the empty table.
/// Response: `IntResult(count_cleared)`.
DropPathTable,
/// Drop every cached announce snapshot and persist the empty cache.
/// Response: `IntResult(count_cleared)`.
DropRecentAnnounces,
/// Remote-status RPC — interface stats + optional link count, wire-format
/// compatible with `Transport.remote_status_handler`.
RemoteStatus {
@@ -526,6 +547,9 @@ pub struct PathTableRpcEntry {
pub hops: u8,
pub expires: f64,
pub interface: String,
pub interface_id: InterfaceId,
pub interface_mode: InterfaceMode,
pub interface_role: InterfaceRole,
}
#[derive(Debug, Clone)]
@@ -545,6 +569,12 @@ pub struct InterfaceStatRpcEntry {
pub held_announces: u64,
pub incoming_announce_frequency: f64,
pub outgoing_announce_frequency: f64,
pub incoming_pr_frequency: f64,
pub outgoing_pr_frequency: f64,
pub burst_active: bool,
pub burst_activated: f64,
pub pr_burst_active: bool,
pub pr_burst_activated: f64,
pub clients: Option<u64>,
pub announce_rate_target: Option<f64>,
pub announce_rate_grace: Option<u32>,
@@ -572,6 +602,11 @@ pub struct AnnounceRpcEntry {
pub timestamp: f64,
pub public_key: Option<[u8; 64]>,
pub ratchet: Option<[u8; 32]>,
/// `SHA-256(app_name)[:10]` for the announced aspect.
pub name_hash: [u8; 10],
/// True when the cached announce arrived as a path response instead of a
/// fresh network announce.
pub is_path_response: bool,
/// Pinned via `RetainDestination`; the maintenance sweep skips the
/// entry regardless of age while this is `true`.
pub retained: bool,
+59 -2
View File
@@ -63,6 +63,20 @@ impl PathEntry {
now_f64() > self.expires
}
/// Mark an actively used route as live. Reticulum's Python path cull is
/// timestamp based; Rust stores an explicit expiry, so both clocks must
/// move together when traffic proves the route is still useful.
pub fn touch(&mut self) {
let now = now_f64();
let lifetime = if self.expires > self.timestamp {
self.expires - self.timestamp
} else {
path_expiry(InterfaceMode::Full) as f64
};
self.timestamp = now;
self.expires = now + lifetime;
}
/// Most recent blobs to persist — older entries can be regenerated from
/// the wire on replay, so we cap the snapshot at `PERSIST_RANDOM_BLOBS`
/// to keep the on-disk table small.
@@ -112,14 +126,22 @@ impl PathTable {
self.entries.get_mut(dest_hash)
}
pub fn get_live(&self, dest_hash: &[u8; 16]) -> Option<&PathEntry> {
self.entries.get(dest_hash).filter(|e| !e.is_expired())
}
pub fn get_live_mut(&mut self, dest_hash: &[u8; 16]) -> Option<&mut PathEntry> {
self.entries.get_mut(dest_hash).filter(|e| !e.is_expired())
}
/// A path exists and has not yet expired. Callers should prefer this
/// over `get().is_some()` so stale entries are not treated as routable.
pub fn has_path(&self, dest_hash: &[u8; 16]) -> bool {
self.entries.get(dest_hash).is_some_and(|e| !e.is_expired())
self.get_live(dest_hash).is_some()
}
pub fn hops_to(&self, dest_hash: &[u8; 16]) -> Option<u8> {
self.entries.get(dest_hash).map(|e| e.hops)
self.get_live(dest_hash).map(|e| e.hops)
}
pub fn remove(&mut self, dest_hash: &[u8; 16]) -> Option<PathEntry> {
@@ -217,6 +239,10 @@ impl PathTable {
pub fn iter(&self) -> impl Iterator<Item = (&DestHash, &PathEntry)> {
self.entries.iter()
}
pub fn iter_live(&self) -> impl Iterator<Item = (&DestHash, &PathEntry)> {
self.entries.iter().filter(|(_, entry)| !entry.is_expired())
}
}
impl Default for PathTable {
@@ -259,6 +285,37 @@ mod tests {
assert_eq!(table.len(), 1);
}
#[test]
fn expired_entries_are_not_live_paths() {
let mut table = PathTable::new();
let hash = [0xA1; 16];
let mut entry = PathEntry::new(None, 1, 1, InterfaceMode::Gateway);
entry.expires = now_f64() - 1.0;
table.insert(hash, entry);
assert!(table.get(&hash).is_some());
assert!(table.get_live(&hash).is_none());
assert!(table.get_live_mut(&hash).is_none());
assert!(!table.has_path(&hash));
assert_eq!(table.hops_to(&hash), None);
assert_eq!(table.iter().count(), 1);
assert_eq!(table.iter_live().count(), 0);
}
#[test]
fn touch_extends_explicit_expiry_with_original_lifetime() {
let mut entry = PathEntry::new(None, 1, 1, InterfaceMode::Roaming);
let lifetime = entry.expires - entry.timestamp;
entry.timestamp -= 10.0;
entry.expires -= 10.0;
entry.touch();
let new_lifetime = entry.expires - entry.timestamp;
assert!((new_lifetime - lifetime).abs() < 0.001);
assert!(entry.expires > now_f64());
}
#[test]
fn test_path_table_remove() {
let mut table = PathTable::new();
+334 -10
View File
@@ -7,6 +7,7 @@ use std::path::Path;
use rmpv::Value;
use serde::{Deserialize, Serialize};
use crate::constants::PERSIST_RANDOM_BLOBS;
use crate::hashlist::PacketHashlist;
use crate::path_table::PathTable;
@@ -129,6 +130,26 @@ pub struct PythonCachedAnnounce {
pub interface_reference: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PythonTunnelEntry {
pub tunnel_id: [u8; 32],
pub interface_hash: Option<[u8; 32]>,
pub paths: Vec<PythonTunnelPath>,
pub expires: f64,
}
#[derive(Debug, Clone)]
pub struct PythonTunnelPath {
pub destination_hash: [u8; 16],
pub timestamp: f64,
pub received_from: [u8; 16],
pub hops: u8,
pub expires: f64,
pub random_blobs: Vec<[u8; 10]>,
pub interface_hash: Option<[u8; 32]>,
pub packet_hash: [u8; 32],
}
pub fn interface_hash_from_name(name: &str) -> [u8; 32] {
rns_crypto::sha::full_hash(name.as_bytes())
}
@@ -240,12 +261,32 @@ pub fn save_python_announce_cache_for_paths<'a, I>(
interface_names: &HashMap<u64, String>,
announce_cache_dir: &Path,
) -> Result<(), PersistenceError>
where
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
{
save_python_announce_cache_for_paths_and_tunnels(
path_entries,
None,
announces,
interface_names,
announce_cache_dir,
)
}
pub fn save_python_announce_cache_for_paths_and_tunnels<'a, I>(
path_entries: &PathTable,
tunnel_table: Option<&crate::tunnel::TunnelTable>,
announces: I,
interface_names: &HashMap<u64, String>,
announce_cache_dir: &Path,
) -> Result<(), PersistenceError>
where
I: IntoIterator<Item = &'a crate::actor::RecentAnnounce>,
{
std::fs::create_dir_all(announce_cache_dir).map_err(PersistenceError::Io)?;
let announces_by_dest: HashMap<[u8; 16], &crate::actor::RecentAnnounce> =
announces.into_iter().map(|a| (a.dest_hash, a)).collect();
let mut written = std::collections::HashSet::new();
for (dest_hash, path_entry) in path_entries.iter() {
let Some(packet_hash) = path_entry.packet_hash else {
@@ -261,19 +302,61 @@ where
.get(&path_entry.interface_id)
.map(|name| Value::String(name.as_str().into()))
.unwrap_or(Value::Nil);
let value = Value::Array(vec![
Value::Binary(announce.raw_packet.clone()),
write_python_cached_announce(
announce_cache_dir,
&packet_hash,
announce.raw_packet.clone(),
interface_reference,
]);
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &value)
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
let path = announce_cache_dir.join(hex::encode(packet_hash));
atomic_write_bytes(&path, &serialized)?;
)?;
written.insert(packet_hash);
}
if let Some(tunnel_table) = tunnel_table {
for tunnel in tunnel_table.iter().map(|(_, tunnel)| tunnel) {
let interface_reference = interface_names
.get(&tunnel.interface_id)
.map(|name| Value::String(name.as_str().into()))
.unwrap_or(Value::Nil);
for (dest_hash, tunnel_path) in &tunnel.tunnel_paths {
let Some(packet_hash) = tunnel_path.packet_hash else {
continue;
};
if written.contains(&packet_hash) {
continue;
}
let Some(announce) = announces_by_dest.get(dest_hash) else {
continue;
};
if announce.raw_packet.is_empty() {
continue;
}
write_python_cached_announce(
announce_cache_dir,
&packet_hash,
announce.raw_packet.clone(),
interface_reference.clone(),
)?;
written.insert(packet_hash);
}
}
}
Ok(())
}
fn write_python_cached_announce(
announce_cache_dir: &Path,
packet_hash: &[u8; 32],
raw_packet: Vec<u8>,
interface_reference: Value,
) -> Result<(), PersistenceError> {
let value = Value::Array(vec![Value::Binary(raw_packet), interface_reference]);
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &value)
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
let path = announce_cache_dir.join(hex::encode(packet_hash));
atomic_write_bytes(&path, &serialized)
}
pub fn load_python_cached_announce(
announce_cache_dir: &Path,
packet_hash: &[u8; 32],
@@ -312,6 +395,142 @@ pub fn load_python_cached_announce(
}))
}
pub fn save_python_tunnel_table(
table: &crate::tunnel::TunnelTable,
interface_names: &HashMap<u64, String>,
path: &Path,
) -> Result<(), PersistenceError> {
let mut tunnel_values = Vec::new();
for (_, tunnel) in table.iter() {
let interface_hash = interface_names
.get(&tunnel.interface_id)
.map(|name| Value::Binary(interface_hash_from_name(name).to_vec()))
.unwrap_or(Value::Nil);
let mut path_values = Vec::new();
for (dest_hash, tunnel_path) in &tunnel.tunnel_paths {
let Some(packet_hash) = tunnel_path.packet_hash else {
continue;
};
let received_from = tunnel_path.next_hop.unwrap_or(*dest_hash);
let random_blob_start = tunnel_path
.random_blobs
.len()
.saturating_sub(PERSIST_RANDOM_BLOBS);
let random_blobs = tunnel_path
.random_blobs
.iter()
.skip(random_blob_start)
.map(|blob| Value::Binary(blob.to_vec()))
.collect::<Vec<_>>();
path_values.push(Value::Array(vec![
Value::Binary(dest_hash.to_vec()),
Value::F64(tunnel_path.timestamp),
Value::Binary(received_from.to_vec()),
Value::Integer((tunnel_path.hops as u64).into()),
Value::F64(tunnel_path.expires),
Value::Array(random_blobs),
interface_hash.clone(),
Value::Binary(packet_hash.to_vec()),
]));
}
tunnel_values.push(Value::Array(vec![
Value::Binary(tunnel.tunnel_id.to_vec()),
interface_hash,
Value::Array(path_values),
Value::F64(tunnel.expires),
]));
}
let mut serialized = Vec::new();
rmpv::encode::write_value(&mut serialized, &Value::Array(tunnel_values))
.map_err(|e| PersistenceError::Serialize(e.to_string()))?;
atomic_write_bytes(path, &serialized)
}
pub fn load_python_tunnel_table(path: &Path) -> Result<Vec<PythonTunnelEntry>, PersistenceError> {
let data = std::fs::read(path).map_err(PersistenceError::Io)?;
let value = rmpv::decode::read_value(&mut std::io::Cursor::new(data))
.map_err(|e| PersistenceError::Deserialize(e.to_string()))?;
let entries = match value {
Value::Array(entries) => entries,
other => {
return Err(PersistenceError::Deserialize(format!(
"expected tunnels array, got {other:?}"
)));
}
};
let mut out = Vec::new();
for entry in entries {
let fields = match entry {
Value::Array(fields) => fields,
_ => continue,
};
if fields.len() < 4 {
continue;
}
let Some(tunnel_id) = value_bin_array::<32>(&fields[0]) else {
continue;
};
let interface_hash = match &fields[1] {
Value::Nil => None,
value => value_bin_array::<32>(value),
};
let paths = match &fields[2] {
Value::Array(path_entries) => path_entries
.iter()
.filter_map(|path_entry| {
let Value::Array(path_fields) = path_entry else {
return None;
};
if path_fields.len() < 8 {
return None;
}
let destination_hash = value_bin_array::<16>(&path_fields[0])?;
let timestamp = value_f64(&path_fields[1]).unwrap_or(0.0);
let received_from = value_bin_array::<16>(&path_fields[2])?;
let hops = value_u8(&path_fields[3])?;
let expires = value_f64(&path_fields[4]).unwrap_or(0.0);
let random_blobs = match &path_fields[5] {
Value::Array(values) => values
.iter()
.filter_map(value_bin_array::<10>)
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let interface_hash = match &path_fields[6] {
Value::Nil => None,
value => value_bin_array::<32>(value),
};
let packet_hash = value_bin_array::<32>(&path_fields[7])?;
Some(PythonTunnelPath {
destination_hash,
timestamp,
received_from,
hops,
expires,
random_blobs,
interface_hash,
packet_hash,
})
})
.collect::<Vec<_>>(),
_ => Vec::new(),
};
let expires = value_f64(&fields[3]).unwrap_or(0.0);
out.push(PythonTunnelEntry {
tunnel_id,
interface_hash,
paths,
expires,
});
}
Ok(out)
}
fn value_bin_array<const N: usize>(value: &Value) -> Option<[u8; N]> {
let Value::Binary(bytes) = value else {
return None;
@@ -693,14 +912,24 @@ pub struct PersistedTunnelEntry {
/// stale `interface_id` once the matching interface registers.
#[serde(default)]
pub interface_name: Option<String>,
/// Python-compatible stable interface hash for remapping canonical
/// `tunnels` entries across restarts.
#[serde(default)]
pub interface_hash: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedTunnelPath {
pub destination_hash: Vec<u8>,
#[serde(default)]
pub next_hop: Option<Vec<u8>>,
pub hops: u8,
pub expires: f64,
pub timestamp: f64,
#[serde(default)]
pub random_blobs: Vec<Vec<u8>>,
#[serde(default)]
pub packet_hash: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -710,8 +939,8 @@ pub struct PersistedTunnelTable {
}
impl PersistedTunnelTable {
pub const CURRENT_VERSION: u32 = 2;
pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2];
pub const CURRENT_VERSION: u32 = 3;
pub const SUPPORTED_VERSIONS: &'static [u32] = &[1, 2, 3];
}
pub fn save_tunnel_table(
@@ -729,9 +958,19 @@ pub fn save_tunnel_table(
.iter()
.map(|(dest, tp)| PersistedTunnelPath {
destination_hash: dest.to_vec(),
next_hop: tp.next_hop.map(|h| h.to_vec()),
hops: tp.hops,
expires: tp.expires,
timestamp: tp.timestamp,
random_blobs: {
let start = tp.random_blobs.len().saturating_sub(PERSIST_RANDOM_BLOBS);
tp.random_blobs
.iter()
.skip(start)
.map(|b| b.to_vec())
.collect()
},
packet_hash: tp.packet_hash.map(|h| h.to_vec()),
})
.collect();
Some(PersistedTunnelEntry {
@@ -740,6 +979,9 @@ pub fn save_tunnel_table(
expires: entry.expires,
paths,
interface_name: Some(interface_name),
interface_hash: interface_names
.get(&entry.interface_id)
.map(|name| interface_hash_from_name(name).to_vec()),
})
})
.collect();
@@ -937,6 +1179,88 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn save_load_python_tunnel_table_and_tunnel_announce_cache() {
let destination_hash = [0xAB; 16];
let next_hop = [0xBC; 16];
let packet_hash = [0xCD; 32];
let tunnel_id = [0xDE; 32];
let mut paths = HashMap::new();
paths.insert(
destination_hash,
crate::tunnel::TunnelPath {
timestamp: 1234.5,
next_hop: Some(next_hop),
hops: 3,
expires: 9876.5,
random_blobs: vec![[0x44; 10]],
packet_hash: Some(packet_hash),
},
);
let mut tunnels = crate::tunnel::TunnelTable::new();
tunnels.insert(crate::tunnel::TunnelEntry {
tunnel_id,
interface_id: 7,
tunnel_paths: paths,
expires: 9999.5,
});
let mut names = HashMap::new();
names.insert(7, "Interface[Tunnel]".to_string());
let dir = std::env::temp_dir().join("reticulum_rs_test_python_tunnels");
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let tunnels_path = dir.join("tunnels");
save_python_tunnel_table(&tunnels, &names, &tunnels_path).unwrap();
let loaded = load_python_tunnel_table(&tunnels_path).unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].tunnel_id, tunnel_id);
assert_eq!(
loaded[0].interface_hash,
Some(interface_hash_from_name("Interface[Tunnel]"))
);
assert_eq!(loaded[0].expires, 9999.5);
assert_eq!(loaded[0].paths.len(), 1);
assert_eq!(loaded[0].paths[0].destination_hash, destination_hash);
assert_eq!(loaded[0].paths[0].received_from, next_hop);
assert_eq!(loaded[0].paths[0].hops, 3);
assert_eq!(loaded[0].paths[0].packet_hash, packet_hash);
let announces = [crate::actor::RecentAnnounce {
dest_hash: destination_hash,
hops: 3,
app_data: None,
timestamp: 1234.5,
public_key: None,
ratchet: None,
raw_packet: vec![0xFE; 42],
retained: false,
name_hash: [0xAB; 10],
}];
let empty_paths = PathTable::new();
let cache_dir = dir.join("cache").join("announces");
save_python_announce_cache_for_paths_and_tunnels(
&empty_paths,
Some(&tunnels),
announces.iter(),
&names,
&cache_dir,
)
.unwrap();
let cached = load_python_cached_announce(&cache_dir, &packet_hash)
.unwrap()
.unwrap();
assert_eq!(cached.raw_packet, vec![0xFE; 42]);
assert_eq!(
cached.interface_reference.as_deref(),
Some("Interface[Tunnel]")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn test_save_load_hashlist() {
let mut hashlist = PacketHashlist::new();
+14
View File
@@ -16,9 +16,11 @@ pub struct TunnelEntry {
#[derive(Debug, Clone)]
pub struct TunnelPath {
pub timestamp: f64,
pub next_hop: Option<[u8; 16]>,
pub hops: u8,
pub expires: f64,
pub random_blobs: Vec<[u8; 10]>,
pub packet_hash: Option<[u8; 32]>,
}
pub struct TunnelTable {
@@ -64,6 +66,18 @@ impl TunnelTable {
self.entries.iter_mut()
}
pub fn get_mut_by_interface(&mut self, interface_id: InterfaceId) -> Option<&mut TunnelEntry> {
self.entries
.values_mut()
.find(|entry| entry.interface_id == interface_id)
}
pub fn tunnel_paths(&self) -> impl Iterator<Item = (&[u8; 16], &TunnelPath)> {
self.entries
.values()
.flat_map(|entry| entry.tunnel_paths.iter())
}
pub fn cull_expired(&mut self) -> usize {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)