feat(client): TLS 1.3 control connection with SPKI pinning and LNEx v3
Replace the custom X25519/HKDF/ChaCha20 TCP layer with rustls (TLS 1.3 only, ALPN vnox-lnex/3, no plaintext or fallback). Add a trust store (pin, trust on first use, public CA), block changed fingerprints and identities, bind the Ed25519 auth signature to the TLS exporter, add RU/EN trust dialog and update the interop test and e2e voice tool.
This commit is contained in:
parent
5f594046a6
commit
29883a3187
31 changed files with 2085 additions and 567 deletions
206
Cargo.lock
generated
206
Cargo.lock
generated
|
|
@ -298,6 +298,45 @@ dependencies = [
|
||||||
"libloading",
|
"libloading",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "asn1-rs"
|
||||||
|
version = "0.7.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
|
||||||
|
dependencies = [
|
||||||
|
"asn1-rs-derive",
|
||||||
|
"asn1-rs-impl",
|
||||||
|
"displaydoc",
|
||||||
|
"nom 7.1.3",
|
||||||
|
"num-traits",
|
||||||
|
"rusticata-macros",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"time",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "asn1-rs-derive"
|
||||||
|
version = "0.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
"synstructure 0.13.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "asn1-rs-impl"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "async-channel"
|
name = "async-channel"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
|
|
@ -458,6 +497,9 @@ name = "bit-vec"
|
||||||
version = "0.9.1"
|
version = "0.9.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
|
|
@ -1108,12 +1150,38 @@ version = "0.11.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "data-encoding"
|
||||||
|
version = "2.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "data-url"
|
name = "data-url"
|
||||||
version = "0.3.2"
|
version = "0.3.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
|
checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "der-parser"
|
||||||
|
version = "10.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
|
||||||
|
dependencies = [
|
||||||
|
"asn1-rs",
|
||||||
|
"displaydoc",
|
||||||
|
"nom 7.1.3",
|
||||||
|
"num-bigint",
|
||||||
|
"num-traits",
|
||||||
|
"rusticata-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deranged"
|
||||||
|
version = "0.5.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "derive_more"
|
name = "derive_more"
|
||||||
version = "2.1.1"
|
version = "2.1.1"
|
||||||
|
|
@ -3368,6 +3436,16 @@ dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-bigint"
|
||||||
|
version = "0.4.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||||
|
dependencies = [
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-complex"
|
name = "num-complex"
|
||||||
version = "0.4.6"
|
version = "0.4.6"
|
||||||
|
|
@ -3378,6 +3456,12 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-conv"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-derive"
|
name = "num-derive"
|
||||||
version = "0.4.2"
|
version = "0.4.2"
|
||||||
|
|
@ -3816,6 +3900,15 @@ dependencies = [
|
||||||
"objc2-foundation 0.2.2",
|
"objc2-foundation 0.2.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "oid-registry"
|
||||||
|
version = "0.8.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
|
||||||
|
dependencies = [
|
||||||
|
"asn1-rs",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
|
|
@ -3977,6 +4070,16 @@ version = "0.2.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pem"
|
||||||
|
version = "4.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.2"
|
version = "2.3.2"
|
||||||
|
|
@ -4185,6 +4288,12 @@ dependencies = [
|
||||||
"zerovec",
|
"zerovec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "powerfmt"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "presser"
|
name = "presser"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
|
|
@ -4399,6 +4508,20 @@ dependencies = [
|
||||||
"crossbeam-utils",
|
"crossbeam-utils",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rcgen"
|
||||||
|
version = "0.14.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
|
||||||
|
dependencies = [
|
||||||
|
"pem",
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"time",
|
||||||
|
"x509-parser",
|
||||||
|
"yasna",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "read-fonts"
|
name = "read-fonts"
|
||||||
version = "0.41.0"
|
version = "0.41.0"
|
||||||
|
|
@ -4629,6 +4752,15 @@ dependencies = [
|
||||||
"transpose",
|
"transpose",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rusticata-macros"
|
||||||
|
version = "4.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
|
||||||
|
dependencies = [
|
||||||
|
"nom 7.1.3",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "0.38.44"
|
version = "0.38.44"
|
||||||
|
|
@ -5227,6 +5359,17 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "synstructure"
|
||||||
|
version = "0.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.119",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "synstructure"
|
name = "synstructure"
|
||||||
version = "0.14.0"
|
version = "0.14.0"
|
||||||
|
|
@ -5360,6 +5503,36 @@ dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time"
|
||||||
|
version = "0.3.55"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||||
|
dependencies = [
|
||||||
|
"deranged",
|
||||||
|
"num-conv",
|
||||||
|
"powerfmt",
|
||||||
|
"serde_core",
|
||||||
|
"time-core",
|
||||||
|
"time-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-core"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "time-macros"
|
||||||
|
version = "0.2.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||||
|
dependencies = [
|
||||||
|
"num-conv",
|
||||||
|
"time-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tiny-skia"
|
name = "tiny-skia"
|
||||||
version = "0.11.4"
|
version = "0.11.4"
|
||||||
|
|
@ -5810,6 +5983,7 @@ dependencies = [
|
||||||
"prost",
|
"prost",
|
||||||
"prost-build",
|
"prost-build",
|
||||||
"rand",
|
"rand",
|
||||||
|
"rcgen",
|
||||||
"rfd",
|
"rfd",
|
||||||
"rustls",
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
|
|
@ -6628,6 +6802,24 @@ dependencies = [
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "x509-parser"
|
||||||
|
version = "0.18.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
|
||||||
|
dependencies = [
|
||||||
|
"asn1-rs",
|
||||||
|
"data-encoding",
|
||||||
|
"der-parser",
|
||||||
|
"lazy_static",
|
||||||
|
"nom 7.1.3",
|
||||||
|
"oid-registry",
|
||||||
|
"ring",
|
||||||
|
"rusticata-macros",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"time",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "xattr"
|
name = "xattr"
|
||||||
version = "1.6.1"
|
version = "1.6.1"
|
||||||
|
|
@ -6675,6 +6867,16 @@ version = "0.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "yasna"
|
||||||
|
version = "0.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
|
||||||
|
dependencies = [
|
||||||
|
"bit-vec",
|
||||||
|
"time",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yazi"
|
name = "yazi"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
|
|
@ -6712,7 +6914,7 @@ dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn 3.0.9",
|
"syn 3.0.9",
|
||||||
"synstructure",
|
"synstructure 0.14.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -6852,7 +7054,7 @@ dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn 3.0.9",
|
"syn 3.0.9",
|
||||||
"synstructure",
|
"synstructure 0.14.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
|
||||||
|
|
@ -62,6 +62,11 @@ nnnoiseless = { version = "0.5.2", default-features = false, optional = t
|
||||||
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] }
|
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp"] }
|
||||||
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal", "wayland"] }
|
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal", "wayland"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
# Test gateway certificates, and a TLS 1.2 only server for the downgrade test.
|
||||||
|
rcgen = "0.14"
|
||||||
|
rustls = { version = "0.23", features = ["tls12"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["screen-capture"]
|
default = ["screen-capture"]
|
||||||
rnnoise = ["dep:nnnoiseless"]
|
rnnoise = ["dep:nnnoiseless"]
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,11 @@ message Hello {
|
||||||
bytes server_pubkey = 2;
|
bytes server_pubkey = 2;
|
||||||
bytes challenge_nonce = 3;
|
bytes challenge_nonce = 3;
|
||||||
string node_name = 4;
|
string node_name = 4;
|
||||||
bytes server_eph_pubkey = 5;
|
// LNEx v3: the ephemeral X25519 exchange was replaced by TLS 1.3.
|
||||||
|
reserved 5;
|
||||||
|
reserved "server_eph_pubkey";
|
||||||
bool private_mode = 6;
|
bool private_mode = 6;
|
||||||
|
// Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty).
|
||||||
bytes server_signature = 7;
|
bytes server_signature = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -17,8 +20,10 @@ message Auth {
|
||||||
bytes client_pubkey = 1;
|
bytes client_pubkey = 1;
|
||||||
string nickname = 2;
|
string nickname = 2;
|
||||||
string lnex_version = 3;
|
string lnex_version = 3;
|
||||||
|
// Ed25519 over the client-auth transcript bound to the TLS exporter (see docs/02-protocol/tls.md).
|
||||||
bytes signature = 4;
|
bytes signature = 4;
|
||||||
bytes client_eph_pubkey = 5;
|
reserved 5;
|
||||||
|
reserved "client_eph_pubkey";
|
||||||
}
|
}
|
||||||
|
|
||||||
message Session {
|
message Session {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
//! Headless authenticated voice smoke test. Run vnox-serverd first (combined gateway+voice relay).
|
//! Headless authenticated voice smoke test. Run vnox-serverd first (combined gateway+voice relay).
|
||||||
|
//!
|
||||||
|
//! The control connection is TLS 1.3, so the gateway certificate must be trusted. Pass the
|
||||||
|
//! fingerprint printed by the gateway (`--fingerprint HEX`) or, for a throwaway loopback
|
||||||
|
//! check only, `--trust-first-use`. The trust store is in memory: nothing is persisted.
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use tokio::time::{Duration, timeout};
|
use tokio::time::{Duration, timeout};
|
||||||
use vnox_client::{
|
use vnox_client::{
|
||||||
|
|
@ -9,15 +13,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res
|
||||||
timeout(Duration::from_secs(8), async {
|
timeout(Duration::from_secs(8), async {
|
||||||
loop {
|
loop {
|
||||||
if let Some(event) = handle.try_recv() {
|
if let Some(event) = handle.try_recv() {
|
||||||
|
if predicate(&event) {
|
||||||
|
return Ok(event);
|
||||||
|
}
|
||||||
if let NetEvent::Disconnected { ref reason, .. } = event {
|
if let NetEvent::Disconnected { ref reason, .. } = event {
|
||||||
anyhow::bail!("connection ended: {reason}");
|
anyhow::bail!("connection ended: {reason}");
|
||||||
}
|
}
|
||||||
if let NetEvent::Error { code, ref message } = event {
|
if let NetEvent::Error { code, ref message } = event {
|
||||||
anyhow::bail!("gateway error {code}: {message}");
|
anyhow::bail!("gateway error {code}: {message}");
|
||||||
}
|
}
|
||||||
if predicate(&event) {
|
|
||||||
return Ok(event);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||||
}
|
}
|
||||||
|
|
@ -25,14 +29,42 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Res
|
||||||
.await
|
.await
|
||||||
.context("timed out waiting for network event")?
|
.context("timed out waiting for network event")?
|
||||||
}
|
}
|
||||||
async fn client(name: &str, address: &str) -> Result<NetHandle> {
|
/// How the smoke test decides about the gateway certificate.
|
||||||
let handle = net::spawn(identity::generate(name));
|
enum Trust {
|
||||||
|
Fingerprint(String),
|
||||||
|
FirstUse,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn client(name: &str, address: &str, trust: &Trust) -> Result<NetHandle> {
|
||||||
|
let handle = net::spawn_with_trust(identity::generate(name), net::TrustStore::in_memory());
|
||||||
|
let key = net::trust::parse_address(address)?.key;
|
||||||
|
match trust {
|
||||||
|
Trust::Fingerprint(fingerprint) => handle.trust().pin(&key, fingerprint)?,
|
||||||
|
Trust::FirstUse => {}
|
||||||
|
}
|
||||||
handle
|
handle
|
||||||
.send(NetCommand::Connect {
|
.send(NetCommand::Connect {
|
||||||
address: address.into(),
|
address: address.into(),
|
||||||
auto_reconnect: false,
|
auto_reconnect: false,
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
if matches!(trust, Trust::FirstUse) {
|
||||||
|
// The explicit opt-in replaces the interactive prompt: pin what the gateway presents.
|
||||||
|
if let NetEvent::TrustProblem(net::TrustProblem::Untrusted { fingerprint, .. }) =
|
||||||
|
event(&handle, |e| matches!(e, NetEvent::TrustProblem(_))).await?
|
||||||
|
{
|
||||||
|
eprintln!("trusting gateway fingerprint {fingerprint} (--trust-first-use)");
|
||||||
|
handle.trust().pin(&key, &fingerprint)?;
|
||||||
|
// The refused first attempt reports its disconnect before we reconnect.
|
||||||
|
event(&handle, |e| matches!(e, NetEvent::Disconnected { .. })).await?;
|
||||||
|
handle
|
||||||
|
.send(NetCommand::Connect {
|
||||||
|
address: address.into(),
|
||||||
|
auto_reconnect: false,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
event(
|
event(
|
||||||
&handle,
|
&handle,
|
||||||
|event| matches!(event,NetEvent::ChannelState {channel_id,..} if channel_id=="general"),
|
|event| matches!(event,NetEvent::ChannelState {channel_id,..} if channel_id=="general"),
|
||||||
|
|
@ -52,11 +84,26 @@ async fn client(name: &str, address: &str) -> Result<NetHandle> {
|
||||||
}
|
}
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() -> Result<()> {
|
||||||
let address = std::env::args()
|
let mut address = "127.0.0.1:7600".to_string();
|
||||||
.nth(1)
|
let mut trust = None;
|
||||||
.unwrap_or_else(|| "127.0.0.1:7600".into());
|
let mut args = std::env::args().skip(1);
|
||||||
let alice = client("voice-fixture-alice", &address).await?;
|
while let Some(argument) = args.next() {
|
||||||
let bob = client("voice-fixture-bob", &address).await?;
|
match argument.as_str() {
|
||||||
|
"--trust-first-use" => trust = Some(Trust::FirstUse),
|
||||||
|
"--fingerprint" => {
|
||||||
|
let value = args.next().context("--fingerprint needs a value")?;
|
||||||
|
trust = Some(Trust::Fingerprint(net::trust::normalize_fingerprint(
|
||||||
|
&value,
|
||||||
|
)?));
|
||||||
|
}
|
||||||
|
other => address = other.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let trust = trust.context(
|
||||||
|
"the gateway certificate must be trusted: pass --fingerprint HEX (from the gateway log) or --trust-first-use",
|
||||||
|
)?;
|
||||||
|
let alice = client("voice-fixture-alice", &address, &trust).await?;
|
||||||
|
let bob = client("voice-fixture-bob", &address, &trust).await?;
|
||||||
// The real network layer registers the current credentials with encrypted empty-Opus packets.
|
// The real network layer registers the current credentials with encrypted empty-Opus packets.
|
||||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||||
let marker = b"authenticated-vnox-voice-fixture";
|
let marker = b"authenticated-vnox-voice-fixture";
|
||||||
|
|
@ -113,6 +160,6 @@ async fn main() -> Result<()> {
|
||||||
.await?;
|
.await?;
|
||||||
alice.send(NetCommand::Disconnect).await;
|
alice.send(NetCommand::Disconnect).await;
|
||||||
bob.send(NetCommand::Disconnect).await;
|
bob.send(NetCommand::Disconnect).await;
|
||||||
println!("Authenticated v2 UDP voice relay passed");
|
println!("TLS 1.3 control plane and authenticated UDP voice relay passed");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
54
src/main.rs
54
src/main.rs
|
|
@ -353,6 +353,60 @@ fn wire_signals(window: &MainWindow, state: &Rc<RefCell<AppState>>) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// First trust: remember the confirmed fingerprint, then connect again.
|
||||||
|
let state = state.clone();
|
||||||
|
window.on_trust_accept(move || {
|
||||||
|
let mut s = state.borrow_mut();
|
||||||
|
let Some(prompt) = s.ui.trust_prompt.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if prompt.kind != ui::state::TrustPromptKind::FirstUse {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Err(error) = s.net.trust().pin(&prompt.address, &prompt.received) {
|
||||||
|
tracing::warn!(%error, "could not save the trusted fingerprint");
|
||||||
|
s.ui.status_msg = Some("Could not save the trusted fingerprint".into());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s.ui.conn = ConnState::Connecting;
|
||||||
|
s.ui.status_msg = Some("Connecting…".into());
|
||||||
|
let auto_reconnect = s.ui.auto_reconnect;
|
||||||
|
let net = s.net.clone();
|
||||||
|
drop(s);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
net.send(NetCommand::Connect {
|
||||||
|
address: prompt.address,
|
||||||
|
auto_reconnect,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
// A blocked change: forgetting is the only way forward and needs a new decision.
|
||||||
|
let state = state.clone();
|
||||||
|
window.on_trust_forget(move || {
|
||||||
|
let mut s = state.borrow_mut();
|
||||||
|
let Some(prompt) = s.ui.trust_prompt.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if let Err(error) = s.net.trust().forget(&prompt.address) {
|
||||||
|
tracing::warn!(%error, "could not forget the server");
|
||||||
|
}
|
||||||
|
s.ui.status_msg =
|
||||||
|
Some("Server forgotten. Connect again to review its fingerprint.".into());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let state = state.clone();
|
||||||
|
window.on_trust_dismiss(move || {
|
||||||
|
state.borrow_mut().ui.trust_prompt = None;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let state = state.clone();
|
let state = state.clone();
|
||||||
window.on_disconnect(move || {
|
window.on_disconnect(move || {
|
||||||
|
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
use chacha20poly1305::{
|
|
||||||
ChaCha20Poly1305, Key, KeyInit, Nonce,
|
|
||||||
aead::{Aead, Payload},
|
|
||||||
};
|
|
||||||
|
|
||||||
fn make_nonce(cid: &[u8; 8], seq: u64) -> [u8; 12] {
|
|
||||||
let mut nonce = [0u8; 12];
|
|
||||||
nonce[..8].copy_from_slice(cid);
|
|
||||||
nonce[8..12].copy_from_slice(&(seq as u32).to_le_bytes());
|
|
||||||
nonce
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn encrypt_with_key(key: &[u8; 32], cid: &[u8; 8], seq: u64, plaintext: &[u8]) -> Vec<u8> {
|
|
||||||
encrypt_with_aad(key, cid, seq, plaintext, &[])
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn encrypt_with_aad(
|
|
||||||
key: &[u8; 32],
|
|
||||||
cid: &[u8; 8],
|
|
||||||
seq: u64,
|
|
||||||
plaintext: &[u8],
|
|
||||||
aad: &[u8],
|
|
||||||
) -> Vec<u8> {
|
|
||||||
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
|
|
||||||
let nonce_bytes = make_nonce(cid, seq);
|
|
||||||
let nonce = Nonce::from(nonce_bytes);
|
|
||||||
cipher
|
|
||||||
.encrypt(
|
|
||||||
&nonce,
|
|
||||||
Payload {
|
|
||||||
msg: plaintext,
|
|
||||||
aad,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.expect("ChaCha20-Poly1305 encryption infallible")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn decrypt_with_key(
|
|
||||||
key: &[u8; 32],
|
|
||||||
cid: &[u8; 8],
|
|
||||||
seq: u64,
|
|
||||||
ciphertext: &[u8],
|
|
||||||
) -> anyhow::Result<Vec<u8>> {
|
|
||||||
decrypt_with_aad(key, cid, seq, ciphertext, &[])
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decrypt_with_aad(
|
|
||||||
key: &[u8; 32],
|
|
||||||
cid: &[u8; 8],
|
|
||||||
seq: u64,
|
|
||||||
ciphertext: &[u8],
|
|
||||||
aad: &[u8],
|
|
||||||
) -> anyhow::Result<Vec<u8>> {
|
|
||||||
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
|
|
||||||
let nonce_bytes = make_nonce(cid, seq);
|
|
||||||
let nonce = Nonce::from(nonce_bytes);
|
|
||||||
cipher
|
|
||||||
.decrypt(
|
|
||||||
&nonce,
|
|
||||||
Payload {
|
|
||||||
msg: ciphertext,
|
|
||||||
aad,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.map_err(|e| anyhow::anyhow!("decryption failed: {e:?}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ciphertext_matches_existing_lnex_wire_format() {
|
|
||||||
let key = core::array::from_fn(|index| index as u8);
|
|
||||||
let cid = [7, 0, 0, 0, 0x40, 0x41, 0x42, 0x43];
|
|
||||||
// Independently checked with Python cryptography and shared with gateway.
|
|
||||||
let expected = hex::decode(
|
|
||||||
"1fa23e7a312509b0fc8729521811348ff880daa5598c43a57635975f81278abdf4461b25af86aee1c3",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let ciphertext = encrypt_with_key(&key, &cid, 0x47464544, b"VNOX dependency migration");
|
|
||||||
assert_eq!(ciphertext, expected);
|
|
||||||
assert_eq!(
|
|
||||||
decrypt_with_key(&key, &cid, 0x47464544, &expected).unwrap(),
|
|
||||||
b"VNOX dependency migration",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
||||||
use hkdf::Hkdf;
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret};
|
|
||||||
|
|
||||||
pub mod cipher;
|
|
||||||
|
|
||||||
/// Session encryption context (mirrors gateway/src/proto/crypto.rs).
|
|
||||||
///
|
|
||||||
/// Two derived keys:
|
|
||||||
/// - `c2s_key`: client → server
|
|
||||||
/// - `s2c_key`: server → client
|
|
||||||
///
|
|
||||||
/// Nonce: `cid (8 bytes) || packet_seq (4 bytes LE)`.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct SessionCrypto {
|
|
||||||
c2s_key: [u8; 32],
|
|
||||||
s2c_key: [u8; 32],
|
|
||||||
cid: [u8; 8],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SessionCrypto {
|
|
||||||
pub fn derive(shared_secret: &[u8; 32], session_id: &str) -> Self {
|
|
||||||
let salt = b"VNOX-LNEx-KDF-v2";
|
|
||||||
let hk = Hkdf::<Sha256>::new(Some(salt), shared_secret);
|
|
||||||
|
|
||||||
let mut keys = [0u8; 64];
|
|
||||||
hk.expand(b"session-keys", &mut keys)
|
|
||||||
.expect("64 bytes within HKDF max");
|
|
||||||
|
|
||||||
let c2s_key: [u8; 32] = keys[..32].try_into().unwrap();
|
|
||||||
let s2c_key: [u8; 32] = keys[32..64].try_into().unwrap();
|
|
||||||
|
|
||||||
let hash = Sha256::digest(session_id.as_bytes());
|
|
||||||
let cid: [u8; 8] = hash[..8].try_into().unwrap();
|
|
||||||
|
|
||||||
Self {
|
|
||||||
c2s_key,
|
|
||||||
s2c_key,
|
|
||||||
cid,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn encrypt_c2s_aad(&self, seq: u64, plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
|
|
||||||
cipher::encrypt_with_aad(&self.c2s_key, &self.cid, seq, plaintext, aad)
|
|
||||||
}
|
|
||||||
pub fn decrypt_s2c_aad(
|
|
||||||
&self,
|
|
||||||
seq: u64,
|
|
||||||
ciphertext: &[u8],
|
|
||||||
aad: &[u8],
|
|
||||||
) -> anyhow::Result<Vec<u8>> {
|
|
||||||
cipher::decrypt_with_aad(&self.s2c_key, &self.cid, seq, ciphertext, aad)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) {
|
|
||||||
let mut rng = rand::rng();
|
|
||||||
let sk = EphemeralSecret::random_from_rng(&mut rng);
|
|
||||||
let pk = PublicKey::from(&sk);
|
|
||||||
(sk, pk)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn ecdh(secret: EphemeralSecret, peer_public: &PublicKey) -> SharedSecret {
|
|
||||||
secret.diffie_hellman(peer_public)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn encrypt_then_decrypt_roundtrip() {
|
|
||||||
let shared_secret = [0xABu8; 32];
|
|
||||||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
|
||||||
|
|
||||||
let plaintext = b"hello encrypted world";
|
|
||||||
let ct = crypto.encrypt_c2s_aad(42, plaintext, b"header");
|
|
||||||
let decrypted =
|
|
||||||
cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 42, &ct, b"header").unwrap();
|
|
||||||
assert_eq!(decrypted, plaintext);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tampered_ciphertext_fails() {
|
|
||||||
let shared_secret = [0xABu8; 32];
|
|
||||||
let crypto = SessionCrypto::derive(&shared_secret, "test-session");
|
|
||||||
|
|
||||||
let mut ct = crypto.encrypt_c2s_aad(0, b"data", b"header");
|
|
||||||
ct[5] ^= 0xFF;
|
|
||||||
assert!(cipher::decrypt_with_aad(&crypto.c2s_key, &crypto.cid, 0, &ct, b"header").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,66 +1,9 @@
|
||||||
|
//! Session frame reader. Frames travel inside the TLS 1.3 stream, so there is no per frame
|
||||||
|
//! encryption: a dedicated task retains partial frames across command/timer selection and
|
||||||
|
//! enforces strictly increasing sequence numbers.
|
||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use tokio::io::AsyncReadExt;
|
|
||||||
use tokio::io::AsyncWriteExt;
|
|
||||||
|
|
||||||
use super::super::crypto::SessionCrypto;
|
|
||||||
use super::super::payloads::HDR_SIZE;
|
|
||||||
use super::RawPacket;
|
use super::RawPacket;
|
||||||
use super::parse_header;
|
|
||||||
|
|
||||||
const ENCRYPTED_FLAG: u16 = 1 << 1;
|
|
||||||
const KNOWN_FLAGS: u16 = ENCRYPTED_FLAG;
|
|
||||||
|
|
||||||
pub async fn read_encrypted(
|
|
||||||
stream: &mut (impl tokio::io::AsyncRead + Unpin),
|
|
||||||
crypto: &SessionCrypto,
|
|
||||||
) -> Result<RawPacket> {
|
|
||||||
let mut buf = [0u8; HDR_SIZE];
|
|
||||||
stream.read_exact(&mut buf).await?;
|
|
||||||
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
|
||||||
if flags & !KNOWN_FLAGS != 0 {
|
|
||||||
return Err(anyhow!("unknown packet flags: 0x{:04X}", flags));
|
|
||||||
}
|
|
||||||
if flags & ENCRYPTED_FLAG == 0 {
|
|
||||||
return Err(anyhow!("packet not encrypted"));
|
|
||||||
}
|
|
||||||
let mut encrypted = vec![0u8; payload_length as usize];
|
|
||||||
if !encrypted.is_empty() {
|
|
||||||
stream.read_exact(&mut encrypted).await?;
|
|
||||||
}
|
|
||||||
let payload = crypto.decrypt_s2c_aad(sequence as u64, &encrypted, &buf)?;
|
|
||||||
Ok(RawPacket {
|
|
||||||
packet_id,
|
|
||||||
sequence,
|
|
||||||
payload,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn write_encrypted(
|
|
||||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
|
||||||
id: u16,
|
|
||||||
seq: &mut u32,
|
|
||||||
payload: &[u8],
|
|
||||||
crypto: &SessionCrypto,
|
|
||||||
) -> Result<()> {
|
|
||||||
if *seq == u32::MAX {
|
|
||||||
return Err(anyhow!("session sequence exhausted; reconnect required"));
|
|
||||||
}
|
|
||||||
if payload.len() > super::super::payloads::MAX_PAYLOAD as usize - 16 {
|
|
||||||
return Err(anyhow!("payload too large"));
|
|
||||||
}
|
|
||||||
let mut hdr = [0u8; HDR_SIZE];
|
|
||||||
hdr[0..2].copy_from_slice(&id.to_be_bytes());
|
|
||||||
hdr[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes());
|
|
||||||
hdr[4..8].copy_from_slice(&seq.to_be_bytes());
|
|
||||||
hdr[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
|
|
||||||
let encrypted = crypto.encrypt_c2s_aad(*seq as u64, payload, &hdr);
|
|
||||||
*seq += 1;
|
|
||||||
let mut frame = Vec::with_capacity(HDR_SIZE + encrypted.len());
|
|
||||||
frame.extend_from_slice(&hdr);
|
|
||||||
frame.extend_from_slice(&encrypted);
|
|
||||||
stream.write_all(&frame).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A dedicated reader retains partial frames across command/timer selection.
|
/// A dedicated reader retains partial frames across command/timer selection.
|
||||||
/// Dropping a session cancels its reader and releases the socket half.
|
/// Dropping a session cancels its reader and releases the socket half.
|
||||||
|
|
@ -69,25 +12,21 @@ pub struct Reader {
|
||||||
task: tokio::task::JoinHandle<()>,
|
task: tokio::task::JoinHandle<()>,
|
||||||
}
|
}
|
||||||
impl Reader {
|
impl Reader {
|
||||||
pub fn new(
|
pub fn new(mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static) -> Self {
|
||||||
mut stream: impl tokio::io::AsyncRead + Unpin + Send + 'static,
|
|
||||||
crypto: SessionCrypto,
|
|
||||||
) -> Self {
|
|
||||||
let (sender, receiver) = tokio::sync::mpsc::channel(32);
|
let (sender, receiver) = tokio::sync::mpsc::channel(32);
|
||||||
let task = tokio::spawn(async move {
|
let task = tokio::spawn(async move {
|
||||||
|
// HELLO was 0 and SESSION was 1.
|
||||||
let mut expected = 2u32;
|
let mut expected = 2u32;
|
||||||
loop {
|
loop {
|
||||||
let result = read_encrypted(&mut stream, &crypto)
|
let result = super::read(&mut stream).await.and_then(|packet| {
|
||||||
.await
|
if packet.sequence != expected {
|
||||||
.and_then(|packet| {
|
return Err(anyhow!("replayed or reordered control packet"));
|
||||||
if packet.sequence != expected {
|
}
|
||||||
return Err(anyhow!("replayed or reordered control packet"));
|
expected = expected
|
||||||
}
|
.checked_add(1)
|
||||||
expected = expected
|
.ok_or_else(|| anyhow!("session sequence exhausted"))?;
|
||||||
.checked_add(1)
|
Ok(packet)
|
||||||
.ok_or_else(|| anyhow!("session sequence exhausted"))?;
|
});
|
||||||
Ok(packet)
|
|
||||||
});
|
|
||||||
let failed = result.is_err();
|
let failed = result.is_err();
|
||||||
if sender.send(result).await.is_err() || failed {
|
if sender.send(result).await.is_err() || failed {
|
||||||
break;
|
break;
|
||||||
|
|
@ -112,34 +51,18 @@ impl Drop for Reader {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use hkdf::Hkdf;
|
use tokio::io::AsyncWriteExt;
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use tokio::time::{Duration, timeout};
|
use tokio::time::{Duration, timeout};
|
||||||
|
|
||||||
fn server_frame(pid: u16, seq: u32, payload: &[u8]) -> Vec<u8> {
|
fn server_frame(pid: u16, seq: u32, payload: &[u8]) -> Vec<u8> {
|
||||||
let mut keys = [0u8; 64];
|
let mut seq = seq;
|
||||||
Hkdf::<Sha256>::new(Some(b"VNOX-LNEx-KDF-v2"), &[7; 32])
|
super::super::encode_frame(pid, &mut seq, payload)
|
||||||
.expand(b"session-keys", &mut keys)
|
|
||||||
.unwrap();
|
|
||||||
let key: [u8; 32] = keys[32..].try_into().unwrap();
|
|
||||||
let cid: [u8; 8] = Sha256::digest(b"fixture-session")[..8].try_into().unwrap();
|
|
||||||
let mut header = [0u8; 12];
|
|
||||||
header[..2].copy_from_slice(&pid.to_be_bytes());
|
|
||||||
header[2..4].copy_from_slice(&ENCRYPTED_FLAG.to_be_bytes());
|
|
||||||
header[4..8].copy_from_slice(&seq.to_be_bytes());
|
|
||||||
header[8..].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
|
|
||||||
let body =
|
|
||||||
crate::net::crypto::cipher::encrypt_with_aad(&key, &cid, seq as u64, payload, &header);
|
|
||||||
[header.as_slice(), body.as_slice()].concat()
|
|
||||||
}
|
|
||||||
fn crypto() -> SessionCrypto {
|
|
||||||
SessionCrypto::derive(&[7; 32], "fixture-session")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn cancelling_wait_retains_partial_control_frame() {
|
async fn cancelling_wait_retains_partial_control_frame() {
|
||||||
let (reader, mut writer) = tokio::io::duplex(256);
|
let (reader, mut writer) = tokio::io::duplex(256);
|
||||||
let mut reader = Reader::new(reader, crypto());
|
let mut reader = Reader::new(reader);
|
||||||
let frame = server_frame(5, 2, b"protobuf");
|
let frame = server_frame(5, 2, b"protobuf");
|
||||||
writer.write_all(&frame[..5]).await.unwrap();
|
writer.write_all(&frame[..5]).await.unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
|
|
@ -157,7 +80,7 @@ mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn replayed_control_sequence_is_rejected() {
|
async fn replayed_control_sequence_is_rejected() {
|
||||||
let (reader, mut writer) = tokio::io::duplex(256);
|
let (reader, mut writer) = tokio::io::duplex(256);
|
||||||
let mut reader = Reader::new(reader, crypto());
|
let mut reader = Reader::new(reader);
|
||||||
let frame = server_frame(5, 2, b"");
|
let frame = server_frame(5, 2, b"");
|
||||||
writer.write_all(&frame).await.unwrap();
|
writer.write_all(&frame).await.unwrap();
|
||||||
reader.next().await.unwrap();
|
reader.next().await.unwrap();
|
||||||
|
|
@ -165,22 +88,12 @@ mod tests {
|
||||||
assert!(reader.next().await.is_err());
|
assert!(reader.next().await.is_err());
|
||||||
}
|
}
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn changing_packet_id_invalidates_authentication() {
|
async fn legacy_encrypted_flag_is_rejected() {
|
||||||
let (mut reader, mut writer) = tokio::io::duplex(256);
|
let (reader, mut writer) = tokio::io::duplex(256);
|
||||||
let mut frame = server_frame(5, 2, b"same body");
|
let mut reader = Reader::new(reader);
|
||||||
frame[1] ^= 1;
|
let mut frame = server_frame(5, 2, b"0123456789abcdef");
|
||||||
|
frame[2..4].copy_from_slice(&2u16.to_be_bytes());
|
||||||
writer.write_all(&frame).await.unwrap();
|
writer.write_all(&frame).await.unwrap();
|
||||||
assert!(read_encrypted(&mut reader, &crypto()).await.is_err());
|
assert!(reader.next().await.is_err());
|
||||||
}
|
|
||||||
#[tokio::test]
|
|
||||||
async fn sequence_exhaustion_never_wraps_nonce() {
|
|
||||||
let (_, mut writer) = tokio::io::duplex(256);
|
|
||||||
let mut seq = u32::MAX;
|
|
||||||
assert!(
|
|
||||||
write_encrypted(&mut writer, 4, &mut seq, b"", &crypto())
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert_eq!(seq, u32::MAX);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ pub fn decode_frame(bytes: &[u8]) -> Result<RawPacket> {
|
||||||
let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length");
|
let hdr: [u8; HDR_SIZE] = bytes[..HDR_SIZE].try_into().expect("header length");
|
||||||
let (packet_id, flags, sequence, payload_length) = parse_header(&hdr)?;
|
let (packet_id, flags, sequence, payload_length) = parse_header(&hdr)?;
|
||||||
if flags != 0 {
|
if flags != 0 {
|
||||||
return Err(anyhow!("unexpected handshake flags"));
|
return Err(anyhow!("unexpected frame flags"));
|
||||||
}
|
}
|
||||||
let end = HDR_SIZE + payload_length as usize;
|
let end = HDR_SIZE + payload_length as usize;
|
||||||
if bytes.len() < end {
|
if bytes.len() < end {
|
||||||
|
|
@ -57,7 +57,7 @@ pub async fn read(stream: &mut (impl tokio::io::AsyncRead + Unpin)) -> Result<Ra
|
||||||
stream.read_exact(&mut buf).await?;
|
stream.read_exact(&mut buf).await?;
|
||||||
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
let (packet_id, flags, sequence, payload_length) = parse_header(&buf)?;
|
||||||
if flags != 0 {
|
if flags != 0 {
|
||||||
return Err(anyhow!("unexpected handshake flags"));
|
return Err(anyhow!("unexpected frame flags"));
|
||||||
}
|
}
|
||||||
let mut payload = vec![0u8; payload_length as usize];
|
let mut payload = vec![0u8; payload_length as usize];
|
||||||
if !payload.is_empty() {
|
if !payload.is_empty() {
|
||||||
|
|
@ -76,6 +76,9 @@ pub async fn write(
|
||||||
seq: &mut u32,
|
seq: &mut u32,
|
||||||
payload: &[u8],
|
payload: &[u8],
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
if *seq == u32::MAX {
|
||||||
|
return Err(anyhow!("session sequence exhausted; reconnect required"));
|
||||||
|
}
|
||||||
let frame = encode_frame(id, seq, payload);
|
let frame = encode_frame(id, seq, payload);
|
||||||
stream.write_all(&frame).await?;
|
stream.write_all(&frame).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
||||||
|
|
@ -3,31 +3,85 @@ use anyhow::{Result, anyhow};
|
||||||
|
|
||||||
use tracing::{debug, info};
|
use tracing::{debug, info};
|
||||||
|
|
||||||
use super::crypto::SessionCrypto;
|
|
||||||
use super::framing;
|
use super::framing;
|
||||||
use super::payloads::*;
|
use super::payloads::*;
|
||||||
|
use super::trust::TransportError;
|
||||||
use crate::identity::Identity;
|
use crate::identity::Identity;
|
||||||
|
|
||||||
/// Perform HELLO → AUTH → SESSION with X25519 ECDH key exchange.
|
const SERVER_HELLO_CONTEXT: &[u8] = b"VNOX-LNEx-v3-server-hello\0";
|
||||||
|
const CLIENT_AUTH_CONTEXT: &[u8] = b"VNOX-LNEx-v3-client-auth\0";
|
||||||
|
|
||||||
|
/// Bytes signed by the server identity: context, TLS exporter, HELLO without signature.
|
||||||
|
pub fn server_hello_transcript(binding: &[u8], unsigned_hello: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = SERVER_HELLO_CONTEXT.to_vec();
|
||||||
|
out.extend_from_slice(binding);
|
||||||
|
out.extend_from_slice(unsigned_hello);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes signed by the client identity. The TLS exporter makes the signature valid for
|
||||||
|
/// this connection only, so it cannot be relayed to another server or connection.
|
||||||
|
pub fn client_auth_transcript(
|
||||||
|
binding: &[u8],
|
||||||
|
signed_hello: &[u8],
|
||||||
|
unsigned_auth: &[u8],
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let mut out = CLIENT_AUTH_CONTEXT.to_vec();
|
||||||
|
out.extend_from_slice(binding);
|
||||||
|
out.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes());
|
||||||
|
out.extend_from_slice(signed_hello);
|
||||||
|
out.extend_from_slice(unsigned_auth);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the handshake learned about the server and the new session.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Outcome {
|
||||||
|
pub session_id: String,
|
||||||
|
pub node_name: String,
|
||||||
|
pub private_mode: bool,
|
||||||
|
/// Lower-case hex Ed25519 identity of the server.
|
||||||
|
pub server_identity: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Perform HELLO, AUTH, SESSION inside an established TLS 1.3 connection.
|
||||||
///
|
///
|
||||||
/// Returns (session_id, node_name, private_mode, crypto).
|
/// * `binding` is the TLS exporter value, covered by both signatures.
|
||||||
/// All subsequent packets must be encrypted with `crypto`.
|
/// * `trust_key` and `expected_identity` implement the identity pin: a server presenting a
|
||||||
|
/// different Ed25519 identity than the stored one is rejected before AUTH is sent.
|
||||||
pub async fn run(
|
pub async fn run(
|
||||||
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
|
||||||
identity: &Identity,
|
identity: &Identity,
|
||||||
seq: &mut u32,
|
seq: &mut u32,
|
||||||
) -> Result<(String, String, bool, SessionCrypto)> {
|
binding: &[u8],
|
||||||
// HELLO — receive server's ephemeral X25519 public key
|
trust_key: &str,
|
||||||
|
expected_identity: Option<&str>,
|
||||||
|
) -> Result<Outcome> {
|
||||||
|
// HELLO
|
||||||
let pkt = framing::read(stream).await?;
|
let pkt = framing::read(stream).await?;
|
||||||
|
if pkt.packet_id == PID_ERROR {
|
||||||
|
let e: ErrorPayload = wire::decode(&pkt.payload)?;
|
||||||
|
return Err(anyhow!("server rejected the connection: {}", e.message));
|
||||||
|
}
|
||||||
if pkt.packet_id != PID_HELLO {
|
if pkt.packet_id != PID_HELLO {
|
||||||
return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id));
|
return Err(anyhow!("expected HELLO, got 0x{:04X}", pkt.packet_id));
|
||||||
}
|
}
|
||||||
let hello: HelloPayload = wire::decode(&pkt.payload)?;
|
|
||||||
debug!("← HELLO node={}", hello.node_name);
|
|
||||||
|
|
||||||
if pkt.sequence != 0 {
|
if pkt.sequence != 0 {
|
||||||
return Err(anyhow!("invalid HELLO sequence"));
|
return Err(anyhow!("invalid HELLO sequence"));
|
||||||
}
|
}
|
||||||
|
let hello: HelloPayload = wire::decode(&pkt.payload)?;
|
||||||
|
debug!("HELLO node={}", hello.node_name);
|
||||||
|
if hello.lnex_version != LNEX_VERSION {
|
||||||
|
return Err(TransportError::ProtocolMismatch(format!(
|
||||||
|
"The server speaks LNEx {} but this client requires {}. Update the outdated side.",
|
||||||
|
hello.lnex_version, LNEX_VERSION
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 {
|
||||||
|
return Err(anyhow!("invalid server handshake key/challenge"));
|
||||||
|
}
|
||||||
|
|
||||||
let server_public: [u8; 32] = hello
|
let server_public: [u8; 32] = hello
|
||||||
.server_pubkey
|
.server_pubkey
|
||||||
.as_slice()
|
.as_slice()
|
||||||
|
|
@ -37,32 +91,27 @@ pub async fn run(
|
||||||
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?;
|
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature)?;
|
||||||
let mut unsigned_hello = hello.clone();
|
let mut unsigned_hello = hello.clone();
|
||||||
unsigned_hello.server_signature.clear();
|
unsigned_hello.server_signature.clear();
|
||||||
let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec();
|
|
||||||
hello_transcript.extend_from_slice(&wire::encode(&unsigned_hello)?);
|
|
||||||
server_key
|
server_key
|
||||||
.verify_strict(&hello_transcript, &signature)
|
.verify_strict(
|
||||||
|
&server_hello_transcript(binding, &wire::encode(&unsigned_hello)?),
|
||||||
|
&signature,
|
||||||
|
)
|
||||||
.map_err(|_| anyhow!("server handshake signature verification failed"))?;
|
.map_err(|_| anyhow!("server handshake signature verification failed"))?;
|
||||||
// Keep full signed hello for the client-auth transcript before moving fields.
|
let server_identity = hex::encode(server_public);
|
||||||
|
if let Some(expected) = expected_identity
|
||||||
|
&& expected != server_identity
|
||||||
|
{
|
||||||
|
return Err(TransportError::IdentityChanged {
|
||||||
|
address: trust_key.to_string(),
|
||||||
|
expected: expected.to_string(),
|
||||||
|
actual: server_identity,
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
// Keep the full signed hello for the client-auth transcript.
|
||||||
let signed_hello = wire::encode(&hello)?;
|
let signed_hello = wire::encode(&hello)?;
|
||||||
|
|
||||||
// Generate our own ephemeral X25519 keypair
|
// AUTH
|
||||||
let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral();
|
|
||||||
let eph_pk_hex = eph_pk.as_bytes().to_vec();
|
|
||||||
|
|
||||||
// Parse server's ephemeral key from HELLO
|
|
||||||
let server_eph_raw = hello.server_eph_pubkey;
|
|
||||||
let server_eph_key: [u8; 32] = server_eph_raw
|
|
||||||
.try_into()
|
|
||||||
.map_err(|_| anyhow!("bad server_eph_pubkey length"))?;
|
|
||||||
let server_eph_pk = x25519_dalek::PublicKey::from(server_eph_key);
|
|
||||||
|
|
||||||
// AUTH — include our ephemeral public key
|
|
||||||
if hello.lnex_version != LNEX_VERSION {
|
|
||||||
return Err(anyhow!("unsupported LNEx version"));
|
|
||||||
}
|
|
||||||
if hello.server_pubkey.len() != 32 || hello.challenge_nonce.len() != 32 {
|
|
||||||
return Err(anyhow!("invalid server handshake key/challenge"));
|
|
||||||
}
|
|
||||||
let sk = identity
|
let sk = identity
|
||||||
.signing_key()
|
.signing_key()
|
||||||
.ok_or_else(|| anyhow!("no signing key"))?;
|
.ok_or_else(|| anyhow!("no signing key"))?;
|
||||||
|
|
@ -73,15 +122,11 @@ pub async fn run(
|
||||||
nickname: identity.nickname.clone(),
|
nickname: identity.nickname.clone(),
|
||||||
lnex_version: LNEX_VERSION.into(),
|
lnex_version: LNEX_VERSION.into(),
|
||||||
signature: Vec::new(),
|
signature: Vec::new(),
|
||||||
client_eph_pubkey: eph_pk_hex,
|
|
||||||
};
|
};
|
||||||
let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec();
|
let transcript = client_auth_transcript(binding, &signed_hello, &wire::encode(&auth)?);
|
||||||
auth_transcript.extend_from_slice(&(signed_hello.len() as u32).to_be_bytes());
|
auth.signature = sk.sign(&transcript).to_bytes().to_vec();
|
||||||
auth_transcript.extend_from_slice(&signed_hello);
|
|
||||||
auth_transcript.extend_from_slice(&wire::encode(&auth)?);
|
|
||||||
auth.signature = sk.sign(&auth_transcript).to_bytes().to_vec();
|
|
||||||
framing::write(stream, PID_AUTH, seq, &wire::encode(&auth)?).await?;
|
framing::write(stream, PID_AUTH, seq, &wire::encode(&auth)?).await?;
|
||||||
debug!("→ AUTH nick={}", identity.nickname);
|
debug!("AUTH sent nick={}", identity.nickname);
|
||||||
|
|
||||||
// SESSION
|
// SESSION
|
||||||
let pkt = framing::read(stream).await?;
|
let pkt = framing::read(stream).await?;
|
||||||
|
|
@ -96,21 +141,172 @@ pub async fn run(
|
||||||
return Err(anyhow!("invalid SESSION sequence"));
|
return Err(anyhow!("invalid SESSION sequence"));
|
||||||
}
|
}
|
||||||
let sess: SessionPayload = wire::decode(&pkt.payload)?;
|
let sess: SessionPayload = wire::decode(&pkt.payload)?;
|
||||||
|
|
||||||
// Derive encryption keys from ECDH shared secret
|
|
||||||
let shared_secret = SessionCrypto::ecdh(eph_sk, &server_eph_pk);
|
|
||||||
if !shared_secret.was_contributory() {
|
|
||||||
return Err(anyhow!("invalid server ECDH key"));
|
|
||||||
}
|
|
||||||
if sess.session_id.is_empty() || sess.token.is_empty() {
|
if sess.session_id.is_empty() || sess.token.is_empty() {
|
||||||
return Err(anyhow!("invalid session response"));
|
return Err(anyhow!("invalid session response"));
|
||||||
}
|
}
|
||||||
let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id);
|
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
"authenticated — session {} encrypted",
|
"authenticated, session {}",
|
||||||
sess.session_id.chars().take(8).collect::<String>()
|
sess.session_id.chars().take(8).collect::<String>()
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok((sess.session_id, hello.node_name, hello.private_mode, crypto))
|
Ok(Outcome {
|
||||||
|
session_id: sess.session_id,
|
||||||
|
node_name: hello.node_name,
|
||||||
|
private_mode: hello.private_mode,
|
||||||
|
server_identity,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use ed25519_dalek::{Signer, SigningKey};
|
||||||
|
use tokio::io::AsyncWriteExt;
|
||||||
|
|
||||||
|
/// Scripted gateway: sends a HELLO signed over `hello_binding` and returns the AUTH it gets.
|
||||||
|
async fn fake_server(
|
||||||
|
mut stream: tokio::io::DuplexStream,
|
||||||
|
server_key: SigningKey,
|
||||||
|
hello_binding: [u8; 32],
|
||||||
|
version: &str,
|
||||||
|
send_session: bool,
|
||||||
|
) -> (AuthPayload, Vec<u8>) {
|
||||||
|
let mut hello = HelloPayload {
|
||||||
|
lnex_version: version.into(),
|
||||||
|
server_pubkey: server_key.verifying_key().to_bytes().to_vec(),
|
||||||
|
challenge_nonce: vec![7; 32],
|
||||||
|
node_name: "fake".into(),
|
||||||
|
private_mode: true,
|
||||||
|
server_signature: Vec::new(),
|
||||||
|
};
|
||||||
|
let unsigned = wire::encode(&hello).unwrap();
|
||||||
|
hello.server_signature = server_key
|
||||||
|
.sign(&server_hello_transcript(&hello_binding, &unsigned))
|
||||||
|
.to_bytes()
|
||||||
|
.to_vec();
|
||||||
|
let signed = wire::encode(&hello).unwrap();
|
||||||
|
let mut seq = 0;
|
||||||
|
framing::write(&mut stream, PID_HELLO, &mut seq, &signed)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let Ok(packet) = framing::read(&mut stream).await else {
|
||||||
|
return (AuthPayload::default(), signed);
|
||||||
|
};
|
||||||
|
let auth: AuthPayload = wire::decode(&packet.payload).unwrap();
|
||||||
|
if send_session {
|
||||||
|
let session = SessionPayload {
|
||||||
|
session_id: "session-1".into(),
|
||||||
|
token: "token".into(),
|
||||||
|
expires_at: 0,
|
||||||
|
};
|
||||||
|
framing::write(
|
||||||
|
&mut stream,
|
||||||
|
PID_SESSION,
|
||||||
|
&mut seq,
|
||||||
|
&wire::encode(&session).unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let _ = stream.shutdown().await;
|
||||||
|
(auth, signed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn identity() -> Identity {
|
||||||
|
crate::identity::generate("handshake-test")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn authenticated_handshake_returns_server_identity_and_binds_signature() {
|
||||||
|
let server_key = SigningKey::generate(&mut rand::rng());
|
||||||
|
let (mut client, server) = tokio::io::duplex(8192);
|
||||||
|
let task = tokio::spawn(fake_server(server, server_key.clone(), [9; 32], "v3", true));
|
||||||
|
let mut seq = 0;
|
||||||
|
let outcome = run(&mut client, &identity(), &mut seq, &[9; 32], "h:7600", None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(outcome.session_id, "session-1");
|
||||||
|
assert_eq!(
|
||||||
|
outcome.server_identity,
|
||||||
|
hex::encode(server_key.verifying_key().to_bytes())
|
||||||
|
);
|
||||||
|
// The AUTH signature is valid for this connection and invalid for any other one.
|
||||||
|
let (auth, signed_hello) = task.await.unwrap();
|
||||||
|
let client_public = ed25519_dalek::VerifyingKey::from_bytes(
|
||||||
|
&auth.client_pubkey.clone().try_into().unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let signature = ed25519_dalek::Signature::from_slice(&auth.signature).unwrap();
|
||||||
|
let mut unsigned_auth = auth.clone();
|
||||||
|
unsigned_auth.signature.clear();
|
||||||
|
let unsigned = wire::encode(&unsigned_auth).unwrap();
|
||||||
|
client_public
|
||||||
|
.verify_strict(
|
||||||
|
&client_auth_transcript(&[9; 32], &signed_hello, &unsigned),
|
||||||
|
&signature,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
client_public
|
||||||
|
.verify_strict(
|
||||||
|
&client_auth_transcript(&[8; 32], &signed_hello, &unsigned),
|
||||||
|
&signature
|
||||||
|
)
|
||||||
|
.is_err(),
|
||||||
|
"a signature made on one TLS connection must not verify on another"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn hello_relayed_from_another_tls_connection_is_rejected() {
|
||||||
|
let server_key = SigningKey::generate(&mut rand::rng());
|
||||||
|
let (mut client, server) = tokio::io::duplex(8192);
|
||||||
|
// The relay forwards a HELLO signed for a different TLS session.
|
||||||
|
tokio::spawn(fake_server(server, server_key, [1; 32], "v3", false));
|
||||||
|
let mut seq = 0;
|
||||||
|
let error = run(&mut client, &identity(), &mut seq, &[2; 32], "h:7600", None)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(error.to_string().contains("signature verification failed"));
|
||||||
|
assert_eq!(seq, 0, "no AUTH may be sent to an unauthenticated peer");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn changed_server_identity_is_blocked_before_auth() {
|
||||||
|
let server_key = SigningKey::generate(&mut rand::rng());
|
||||||
|
let (mut client, server) = tokio::io::duplex(8192);
|
||||||
|
tokio::spawn(fake_server(server, server_key, [3; 32], "v3", false));
|
||||||
|
let mut seq = 0;
|
||||||
|
let error = run(
|
||||||
|
&mut client,
|
||||||
|
&identity(),
|
||||||
|
&mut seq,
|
||||||
|
&[3; 32],
|
||||||
|
"h:7600",
|
||||||
|
Some(&"00".repeat(32)),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error.downcast_ref::<TransportError>(),
|
||||||
|
Some(TransportError::IdentityChanged { .. })
|
||||||
|
));
|
||||||
|
assert_eq!(seq, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn old_protocol_version_gives_explicit_error() {
|
||||||
|
let server_key = SigningKey::generate(&mut rand::rng());
|
||||||
|
let (mut client, server) = tokio::io::duplex(8192);
|
||||||
|
tokio::spawn(fake_server(server, server_key, [4; 32], "v2", false));
|
||||||
|
let mut seq = 0;
|
||||||
|
let error = run(&mut client, &identity(), &mut seq, &[4; 32], "h:7600", None)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error.downcast_ref::<TransportError>(),
|
||||||
|
Some(TransportError::ProtocolMismatch(m)) if m.contains("v2") && m.contains("v3")
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,15 @@
|
||||||
pub mod crypto;
|
|
||||||
pub mod framing;
|
pub mod framing;
|
||||||
pub mod handshake;
|
pub mod handshake;
|
||||||
mod internal;
|
mod internal;
|
||||||
pub mod payloads;
|
pub mod payloads;
|
||||||
mod session;
|
mod session;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
|
pub mod trust;
|
||||||
mod types;
|
mod types;
|
||||||
pub mod voice;
|
pub mod voice;
|
||||||
pub mod wire;
|
pub mod wire;
|
||||||
|
|
||||||
|
pub use trust::{TransportError, TrustProblem, TrustStore};
|
||||||
pub use types::{
|
pub use types::{
|
||||||
ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo,
|
ChatMsg, FriendInfo, GuildInfo, MemberInfo, NetCommand, NetEvent, PresenceInfo,
|
||||||
WebhookManagementResult, WebhookOperation,
|
WebhookManagementResult, WebhookOperation,
|
||||||
|
|
@ -26,23 +27,35 @@ use crate::identity::Identity;
|
||||||
pub struct NetHandle {
|
pub struct NetHandle {
|
||||||
cmd_tx: mpsc::Sender<NetCommand>,
|
cmd_tx: mpsc::Sender<NetCommand>,
|
||||||
event_rx: Arc<Mutex<mpsc::Receiver<NetEvent>>>,
|
event_rx: Arc<Mutex<mpsc::Receiver<NetEvent>>>,
|
||||||
|
trust: trust::TrustStore,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NetHandle {
|
impl NetHandle {
|
||||||
pub async fn send(&self, cmd: NetCommand) {
|
pub async fn send(&self, cmd: NetCommand) {
|
||||||
let _ = self.cmd_tx.send(cmd).await;
|
let _ = self.cmd_tx.send(cmd).await;
|
||||||
}
|
}
|
||||||
|
/// Server trust decisions (pinned fingerprints). Share it with the UI.
|
||||||
|
pub fn trust(&self) -> &trust::TrustStore {
|
||||||
|
&self.trust
|
||||||
|
}
|
||||||
pub fn try_recv(&self) -> Option<NetEvent> {
|
pub fn try_recv(&self) -> Option<NetEvent> {
|
||||||
self.event_rx.try_lock().ok()?.try_recv().ok()
|
self.event_rx.try_lock().ok()?.try_recv().ok()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Spawn the network task with the persistent trust store.
|
||||||
pub fn spawn(identity: Identity) -> NetHandle {
|
pub fn spawn(identity: Identity) -> NetHandle {
|
||||||
|
spawn_with_trust(identity, trust::TrustStore::load_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn with an explicit trust store (tests, headless tools).
|
||||||
|
pub fn spawn_with_trust(identity: Identity, trust: trust::TrustStore) -> NetHandle {
|
||||||
let (cmd_tx, cmd_rx) = mpsc::channel::<NetCommand>(64);
|
let (cmd_tx, cmd_rx) = mpsc::channel::<NetCommand>(64);
|
||||||
let (event_tx, event_rx) = mpsc::channel::<NetEvent>(256);
|
let (event_tx, event_rx) = mpsc::channel::<NetEvent>(256);
|
||||||
tokio::spawn(session::net_task(identity, cmd_rx, event_tx));
|
tokio::spawn(session::net_task(identity, trust.clone(), cmd_rx, event_tx));
|
||||||
NetHandle {
|
NetHandle {
|
||||||
cmd_tx,
|
cmd_tx,
|
||||||
event_rx: Arc::new(Mutex::new(event_rx)),
|
event_rx: Arc::new(Mutex::new(event_rx)),
|
||||||
|
trust,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,7 @@ pub const PID_FRIEND_EVENT: u16 = 0x0158;
|
||||||
pub const PID_ERROR: u16 = 0x00F0;
|
pub const PID_ERROR: u16 = 0x00F0;
|
||||||
pub const PID_DISCONNECT: u16 = 0x00FF;
|
pub const PID_DISCONNECT: u16 = 0x00FF;
|
||||||
|
|
||||||
pub const LNEX_VERSION: &str = "v2";
|
pub const LNEX_VERSION: &str = "v3";
|
||||||
pub const HDR_SIZE: usize = 12;
|
pub const HDR_SIZE: usize = 12;
|
||||||
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
|
pub const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ use crate::net::wire;
|
||||||
use crate::net::{
|
use crate::net::{
|
||||||
framing, handshake, internal,
|
framing, handshake, internal,
|
||||||
payloads::*,
|
payloads::*,
|
||||||
|
trust::TrustStore,
|
||||||
types::{NetCommand, NetEvent},
|
types::{NetCommand, NetEvent},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -20,6 +21,7 @@ use super::{VoiceState, handle_cmd};
|
||||||
pub async fn session_loop(
|
pub async fn session_loop(
|
||||||
identity: &Identity,
|
identity: &Identity,
|
||||||
address: &str,
|
address: &str,
|
||||||
|
trust: &TrustStore,
|
||||||
channels: &mut Vec<String>,
|
channels: &mut Vec<String>,
|
||||||
restored: bool,
|
restored: bool,
|
||||||
cmd_rx: &mut mpsc::Receiver<NetCommand>,
|
cmd_rx: &mut mpsc::Receiver<NetCommand>,
|
||||||
|
|
@ -27,7 +29,7 @@ pub async fn session_loop(
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let connection = tokio::time::timeout(
|
let connection = tokio::time::timeout(
|
||||||
Duration::from_secs(10),
|
Duration::from_secs(10),
|
||||||
crate::net::transport::connect_with_peer(address),
|
crate::net::transport::connect_with_peer(address, trust),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.context("gateway connection timed out")??;
|
.context("gateway connection timed out")??;
|
||||||
|
|
@ -35,12 +37,29 @@ pub async fn session_loop(
|
||||||
let mut stream = connection.stream;
|
let mut stream = connection.stream;
|
||||||
let mut seq = 0u32;
|
let mut seq = 0u32;
|
||||||
|
|
||||||
let (session_id, node_name, private_mode, crypto) = tokio::time::timeout(
|
let outcome = tokio::time::timeout(
|
||||||
Duration::from_secs(10),
|
Duration::from_secs(10),
|
||||||
handshake::run(&mut stream, identity, &mut seq),
|
handshake::run(
|
||||||
|
&mut stream,
|
||||||
|
identity,
|
||||||
|
&mut seq,
|
||||||
|
&connection.binding,
|
||||||
|
&connection.trust_key,
|
||||||
|
connection
|
||||||
|
.record
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|record| record.identity.as_deref()),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.context("gateway handshake timed out")??;
|
.context("gateway handshake timed out")??;
|
||||||
|
// The identity is learned inside an already trusted channel and then pinned.
|
||||||
|
if let Err(error) = trust.set_identity(&connection.trust_key, &outcome.server_identity) {
|
||||||
|
tracing::warn!(%error, "could not store the server identity");
|
||||||
|
}
|
||||||
|
let session_id = outcome.session_id;
|
||||||
|
let node_name = outcome.node_name;
|
||||||
|
let private_mode = outcome.private_mode;
|
||||||
let _ = event_tx
|
let _ = event_tx
|
||||||
.send(NetEvent::Connected {
|
.send(NetEvent::Connected {
|
||||||
session_id: session_id.clone(),
|
session_id: session_id.clone(),
|
||||||
|
|
@ -51,18 +70,17 @@ pub async fn session_loop(
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
for channel_id in channels.clone() {
|
for channel_id in channels.clone() {
|
||||||
framing::io::write_encrypted(
|
framing::write(
|
||||||
&mut stream,
|
&mut stream,
|
||||||
PID_JOIN_CHANNEL,
|
PID_JOIN_CHANNEL,
|
||||||
&mut seq,
|
&mut seq,
|
||||||
&wire::encode(&JoinChannelPayload { channel_id })?,
|
&wire::encode(&JoinChannelPayload { channel_id })?,
|
||||||
&crypto,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let (reader, mut stream) = tokio::io::split(stream);
|
let (reader, mut stream) = tokio::io::split(stream);
|
||||||
let mut incoming = framing::io::Reader::new(reader, crypto.clone());
|
let mut incoming = framing::io::Reader::new(reader);
|
||||||
let mut voice_state: Option<VoiceState> = None;
|
let mut voice_state: Option<VoiceState> = None;
|
||||||
let mut used_voice_routes = std::collections::HashSet::new();
|
let mut used_voice_routes = std::collections::HashSet::new();
|
||||||
let mut voice_endpoint: Option<std::net::SocketAddr> = None;
|
let mut voice_endpoint: Option<std::net::SocketAddr> = None;
|
||||||
|
|
@ -77,7 +95,7 @@ pub async fn session_loop(
|
||||||
_ = ping_tick.tick() => {
|
_ = ping_tick.tick() => {
|
||||||
let ts = now_ms();
|
let ts = now_ms();
|
||||||
let payload = wire::encode(&PingPayload { timestamp: ts })?;
|
let payload = wire::encode(&PingPayload { timestamp: ts })?;
|
||||||
framing::io::write_encrypted(&mut stream, PID_PING, &mut seq, &payload, &crypto).await?;
|
framing::write(&mut stream, PID_PING, &mut seq, &payload).await?;
|
||||||
}
|
}
|
||||||
result = incoming.next() => {
|
result = incoming.next() => {
|
||||||
let pkt = result?;
|
let pkt = result?;
|
||||||
|
|
@ -113,8 +131,8 @@ pub async fn session_loop(
|
||||||
cmd = cmd_rx.recv() => {
|
cmd = cmd_rx.recv() => {
|
||||||
match cmd {
|
match cmd {
|
||||||
None | Some(NetCommand::Disconnect) => {
|
None | Some(NetCommand::Disconnect) => {
|
||||||
let _ = framing::io::write_encrypted(&mut stream, PID_DISCONNECT, &mut seq,
|
let _ = framing::write(&mut stream, PID_DISCONNECT, &mut seq,
|
||||||
&wire::encode(&Disconnect {reason: "bye".into()})?, &crypto).await;
|
&wire::encode(&Disconnect {reason: "bye".into()})?).await;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Some(NetCommand::Connect { address, auto_reconnect }) => {
|
Some(NetCommand::Connect { address, auto_reconnect }) => {
|
||||||
|
|
@ -129,14 +147,14 @@ pub async fn session_loop(
|
||||||
}
|
}
|
||||||
Some(NetCommand::JoinChannel { channel_id }) => {
|
Some(NetCommand::JoinChannel { channel_id }) => {
|
||||||
track_channel(channels, &channel_id);
|
track_channel(channels, &channel_id);
|
||||||
framing::io::write_encrypted(&mut stream, PID_JOIN_CHANNEL, &mut seq,
|
framing::write(&mut stream, PID_JOIN_CHANNEL, &mut seq,
|
||||||
&wire::encode(&JoinChannelPayload { channel_id })?, &crypto).await?;
|
&wire::encode(&JoinChannelPayload { channel_id })?).await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::LeaveChannel { channel_id }) => {
|
Some(NetCommand::LeaveChannel { channel_id }) => {
|
||||||
channels.retain(|c| c != &channel_id);
|
channels.retain(|c| c != &channel_id);
|
||||||
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
|
if voice_state.as_ref().and_then(|value|value.channel_id())==Some(channel_id.as_str()) {voice_state=None;voice_endpoint=None;}
|
||||||
framing::io::write_encrypted(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
|
framing::write(&mut stream, PID_LEAVE_CHANNEL, &mut seq,
|
||||||
&wire::encode(&LeaveChannelPayload { channel_id })?, &crypto).await?;
|
&wire::encode(&LeaveChannelPayload { channel_id })?).await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
|
Some(NetCommand::ChannelCreate { channel_id, channel_name, kind, guild_id }) => {
|
||||||
let payload = wire::encode(&ChannelCreatePayload {
|
let payload = wire::encode(&ChannelCreatePayload {
|
||||||
|
|
@ -145,14 +163,14 @@ pub async fn session_loop(
|
||||||
kind,
|
kind,
|
||||||
guild_id,
|
guild_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload, &crypto).await?;
|
framing::write(&mut stream, PID_CHANNEL_CREATE, &mut seq, &payload).await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::ChannelDelete { channel_id }) => {
|
Some(NetCommand::ChannelDelete { channel_id }) => {
|
||||||
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
|
let payload = wire::encode(&ChannelDeletePayload { channel_id })?;
|
||||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload, &crypto).await?;
|
framing::write(&mut stream, PID_CHANNEL_DELETE, &mut seq, &payload).await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::ChannelList) => {
|
Some(NetCommand::ChannelList) => {
|
||||||
framing::io::write_encrypted(&mut stream, PID_CHANNEL_LIST, &mut seq, b"", &crypto).await?;
|
framing::write(&mut stream, PID_CHANNEL_LIST, &mut seq, b"").await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
|
Some(NetCommand::SendChat { channel_id, content, reply_to }) => {
|
||||||
let msg = ChatMessagePayload {
|
let msg = ChatMessagePayload {
|
||||||
|
|
@ -162,16 +180,16 @@ pub async fn session_loop(
|
||||||
edited: false,
|
edited: false,
|
||||||
reply_to,
|
reply_to,
|
||||||
};
|
};
|
||||||
framing::io::write_encrypted(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?, &crypto).await?;
|
framing::write(&mut stream, PID_CHAT_MESSAGE, &mut seq, &wire::encode(&msg)?).await?;
|
||||||
}
|
}
|
||||||
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
|
Some(NetCommand::SendVoice { channel_id, voice_seq: voice_pkt_seq, timestamp, opus_data }) => {
|
||||||
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
|
if let Some(voice)=voice_state.as_mut(){voice.send(Some(channel_id), voice_pkt_seq, timestamp, &opus_data).await?;}
|
||||||
}
|
}
|
||||||
Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => {
|
Some(NetCommand::ReadReceipt { channel_id, last_read_message_id }) => {
|
||||||
let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?;
|
let payload = wire::encode(&ReadReceipt {channel_id,last_read_message_id,user_id: identity.pubkey_hex.clone()})?;
|
||||||
framing::io::write_encrypted(&mut stream, PID_READ_RECEIPT, &mut seq, &payload, &crypto).await?;
|
framing::write(&mut stream, PID_READ_RECEIPT, &mut seq, &payload).await?;
|
||||||
}
|
}
|
||||||
Some(other) => handle_cmd(other, &mut stream, &mut seq, &crypto, identity).await?,
|
Some(other) => handle_cmd(other, &mut stream, &mut seq, identity).await?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,12 @@
|
||||||
use crate::net::wire;
|
use crate::net::wire;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
use crate::net::{framing, payloads::*, types::NetCommand};
|
||||||
|
|
||||||
pub async fn handle_cmd(
|
pub async fn handle_cmd(
|
||||||
cmd: NetCommand,
|
cmd: NetCommand,
|
||||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||||
seq: &mut u32,
|
seq: &mut u32,
|
||||||
crypto: &SessionCrypto,
|
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
match cmd {
|
match cmd {
|
||||||
NetCommand::PresenceUpdate {
|
NetCommand::PresenceUpdate {
|
||||||
|
|
@ -21,44 +20,43 @@ pub async fn handle_cmd(
|
||||||
activity_type: activity,
|
activity_type: activity,
|
||||||
activity_text,
|
activity_text,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_PRESENCE_UPDATE, seq, &payload, crypto)
|
framing::write(stream, PID_PRESENCE_UPDATE, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::FriendRequest { target_user_id } => {
|
NetCommand::FriendRequest { target_user_id } => {
|
||||||
let payload = wire::encode(&FriendRequestPayload {
|
let payload = wire::encode(&FriendRequestPayload {
|
||||||
to_user_id: target_user_id,
|
to_user_id: target_user_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_FRIEND_REQUEST, seq, &payload, crypto).await?;
|
framing::write(stream, PID_FRIEND_REQUEST, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::FriendAccept { user_id } => {
|
NetCommand::FriendAccept { user_id } => {
|
||||||
let payload = wire::encode(&FriendAcceptPayload {
|
let payload = wire::encode(&FriendAcceptPayload {
|
||||||
from_user_id: user_id,
|
from_user_id: user_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_FRIEND_ACCEPT, seq, &payload, crypto).await?;
|
framing::write(stream, PID_FRIEND_ACCEPT, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::FriendDecline { user_id } => {
|
NetCommand::FriendDecline { user_id } => {
|
||||||
let payload = wire::encode(&FriendDeclinePayload {
|
let payload = wire::encode(&FriendDeclinePayload {
|
||||||
from_user_id: user_id,
|
from_user_id: user_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_FRIEND_DECLINE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_FRIEND_DECLINE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::FriendRemove { user_id } => {
|
NetCommand::FriendRemove { user_id } => {
|
||||||
let payload = wire::encode(&FriendRemovePayload { user_id })?;
|
let payload = wire::encode(&FriendRemovePayload { user_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_FRIEND_REMOVE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_FRIEND_REMOVE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::FriendList => {
|
NetCommand::FriendList => {
|
||||||
framing::io::write_encrypted(stream, PID_FRIEND_LIST, seq, b"", crypto).await?;
|
framing::write(stream, PID_FRIEND_LIST, seq, b"").await?;
|
||||||
}
|
}
|
||||||
NetCommand::BlockUser { user_id } => {
|
NetCommand::BlockUser { user_id } => {
|
||||||
let payload = wire::encode(&BlockUserPayload { user_id })?;
|
let payload = wire::encode(&BlockUserPayload { user_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_BLOCK_USER, seq, &payload, crypto).await?;
|
framing::write(stream, PID_BLOCK_USER, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::UnblockUser { user_id } => {
|
NetCommand::UnblockUser { user_id } => {
|
||||||
let payload = wire::encode(&UnblockUserPayload { user_id })?;
|
let payload = wire::encode(&UnblockUserPayload { user_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_UNBLOCK_USER, seq, &payload, crypto).await?;
|
framing::write(stream, PID_UNBLOCK_USER, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::BlockList => {
|
NetCommand::BlockList => {
|
||||||
framing::io::write_encrypted(stream, PID_BLOCK_LIST, seq, b"", crypto).await?;
|
framing::write(stream, PID_BLOCK_LIST, seq, b"").await?;
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,25 +1,24 @@
|
||||||
use crate::net::wire;
|
use crate::net::wire;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
use crate::net::{framing, payloads::*, types::NetCommand};
|
||||||
|
|
||||||
pub async fn handle_cmd(
|
pub async fn handle_cmd(
|
||||||
cmd: NetCommand,
|
cmd: NetCommand,
|
||||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||||
seq: &mut u32,
|
seq: &mut u32,
|
||||||
crypto: &SessionCrypto,
|
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
match cmd {
|
match cmd {
|
||||||
NetCommand::GuildCreate { name } => {
|
NetCommand::GuildCreate { name } => {
|
||||||
let payload = wire::encode(&GuildCreatePayload { name })?;
|
let payload = wire::encode(&GuildCreatePayload { name })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_CREATE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_GUILD_CREATE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::GuildDelete { guild_id } => {
|
NetCommand::GuildDelete { guild_id } => {
|
||||||
let payload = wire::encode(&GuildDeletePayload { guild_id })?;
|
let payload = wire::encode(&GuildDeletePayload { guild_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_DELETE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_GUILD_DELETE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::GuildList => {
|
NetCommand::GuildList => {
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_LIST, seq, b"", crypto).await?;
|
framing::write(stream, PID_GUILD_LIST, seq, b"").await?;
|
||||||
}
|
}
|
||||||
NetCommand::GuildJoin {
|
NetCommand::GuildJoin {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -30,12 +29,10 @@ pub async fn handle_cmd(
|
||||||
code,
|
code,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto)
|
framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
} else {
|
} else {
|
||||||
let payload = wire::encode(&GuildJoinPayload { guild_id })?;
|
let payload = wire::encode(&GuildJoinPayload { guild_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_JOIN, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_MEMBER_JOIN, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NetCommand::GuildLeave { guild_id } => {
|
NetCommand::GuildLeave { guild_id } => {
|
||||||
|
|
@ -43,8 +40,7 @@ pub async fn handle_cmd(
|
||||||
guild_id,
|
guild_id,
|
||||||
user_id: String::new(),
|
user_id: String::new(),
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_MEMBER_LEAVE, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::InviteCreate {
|
NetCommand::InviteCreate {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -56,14 +52,14 @@ pub async fn handle_cmd(
|
||||||
max_uses,
|
max_uses,
|
||||||
expires_in_seconds,
|
expires_in_seconds,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_INVITE_CREATE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_INVITE_CREATE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::InviteAccept { code } => {
|
NetCommand::InviteAccept { code } => {
|
||||||
let payload = wire::encode(&InviteAcceptPayload {
|
let payload = wire::encode(&InviteAcceptPayload {
|
||||||
code,
|
code,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_INVITE_ACCEPT, seq, &payload, crypto).await?;
|
framing::write(stream, PID_INVITE_ACCEPT, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::InviteDelete {
|
NetCommand::InviteDelete {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -73,7 +69,7 @@ pub async fn handle_cmd(
|
||||||
guild_id,
|
guild_id,
|
||||||
invite_id,
|
invite_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_INVITE_DELETE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_INVITE_DELETE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::RoleCreate {
|
NetCommand::RoleCreate {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -88,32 +84,23 @@ pub async fn handle_cmd(
|
||||||
permissions,
|
permissions,
|
||||||
id: String::new(),
|
id: String::new(),
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_ROLE_CREATE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_ROLE_CREATE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::RoleDelete { guild_id, role_id } => {
|
NetCommand::RoleDelete { guild_id, role_id } => {
|
||||||
let payload = wire::encode(&RoleDeletePayload { guild_id, role_id })?;
|
let payload = wire::encode(&RoleDeletePayload { guild_id, role_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_ROLE_DELETE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_ROLE_DELETE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::GuildMemberKick { guild_id, user_id } => {
|
NetCommand::GuildMemberKick { guild_id, user_id } => {
|
||||||
let payload = wire::encode(&GuildMemberKickPayload { guild_id, user_id })?;
|
let payload = wire::encode(&GuildMemberKickPayload { guild_id, user_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_MEMBER_KICK, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_MEMBER_KICK, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::GuildAuditLogFetch { guild_id, limit } => {
|
NetCommand::GuildAuditLogFetch { guild_id, limit } => {
|
||||||
let payload = wire::encode(&GuildAuditLogFetchPayload { guild_id, limit })?;
|
let payload = wire::encode(&GuildAuditLogFetchPayload { guild_id, limit })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_AUDIT_LOG_FETCH, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::GuildMemberListFetch { guild_id } => {
|
NetCommand::GuildMemberListFetch { guild_id } => {
|
||||||
let payload = wire::encode(&GuildMemberListFetchPayload { guild_id })?;
|
let payload = wire::encode(&GuildMemberListFetchPayload { guild_id })?;
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, PID_GUILD_MEMBER_LIST_FETCH, seq, &payload).await?;
|
||||||
stream,
|
|
||||||
PID_GUILD_MEMBER_LIST_FETCH,
|
|
||||||
seq,
|
|
||||||
&payload,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::GuildRoleAssign {
|
NetCommand::GuildRoleAssign {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -125,8 +112,7 @@ pub async fn handle_cmd(
|
||||||
user_id,
|
user_id,
|
||||||
role_id,
|
role_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_ROLE_ASSIGN, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::GuildRoleUnassign {
|
NetCommand::GuildRoleUnassign {
|
||||||
guild_id,
|
guild_id,
|
||||||
|
|
@ -138,13 +124,11 @@ pub async fn handle_cmd(
|
||||||
user_id,
|
user_id,
|
||||||
role_id,
|
role_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_ROLE_UNASSIGN, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::GuildRoleListFetch { guild_id } => {
|
NetCommand::GuildRoleListFetch { guild_id } => {
|
||||||
let payload = wire::encode(&GuildRoleListFetchPayload { guild_id })?;
|
let payload = wire::encode(&GuildRoleListFetchPayload { guild_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload, crypto)
|
framing::write(stream, PID_GUILD_ROLE_LIST_FETCH, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use crate::net::wire;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use crate::identity::Identity;
|
use crate::identity::Identity;
|
||||||
use crate::net::{crypto::SessionCrypto, framing, payloads::*, types::NetCommand};
|
use crate::net::{framing, payloads::*, types::NetCommand};
|
||||||
|
|
||||||
use super::core::now_ms;
|
use super::core::now_ms;
|
||||||
|
|
||||||
|
|
@ -13,29 +13,14 @@ pub async fn handle_cmd(
|
||||||
cmd: NetCommand,
|
cmd: NetCommand,
|
||||||
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
stream: &mut (impl tokio::io::AsyncWrite + Unpin),
|
||||||
seq: &mut u32,
|
seq: &mut u32,
|
||||||
crypto: &SessionCrypto,
|
|
||||||
identity: &Identity,
|
identity: &Identity,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
match cmd {
|
match cmd {
|
||||||
NetCommand::MediaControl(message) => {
|
NetCommand::MediaControl(message) => {
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, PID_MEDIA_CONTROL, seq, &wire::encode(&message)?).await?;
|
||||||
stream,
|
|
||||||
PID_MEDIA_CONTROL,
|
|
||||||
seq,
|
|
||||||
&wire::encode(&message)?,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::Webhook { operation, request } => {
|
NetCommand::Webhook { operation, request } => {
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, operation.packet_id(), seq, &wire::encode(&request)?).await?;
|
||||||
stream,
|
|
||||||
operation.packet_id(),
|
|
||||||
seq,
|
|
||||||
&wire::encode(&request)?,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
cmd @ (NetCommand::GuildCreate { .. }
|
cmd @ (NetCommand::GuildCreate { .. }
|
||||||
| NetCommand::GuildDelete { .. }
|
| NetCommand::GuildDelete { .. }
|
||||||
|
|
@ -52,9 +37,7 @@ pub async fn handle_cmd(
|
||||||
| NetCommand::GuildMemberListFetch { .. }
|
| NetCommand::GuildMemberListFetch { .. }
|
||||||
| NetCommand::GuildRoleAssign { .. }
|
| NetCommand::GuildRoleAssign { .. }
|
||||||
| NetCommand::GuildRoleUnassign { .. }
|
| NetCommand::GuildRoleUnassign { .. }
|
||||||
| NetCommand::GuildRoleListFetch { .. }) => {
|
| NetCommand::GuildRoleListFetch { .. }) => guild::handle_cmd(cmd, stream, seq).await?,
|
||||||
guild::handle_cmd(cmd, stream, seq, crypto).await?
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd @ (NetCommand::PresenceUpdate { .. }
|
cmd @ (NetCommand::PresenceUpdate { .. }
|
||||||
| NetCommand::FriendRequest { .. }
|
| NetCommand::FriendRequest { .. }
|
||||||
|
|
@ -64,7 +47,7 @@ pub async fn handle_cmd(
|
||||||
| NetCommand::FriendList
|
| NetCommand::FriendList
|
||||||
| NetCommand::BlockUser { .. }
|
| NetCommand::BlockUser { .. }
|
||||||
| NetCommand::UnblockUser { .. }
|
| NetCommand::UnblockUser { .. }
|
||||||
| NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq, crypto).await?,
|
| NetCommand::BlockList) => friends::handle_cmd(cmd, stream, seq).await?,
|
||||||
|
|
||||||
NetCommand::ReactionAdd {
|
NetCommand::ReactionAdd {
|
||||||
channel_id,
|
channel_id,
|
||||||
|
|
@ -77,8 +60,7 @@ pub async fn handle_cmd(
|
||||||
emoji,
|
emoji,
|
||||||
user_id: String::new(),
|
user_id: String::new(),
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_MESSAGE_REACTION_ADD, seq, &payload, crypto)
|
framing::write(stream, PID_MESSAGE_REACTION_ADD, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::ReactionRemove {
|
NetCommand::ReactionRemove {
|
||||||
channel_id,
|
channel_id,
|
||||||
|
|
@ -91,14 +73,7 @@ pub async fn handle_cmd(
|
||||||
emoji,
|
emoji,
|
||||||
user_id: String::new(),
|
user_id: String::new(),
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, PID_MESSAGE_REACTION_REMOVE, seq, &payload).await?;
|
||||||
stream,
|
|
||||||
PID_MESSAGE_REACTION_REMOVE,
|
|
||||||
seq,
|
|
||||||
&payload,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::MessageEdit {
|
NetCommand::MessageEdit {
|
||||||
channel_id,
|
channel_id,
|
||||||
|
|
@ -110,7 +85,7 @@ pub async fn handle_cmd(
|
||||||
channel_id,
|
channel_id,
|
||||||
content,
|
content,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_MESSAGE_EDIT, seq, &payload, crypto).await?;
|
framing::write(stream, PID_MESSAGE_EDIT, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::MessageDelete {
|
NetCommand::MessageDelete {
|
||||||
channel_id,
|
channel_id,
|
||||||
|
|
@ -120,11 +95,11 @@ pub async fn handle_cmd(
|
||||||
message_id,
|
message_id,
|
||||||
channel_id,
|
channel_id,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_MESSAGE_DELETE, seq, &payload, crypto).await?;
|
framing::write(stream, PID_MESSAGE_DELETE, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::DmStart { target_user_id } => {
|
NetCommand::DmStart { target_user_id } => {
|
||||||
let payload = wire::encode(&DmStartPayload { target_user_id })?;
|
let payload = wire::encode(&DmStartPayload { target_user_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_DM_START, seq, &payload, crypto).await?;
|
framing::write(stream, PID_DM_START, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::DmSend { dm_id, content } => {
|
NetCommand::DmSend { dm_id, content } => {
|
||||||
let msg = DmMessagePayload {
|
let msg = DmMessagePayload {
|
||||||
|
|
@ -133,16 +108,15 @@ pub async fn handle_cmd(
|
||||||
content,
|
content,
|
||||||
timestamp: now_ms(),
|
timestamp: now_ms(),
|
||||||
};
|
};
|
||||||
framing::io::write_encrypted(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?, crypto)
|
framing::write(stream, PID_DM_MESSAGE, seq, &wire::encode(&msg)?).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::TypingStart { channel_id } => {
|
NetCommand::TypingStart { channel_id } => {
|
||||||
let payload = wire::encode(&TypingStart { channel_id })?;
|
let payload = wire::encode(&TypingStart { channel_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_TYPING_START, seq, &payload, crypto).await?;
|
framing::write(stream, PID_TYPING_START, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::DmReadAck { dm_id } => {
|
NetCommand::DmReadAck { dm_id } => {
|
||||||
let payload = wire::encode(&crate::net::wire::DmReadAck { dm_id })?;
|
let payload = wire::encode(&crate::net::wire::DmReadAck { dm_id })?;
|
||||||
framing::io::write_encrypted(stream, PID_DM_READ_ACK, seq, &payload, crypto).await?;
|
framing::write(stream, PID_DM_READ_ACK, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::DmSearch { dm_id, query } => {
|
NetCommand::DmSearch { dm_id, query } => {
|
||||||
let payload = wire::encode(&DmHistoryPayload {
|
let payload = wire::encode(&DmHistoryPayload {
|
||||||
|
|
@ -151,7 +125,7 @@ pub async fn handle_cmd(
|
||||||
search_query: if query.is_empty() { None } else { Some(query) },
|
search_query: if query.is_empty() { None } else { Some(query) },
|
||||||
limit: None,
|
limit: None,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_DM_HISTORY, seq, &payload, crypto).await?;
|
framing::write(stream, PID_DM_HISTORY, seq, &payload).await?;
|
||||||
}
|
}
|
||||||
NetCommand::E2eeDmKeyExchange {
|
NetCommand::E2eeDmKeyExchange {
|
||||||
dm_id,
|
dm_id,
|
||||||
|
|
@ -161,19 +135,11 @@ pub async fn handle_cmd(
|
||||||
dm_id,
|
dm_id,
|
||||||
e2ee_public_key,
|
e2ee_public_key,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload, crypto)
|
framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::E2eeDmKeyExchangeAck { dm_id } => {
|
NetCommand::E2eeDmKeyExchangeAck { dm_id } => {
|
||||||
let payload = wire::encode(&E2eeDmKeyExchangeAckPayload { dm_id })?;
|
let payload = wire::encode(&E2eeDmKeyExchangeAckPayload { dm_id })?;
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, PID_E2EE_DM_KEY_EXCHANGE_ACK, seq, &payload).await?;
|
||||||
stream,
|
|
||||||
PID_E2EE_DM_KEY_EXCHANGE_ACK,
|
|
||||||
seq,
|
|
||||||
&payload,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::E2eeDmSend { dm_id, ciphertext } => {
|
NetCommand::E2eeDmSend { dm_id, ciphertext } => {
|
||||||
let msg = E2eeDmMessagePayload {
|
let msg = E2eeDmMessagePayload {
|
||||||
|
|
@ -182,14 +148,7 @@ pub async fn handle_cmd(
|
||||||
ciphertext,
|
ciphertext,
|
||||||
timestamp: now_ms(),
|
timestamp: now_ms(),
|
||||||
};
|
};
|
||||||
framing::io::write_encrypted(
|
framing::write(stream, PID_E2EE_DM_MESSAGE, seq, &wire::encode(&msg)?).await?;
|
||||||
stream,
|
|
||||||
PID_E2EE_DM_MESSAGE,
|
|
||||||
seq,
|
|
||||||
&wire::encode(&msg)?,
|
|
||||||
crypto,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
NetCommand::E2eeDmHistory { dm_id, limit } => {
|
NetCommand::E2eeDmHistory { dm_id, limit } => {
|
||||||
let payload = wire::encode(&E2eeDmHistoryPayload {
|
let payload = wire::encode(&E2eeDmHistoryPayload {
|
||||||
|
|
@ -197,8 +156,7 @@ pub async fn handle_cmd(
|
||||||
messages: vec![],
|
messages: vec![],
|
||||||
limit,
|
limit,
|
||||||
})?;
|
})?;
|
||||||
framing::io::write_encrypted(stream, PID_E2EE_DM_HISTORY, seq, &payload, crypto)
|
framing::write(stream, PID_E2EE_DM_HISTORY, seq, &payload).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ use tokio::time::sleep;
|
||||||
use tracing::{error, info};
|
use tracing::{error, info};
|
||||||
|
|
||||||
use crate::identity::Identity;
|
use crate::identity::Identity;
|
||||||
|
use crate::net::trust::{TransportError, TrustStore};
|
||||||
use crate::net::types::{NetCommand, NetEvent};
|
use crate::net::types::{NetCommand, NetEvent};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
|
|
@ -13,6 +14,7 @@ use super::{
|
||||||
|
|
||||||
pub async fn net_task(
|
pub async fn net_task(
|
||||||
identity: Identity,
|
identity: Identity,
|
||||||
|
trust: TrustStore,
|
||||||
mut cmd_rx: mpsc::Receiver<NetCommand>,
|
mut cmd_rx: mpsc::Receiver<NetCommand>,
|
||||||
event_tx: mpsc::Sender<NetEvent>,
|
event_tx: mpsc::Sender<NetEvent>,
|
||||||
) {
|
) {
|
||||||
|
|
@ -71,6 +73,7 @@ pub async fn net_task(
|
||||||
match session_loop(
|
match session_loop(
|
||||||
&identity,
|
&identity,
|
||||||
&session.address,
|
&session.address,
|
||||||
|
&trust,
|
||||||
&mut session.channels,
|
&mut session.channels,
|
||||||
restored,
|
restored,
|
||||||
&mut cmd_rx,
|
&mut cmd_rx,
|
||||||
|
|
@ -97,7 +100,12 @@ pub async fn net_task(
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
error!("session ended: {e}");
|
error!("session ended: {e}");
|
||||||
let retry = session.auto_reconnect;
|
// Trust failures and protocol mismatches never improve by retrying.
|
||||||
|
let transport = e.downcast_ref::<TransportError>();
|
||||||
|
if let Some(problem) = transport.and_then(TransportError::trust_problem) {
|
||||||
|
let _ = event_tx.send(NetEvent::TrustProblem(problem)).await;
|
||||||
|
}
|
||||||
|
let retry = session.auto_reconnect && transport.is_none();
|
||||||
let _ = event_tx
|
let _ = event_tx
|
||||||
.send(NetEvent::Disconnected {
|
.send(NetEvent::Disconnected {
|
||||||
reason: e.to_string(),
|
reason: e.to_string(),
|
||||||
|
|
|
||||||
|
|
@ -1,112 +1,509 @@
|
||||||
//! TCP/TLS transport selection. TLS never falls back to plaintext after an error.
|
//! TLS 1.3 transport. There is no plaintext mode and no fallback after any error.
|
||||||
use anyhow::{Context, Result, bail};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use rustls::client::WebPkiServerVerifier;
|
||||||
|
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||||
|
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
|
||||||
|
use rustls::{CertificateError, DigitallySignedStruct, SignatureScheme};
|
||||||
use tokio::io::{AsyncRead, AsyncWrite};
|
use tokio::io::{AsyncRead, AsyncWrite};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
|
|
||||||
|
use super::trust::{
|
||||||
|
ServerRecord, TransportError, TrustKind, TrustStore, parse_address, spki_fingerprint,
|
||||||
|
};
|
||||||
|
|
||||||
pub trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
pub trait AsyncStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
|
impl<T: AsyncRead + AsyncWrite + Unpin + Send> AsyncStream for T {}
|
||||||
pub type Stream = Box<dyn AsyncStream>;
|
pub type Stream = Box<dyn AsyncStream>;
|
||||||
|
|
||||||
|
/// ALPN protocol id required from the gateway.
|
||||||
|
pub const ALPN: &[u8] = b"vnox-lnex/3";
|
||||||
|
/// TLS exporter label of the channel binding (must match the gateway).
|
||||||
|
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
|
||||||
|
/// Length of the exported channel binding.
|
||||||
|
pub const BINDING_LEN: usize = 32;
|
||||||
|
|
||||||
pub struct Connected {
|
pub struct Connected {
|
||||||
pub stream: Stream,
|
pub stream: Stream,
|
||||||
pub peer: std::net::SocketAddr,
|
pub peer: std::net::SocketAddr,
|
||||||
|
/// TLS exporter value of this connection, signed by both sides of the LNEx handshake.
|
||||||
|
pub binding: [u8; BINDING_LEN],
|
||||||
|
/// Trust store key (`host:port`).
|
||||||
|
pub trust_key: String,
|
||||||
|
/// Stored record at connect time (for the identity check).
|
||||||
|
pub record: Option<ServerRecord>,
|
||||||
}
|
}
|
||||||
pub async fn connect(address: &str) -> Result<Stream> {
|
|
||||||
Ok(connect_with_peer(address).await?.stream)
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
enum Mode {
|
||||||
|
/// Certificate SPKI must equal the stored pin.
|
||||||
|
Pin,
|
||||||
|
/// Certificate must pass public WebPKI validation.
|
||||||
|
Ca,
|
||||||
|
/// Unknown server: finish the handshake to learn the fingerprint, send nothing.
|
||||||
|
Probe,
|
||||||
}
|
}
|
||||||
pub async fn connect_with_peer(address: &str) -> Result<Connected> {
|
|
||||||
let explicit_plain = address.starts_with("lnex://");
|
#[derive(Default, Debug)]
|
||||||
let authority = address
|
struct Observed {
|
||||||
.strip_prefix("lnexs://")
|
fingerprint: Option<String>,
|
||||||
.or_else(|| address.strip_prefix("lnex://"))
|
mismatch: bool,
|
||||||
.unwrap_or(address);
|
ca_valid: bool,
|
||||||
if authority.contains('/')
|
ca_error: Option<String>,
|
||||||
|| authority.contains('@')
|
}
|
||||||
|| authority.contains('?')
|
|
||||||
|| authority.contains('#')
|
#[derive(Debug)]
|
||||||
{
|
struct TrustVerifier {
|
||||||
bail!("expected a server host and port");
|
mode: Mode,
|
||||||
|
pin: Option<String>,
|
||||||
|
webpki: Arc<WebPkiServerVerifier>,
|
||||||
|
algorithms: rustls::crypto::WebPkiSupportedAlgorithms,
|
||||||
|
observed: Arc<Mutex<Observed>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrustVerifier {
|
||||||
|
fn observe<R>(&self, f: impl FnOnce(&mut Observed) -> R) -> R {
|
||||||
|
f(&mut self
|
||||||
|
.observed
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner))
|
||||||
}
|
}
|
||||||
let (host, port) = if let Some(value) = authority.strip_prefix('[') {
|
}
|
||||||
let (host, tail) = value.split_once(']').context("invalid IPv6 address")?;
|
|
||||||
let port = if tail.is_empty() {
|
impl ServerCertVerifier for TrustVerifier {
|
||||||
7600
|
fn verify_server_cert(
|
||||||
} else {
|
&self,
|
||||||
tail.strip_prefix(':')
|
end_entity: &CertificateDer<'_>,
|
||||||
.context("invalid server address")?
|
intermediates: &[CertificateDer<'_>],
|
||||||
.parse()?
|
server_name: &ServerName<'_>,
|
||||||
|
ocsp_response: &[u8],
|
||||||
|
now: UnixTime,
|
||||||
|
) -> std::result::Result<ServerCertVerified, rustls::Error> {
|
||||||
|
let fingerprint = spki_fingerprint(end_entity.as_ref())
|
||||||
|
.map_err(|_| rustls::Error::InvalidCertificate(CertificateError::BadEncoding))?;
|
||||||
|
self.observe(|o| o.fingerprint = Some(fingerprint.clone()));
|
||||||
|
let public = || {
|
||||||
|
self.webpki.verify_server_cert(
|
||||||
|
end_entity,
|
||||||
|
intermediates,
|
||||||
|
server_name,
|
||||||
|
ocsp_response,
|
||||||
|
now,
|
||||||
|
)
|
||||||
};
|
};
|
||||||
(host, port)
|
match self.mode {
|
||||||
} else if let Some((host, port)) = authority.rsplit_once(':') {
|
Mode::Pin => {
|
||||||
(host, port.parse()?)
|
if self.pin.as_deref() == Some(fingerprint.as_str()) {
|
||||||
} else {
|
Ok(ServerCertVerified::assertion())
|
||||||
(authority, 7600)
|
} else {
|
||||||
};
|
self.observe(|o| o.mismatch = true);
|
||||||
if host.is_empty() {
|
Err(rustls::Error::InvalidCertificate(
|
||||||
bail!("server host is empty");
|
CertificateError::ApplicationVerificationFailure,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Mode::Ca => public().inspect_err(|e| {
|
||||||
|
self.observe(|o| o.ca_error = Some(e.to_string()));
|
||||||
|
}),
|
||||||
|
Mode::Probe => {
|
||||||
|
// Accept only to complete the handshake; the caller drops the connection
|
||||||
|
// before any LNEx byte is sent unless the certificate is publicly valid.
|
||||||
|
if public().is_ok() {
|
||||||
|
self.observe(|o| o.ca_valid = true);
|
||||||
|
}
|
||||||
|
Ok(ServerCertVerified::assertion())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let tcp = TcpStream::connect((host, port))
|
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||||
|
self.algorithms.supported_schemes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connect, verify and return the TLS stream plus the channel binding.
|
||||||
|
pub async fn connect(address: &str, trust: &TrustStore) -> Result<Stream> {
|
||||||
|
Ok(connect_with_peer(address, trust).await?.stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn connect_with_peer(address: &str, trust: &TrustStore) -> Result<Connected> {
|
||||||
|
let parsed = parse_address(address)?;
|
||||||
|
let tcp = TcpStream::connect((parsed.host.as_str(), parsed.port))
|
||||||
.await
|
.await
|
||||||
.context("connect to gateway")?;
|
.context("connect to gateway")?;
|
||||||
tcp.set_nodelay(true)?;
|
tcp.set_nodelay(true)?;
|
||||||
let peer = tcp.peer_addr()?;
|
let peer = tcp.peer_addr()?;
|
||||||
let loopback_host = host.eq_ignore_ascii_case("localhost")
|
let record = trust.get(&parsed.key);
|
||||||
|| host
|
let (mode, pin) = match &record {
|
||||||
.parse::<std::net::IpAddr>()
|
Some(r) if r.trust == TrustKind::Pin => (Mode::Pin, r.spki_sha256.clone()),
|
||||||
.is_ok_and(|ip| ip.is_loopback());
|
Some(_) => (Mode::Ca, None),
|
||||||
let plain = explicit_plain || (!address.starts_with("lnexs://") && loopback_host);
|
None => (Mode::Probe, None),
|
||||||
if plain {
|
};
|
||||||
if !tcp.peer_addr()?.ip().is_loopback() {
|
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
|
||||||
bail!("plaintext LNEx is restricted to loopback development; use lnexs://");
|
|
||||||
}
|
|
||||||
return Ok(Connected {
|
|
||||||
stream: Box::new(tcp),
|
|
||||||
peer,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||||
let config = rustls::ClientConfig::builder_with_provider(
|
let webpki = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone())
|
||||||
rustls::crypto::aws_lc_rs::default_provider().into(),
|
.build()
|
||||||
)
|
.context("build public certificate verifier")?;
|
||||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
let observed = Arc::new(Mutex::new(Observed::default()));
|
||||||
.with_root_certificates(roots)
|
let verifier = Arc::new(TrustVerifier {
|
||||||
.with_no_client_auth();
|
mode,
|
||||||
let server_name = rustls::pki_types::ServerName::try_from(host.to_owned())
|
pin,
|
||||||
.context("invalid TLS server name")?;
|
webpki,
|
||||||
let tls = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config))
|
algorithms: provider.signature_verification_algorithms,
|
||||||
|
observed: observed.clone(),
|
||||||
|
});
|
||||||
|
let mut config = rustls::ClientConfig::builder_with_provider(provider)
|
||||||
|
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||||
|
.dangerous()
|
||||||
|
.with_custom_certificate_verifier(verifier)
|
||||||
|
.with_no_client_auth();
|
||||||
|
config.alpn_protocols = vec![ALPN.to_vec()];
|
||||||
|
let server_name =
|
||||||
|
ServerName::try_from(parsed.host.clone()).context("invalid TLS server name")?;
|
||||||
|
let tls = match tokio_rustls::TlsConnector::from(Arc::new(config))
|
||||||
.connect(server_name, tcp)
|
.connect(server_name, tcp)
|
||||||
.await
|
.await
|
||||||
.context("TLS certificate/connection verification failed")?;
|
{
|
||||||
|
Ok(tls) => tls,
|
||||||
|
Err(error) => {
|
||||||
|
return Err(map_tls_error(
|
||||||
|
error,
|
||||||
|
&parsed.key,
|
||||||
|
mode,
|
||||||
|
record.as_ref().and_then(|r| r.spki_sha256.as_deref()),
|
||||||
|
&observed,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let seen = observed
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
if mode == Mode::Probe {
|
||||||
|
if seen.ca_valid {
|
||||||
|
// A publicly valid certificate for this host name: remember it, no prompt.
|
||||||
|
drop(seen);
|
||||||
|
if let Err(error) = trust.trust_public_ca(&parsed.key) {
|
||||||
|
tracing::warn!(%error, "could not save trust record");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let fingerprint = seen.fingerprint.clone().unwrap_or_default();
|
||||||
|
return Err(TransportError::UntrustedServer {
|
||||||
|
address: parsed.key,
|
||||||
|
fingerprint,
|
||||||
|
}
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
drop(seen);
|
||||||
|
}
|
||||||
|
let connection = tls.get_ref().1;
|
||||||
|
if connection.protocol_version() != Some(rustls::ProtocolVersion::TLSv1_3)
|
||||||
|
|| connection.alpn_protocol() != Some(ALPN)
|
||||||
|
{
|
||||||
|
return Err(TransportError::ProtocolMismatch(
|
||||||
|
"The server did not negotiate TLS 1.3 with LNEx v3. Ask its owner to update the server."
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let binding = connection
|
||||||
|
.export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None)
|
||||||
|
.context("TLS exporter unavailable")?;
|
||||||
Ok(Connected {
|
Ok(Connected {
|
||||||
stream: Box::new(tls),
|
stream: Box::new(tls),
|
||||||
peer,
|
peer,
|
||||||
|
binding,
|
||||||
|
record: trust.get(&parsed.key),
|
||||||
|
trust_key: parsed.key,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const NOT_TLS13: &str = "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server or a non-VNOX port, ask its owner to update it.";
|
||||||
|
|
||||||
|
fn map_tls_error(
|
||||||
|
error: std::io::Error,
|
||||||
|
key: &str,
|
||||||
|
mode: Mode,
|
||||||
|
pin: Option<&str>,
|
||||||
|
observed: &Mutex<Observed>,
|
||||||
|
) -> anyhow::Error {
|
||||||
|
let seen = observed
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
if mode == Mode::Pin && seen.mismatch {
|
||||||
|
return TransportError::FingerprintChanged {
|
||||||
|
address: key.to_string(),
|
||||||
|
expected: pin.unwrap_or_default().to_string(),
|
||||||
|
actual: seen.fingerprint.clone().unwrap_or_default(),
|
||||||
|
}
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
if mode == Mode::Ca
|
||||||
|
&& let Some(reason) = &seen.ca_error
|
||||||
|
{
|
||||||
|
return TransportError::CertificateInvalid {
|
||||||
|
address: key.to_string(),
|
||||||
|
reason: reason.clone(),
|
||||||
|
}
|
||||||
|
.into();
|
||||||
|
}
|
||||||
|
let rustls_error = error
|
||||||
|
.get_ref()
|
||||||
|
.and_then(|inner| inner.downcast_ref::<rustls::Error>());
|
||||||
|
match rustls_error {
|
||||||
|
Some(
|
||||||
|
rustls::Error::InvalidMessage(_)
|
||||||
|
| rustls::Error::PeerIncompatible(_)
|
||||||
|
| rustls::Error::PeerMisbehaved(_),
|
||||||
|
) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(),
|
||||||
|
Some(rustls::Error::AlertReceived(
|
||||||
|
rustls::AlertDescription::ProtocolVersion
|
||||||
|
| rustls::AlertDescription::NoApplicationProtocol
|
||||||
|
| rustls::AlertDescription::HandshakeFailure
|
||||||
|
| rustls::AlertDescription::InsufficientSecurity,
|
||||||
|
)) => TransportError::ProtocolMismatch(NOT_TLS13.into()).into(),
|
||||||
|
_ if error.kind() == std::io::ErrorKind::UnexpectedEof => {
|
||||||
|
TransportError::ProtocolMismatch(NOT_TLS13.into()).into()
|
||||||
|
}
|
||||||
|
_ => anyhow::Error::new(error).context("TLS handshake failed"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use tokio::io::AsyncReadExt;
|
use std::sync::Arc;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
struct TestServer {
|
||||||
|
port: u16,
|
||||||
|
fingerprint: String,
|
||||||
|
/// Application bytes received per connection, and the server side exporter value.
|
||||||
|
received: tokio::sync::mpsc::UnboundedReceiver<(Vec<u8>, Option<[u8; BINDING_LEN]>)>,
|
||||||
|
task: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
impl Drop for TestServer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.task.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve(
|
||||||
|
versions: &[&'static rustls::SupportedProtocolVersion],
|
||||||
|
alpn: bool,
|
||||||
|
) -> TestServer {
|
||||||
|
let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
|
||||||
|
let fingerprint = spki_fingerprint(certified.cert.der().as_ref()).unwrap();
|
||||||
|
let key = rustls::pki_types::PrivateKeyDer::try_from(certified.signing_key.serialize_der())
|
||||||
|
.unwrap();
|
||||||
|
let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||||
|
rustls::crypto::aws_lc_rs::default_provider(),
|
||||||
|
))
|
||||||
|
.with_protocol_versions(versions)
|
||||||
|
.unwrap()
|
||||||
|
.with_no_client_auth()
|
||||||
|
.with_single_cert(vec![certified.cert.der().clone()], key)
|
||||||
|
.unwrap();
|
||||||
|
if alpn {
|
||||||
|
config.alpn_protocols = vec![ALPN.to_vec()];
|
||||||
|
}
|
||||||
|
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let (sender, received) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((tcp, _)) = listener.accept().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let acceptor = acceptor.clone();
|
||||||
|
let sender = sender.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let Ok(mut tls) = acceptor.accept(tcp).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let binding = tls
|
||||||
|
.get_ref()
|
||||||
|
.1
|
||||||
|
.export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None)
|
||||||
|
.ok();
|
||||||
|
let mut data = Vec::new();
|
||||||
|
let _ = tls.read_to_end(&mut data).await;
|
||||||
|
let _ = sender.send((data, binding));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
TestServer {
|
||||||
|
port,
|
||||||
|
fingerprint,
|
||||||
|
received,
|
||||||
|
task,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_of(result: Result<Connected>) -> TransportError {
|
||||||
|
match result {
|
||||||
|
Ok(_) => panic!("connection must not succeed"),
|
||||||
|
Err(error) => error
|
||||||
|
.downcast_ref::<TransportError>()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| panic!("not a transport error: {error:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn quiet(server: &mut TestServer) -> bool {
|
||||||
|
// A rejected connection must not have carried a single application byte.
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_millis(300),
|
||||||
|
server.received.recv(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some((data, _))) => data.is_empty(),
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn tls_failure_never_retries_plaintext() {
|
async fn unknown_self_signed_server_needs_confirmation_and_receives_nothing() {
|
||||||
|
let mut server = serve(&[&rustls::version::TLS13], true).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
let address = format!("127.0.0.1:{}", server.port);
|
||||||
|
let error = error_of(connect_with_peer(&address, &trust).await);
|
||||||
|
assert_eq!(
|
||||||
|
error,
|
||||||
|
TransportError::UntrustedServer {
|
||||||
|
address: address.clone(),
|
||||||
|
fingerprint: server.fingerprint.clone()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert!(trust.get(&address).is_none(), "no implicit trust");
|
||||||
|
assert!(quiet(&mut server).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn pinned_fingerprint_connects_and_shares_the_channel_binding() {
|
||||||
|
let mut server = serve(&[&rustls::version::TLS13], true).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
let key = format!("127.0.0.1:{}", server.port);
|
||||||
|
trust.pin(&key, &server.fingerprint).unwrap();
|
||||||
|
// The lnex:// and lnexs:// schemes are both TLS and map to the same record.
|
||||||
|
let mut connected = connect_with_peer(&format!("lnex://{key}"), &trust)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
connected.stream.write_all(b"hello").await.unwrap();
|
||||||
|
connected.stream.shutdown().await.unwrap();
|
||||||
|
let (data, server_binding) = server.received.recv().await.unwrap();
|
||||||
|
assert_eq!(data, b"hello");
|
||||||
|
assert_eq!(server_binding, Some(connected.binding));
|
||||||
|
assert_ne!(connected.binding, [0u8; BINDING_LEN]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn changed_fingerprint_is_rejected_without_application_data() {
|
||||||
|
let mut server = serve(&[&rustls::version::TLS13], true).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
let key = format!("127.0.0.1:{}", server.port);
|
||||||
|
let trusted_before = "ab".repeat(32);
|
||||||
|
trust.pin(&key, &trusted_before).unwrap();
|
||||||
|
let error = error_of(connect_with_peer(&key, &trust).await);
|
||||||
|
assert_eq!(
|
||||||
|
error,
|
||||||
|
TransportError::FingerprintChanged {
|
||||||
|
address: key.clone(),
|
||||||
|
expected: trusted_before.clone(),
|
||||||
|
actual: server.fingerprint.clone(),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert!(error.trust_problem().is_some());
|
||||||
|
assert_eq!(
|
||||||
|
trust.get(&key).unwrap().spki_sha256.as_deref(),
|
||||||
|
Some(trusted_before.as_str()),
|
||||||
|
"the stored pin is never replaced automatically"
|
||||||
|
);
|
||||||
|
assert!(quiet(&mut server).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn public_ca_trust_never_degrades_to_trust_on_first_use() {
|
||||||
|
let mut server = serve(&[&rustls::version::TLS13], true).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
let key = format!("127.0.0.1:{}", server.port);
|
||||||
|
trust.trust_public_ca(&key).unwrap();
|
||||||
|
let error = error_of(connect_with_peer(&key, &trust).await);
|
||||||
|
assert!(matches!(error, TransportError::CertificateInvalid { .. }));
|
||||||
|
assert!(error.trust_problem().is_none());
|
||||||
|
assert!(quiet(&mut server).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tls12_only_server_is_rejected_with_a_clear_error() {
|
||||||
|
let server = serve(&[&rustls::version::TLS12], true).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
trust
|
||||||
|
.pin(&format!("127.0.0.1:{}", server.port), &server.fingerprint)
|
||||||
|
.unwrap();
|
||||||
|
let error =
|
||||||
|
error_of(connect_with_peer(&format!("127.0.0.1:{}", server.port), &trust).await);
|
||||||
|
assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn server_without_lnex_alpn_is_rejected() {
|
||||||
|
let server = serve(&[&rustls::version::TLS13], false).await;
|
||||||
|
let trust = TrustStore::in_memory();
|
||||||
|
let key = format!("127.0.0.1:{}", server.port);
|
||||||
|
trust.pin(&key, &server.fingerprint).unwrap();
|
||||||
|
let error = error_of(connect_with_peer(&key, &trust).await);
|
||||||
|
assert!(matches!(error, TransportError::ProtocolMismatch(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn old_plaintext_v2_server_is_reported_and_never_retried() {
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let address = listener.local_addr().unwrap();
|
let address = listener.local_addr().unwrap();
|
||||||
let task = tokio::spawn(async move {
|
let task = tokio::spawn(async move {
|
||||||
let (mut stream, _) = listener.accept().await.unwrap();
|
let (mut stream, _) = listener.accept().await.unwrap();
|
||||||
|
// An LNEx v2 gateway speaks first: HELLO frame header (id 0x0001).
|
||||||
|
stream
|
||||||
|
.write_all(&[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4])
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
let first = stream.read_u8().await.unwrap();
|
let first = stream.read_u8().await.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
first, 22,
|
first, 22,
|
||||||
"first record must be a TLS handshake, never LNEx plaintext"
|
"the client must start a TLS handshake, never LNEx plaintext"
|
||||||
);
|
);
|
||||||
drop(stream);
|
drop(stream);
|
||||||
assert!(
|
assert!(
|
||||||
tokio::time::timeout(std::time::Duration::from_millis(30), listener.accept())
|
tokio::time::timeout(std::time::Duration::from_millis(100), listener.accept())
|
||||||
.await
|
.await
|
||||||
.is_err(),
|
.is_err(),
|
||||||
"certificate/handshake errors must not cause a downgrade reconnect"
|
"no downgrade reconnect after a failed TLS handshake"
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
assert!(connect(&format!("lnexs://{address}")).await.is_err());
|
let trust = TrustStore::in_memory();
|
||||||
|
let error = error_of(connect_with_peer(&format!("lnexs://{address}"), &trust).await);
|
||||||
|
assert!(matches!(&error, TransportError::ProtocolMismatch(m) if m.contains("TLS 1.3")));
|
||||||
task.await.unwrap();
|
task.await.unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
569
src/net/trust.rs
Normal file
569
src/net/trust.rs
Normal file
|
|
@ -0,0 +1,569 @@
|
||||||
|
//! Server trust for the TLS 1.3 control connection (LNEx v3).
|
||||||
|
//!
|
||||||
|
//! Model (see `VNOX-Server/docs/02-protocol/tls.md`):
|
||||||
|
//! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins,
|
||||||
|
//! * without a record a certificate valid for the host name under the bundled public roots is
|
||||||
|
//! accepted (`ca` trust),
|
||||||
|
//! * otherwise the user must confirm the fingerprint once (trust on first use),
|
||||||
|
//! * a changed fingerprint is a hard error, never an automatic downgrade.
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// Default gateway port.
|
||||||
|
pub const DEFAULT_PORT: u16 = 7600;
|
||||||
|
|
||||||
|
/// Why a connection was stopped for trust reasons. Downcast from `anyhow::Error`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum TransportError {
|
||||||
|
/// No trust record and no valid public certificate: the user must confirm `fingerprint`.
|
||||||
|
UntrustedServer {
|
||||||
|
address: String,
|
||||||
|
fingerprint: String,
|
||||||
|
},
|
||||||
|
/// The pinned fingerprint of a known server changed.
|
||||||
|
FingerprintChanged {
|
||||||
|
address: String,
|
||||||
|
expected: String,
|
||||||
|
actual: String,
|
||||||
|
},
|
||||||
|
/// The server authenticated with another Ed25519 identity than the stored one.
|
||||||
|
IdentityChanged {
|
||||||
|
address: String,
|
||||||
|
expected: String,
|
||||||
|
actual: String,
|
||||||
|
},
|
||||||
|
/// A server marked as CA trusted no longer presents a valid public certificate.
|
||||||
|
CertificateInvalid { address: String, reason: String },
|
||||||
|
/// The peer does not speak TLS 1.3 / LNEx v3.
|
||||||
|
ProtocolMismatch(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for TransportError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::UntrustedServer {
|
||||||
|
address,
|
||||||
|
fingerprint,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"server {address} is not trusted yet (fingerprint {fingerprint})"
|
||||||
|
),
|
||||||
|
Self::FingerprintChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"certificate fingerprint of {address} changed: expected {expected}, received {actual}"
|
||||||
|
),
|
||||||
|
Self::IdentityChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => write!(
|
||||||
|
f,
|
||||||
|
"server identity of {address} changed: expected {expected}, received {actual}"
|
||||||
|
),
|
||||||
|
Self::CertificateInvalid { address, reason } => {
|
||||||
|
write!(f, "certificate of {address} is not valid: {reason}")
|
||||||
|
}
|
||||||
|
Self::ProtocolMismatch(message) => f.write_str(message),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl std::error::Error for TransportError {}
|
||||||
|
|
||||||
|
/// A trust decision the UI has to present.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum TrustProblem {
|
||||||
|
Untrusted {
|
||||||
|
address: String,
|
||||||
|
fingerprint: String,
|
||||||
|
},
|
||||||
|
FingerprintChanged {
|
||||||
|
address: String,
|
||||||
|
expected: String,
|
||||||
|
actual: String,
|
||||||
|
},
|
||||||
|
IdentityChanged {
|
||||||
|
address: String,
|
||||||
|
expected: String,
|
||||||
|
actual: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TransportError {
|
||||||
|
/// The trust prompt for this error, if the user can act on it.
|
||||||
|
pub fn trust_problem(&self) -> Option<TrustProblem> {
|
||||||
|
match self.clone() {
|
||||||
|
Self::UntrustedServer {
|
||||||
|
address,
|
||||||
|
fingerprint,
|
||||||
|
} => Some(TrustProblem::Untrusted {
|
||||||
|
address,
|
||||||
|
fingerprint,
|
||||||
|
}),
|
||||||
|
Self::FingerprintChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => Some(TrustProblem::FingerprintChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
}),
|
||||||
|
Self::IdentityChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => Some(TrustProblem::IdentityChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
}),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a server is trusted.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum TrustKind {
|
||||||
|
/// Certificate SPKI SHA-256 must equal `spki_sha256`.
|
||||||
|
Pin,
|
||||||
|
/// Certificate must validate for the host name under the bundled public roots.
|
||||||
|
Ca,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stored trust for one `host:port`.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ServerRecord {
|
||||||
|
pub trust: TrustKind,
|
||||||
|
/// Lower-case hex SHA-256 of the certificate SPKI (only for `pin`).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub spki_sha256: Option<String>,
|
||||||
|
/// Lower-case hex Ed25519 server identity, stored after the first authenticated handshake.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub identity: Option<String>,
|
||||||
|
pub first_seen: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Serialize, Deserialize)]
|
||||||
|
struct FileFormat {
|
||||||
|
version: u32,
|
||||||
|
servers: BTreeMap<String, ServerRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
path: Option<PathBuf>,
|
||||||
|
servers: BTreeMap<String, ServerRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thread safe, file backed trust store (`<config dir>/vnox/known_servers.json`).
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct TrustStore {
|
||||||
|
inner: Arc<Mutex<Inner>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A parsed server address.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ServerAddress {
|
||||||
|
pub host: String,
|
||||||
|
pub port: u16,
|
||||||
|
/// Normalised `host:port` key used by the trust store.
|
||||||
|
pub key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `host`, `host:port`, `[v6]:port`, optionally prefixed with `lnexs://` or `lnex://`.
|
||||||
|
/// Both schemes mean TLS 1.3; plaintext does not exist anymore.
|
||||||
|
pub fn parse_address(address: &str) -> Result<ServerAddress> {
|
||||||
|
let authority = address
|
||||||
|
.strip_prefix("lnexs://")
|
||||||
|
.or_else(|| address.strip_prefix("lnex://"))
|
||||||
|
.unwrap_or(address)
|
||||||
|
.trim();
|
||||||
|
if authority.contains('/')
|
||||||
|
|| authority.contains('@')
|
||||||
|
|| authority.contains('?')
|
||||||
|
|| authority.contains('#')
|
||||||
|
|| authority.contains(char::is_whitespace)
|
||||||
|
{
|
||||||
|
bail!("expected a server host and port");
|
||||||
|
}
|
||||||
|
let (host, port) = if let Some(value) = authority.strip_prefix('[') {
|
||||||
|
let (host, tail) = value.split_once(']').context("invalid IPv6 address")?;
|
||||||
|
let port = if tail.is_empty() {
|
||||||
|
DEFAULT_PORT
|
||||||
|
} else {
|
||||||
|
tail.strip_prefix(':')
|
||||||
|
.context("invalid server address")?
|
||||||
|
.parse()?
|
||||||
|
};
|
||||||
|
(host, port)
|
||||||
|
} else if let Some((host, port)) = authority.rsplit_once(':') {
|
||||||
|
(host, port.parse()?)
|
||||||
|
} else {
|
||||||
|
(authority, DEFAULT_PORT)
|
||||||
|
};
|
||||||
|
if host.is_empty() {
|
||||||
|
bail!("server host is empty");
|
||||||
|
}
|
||||||
|
let host = host.to_ascii_lowercase();
|
||||||
|
let key = if host.contains(':') {
|
||||||
|
format!("[{host}]:{port}")
|
||||||
|
} else {
|
||||||
|
format!("{host}:{port}")
|
||||||
|
};
|
||||||
|
Ok(ServerAddress { host, port, key })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_secs() -> i64 {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs() as i64)
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TrustStore {
|
||||||
|
/// `<config dir>/vnox/known_servers.json`.
|
||||||
|
pub fn default_path() -> Option<PathBuf> {
|
||||||
|
dirs::config_dir().map(|p| p.join("vnox").join("known_servers.json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the default store. A missing or unreadable file yields an empty store: the user
|
||||||
|
/// is asked again, trust is never granted implicitly.
|
||||||
|
pub fn load_default() -> Self {
|
||||||
|
match Self::default_path() {
|
||||||
|
Some(path) => Self::load(path),
|
||||||
|
None => Self::in_memory(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(path: PathBuf) -> Self {
|
||||||
|
let servers = match std::fs::read(&path) {
|
||||||
|
Ok(bytes) => match serde_json::from_slice::<FileFormat>(&bytes) {
|
||||||
|
Ok(file) if file.version == 1 => file.servers,
|
||||||
|
Ok(file) => {
|
||||||
|
tracing::warn!(version = file.version, "unsupported trust store version");
|
||||||
|
BTreeMap::new()
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(%error, "trust store is corrupt, starting empty");
|
||||||
|
BTreeMap::new()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(_) => BTreeMap::new(),
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
inner: Arc::new(Mutex::new(Inner {
|
||||||
|
path: Some(path),
|
||||||
|
servers,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store that is never written to disk (tests, headless tools).
|
||||||
|
pub fn in_memory() -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Arc::new(Mutex::new(Inner {
|
||||||
|
path: None,
|
||||||
|
servers: BTreeMap::new(),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
|
||||||
|
self.inner
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, key: &str) -> Option<ServerRecord> {
|
||||||
|
self.lock().servers.get(key).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trust exactly this certificate fingerprint for `key` (replaces any previous record).
|
||||||
|
pub fn pin(&self, key: &str, spki_sha256: &str) -> Result<()> {
|
||||||
|
let fingerprint = normalize_fingerprint(spki_sha256)?;
|
||||||
|
let mut inner = self.lock();
|
||||||
|
inner.servers.insert(
|
||||||
|
key.to_string(),
|
||||||
|
ServerRecord {
|
||||||
|
trust: TrustKind::Pin,
|
||||||
|
spki_sha256: Some(fingerprint),
|
||||||
|
identity: None,
|
||||||
|
first_seen: now_secs(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Self::save(&inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remember that `key` presented a certificate valid under the public roots.
|
||||||
|
pub fn trust_public_ca(&self, key: &str) -> Result<()> {
|
||||||
|
let mut inner = self.lock();
|
||||||
|
if inner.servers.contains_key(key) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
inner.servers.insert(
|
||||||
|
key.to_string(),
|
||||||
|
ServerRecord {
|
||||||
|
trust: TrustKind::Ca,
|
||||||
|
spki_sha256: None,
|
||||||
|
identity: None,
|
||||||
|
first_seen: now_secs(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Self::save(&inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store the authenticated server identity once.
|
||||||
|
pub fn set_identity(&self, key: &str, identity_hex: &str) -> Result<()> {
|
||||||
|
let mut inner = self.lock();
|
||||||
|
let Some(record) = inner.servers.get_mut(key) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if record.identity.as_deref() == Some(identity_hex) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if record.identity.is_some() {
|
||||||
|
bail!("refusing to overwrite the stored server identity");
|
||||||
|
}
|
||||||
|
record.identity = Some(identity_hex.to_string());
|
||||||
|
Self::save(&inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete the record. The next connection starts a fresh trust decision.
|
||||||
|
pub fn forget(&self, key: &str) -> Result<()> {
|
||||||
|
let mut inner = self.lock();
|
||||||
|
if inner.servers.remove(key).is_some() {
|
||||||
|
Self::save(&inner)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(inner: &Inner) -> Result<()> {
|
||||||
|
let Some(path) = &inner.path else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let parent = path.parent().context("trust store path has no parent")?;
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
let bytes = serde_json::to_vec_pretty(&FileFormat {
|
||||||
|
version: 1,
|
||||||
|
servers: inner.servers.clone(),
|
||||||
|
})?;
|
||||||
|
write_private(path, &bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
|
||||||
|
let mut options = std::fs::OpenOptions::new();
|
||||||
|
options.write(true).create_new(true);
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
options.mode(0o600);
|
||||||
|
}
|
||||||
|
let result = (|| -> Result<()> {
|
||||||
|
let mut file = options.open(&temporary)?;
|
||||||
|
file.write_all(bytes)?;
|
||||||
|
file.sync_all()?;
|
||||||
|
std::fs::rename(&temporary, path)?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = std::fs::remove_file(&temporary);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accept `ab:cd:...`, upper or lower case, with optional `sha256:` prefix; return 64 lower-case hex.
|
||||||
|
pub fn normalize_fingerprint(value: &str) -> Result<String> {
|
||||||
|
let cleaned: String = value
|
||||||
|
.trim()
|
||||||
|
.trim_start_matches("sha256:")
|
||||||
|
.chars()
|
||||||
|
.filter(|c| *c != ':' && !c.is_whitespace())
|
||||||
|
.collect::<String>()
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
if cleaned.len() != 64 || !cleaned.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||||
|
bail!("a SHA-256 fingerprint is 64 hexadecimal characters");
|
||||||
|
}
|
||||||
|
Ok(cleaned)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ab cd ef ...` grouped for display (pairs separated by colons).
|
||||||
|
pub fn display_fingerprint(hex_fingerprint: &str) -> String {
|
||||||
|
hex_fingerprint
|
||||||
|
.as_bytes()
|
||||||
|
.chunks(2)
|
||||||
|
.map(|pair| String::from_utf8_lossy(pair).to_ascii_uppercase())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(":")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_tlv(data: &[u8]) -> Result<(u8, usize, usize)> {
|
||||||
|
let tag = *data.first().context("truncated DER")?;
|
||||||
|
let first = *data.get(1).context("truncated DER")?;
|
||||||
|
let (header, length) = if first & 0x80 == 0 {
|
||||||
|
(2usize, first as usize)
|
||||||
|
} else {
|
||||||
|
let count = (first & 0x7F) as usize;
|
||||||
|
if count == 0 || count > 4 {
|
||||||
|
bail!("unsupported DER length");
|
||||||
|
}
|
||||||
|
let bytes = data.get(2..2 + count).context("truncated DER")?;
|
||||||
|
(
|
||||||
|
2 + count,
|
||||||
|
bytes.iter().fold(0usize, |acc, b| (acc << 8) | *b as usize),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if data.len() < header + length {
|
||||||
|
bail!("truncated DER");
|
||||||
|
}
|
||||||
|
Ok((tag, header, length))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The complete SubjectPublicKeyInfo SEQUENCE of an X.509 certificate.
|
||||||
|
pub fn spki_der(cert_der: &[u8]) -> Result<&[u8]> {
|
||||||
|
let (tag, header, length) = read_tlv(cert_der)?;
|
||||||
|
anyhow::ensure!(tag == 0x30, "certificate is not a SEQUENCE");
|
||||||
|
let tbs_all = &cert_der[header..header + length];
|
||||||
|
let (tag, header, length) = read_tlv(tbs_all)?;
|
||||||
|
anyhow::ensure!(tag == 0x30, "tbsCertificate is not a SEQUENCE");
|
||||||
|
let mut rest = &tbs_all[header..header + length];
|
||||||
|
// [version], serial, signature, issuer, validity, subject precede the SPKI.
|
||||||
|
let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 };
|
||||||
|
while skip > 0 {
|
||||||
|
let (_, header, length) = read_tlv(rest)?;
|
||||||
|
rest = &rest[header + length..];
|
||||||
|
skip -= 1;
|
||||||
|
}
|
||||||
|
let (tag, header, length) = read_tlv(rest)?;
|
||||||
|
anyhow::ensure!(tag == 0x30, "SubjectPublicKeyInfo is not a SEQUENCE");
|
||||||
|
Ok(&rest[..header + length])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lower-case hex SHA-256 over the certificate SPKI DER.
|
||||||
|
pub fn spki_fingerprint(cert_der: &[u8]) -> Result<String> {
|
||||||
|
Ok(hex::encode(Sha256::digest(spki_der(cert_der)?)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn temp_path() -> PathBuf {
|
||||||
|
std::env::temp_dir()
|
||||||
|
.join(format!("vnox-trust-{}", uuid::Uuid::new_v4()))
|
||||||
|
.join("known_servers.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn address_forms_are_normalised() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_address("Example.ORG").unwrap().key,
|
||||||
|
"example.org:7600"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_address("lnexs://example.org:7700").unwrap().key,
|
||||||
|
"example.org:7700"
|
||||||
|
);
|
||||||
|
assert_eq!(parse_address("lnex://[::1]").unwrap().key, "[::1]:7600");
|
||||||
|
assert_eq!(parse_address("127.0.0.1:1").unwrap().port, 1);
|
||||||
|
for bad in ["", "host/path", "user@host", "host?x", "host#x", "a b"] {
|
||||||
|
assert!(parse_address(bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fingerprint_normalisation_and_display() {
|
||||||
|
let hex64 = "ab".repeat(32);
|
||||||
|
let colons = hex64
|
||||||
|
.as_bytes()
|
||||||
|
.chunks(2)
|
||||||
|
.map(|c| String::from_utf8_lossy(c).to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(":")
|
||||||
|
.to_ascii_uppercase();
|
||||||
|
assert_eq!(normalize_fingerprint(&colons).unwrap(), hex64);
|
||||||
|
assert_eq!(
|
||||||
|
normalize_fingerprint(&format!("sha256:{hex64}")).unwrap(),
|
||||||
|
hex64
|
||||||
|
);
|
||||||
|
assert!(normalize_fingerprint("abcd").is_err());
|
||||||
|
assert!(normalize_fingerprint(&"zz".repeat(32)).is_err());
|
||||||
|
assert_eq!(display_fingerprint(&hex64), colons);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spki_fingerprint_of_ed25519_certificate_is_hash_of_fixed_prefix_and_key() {
|
||||||
|
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap();
|
||||||
|
let cert = rcgen::CertificateParams::new(vec!["x.example".into()])
|
||||||
|
.unwrap()
|
||||||
|
.self_signed(&key)
|
||||||
|
.unwrap();
|
||||||
|
let mut spki = vec![
|
||||||
|
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
|
||||||
|
];
|
||||||
|
spki.extend_from_slice(key.public_key_raw());
|
||||||
|
assert_eq!(
|
||||||
|
spki_fingerprint(cert.der().as_ref()).unwrap(),
|
||||||
|
hex::encode(Sha256::digest(&spki))
|
||||||
|
);
|
||||||
|
assert!(spki_fingerprint(b"junk").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn records_persist_with_private_permissions_and_forget_works() {
|
||||||
|
let path = temp_path();
|
||||||
|
let store = TrustStore::load(path.clone());
|
||||||
|
let fingerprint = "cd".repeat(32);
|
||||||
|
store.pin("h:7600", &fingerprint).unwrap();
|
||||||
|
store.set_identity("h:7600", &"11".repeat(32)).unwrap();
|
||||||
|
// The identity of a known server can never be silently replaced.
|
||||||
|
assert!(store.set_identity("h:7600", &"22".repeat(32)).is_err());
|
||||||
|
let reloaded = TrustStore::load(path.clone());
|
||||||
|
let record = reloaded.get("h:7600").unwrap();
|
||||||
|
assert_eq!(record.trust, TrustKind::Pin);
|
||||||
|
assert_eq!(record.spki_sha256.as_deref(), Some(fingerprint.as_str()));
|
||||||
|
assert_eq!(record.identity.as_deref(), Some("11".repeat(32).as_str()));
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||||
|
0o600
|
||||||
|
);
|
||||||
|
}
|
||||||
|
reloaded.forget("h:7600").unwrap();
|
||||||
|
assert!(TrustStore::load(path.clone()).get("h:7600").is_none());
|
||||||
|
std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corrupt_store_starts_empty_instead_of_trusting() {
|
||||||
|
let path = temp_path();
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&path, b"{not json").unwrap();
|
||||||
|
let store = TrustStore::load(path.clone());
|
||||||
|
assert!(store.get("h:7600").is_none());
|
||||||
|
std::fs::remove_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn public_ca_record_is_not_overwritten_and_pin_rejects_bad_hex() {
|
||||||
|
let store = TrustStore::in_memory();
|
||||||
|
store.trust_public_ca("h:1").unwrap();
|
||||||
|
store.trust_public_ca("h:1").unwrap();
|
||||||
|
assert_eq!(store.get("h:1").unwrap().trust, TrustKind::Ca);
|
||||||
|
assert!(store.pin("h:1", "nothex").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -20,6 +20,8 @@ pub enum NetEvent {
|
||||||
reason: String,
|
reason: String,
|
||||||
will_retry: bool,
|
will_retry: bool,
|
||||||
},
|
},
|
||||||
|
/// The user has to decide about a server certificate (first use or changed fingerprint).
|
||||||
|
TrustProblem(crate::net::trust::TrustProblem),
|
||||||
Reconnecting {
|
Reconnecting {
|
||||||
attempt: u32,
|
attempt: u32,
|
||||||
delay_secs: u64,
|
delay_secs: u64,
|
||||||
|
|
|
||||||
|
|
@ -382,6 +382,30 @@ pub fn sync_connect(window: &MainWindow, state: &UiState) {
|
||||||
ConnState::Connecting | ConnState::Reconnecting { .. }
|
ConnState::Connecting | ConnState::Reconnecting { .. }
|
||||||
));
|
));
|
||||||
window.set_auto_reconnect(state.auto_reconnect);
|
window.set_auto_reconnect(state.auto_reconnect);
|
||||||
|
{
|
||||||
|
use crate::ui::state::TrustPromptKind;
|
||||||
|
let (kind, address, received, expected) = match &state.trust_prompt {
|
||||||
|
None => (0, "", "", ""),
|
||||||
|
Some(prompt) => (
|
||||||
|
match prompt.kind {
|
||||||
|
TrustPromptKind::FirstUse => 1,
|
||||||
|
TrustPromptKind::FingerprintChanged => 2,
|
||||||
|
TrustPromptKind::IdentityChanged => 3,
|
||||||
|
},
|
||||||
|
prompt.address.as_str(),
|
||||||
|
prompt.received.as_str(),
|
||||||
|
prompt.expected.as_str(),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
window.set_trust_kind(kind);
|
||||||
|
window.set_trust_address(SharedString::from(address));
|
||||||
|
window.set_trust_received(SharedString::from(
|
||||||
|
vnox_client::net::trust::display_fingerprint(received),
|
||||||
|
));
|
||||||
|
window.set_trust_expected(SharedString::from(
|
||||||
|
vnox_client::net::trust::display_fingerprint(expected),
|
||||||
|
));
|
||||||
|
}
|
||||||
if let ConnState::Connected { ref node_name, .. } = state.conn {
|
if let ConnState::Connected { ref node_name, .. } = state.conn {
|
||||||
window.set_node_name(SharedString::from(node_name.as_str()));
|
window.set_node_name(SharedString::from(node_name.as_str()));
|
||||||
} else if matches!(state.conn, ConnState::Disconnected) {
|
} else if matches!(state.conn, ConnState::Disconnected) {
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,14 @@ export component ConnectScreen inherits Rectangle {
|
||||||
callback remove-bookmark(string);
|
callback remove-bookmark(string);
|
||||||
callback add-bookmark(string);
|
callback add-bookmark(string);
|
||||||
callback open-settings();
|
callback open-settings();
|
||||||
|
// 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed
|
||||||
|
in property <int> trust-kind: 0;
|
||||||
|
in property <string> trust-address;
|
||||||
|
in property <string> trust-received;
|
||||||
|
in property <string> trust-expected;
|
||||||
|
callback trust-accept();
|
||||||
|
callback trust-forget();
|
||||||
|
callback trust-dismiss();
|
||||||
background: Theme.bg-base;
|
background: Theme.bg-base;
|
||||||
VerticalLayout {
|
VerticalLayout {
|
||||||
padding: 32px; spacing: 22px;
|
padding: 32px; spacing: 22px;
|
||||||
|
|
@ -86,4 +94,50 @@ export component ConnectScreen inherits Rectangle {
|
||||||
Rectangle { vertical-stretch: 1; }
|
Rectangle { vertical-stretch: 1; }
|
||||||
Text { text: @tr("Your server. Your community."); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; }
|
Text { text: @tr("Your server. Your community."); color: Theme.text-disabled; font-size: Math.max(11px, Theme.font-size * 0.75); horizontal-alignment: center; }
|
||||||
}
|
}
|
||||||
|
if root.trust-kind != 0 : Rectangle {
|
||||||
|
background: #000000a0;
|
||||||
|
TouchArea { }
|
||||||
|
HorizontalLayout {
|
||||||
|
Rectangle { horizontal-stretch: 1; }
|
||||||
|
VerticalLayout {
|
||||||
|
Rectangle { vertical-stretch: 1; }
|
||||||
|
Rectangle {
|
||||||
|
width: 560px;
|
||||||
|
height: trust-card.preferred-height;
|
||||||
|
background: Theme.bg-surface; border-radius: 14px;
|
||||||
|
border-width: 1px; border-color: root.trust-kind == 1 ? Theme.border : Theme.danger;
|
||||||
|
trust-card := VerticalLayout {
|
||||||
|
padding: 26px; spacing: 12px; alignment: start;
|
||||||
|
Text {
|
||||||
|
text: root.trust-kind == 1 ? @tr("Trust this server?") : root.trust-kind == 2 ? @tr("Server fingerprint changed") : @tr("Server identity changed");
|
||||||
|
color: root.trust-kind == 1 ? Theme.text-primary : Theme.danger;
|
||||||
|
font-size: Math.max(11px, Theme.font-size * 1.375); font-weight: 600; wrap: word-wrap;
|
||||||
|
}
|
||||||
|
Text {
|
||||||
|
text: root.trust-kind == 1
|
||||||
|
? @tr("This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.")
|
||||||
|
: root.trust-kind == 2
|
||||||
|
? @tr("The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.")
|
||||||
|
: @tr("The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.");
|
||||||
|
color: Theme.text-secondary; font-size: Math.max(11px, Theme.font-size * 0.8125); wrap: word-wrap;
|
||||||
|
}
|
||||||
|
Text { text: @tr("Server address"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
|
||||||
|
Text { text: root.trust-address; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.875); wrap: word-wrap; }
|
||||||
|
if root.trust-kind != 1 : Text { text: @tr("Previously trusted fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
|
||||||
|
if root.trust-kind != 1 : Text { text: root.trust-expected; color: Theme.text-primary; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; }
|
||||||
|
Text { text: root.trust-kind == 1 ? @tr("Fingerprint (SHA-256)") : @tr("Received fingerprint"); color: Theme.text-muted; font-size: Math.max(11px, Theme.font-size * 0.75); }
|
||||||
|
Text { text: root.trust-received; color: root.trust-kind == 1 ? Theme.accent : Theme.danger; font-size: Math.max(11px, Theme.font-size * 0.75); wrap: word-wrap; }
|
||||||
|
HorizontalLayout {
|
||||||
|
spacing: 9px; alignment: end;
|
||||||
|
if root.trust-kind != 1 : ActionButton { text: @tr("Forget this server"); danger: true; clicked => { root.trust-forget(); } }
|
||||||
|
ActionButton { text: root.trust-kind == 1 ? @tr("Cancel") : @tr("Close"); clicked => { root.trust-dismiss(); } }
|
||||||
|
if root.trust-kind == 1 : ActionButton { text: @tr("Trust and connect"); active: true; clicked => { root.trust-accept(); } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rectangle { vertical-stretch: 1; }
|
||||||
|
}
|
||||||
|
Rectangle { horizontal-stretch: 1; }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -71,6 +71,11 @@ export component MainWindow inherits Window {
|
||||||
in-out property <bool> connecting: false;
|
in-out property <bool> connecting: false;
|
||||||
in-out property <bool> auto-reconnect: false;
|
in-out property <bool> auto-reconnect: false;
|
||||||
in-out property <string> node-name: "";
|
in-out property <string> node-name: "";
|
||||||
|
// 0 none, 1 first use, 2 certificate fingerprint changed, 3 server identity changed
|
||||||
|
in-out property <int> trust-kind: 0;
|
||||||
|
in-out property <string> trust-address: "";
|
||||||
|
in-out property <string> trust-received: "";
|
||||||
|
in-out property <string> trust-expected: "";
|
||||||
|
|
||||||
in-out property <string> identity-pubkey: "";
|
in-out property <string> identity-pubkey: "";
|
||||||
in-out property <bool> vault-enabled: false;
|
in-out property <bool> vault-enabled: false;
|
||||||
|
|
@ -155,6 +160,9 @@ export component MainWindow inherits Window {
|
||||||
callback connect(string);
|
callback connect(string);
|
||||||
callback remove-bookmark(string);
|
callback remove-bookmark(string);
|
||||||
callback add-bookmark(string);
|
callback add-bookmark(string);
|
||||||
|
callback trust-accept();
|
||||||
|
callback trust-forget();
|
||||||
|
callback trust-dismiss();
|
||||||
callback close-settings();
|
callback close-settings();
|
||||||
callback set-passphrase(string, string);
|
callback set-passphrase(string, string);
|
||||||
callback remove-passphrase();
|
callback remove-passphrase();
|
||||||
|
|
@ -177,6 +185,13 @@ export component MainWindow inherits Window {
|
||||||
connecting: root.connecting;
|
connecting: root.connecting;
|
||||||
auto-reconnect <=> root.auto-reconnect;
|
auto-reconnect <=> root.auto-reconnect;
|
||||||
node-name: root.node-name;
|
node-name: root.node-name;
|
||||||
|
trust-kind: root.trust-kind;
|
||||||
|
trust-address: root.trust-address;
|
||||||
|
trust-received: root.trust-received;
|
||||||
|
trust-expected: root.trust-expected;
|
||||||
|
trust-accept => { root.trust-accept(); }
|
||||||
|
trust-forget => { root.trust-forget(); }
|
||||||
|
trust-dismiss => { root.trust-dismiss(); }
|
||||||
open-settings => { root.open-settings(); }
|
open-settings => { root.open-settings(); }
|
||||||
address-edited(text) => { root.address-edited(text); }
|
address-edited(text) => { root.address-edited(text); }
|
||||||
auto-reconnect-changed(value) => { root.auto-reconnect-changed(value); }
|
auto-reconnect-changed(value) => { root.auto-reconnect-changed(value); }
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ impl Default for UiState {
|
||||||
bookmarks: default_bookmarks(),
|
bookmarks: default_bookmarks(),
|
||||||
selected_bookmark: 0,
|
selected_bookmark: 0,
|
||||||
status_msg: None,
|
status_msg: None,
|
||||||
|
trust_prompt: None,
|
||||||
channels: Vec::new(),
|
channels: Vec::new(),
|
||||||
active_channel: None,
|
active_channel: None,
|
||||||
messages: Default::default(),
|
messages: Default::default(),
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ mod navigation;
|
||||||
mod types;
|
mod types;
|
||||||
|
|
||||||
pub use models::{Channel, ChatMessage, DmConversation, FriendState, GuildState, NodeBookmark};
|
pub use models::{Channel, ChatMessage, DmConversation, FriendState, GuildState, NodeBookmark};
|
||||||
pub use types::{ConnState, UiState, VoiceUiState};
|
pub use types::{ConnState, TrustPrompt, TrustPromptKind, UiState, VoiceUiState};
|
||||||
|
|
||||||
use models::bookmark_label_from_address;
|
use models::bookmark_label_from_address;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,25 @@ pub enum ConnState {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A pending server trust decision (first use or blocked fingerprint change).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct TrustPrompt {
|
||||||
|
pub kind: TrustPromptKind,
|
||||||
|
/// Trust store key, `host:port`.
|
||||||
|
pub address: String,
|
||||||
|
/// Lower-case hex value that was received.
|
||||||
|
pub received: String,
|
||||||
|
/// Lower-case hex value that was trusted before (changed fingerprint or identity).
|
||||||
|
pub expected: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum TrustPromptKind {
|
||||||
|
FirstUse,
|
||||||
|
FingerprintChanged,
|
||||||
|
IdentityChanged,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct UiState {
|
pub struct UiState {
|
||||||
pub appearance: crate::ui::appearance::AppearancePreferences,
|
pub appearance: crate::ui::appearance::AppearancePreferences,
|
||||||
pub conn: ConnState,
|
pub conn: ConnState,
|
||||||
|
|
@ -31,6 +50,7 @@ pub struct UiState {
|
||||||
pub bookmarks: Vec<super::NodeBookmark>,
|
pub bookmarks: Vec<super::NodeBookmark>,
|
||||||
pub selected_bookmark: usize,
|
pub selected_bookmark: usize,
|
||||||
pub status_msg: Option<crate::ui::i18n::Message>,
|
pub status_msg: Option<crate::ui::i18n::Message>,
|
||||||
|
pub trust_prompt: Option<TrustPrompt>,
|
||||||
|
|
||||||
pub channels: Vec<super::Channel>,
|
pub channels: Vec<super::Channel>,
|
||||||
pub active_channel: Option<String>,
|
pub active_channel: Option<String>,
|
||||||
|
|
|
||||||
|
|
@ -75,6 +75,41 @@ pub fn process_net_events(state: &mut AppState) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
NetEvent::TrustProblem(problem) => {
|
||||||
|
use crate::ui::state::{TrustPrompt, TrustPromptKind};
|
||||||
|
use vnox_client::net::TrustProblem;
|
||||||
|
state.ui.trust_prompt = Some(match problem {
|
||||||
|
TrustProblem::Untrusted {
|
||||||
|
address,
|
||||||
|
fingerprint,
|
||||||
|
} => TrustPrompt {
|
||||||
|
kind: TrustPromptKind::FirstUse,
|
||||||
|
address,
|
||||||
|
received: fingerprint,
|
||||||
|
expected: String::new(),
|
||||||
|
},
|
||||||
|
TrustProblem::FingerprintChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => TrustPrompt {
|
||||||
|
kind: TrustPromptKind::FingerprintChanged,
|
||||||
|
address,
|
||||||
|
received: actual,
|
||||||
|
expected,
|
||||||
|
},
|
||||||
|
TrustProblem::IdentityChanged {
|
||||||
|
address,
|
||||||
|
expected,
|
||||||
|
actual,
|
||||||
|
} => TrustPrompt {
|
||||||
|
kind: TrustPromptKind::IdentityChanged,
|
||||||
|
address,
|
||||||
|
received: actual,
|
||||||
|
expected,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
NetEvent::Disconnected { reason, will_retry } => {
|
NetEvent::Disconnected { reason, will_retry } => {
|
||||||
if let Some(ui) = &state.webhooks {
|
if let Some(ui) = &state.webhooks {
|
||||||
ui.disconnected();
|
ui.disconnected();
|
||||||
|
|
@ -97,10 +132,14 @@ pub fn process_net_events(state: &mut AppState) {
|
||||||
state.ui.active_channel = None;
|
state.ui.active_channel = None;
|
||||||
state.ui.user_names.clear();
|
state.ui.user_names.clear();
|
||||||
state.ui.rtt_ms = None;
|
state.ui.rtt_ms = None;
|
||||||
state.ui.status_msg = Some(crate::ui::i18n::Message::with(
|
state.ui.status_msg = if state.ui.trust_prompt.is_some() {
|
||||||
"Disconnected: {reason}",
|
None
|
||||||
vec![("reason", reason.to_string())],
|
} else {
|
||||||
));
|
Some(crate::ui::i18n::Message::with(
|
||||||
|
"Disconnected: {reason}",
|
||||||
|
vec![("reason", reason.to_string())],
|
||||||
|
))
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if !will_retry {
|
if !will_retry {
|
||||||
state.ui.dm_conversations.clear();
|
state.ui.dm_conversations.clear();
|
||||||
|
|
@ -348,6 +387,7 @@ fn process_net_event(ui: &mut UiState, net: &NetHandle, event: NetEvent) {
|
||||||
| NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"),
|
| NetEvent::WebhookError(_) => unreachable!("handled before generic UI dispatch"),
|
||||||
NetEvent::Connected { .. }
|
NetEvent::Connected { .. }
|
||||||
| NetEvent::Disconnected { .. }
|
| NetEvent::Disconnected { .. }
|
||||||
|
| NetEvent::TrustProblem(_)
|
||||||
| NetEvent::Reconnecting { .. }
|
| NetEvent::Reconnecting { .. }
|
||||||
| NetEvent::VoicePacket { .. }
|
| NetEvent::VoicePacket { .. }
|
||||||
| NetEvent::E2eeDmKeyExchange { .. }
|
| NetEvent::E2eeDmKeyExchange { .. }
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
//! Real gateway fixture. Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored.
|
//! Real gateway fixture over TLS 1.3 (LNEx v3).
|
||||||
|
//! Run with VNOX_GATEWAY_BIN=/path/to/vnox-gateway cargo test --test gateway_interop -- --ignored.
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
process::{Child, Command, Stdio},
|
process::{Child, Command, Stdio},
|
||||||
|
|
@ -6,7 +7,7 @@ use std::{
|
||||||
};
|
};
|
||||||
use vnox_client::{
|
use vnox_client::{
|
||||||
identity,
|
identity,
|
||||||
net::{self, NetCommand, NetEvent, NetHandle},
|
net::{self, NetCommand, NetEvent, NetHandle, TrustProblem, TrustStore},
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Gateway {
|
struct Gateway {
|
||||||
|
|
@ -27,15 +28,15 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net
|
||||||
tokio::time::timeout(Duration::from_secs(8), async {
|
tokio::time::timeout(Duration::from_secs(8), async {
|
||||||
loop {
|
loop {
|
||||||
if let Some(event) = handle.try_recv() {
|
if let Some(event) = handle.try_recv() {
|
||||||
|
if predicate(&event) {
|
||||||
|
return event;
|
||||||
|
}
|
||||||
if let NetEvent::Disconnected { ref reason, .. } = event {
|
if let NetEvent::Disconnected { ref reason, .. } = event {
|
||||||
panic!("unexpected disconnect: {reason}");
|
panic!("unexpected disconnect: {reason}");
|
||||||
}
|
}
|
||||||
if let NetEvent::Error { code, ref message } = event {
|
if let NetEvent::Error { code, ref message } = event {
|
||||||
panic!("gateway error {code}: {message}");
|
panic!("gateway error {code}: {message}");
|
||||||
}
|
}
|
||||||
if predicate(&event) {
|
|
||||||
return event;
|
|
||||||
}
|
|
||||||
if let NetEvent::WebhookError(ref result) = event {
|
if let NetEvent::WebhookError(ref result) = event {
|
||||||
panic!(
|
panic!(
|
||||||
"unexpected webhook error at stage {stage}, request {}: {} ({})",
|
"unexpected webhook error at stage {stage}, request {}: {} ({})",
|
||||||
|
|
@ -49,6 +50,43 @@ async fn event(handle: &NetHandle, predicate: impl Fn(&NetEvent) -> bool) -> Net
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| panic!("gateway event timeout at stage {stage}"))
|
.unwrap_or_else(|_| panic!("gateway event timeout at stage {stage}"))
|
||||||
}
|
}
|
||||||
|
/// First connection: the client must stop at the untrusted certificate, show the same
|
||||||
|
/// fingerprint the gateway published, and connect only after the fingerprint is pinned.
|
||||||
|
async fn connect_with_first_trust(handle: &NetHandle, address: &str, published: &str) {
|
||||||
|
handle
|
||||||
|
.send(NetCommand::Connect {
|
||||||
|
address: address.into(),
|
||||||
|
auto_reconnect: false,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let prompt = event(handle, |e| matches!(e, NetEvent::TrustProblem(_))).await;
|
||||||
|
let NetEvent::TrustProblem(TrustProblem::Untrusted { fingerprint, .. }) = prompt else {
|
||||||
|
panic!("expected the first-use trust prompt, got {prompt:?}");
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
fingerprint, published,
|
||||||
|
"the prompt must show the fingerprint published by the gateway"
|
||||||
|
);
|
||||||
|
event(handle, |e| {
|
||||||
|
matches!(
|
||||||
|
e,
|
||||||
|
NetEvent::Disconnected {
|
||||||
|
will_retry: false,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let key = net::trust::parse_address(address).unwrap().key;
|
||||||
|
handle.trust().pin(&key, &fingerprint).unwrap();
|
||||||
|
handle
|
||||||
|
.send(NetCommand::Connect {
|
||||||
|
address: address.into(),
|
||||||
|
auto_reconnect: false,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
fn free_port() -> u16 {
|
fn free_port() -> u16 {
|
||||||
std::net::TcpListener::bind("127.0.0.1:0")
|
std::net::TcpListener::bind("127.0.0.1:0")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
|
|
@ -59,7 +97,7 @@ fn free_port() -> u16 {
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[ignore = "requires a freshly built current VNOX gateway binary"]
|
#[ignore = "requires a freshly built current VNOX gateway binary"]
|
||||||
async fn native_network_connects_signed_v2_and_exchanges_protobuf_chat() {
|
async fn native_network_connects_signed_v3_over_tls_and_exchanges_protobuf_chat() {
|
||||||
let binary = std::env::var_os("VNOX_GATEWAY_BIN")
|
let binary = std::env::var_os("VNOX_GATEWAY_BIN")
|
||||||
.expect("set VNOX_GATEWAY_BIN to the current server binary");
|
.expect("set VNOX_GATEWAY_BIN to the current server binary");
|
||||||
let directory = std::env::temp_dir().join(format!("vnox-interop-{}", uuid::Uuid::new_v4()));
|
let directory = std::env::temp_dir().join(format!("vnox-interop-{}", uuid::Uuid::new_v4()));
|
||||||
|
|
@ -95,6 +133,7 @@ mode = "private"
|
||||||
.stderr(Stdio::inherit())
|
.stderr(Stdio::inherit())
|
||||||
.spawn()
|
.spawn()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let data_dir = directory.clone();
|
||||||
let _gateway = Gateway { child, directory };
|
let _gateway = Gateway { child, directory };
|
||||||
let address = format!("127.0.0.1:{port}");
|
let address = format!("127.0.0.1:{port}");
|
||||||
tokio::time::timeout(Duration::from_secs(8), async {
|
tokio::time::timeout(Duration::from_secs(8), async {
|
||||||
|
|
@ -110,13 +149,44 @@ mode = "private"
|
||||||
// In-memory identity only; never touch a real profile or encrypted vault.
|
// In-memory identity only; never touch a real profile or encrypted vault.
|
||||||
let alice_identity = identity::generate("interop-alice");
|
let alice_identity = identity::generate("interop-alice");
|
||||||
let alice_user_id = alice_identity.pubkey_hex.clone();
|
let alice_user_id = alice_identity.pubkey_hex.clone();
|
||||||
let alice = net::spawn(alice_identity);
|
// Trust is kept in memory: never touch the real ~/.config/vnox/known_servers.json.
|
||||||
alice
|
let alice = net::spawn_with_trust(alice_identity, TrustStore::in_memory());
|
||||||
|
let published = std::fs::read_to_string(data_dir.join("tls").join("fingerprint.txt"))
|
||||||
|
.unwrap()
|
||||||
|
.trim()
|
||||||
|
.to_string();
|
||||||
|
// A client that pinned another fingerprint is blocked before sending anything.
|
||||||
|
let impostor =
|
||||||
|
net::spawn_with_trust(identity::generate("interop-pin"), TrustStore::in_memory());
|
||||||
|
impostor
|
||||||
|
.trust()
|
||||||
|
.pin(
|
||||||
|
&net::trust::parse_address(&address).unwrap().key,
|
||||||
|
&"ab".repeat(32),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
impostor
|
||||||
.send(NetCommand::Connect {
|
.send(NetCommand::Connect {
|
||||||
address,
|
address: address.clone(),
|
||||||
auto_reconnect: false,
|
auto_reconnect: true,
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
let blocked = event(&impostor, |e| matches!(e, NetEvent::TrustProblem(_))).await;
|
||||||
|
assert!(matches!(
|
||||||
|
blocked,
|
||||||
|
NetEvent::TrustProblem(TrustProblem::FingerprintChanged { ref actual, .. }) if actual == &published
|
||||||
|
));
|
||||||
|
event(&impostor, |e| {
|
||||||
|
matches!(
|
||||||
|
e,
|
||||||
|
NetEvent::Disconnected {
|
||||||
|
will_retry: false,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
connect_with_first_trust(&alice, &address, &published).await;
|
||||||
event(
|
event(
|
||||||
&alice,
|
&alice,
|
||||||
|e| matches!(e,NetEvent::Connected {node_name,..} if node_name=="interop-node"),
|
|e| matches!(e,NetEvent::Connected {node_name,..} if node_name=="interop-node"),
|
||||||
|
|
@ -260,7 +330,16 @@ mode = "private"
|
||||||
event(&alice,|e|matches!(e,NetEvent::WebhookResult(result) if result.request_id=="revoke-fixture" && result.secret.is_empty() && result.hook.as_ref().is_some_and(|hook|hook.revoked))).await;
|
event(&alice,|e|matches!(e,NetEvent::WebhookResult(result) if result.request_id=="revoke-fixture" && result.secret.is_empty() && result.hook.as_ref().is_some_and(|hook|hook.revoked))).await;
|
||||||
let guest_identity = identity::generate("webhook-unprivileged");
|
let guest_identity = identity::generate("webhook-unprivileged");
|
||||||
let guest_user_id = guest_identity.pubkey_hex.clone();
|
let guest_user_id = guest_identity.pubkey_hex.clone();
|
||||||
let guest = net::spawn(guest_identity);
|
let guest = net::spawn_with_trust(guest_identity, TrustStore::in_memory());
|
||||||
|
guest
|
||||||
|
.trust()
|
||||||
|
.pin(
|
||||||
|
&net::trust::parse_address(&format!("127.0.0.1:{port}"))
|
||||||
|
.unwrap()
|
||||||
|
.key,
|
||||||
|
&published,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
guest
|
guest
|
||||||
.send(NetCommand::Connect {
|
.send(NetCommand::Connect {
|
||||||
address: format!("127.0.0.1:{port}"),
|
address: format!("127.0.0.1:{port}"),
|
||||||
|
|
@ -301,6 +380,22 @@ mode = "private"
|
||||||
.await;
|
.await;
|
||||||
alice.send(NetCommand::FriendList).await;
|
alice.send(NetCommand::FriendList).await;
|
||||||
event(&alice,|e|matches!(e,NetEvent::FriendList {friends} if friends.iter().any(|friend|friend.user_id==guest_user_id))).await;
|
event(&alice,|e|matches!(e,NetEvent::FriendList {friends} if friends.iter().any(|friend|friend.user_id==guest_user_id))).await;
|
||||||
|
// The server identity was stored after the first authenticated handshake.
|
||||||
|
let identity_file: serde_json::Value =
|
||||||
|
serde_json::from_slice(&std::fs::read(data_dir.join("server_identity.json")).unwrap())
|
||||||
|
.unwrap();
|
||||||
|
let record = alice
|
||||||
|
.trust()
|
||||||
|
.get(
|
||||||
|
&net::trust::parse_address(&format!("127.0.0.1:{port}"))
|
||||||
|
.unwrap()
|
||||||
|
.key,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
record.identity.as_deref(),
|
||||||
|
identity_file["pubkey_hex"].as_str()
|
||||||
|
);
|
||||||
guest.send(NetCommand::Disconnect).await;
|
guest.send(NetCommand::Disconnect).await;
|
||||||
alice.send(NetCommand::Disconnect).await;
|
alice.send(NetCommand::Disconnect).await;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -214,9 +214,15 @@ msgstr "Export keys"
|
||||||
msgid "Extra dark"
|
msgid "Extra dark"
|
||||||
msgstr "Extra dark"
|
msgstr "Extra dark"
|
||||||
|
|
||||||
|
msgid "Fingerprint (SHA-256)"
|
||||||
|
msgstr "Fingerprint (SHA-256)"
|
||||||
|
|
||||||
msgid "For example: /home/user/themes/my-vnox.css"
|
msgid "For example: /home/user/themes/my-vnox.css"
|
||||||
msgstr "For example: /home/user/themes/my-vnox.css"
|
msgstr "For example: /home/user/themes/my-vnox.css"
|
||||||
|
|
||||||
|
msgid "Forget this server"
|
||||||
|
msgstr "Forget this server"
|
||||||
|
|
||||||
msgid "Friends"
|
msgid "Friends"
|
||||||
msgstr "Friends"
|
msgstr "Friends"
|
||||||
|
|
||||||
|
|
@ -409,6 +415,9 @@ msgstr "Preview active · not broadcasting"
|
||||||
msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
||||||
msgstr "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
msgstr "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
||||||
|
|
||||||
|
msgid "Previously trusted fingerprint"
|
||||||
|
msgstr "Previously trusted fingerprint"
|
||||||
|
|
||||||
msgid "Profile and keys"
|
msgid "Profile and keys"
|
||||||
msgstr "Profile and keys"
|
msgstr "Profile and keys"
|
||||||
|
|
||||||
|
|
@ -424,6 +433,9 @@ msgstr "Push to talk"
|
||||||
msgid "Receive updates here, or send signed channel events to your own service."
|
msgid "Receive updates here, or send signed channel events to your own service."
|
||||||
msgstr "Receive updates here, or send signed channel events to your own service."
|
msgstr "Receive updates here, or send signed channel events to your own service."
|
||||||
|
|
||||||
|
msgid "Received fingerprint"
|
||||||
|
msgstr "Received fingerprint"
|
||||||
|
|
||||||
msgid "Reconnect automatically"
|
msgid "Reconnect automatically"
|
||||||
msgstr "Reconnect automatically"
|
msgstr "Reconnect automatically"
|
||||||
|
|
||||||
|
|
@ -496,6 +508,12 @@ msgstr "Send"
|
||||||
msgid "Server address"
|
msgid "Server address"
|
||||||
msgstr "Server address"
|
msgstr "Server address"
|
||||||
|
|
||||||
|
msgid "Server fingerprint changed"
|
||||||
|
msgstr "Server fingerprint changed"
|
||||||
|
|
||||||
|
msgid "Server identity changed"
|
||||||
|
msgstr "Server identity changed"
|
||||||
|
|
||||||
msgid "Settings"
|
msgid "Settings"
|
||||||
msgstr "Settings"
|
msgstr "Settings"
|
||||||
|
|
||||||
|
|
@ -541,9 +559,15 @@ msgstr "Text size"
|
||||||
msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
||||||
msgstr "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
msgstr "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
||||||
|
|
||||||
|
msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
msgstr "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
|
||||||
msgid "The old secret stops working. Update the external integration with the new secret."
|
msgid "The old secret stops working. Update the external integration with the new secret."
|
||||||
msgstr "The old secret stops working. Update the external integration with the new secret."
|
msgstr "The old secret stops working. Update the external integration with the new secret."
|
||||||
|
|
||||||
|
msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
msgstr "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
|
||||||
msgid "Theme editor"
|
msgid "Theme editor"
|
||||||
msgstr "Theme editor"
|
msgstr "Theme editor"
|
||||||
|
|
||||||
|
|
@ -556,6 +580,15 @@ msgstr "Themes, colours and text"
|
||||||
msgid "This cannot be undone."
|
msgid "This cannot be undone."
|
||||||
msgstr "This cannot be undone."
|
msgstr "This cannot be undone."
|
||||||
|
|
||||||
|
msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match."
|
||||||
|
msgstr "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match."
|
||||||
|
|
||||||
|
msgid "Trust and connect"
|
||||||
|
msgstr "Trust and connect"
|
||||||
|
|
||||||
|
msgid "Trust this server?"
|
||||||
|
msgstr "Trust this server?"
|
||||||
|
|
||||||
msgid "Undeafen"
|
msgid "Undeafen"
|
||||||
msgstr "Undeafen"
|
msgstr "Undeafen"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -351,5 +351,18 @@
|
||||||
"Starting broadcast…": "Запуск трансляции…",
|
"Starting broadcast…": "Запуск трансляции…",
|
||||||
"WebRTC connection timed out": "Время ожидания соединения WebRTC истекло",
|
"WebRTC connection timed out": "Время ожидания соединения WebRTC истекло",
|
||||||
"Broadcast authorization timed out": "Время ожидания разрешения на трансляцию истекло",
|
"Broadcast authorization timed out": "Время ожидания разрешения на трансляцию истекло",
|
||||||
"Broadcast connection timed out": "Время ожидания подключения к трансляции истекло"
|
"Broadcast connection timed out": "Время ожидания подключения к трансляции истекло",
|
||||||
|
"Trust this server?": "Доверять этому серверу?",
|
||||||
|
"This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match.": "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают.",
|
||||||
|
"Server fingerprint changed": "Отпечаток сервера изменился",
|
||||||
|
"The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.",
|
||||||
|
"Server identity changed": "Ключ сервера изменился",
|
||||||
|
"The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected.": "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение.",
|
||||||
|
"Previously trusted fingerprint": "Ранее доверенный отпечаток",
|
||||||
|
"Fingerprint (SHA-256)": "Отпечаток (SHA-256)",
|
||||||
|
"Received fingerprint": "Полученный отпечаток",
|
||||||
|
"Forget this server": "Забыть этот сервер",
|
||||||
|
"Trust and connect": "Доверять и подключиться",
|
||||||
|
"Could not save the trusted fingerprint": "Не удалось сохранить доверенный отпечаток",
|
||||||
|
"Server forgotten. Connect again to review its fingerprint.": "Сервер забыт. Подключись снова, чтобы проверить его отпечаток."
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -215,9 +215,15 @@ msgstr "Экспортировать ключи"
|
||||||
msgid "Extra dark"
|
msgid "Extra dark"
|
||||||
msgstr "Мега-тёмная"
|
msgstr "Мега-тёмная"
|
||||||
|
|
||||||
|
msgid "Fingerprint (SHA-256)"
|
||||||
|
msgstr "Отпечаток (SHA-256)"
|
||||||
|
|
||||||
msgid "For example: /home/user/themes/my-vnox.css"
|
msgid "For example: /home/user/themes/my-vnox.css"
|
||||||
msgstr "Например: /home/user/themes/my-vnox.css"
|
msgstr "Например: /home/user/themes/my-vnox.css"
|
||||||
|
|
||||||
|
msgid "Forget this server"
|
||||||
|
msgstr "Забыть этот сервер"
|
||||||
|
|
||||||
msgid "Friends"
|
msgid "Friends"
|
||||||
msgstr "Друзья"
|
msgstr "Друзья"
|
||||||
|
|
||||||
|
|
@ -410,6 +416,9 @@ msgstr "Предпросмотр активен · без трансляции"
|
||||||
msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
msgid "Preview stays local until you start broadcasting. Only members of your voice channel can watch."
|
||||||
msgstr "Предпросмотр остаётся локальным, пока ты не начнёшь трансляцию. Смотреть её могут только участники твоей голосовой комнаты."
|
msgstr "Предпросмотр остаётся локальным, пока ты не начнёшь трансляцию. Смотреть её могут только участники твоей голосовой комнаты."
|
||||||
|
|
||||||
|
msgid "Previously trusted fingerprint"
|
||||||
|
msgstr "Ранее доверенный отпечаток"
|
||||||
|
|
||||||
msgid "Profile and keys"
|
msgid "Profile and keys"
|
||||||
msgstr "Профиль и ключи"
|
msgstr "Профиль и ключи"
|
||||||
|
|
||||||
|
|
@ -425,6 +434,9 @@ msgstr "Нажми и говори"
|
||||||
msgid "Receive updates here, or send signed channel events to your own service."
|
msgid "Receive updates here, or send signed channel events to your own service."
|
||||||
msgstr "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис."
|
msgstr "Получайте обновления в этом канале или отправляйте подписанные события в свой сервис."
|
||||||
|
|
||||||
|
msgid "Received fingerprint"
|
||||||
|
msgstr "Полученный отпечаток"
|
||||||
|
|
||||||
msgid "Reconnect automatically"
|
msgid "Reconnect automatically"
|
||||||
msgstr "Переподключаться при потере связи"
|
msgstr "Переподключаться при потере связи"
|
||||||
|
|
||||||
|
|
@ -497,6 +509,12 @@ msgstr "Отправить"
|
||||||
msgid "Server address"
|
msgid "Server address"
|
||||||
msgstr "Адрес сервера"
|
msgstr "Адрес сервера"
|
||||||
|
|
||||||
|
msgid "Server fingerprint changed"
|
||||||
|
msgstr "Отпечаток сервера изменился"
|
||||||
|
|
||||||
|
msgid "Server identity changed"
|
||||||
|
msgstr "Ключ сервера изменился"
|
||||||
|
|
||||||
msgid "Settings"
|
msgid "Settings"
|
||||||
msgstr "Настройки"
|
msgstr "Настройки"
|
||||||
|
|
||||||
|
|
@ -542,9 +560,15 @@ msgstr "Размер текста"
|
||||||
msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
msgid "The backup passphrase is optional. Without it, your backup contains an unprotected secret key."
|
||||||
msgstr "Пароль резервной копии можно оставить пустым. Такая копия содержит секретный ключ без защиты."
|
msgstr "Пароль резервной копии можно оставить пустым. Такая копия содержит секретный ключ без защиты."
|
||||||
|
|
||||||
|
msgid "The certificate of this server is different from the one you trusted before. This can mean an attack on your connection, or the owner reinstalled the server. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
msgstr "Сертификат этого сервера отличается от того, которому ты доверял раньше. Это может быть атакой на соединение, или владелец переустановил сервер. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение."
|
||||||
|
|
||||||
msgid "The old secret stops working. Update the external integration with the new secret."
|
msgid "The old secret stops working. Update the external integration with the new secret."
|
||||||
msgstr "Старый секрет перестанет работать. Укажите новый секрет во внешней интеграции."
|
msgstr "Старый секрет перестанет работать. Укажите новый секрет во внешней интеграции."
|
||||||
|
|
||||||
|
msgid "The server proved a different identity key than the one you trusted before. The connection was blocked and nothing was sent. Ask the owner whether the change is expected."
|
||||||
|
msgstr "Сервер подтвердил другой ключ, чем тот, которому ты доверял раньше. Соединение заблокировано, ничего не отправлено. Спроси у владельца, ожидаемо ли это изменение."
|
||||||
|
|
||||||
msgid "Theme editor"
|
msgid "Theme editor"
|
||||||
msgstr "Редактор темы"
|
msgstr "Редактор темы"
|
||||||
|
|
||||||
|
|
@ -557,6 +581,15 @@ msgstr "Темы, цвета и текст"
|
||||||
msgid "This cannot be undone."
|
msgid "This cannot be undone."
|
||||||
msgstr "Это действие нельзя отменить."
|
msgstr "Это действие нельзя отменить."
|
||||||
|
|
||||||
|
msgid "This is the first connection to this server. Its certificate is not issued by a public authority, so Vnox cannot verify it automatically. Compare the fingerprint with the one published by the server owner and trust it only if they match."
|
||||||
|
msgstr "Это первое подключение к этому серверу. Его сертификат выдан не публичным центром сертификации, поэтому Vnox не может проверить его автоматически. Сравни отпечаток с тем, что опубликовал владелец сервера, и доверяй, только если они совпадают."
|
||||||
|
|
||||||
|
msgid "Trust and connect"
|
||||||
|
msgstr "Доверять и подключиться"
|
||||||
|
|
||||||
|
msgid "Trust this server?"
|
||||||
|
msgstr "Доверять этому серверу?"
|
||||||
|
|
||||||
msgid "Undeafen"
|
msgid "Undeafen"
|
||||||
msgstr "Включить звук"
|
msgstr "Включить звук"
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue