Compare commits

..

2 commits

Author SHA1 Message Date
f43a69a26f
docs: TLS 1.3 trust model, LNEx v3 and operator guide
Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:05:30 +02:00
0d2af0ddd6
feat(gateway): TLS 1.3 only control plane and LNEx v3 channel-bound handshake
Replace the X25519/HKDF/ChaCha20 TCP layer with rustls TLS 1.3 (ALPN
vnox-lnex/3). Auto-generate a self-signed certificate keyed by the server
identity or load an operator certificate, publish the SPKI fingerprint,
bind HELLO and AUTH signatures to the TLS exporter, reject plaintext, TLS 1.2
and LNEx v2 peers with an explicit error. BREAKING: protocol v3.

Claude-Session: https://claude.ai/code/session_01GDjxLvBcnJqniFQGUGb1V4
2026-10-24 22:05:30 +02:00
57 changed files with 1670 additions and 931 deletions

View file

@ -5,6 +5,14 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
### Changed (breaking): LNEx v3, TLS 1.3 on the TCP control plane
- The custom X25519 + HKDF + ChaCha20-Poly1305 layer on TCP is removed. The gateway listens with TLS 1.3 only (rustls, ALPN `vnox-lnex/3`); there is no plaintext, TLS 1.2 or LNEx v2 mode.
- Protocol version bumped `v2` to `v3`. `Hello.server_eph_pubkey` and `Auth.client_eph_pubkey` are reserved. Old clients cannot connect and old gateways are refused by new clients with an explicit error.
- Ed25519 server HELLO and client AUTH signatures now cover a TLS exporter value (channel binding) and cannot be replayed on another connection.
- Certificate: auto generated on first start in `data_dir/tls/self-signed.pem` using the server identity key (fingerprint stable, no extra secret), or `tls_cert_path` / `tls_key_path` for a CA certificate. The SPKI SHA-256 fingerprint is logged and written to `data_dir/tls/fingerprint.txt`.
- `gateway.tls_enabled = false` is now a startup error. UDP voice is unchanged.
- Design: `docs/02-protocol/tls.md`.
### Added — Phase 2 guild member list + identity export/import + channel rate limit (fourth batch)
#### Phase 2 guild member list with kick / role-assign UI (Phase E4)

View file

@ -20,12 +20,10 @@ tokio = { version = "1.54", features = ["fs", "io-util", "macros", "net", "rt-mu
serde = { version = "1", features = ["derive"] }
serde_json = "1"
ed25519-dalek = { version = "3", features = ["rand_core"] }
x25519-dalek = "3"
chacha20poly1305 = "0.11"
rand = "0.10"
uuid = { version = "1", features = ["v4"] }
hex = "0.4"
hkdf = "0.13"
sha2 = "0.11"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

View file

@ -72,7 +72,7 @@ Full architecture details: [docs/01-architecture.md](docs/01-architecture.md)
### Implemented
- **Auth:** Ed25519 challenge-response, session tokens, reconnect with backoff
- **Encryption:** ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange + HKDF key derivation
- **Encryption:** TLS 1.3 (rustls) on TCP with SPKI pinning, ChaCha20-Poly1305 on UDP voice
- **Channels:** Create, delete, list; text and voice channel types
- **Text chat:** Persistent history via SQLite, reactions, replies, edit, delete, typing indicators, read receipts
- **Direct Messages:** 1:1 DMs with persistent history, unread badges, search
@ -89,7 +89,6 @@ Full architecture details: [docs/01-architecture.md](docs/01-architecture.md)
- **Keyfile export/import:** Encrypted or plain JSON keyfile with passphrase
### Planned
- TLS 1.3 on TCP (Phase 2)
- Protobuf wire format (Phase 2)
- PostgreSQL backend (Phase 2)
- Federation protocol (Phase 3)
@ -107,7 +106,7 @@ Phase 1 is implemented. Not production ready.
| Voice node | UDP relay, voice packet routing, jitter buffer |
| Desktop client | Slint UI, net layer, audio pipeline (partial) |
| LNEx protocol | Specified and implemented (JSON in Phase 1) |
| Encryption | ChaCha20-Poly1305 AEAD + X25519 ECDH — DONE |
| Encryption | TLS 1.3 (TCP) + ChaCha20-Poly1305 (UDP voice) - DONE |
| Federation | Planned (Phase 3) |
| Mobile client | Planned (Phase 3) |

View file

@ -12,6 +12,12 @@ admin_bind = "127.0.0.1:7601"
message_rate_per_sec = 5
# Burst size for the token bucket.
message_rate_burst = 10
# TLS 1.3 is always on (LNEx v3). With neither option below the gateway generates
# a self-signed certificate in <data_dir>/tls/ (key = server identity) and prints its
# SPKI SHA-256 fingerprint at startup. Clients pin it on first use.
# For a public CA certificate (for example Let's Encrypt) set both paths and restart on renewal:
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
[voice]
bind = "127.0.0.1:7700"

View file

@ -43,7 +43,7 @@ You run it, you own it.
**Federated** — nodes can talk to each other. Your community isn't an island (Phase 3).
**Encrypted** — all traffic is encrypted with ChaCha20-Poly1305 AEAD + X25519 ECDH key exchange. Forward secrecy by default.
**Encrypted** - the control plane runs over TLS 1.3, voice over per-route ChaCha20-Poly1305 keys. Forward secrecy by default.
**Plugin-first** — extend the platform with plugins via WebSocket RPC. Bots, moderation, automations. Sandboxed by design.

View file

@ -7,6 +7,12 @@ Last updated: 2026-10-24.
---
## Update 2026-10 (LNEx v3, TLS 1.3)
- TCP control plane is TLS 1.3 only (rustls); the custom X25519/HKDF/ChaCha20 TCP layer was removed (**breaking**, protocol `v3`). See [02-protocol/tls.md](02-protocol/tls.md).
- Self-hosted trust model: certificate pinned by SPKI SHA-256 with trust on first use in the client, changed fingerprint is blocked; public CA certificates work without a prompt.
- Ed25519 auth is bound to the TLS session (exporter), UDP voice unchanged.
## Update 2026-10 (protocol v2)
- Signed v2 handshake and protobuf payloads between client and gateway (verified by `VNOX-Client/tests/gateway_interop.rs`).
@ -74,7 +80,6 @@ Last updated: 2026-10-24.
| Feature | Target phase |
|---------|--------------|
| TLS 1.3 on TCP | Phase 2 |
| Seed phrase / encrypted keyfile export UI | Phase 2 |
| Gateway to voice-node membership signaling | Phase 2 |
| Protobuf payloads (replacing JSON) | Phase 2 |
@ -90,11 +95,11 @@ Last updated: 2026-10-24.
## Security notes
- **TCP control plane:** Encrypted with ChaCha20-Poly1305 (✅ Phase 1.1)
- **TCP control plane:** TLS 1.3 only, channel-bound Ed25519 auth (LNEx v3)
- **UDP voice data:** Encrypted with ChaCha20-Poly1305 (✅ Phase 1.1)
- **Client auth:** Ed25519 challenge-response; identity proven, transport encrypted.
- **Server pubkey:** Real (Ed25519), verified during handshake.
- **Ephemeral keys:** X25519 ECDH with HKDF-SHA256 key derivation for forward secrecy.
- **Forward secrecy on TCP:** provided by TLS 1.3. UDP voice keys are random per route and delivered over TLS.
- **Voice node:** Transparent relay (does not decrypt voice — encrypted end-to-end between clients).
- **Identity at rest:** Optional Argon2id passphrase + ChaCha20-Poly1305 AEAD vault (✅ Phase 2).
- **Rate limiting:** Per-session token bucket on chat + DM (✅ Phase 2).

View file

@ -29,7 +29,7 @@ encryption, routing, identity, and federation.
## Version
Current version: `LNEx v1`
Current version: `LNEx v3` (TCP runs inside TLS 1.3, see [tls.md](tls.md)). There is no negotiation with older versions.
Version is negotiated during handshake. Clients and servers advertise
their supported versions. If no common version exists, the connection
@ -83,3 +83,4 @@ Full state machine: see individual spec files.
- [federation/README.md](federation/README.md) — node discovery, cross-node routing
- [identity.md](identity.md) — keypair model, auth flow, permissions
- [security.md](security.md) — encryption, threat model
- [tls.md](tls.md) — TLS 1.3 control plane, trust model, LNEx v3 handshake

View file

@ -22,7 +22,7 @@ All LNEx packets share a common header, regardless of transport.
```
bit 0 — COMPRESSED payload is zstd compressed
bit 1 — ENCRYPTED payload is encrypted (ChaCha20-Poly1305)
bit 1 — ENCRYPTED reserved; must be 0 on TCP since LNEx v3 (TLS protects the stream)
bit 2 — FRAGMENTED this is a fragment of a larger payload
bit 3 — LAST_FRAG this is the last fragment
bit 4 — ACK_REQ sender requests acknowledgement (TCP path only)

View file

@ -1,6 +1,6 @@
# Security
> **Phase 1.1 status.** TCP traffic is encrypted with ChaCha20-Poly1305 AEAD.
> **LNEx v3 status.** TCP traffic runs over TLS 1.3.
> UDP voice path is still plaintext (Phase 2). See
> [features/encryption.md](../05-features/encryption.md) for details.
@ -11,7 +11,7 @@ The threat model covers:
| Threat | Mitigated by |
|--------|--------------|
| MITM on client-server connection | LNEx packet encryption (ChaCha20-Poly1305) active on TCP |
| MITM on client-server connection | TLS 1.3 with SPKI pinning / public CA, channel-bound Ed25519 auth |
| MITM on UDP voice path | LNEx packet encryption (Phase 2; not active in v0.1.x) |
| Rogue node in federation | Mutual keypair authentication on federation handshake (Phase 3) |
| Identity spoofing | Ed25519 signature on every auth (challenge-response) |
@ -31,47 +31,15 @@ The threat model covers:
## Encryption
> **Phase 1.1 target.** See [features/encryption.md](../05-features/encryption.md) for the implementation plan.
> Phase 1 uses JSON over plain TCP and raw Opus over UDP.
TCP control traffic is protected by **TLS 1.3** (rustls, ALPN `vnox-lnex/3`). The earlier
LNEx v2 per-frame ChaCha20-Poly1305 layer is removed. Trust model, certificate handling,
channel binding and version bump: see [tls.md](tls.md).
### LNEx packet encryption
All LNEx packets (both TCP and UDP paths) are encrypted at the LNEx layer.
Algorithm: **ChaCha20-Poly1305** (AEAD)
- ChaCha20 for stream cipher
- Poly1305 for authentication tag (16 bytes)
- 96-bit nonce, derived from: `session_id || sequence`
- Key derived from ECDH exchange during handshake (X25519)
ChaCha20-Poly1305 is chosen over AES-GCM because:
- constant-time on all platforms (no hardware AES requirement)
- faster in software on hardware without AES-NI (common on ARM)
- simpler nonce management
### Key exchange
During the LNEx handshake:
1. Server sends its ephemeral X25519 public key in HELLO
2. Client generates its own ephemeral X25519 keypair
3. Both compute the shared secret via X25519 ECDH
4. Shared secret is passed through HKDF-SHA256 to derive:
- client → server encryption key
- server → client encryption key
Ephemeral keys are discarded after the session. This provides
**forward secrecy** — compromising the long-term identity keypair
does not expose past sessions.
### TCP transport
TCP connections additionally use TLS 1.3.
LNEx packet encryption runs inside TLS — defense in depth.
TLS certificate: self-signed by default, pinned on first connect (TOFU).
Node operators may configure a proper CA-signed certificate.
- Self-hosted servers: self-signed certificate (key = server identity), client pins the SPKI
SHA-256 fingerprint on first use and blocks any change.
- Public CA certificates are accepted without a prompt.
- Ed25519 client authentication is signed over a TLS exporter value so it cannot be relayed.
- A TLS-terminating reverse proxy is not supported (it breaks the channel binding); use TCP passthrough.
### UDP transport
@ -141,7 +109,7 @@ temporary ban depending on node configuration.
### Recommended hardening
- run gateway behind a reverse proxy (nginx / caddy) for TLS termination
- if a proxy is used, pass TCP through (no TLS termination)
- restrict UDP port to known IP ranges if possible
- enable fail2ban or equivalent on auth failure logs
- back up the node keypair (used for federation identity)

275
docs/02-protocol/tls.md Normal file
View file

@ -0,0 +1,275 @@
# TLS 1.3 for the TCP control plane (LNEx v3)
> Status: design accepted and implemented together with this document.
> This is a **breaking change**: LNEx v2 (custom X25519 + HKDF + ChaCha20-Poly1305
> layer on TCP) is removed. The protocol version is bumped to `v3`.
> UDP voice is **not** affected (see [Voice](#voice-udp-is-unchanged)).
## Goals
1. Replace the home-grown encrypted framing on the TCP control plane with standard
TLS 1.3 ([RFC 8446](https://www.rfc-editor.org/rfc/rfc8446)) implemented by `rustls`
(no OpenSSL).
2. Work for self-hosted servers that have no public CA certificate, without asking
users to click through "accept anything" warnings.
3. Keep the existing Ed25519 identity model: the server identity (`server_identity.json`)
and the client identity keep their meaning.
4. No silent fallback: no plaintext mode, no TLS 1.2, no LNEx v2 handshake.
## Non-goals
- Changing the UDP voice relay or its keys.
- Federation (node to node) TLS. This document covers client to gateway only.
- Mutual TLS with client certificates. The client is authenticated at the LNEx layer
with its Ed25519 key (see [Client authentication](#client-authentication-over-tls)).
## Summary of decisions
| # | Decision |
|---|----------|
| D1 | `rustls` 0.23 with the `aws_lc_rs` provider, **TLS 1.3 only** on both sides. ALPN `vnox-lnex/3` is required. |
| D2 | The server certificate is either user supplied (`tls_cert_path` / `tls_key_path`, for example Let's Encrypt) or **auto generated** on first start and stored in `data_dir/tls/self-signed.pem`. |
| D3 | The auto generated certificate uses the **server identity Ed25519 key as its TLS key**. Therefore the certificate fingerprint is a pure function of the identity key, survives certificate regeneration, and no second private key is stored. |
| D4 | The **pin** is `SHA-256(SubjectPublicKeyInfo DER)` of the leaf certificate (the "SPKI fingerprint"). It is the trust anchor for self-signed servers. |
| D5 | Client trust is **pin first**: stored pin wins over everything. No pin: try normal WebPKI validation (bundled Mozilla roots, hostname must match). If that fails, **TOFU**: the user sees the fingerprint and must confirm before anything is sent. |
| D6 | A changed fingerprint is a **hard block** with a warning. There is no "connect anyway". The only way forward is an explicit "forget this server" followed by a new trust decision. |
| D7 | The Ed25519 client authentication stays, but its signature covers a **TLS exporter value (channel binding)**, so it cannot be relayed over another TLS connection. The server HELLO is signed with its identity key over the same binding. |
| D8 | The X25519 + HKDF + ChaCha20-Poly1305 layer on TCP, the `ENCRYPTED` packet flag on TCP and the ephemeral key fields in `Hello` and `Auth` are removed. |
| D9 | LNEx version is bumped from `v2` to `v3`. Old clients and old servers fail with an explicit error. Downgrade is impossible by construction. |
## Threat model
| Threat | Mitigation |
|--------|-----------|
| Passive network observer | TLS 1.3 (AEAD, forward secrecy). |
| Active MITM terminating TLS with its own certificate | Pin mismatch (known server) or TOFU prompt showing a different fingerprint (new server). Even if the user accepted a wrong fingerprint, the MITM cannot produce the server's Ed25519 signature over this connection's exporter, and the client rejects a server identity that differs from the stored one. |
| MITM relaying the server's HELLO to the client | HELLO signature covers the exporter of the TLS session between the client and the relay, which differs from the relay to server session. Verification fails. |
| Malicious server relaying a client's AUTH to another server | AUTH signature covers the exporter of the connection to the malicious server. Another server computes a different value and rejects it. |
| Downgrade to plaintext, TLS 1.2 or LNEx v2 | The client never opens a plaintext socket, the rustls configs list only TLS 1.3, the server requires ALPN `vnox-lnex/3`, and the version string `v3` is inside the signed transcripts. |
| First connection MITM (TOFU weakness) | Unavoidable without a CA or out of band data. Mitigation: the server prints its fingerprint at startup and writes it to `data_dir/tls/fingerprint.txt`; owners should publish it with the invitation, users compare before confirming. Public CA certificates skip TOFU. |
| Compromised or replaced server key | Fingerprint changes, clients block (D6). |
Out of scope: a compromised server host, a user who ignores a fingerprint mismatch and
explicitly forgets the server.
## Server
### Certificate sources
```toml
[gateway]
bind = "0.0.0.0:7600"
# Optional. Both or none. PEM certificate chain (leaf first) and PKCS#8/SEC1/PKCS#1 key.
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
```
- Neither set: the gateway loads `data_dir/tls/self-signed.pem`. If the file is missing,
unreadable or its public key does not match the server identity, it is regenerated
(it contains no secret, the key is the identity key). SAN entries: `node.address`,
`localhost`, `127.0.0.1`, `::1`. Validity is long (the client does not use expiry for
pinned servers).
- Both set: the chain and key are loaded at start, validated to match, and used as is.
Renewal requires a gateway restart (hot reload is a possible follow-up).
- Only one set: startup error.
- `tls_enabled` is deprecated. `true` is accepted with a warning, `false` is a startup
error: **plaintext is no longer supported**.
At startup the gateway logs `TLS SPKI SHA-256 fingerprint: <hex>` and writes it to
`data_dir/tls/fingerprint.txt` (public information).
### TLS parameters
- Protocol versions: TLS 1.3 only (`rustls::version::TLS13`).
- Cipher suites: the rustls defaults for TLS 1.3 (AES-GCM, ChaCha20-Poly1305).
- ALPN: `vnox-lnex/3`. A connection without the negotiated ALPN is dropped before any
LNEx byte is read.
- No client certificates.
- Handshake timeouts: 15 seconds for the TLS handshake and 15 seconds for the LNEx HELLO/AUTH/SESSION exchange.
### Reverse proxies
The exporter binding (below) is computed per TLS session. A proxy that **terminates**
TLS breaks authentication by design. If a proxy is used it must forward the TCP stream
(`stream`/SNI passthrough, HAProxy `mode tcp`) and must not terminate TLS.
### Legacy and plaintext clients
The server peeks at the first byte of a new connection (up to 2 seconds).
A TLS client sends a handshake record (`0x16`) immediately. Anything else (a v2 client
waits for the server HELLO and sends nothing, a plaintext client sends LNEx bytes)
receives one plaintext LNEx `Error` frame, `ErrorCode::VersionMismatch`, with the message
`TLS 1.3 required (LNEx v3): update your client`, and the connection is closed. This
frame is the only plaintext the gateway ever writes and it contains no secrets.
## Client
### Trust store
File: `<config dir>/vnox/known_servers.json` (Linux: `~/.config/vnox/`), written atomically
with mode `0600` on Unix.
```json
{
"version": 1,
"servers": {
"chat.example.org:7600": {
"trust": "pin",
"spki_sha256": "9f...64 hex chars...",
"identity": "ab...64 hex chars (Ed25519 server key)...",
"first_seen": 1790000000
}
}
}
```
The key is the lower-cased `host:port` (default port 7600). `trust` is `pin` or `ca`.
`spki_sha256` exists only for `pin`. `identity` is stored after the first successful
authenticated handshake.
Bookmarks (the "saved servers" list) are only address labels; trust decisions are
independent of them and keyed by `host:port`, so removing a bookmark does not revoke trust.
### Connection algorithm
```
parse address (scheme lnexs:// or lnex:// is cosmetic, both mean TLS 1.3)
rec = trust_store[host:port]
TLS 1.3 handshake with a custom ServerCertVerifier:
rec.trust == pin : cert SPKI sha256 must equal rec.spki_sha256
else ERROR FingerprintChanged (hard block, D6)
rec.trust == ca : WebPKI chain + hostname validation must succeed
else ERROR CertificateInvalid (hard block, no TOFU downgrade)
no record : WebPKI validation succeeds -> trust = ca
otherwise -> probe: finish the TLS
handshake, send NOTHING, close, and report
UntrustedServer { fingerprint } to the UI
(in every case the TLS 1.3 CertificateVerify signature is verified by rustls)
UI on UntrustedServer: show host, fingerprint (grouped hex), "Trust" / "Cancel".
Trust -> trust_store[host:port] = { pin, fingerprint }, reconnect.
LNEx v3 handshake inside the tunnel (see below)
after a valid server HELLO:
rec.identity set and != server_pubkey -> ERROR IdentityChanged (hard block)
otherwise store identity (TOFU of the identity inside an already trusted channel)
```
Because the probe finishes the TLS handshake without sending application data, the
client's Ed25519 signature and nickname are never sent to an unverified endpoint.
The client uses the bundled Mozilla root set (`webpki-roots`), not the operating system
store, so behaviour is identical on all platforms. Servers with a private CA use the
pin path.
### Fingerprint changes
When a pinned server presents another SPKI the client:
1. aborts the connection before sending any LNEx data,
2. does **not** retry automatically (auto reconnect is suspended for this error),
3. shows a warning with the expected and the received fingerprint,
4. offers "Forget this server". After forgetting, the next connect starts a fresh
TOFU decision. This is deliberate friction: it is the only path for a legitimate
server migration (for example moving from a self-signed certificate to Let's Encrypt
or restoring a server without its `server_identity.json`).
## LNEx v3 handshake inside TLS
The 12 byte packet header and protobuf payloads are unchanged. Frames are written
directly into the TLS stream. The `flags` field must be `0` on the TCP control plane
(the `ENCRYPTED` flag is rejected).
```
Client Gateway
| -- TCP + TLS 1.3 handshake (ALPN) ---> |
| both sides: binding = Export("EXPORTER-VNOX-LNEx-v3-channel-binding", no context, 32)
| <------ HELLO (seq 0) ---------------- | lnex_version="v3", server_pubkey, challenge_nonce,
| | node_name, private_mode, server_signature
| ------- AUTH (seq 0) ----------------> | client_pubkey, nickname, lnex_version="v3", signature
| <------ SESSION (seq 1) -------------- | session_id, token, expires_at
```
Signatures (Ed25519, strict verification):
```
server_signature = Sign(server_key,
"VNOX-LNEx-v3-server-hello\0" || binding || protobuf(Hello with server_signature empty))
client signature = Sign(client_key,
"VNOX-LNEx-v3-client-auth\0" || binding
|| u32be(len(signed_hello)) || signed_hello
|| protobuf(Auth with signature empty))
```
`binding` is unique per TLS session (RFC 8446 section 7.5, RFC 5705), so a signature made on
one connection fails on every other connection. The client signature also covers the
signed HELLO, which carries the server challenge and server key, so the client proves
"I am talking to this server key on this channel".
### What stays from v2
- Ed25519 client identity and challenge-response authentication (now channel bound).
- Server Ed25519 identity and signed HELLO (now channel bound, identity is the stable
anchor that survives certificate changes).
- `Session` packet with `session_id` and `token`.
- Ban check, rate limiting, protobuf payloads, packet ids, packet header, sequence
numbers (kept as a cheap ordering sanity check, no longer part of a nonce).
### What is removed
- `Hello.server_eph_pubkey` (field 5) and `Auth.client_eph_pubkey` (field 5) are reserved
in `lnex.proto`.
- `SessionCrypto` (X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305 per frame) on the gateway and
the client, and the `ENCRYPTED` flag on TCP frames.
- The optional, off by default `tls_enabled` listener that wrapped the old protocol.
- The client's plaintext loopback shortcut and the `lnex://` plaintext scheme.
### Voice (UDP) is unchanged
Voice keys are not derived from the TCP handshake. The gateway creates per route random
`c2s_key` and `s2c_key` and delivers them in the `VoiceSession` packet over the control
connection. Previously they were protected by the LNEx layer, now by TLS 1.3. The UDP
format, nonces and the voice node are untouched. `vnox-e2e-voice` keeps working and only
needs the client to trust the gateway certificate (`--trust-first-use` or `--fingerprint`).
## Version bump and incompatibility behaviour
| Client | Server | Result |
|--------|--------|--------|
| v3 | v3 | works |
| v2 (old) | v3 | server sends a plaintext `Error(VersionMismatch)` "TLS 1.3 required (LNEx v3): update your client"; an old client shows a handshake error or times out. Nothing is negotiated. |
| v3 | v2 (old) | the server answers the TLS ClientHello with LNEx bytes. The client maps the rustls decode failure to "The server does not speak TLS 1.3 (LNEx v3). It is probably an outdated server, ask the owner to update." No retry in plaintext. |
| v3, TLS 1.2 only peer | v3 | handshake failure, protocol version alert, same explicit message. |
| v3 | v3 with `lnex_version` other than `v3` in HELLO/AUTH | `VersionMismatch`, connection closed. |
There is no version negotiation and no compatibility window: the old handshake is not
implemented in the new binaries.
## Operations: enabling it on a server
1. Update the gateway (and `serverd`) to the LNEx v3 build. Remove `tls_enabled = false`
if present.
2. Self-signed: nothing to configure. Start the gateway, read the fingerprint from the
log or `data_dir/tls/fingerprint.txt`, publish it to your users.
CA certificate: set `tls_cert_path` and `tls_key_path`, restart after renewals.
3. Make sure the firewall allows TCP 7600 as before and that no TLS terminating proxy is
in front of it.
4. Update all clients. Old clients cannot connect.
5. Users: on the first connection compare the shown fingerprint with the published one
and press "Trust".
## Test plan
- Fingerprint extraction from a certificate (DER SPKI) and formatting.
- Pin accepted, changed pin rejected, unknown server reported with its fingerprint,
CA-mode failure not downgraded to TOFU.
- A TLS 1.2 only client is rejected by the gateway listener.
- A client without ALPN is rejected.
- A plaintext or v2 client receives the explicit version error.
- A client signature made for connection A is rejected on connection B.
- A server HELLO signature made for connection A is rejected by a client on connection B.
- Full interoperability test `tests/gateway_interop.rs` against the real gateway binary,
including the TOFU prompt flow.
- `vnox-e2e-voice` against `vnox-serverd` still relays voice.

View file

@ -76,10 +76,11 @@ max_pps_per_user = 60
# Generated automatically on first start if not present.
keypair_path = "/var/lib/vnox/node.key"
# TLS certificate for the TCP gateway.
# If not set, a self-signed certificate is generated.
# tls_cert = "/etc/vnox/tls/cert.pem"
# tls_key = "/etc/vnox/tls/key.pem"
# TLS 1.3 is always on (LNEx v3). TLS keys live in the [gateway] section:
# tls_cert_path = "/etc/letsencrypt/live/chat.example.org/fullchain.pem"
# tls_key_path = "/etc/letsencrypt/live/chat.example.org/privkey.pem"
# Both unset: a self-signed certificate is generated in <data_dir>/tls/ and its
# fingerprint is logged. See docs/02-protocol/tls.md.
# ─── CHANNELS ──────────────────────────────────────────────────────────────

View file

@ -214,5 +214,5 @@ with a migration guide.
- [ ] `node.key` backup exists and is stored securely
- [ ] `VNOX_LOGGING_LEVEL` is `info` or `warn` in production (not `trace`)
- [ ] `[gateway.rate_limits]` are configured appropriately for your user base
- [ ] TLS certificate is valid (or TOFU is acceptable for your use case)
- [ ] TLS: either a CA certificate (`tls_cert_path`/`tls_key_path`) or the self-signed fingerprint (`data_dir/tls/fingerprint.txt`) is published to users; no TLS-terminating proxy in front of TCP 7600
- [ ] Federation disabled if not needed (`[federation] enabled = false`)

View file

@ -1,78 +1,44 @@
# Encryption — Phase 1.1
# Encryption
> **Phase 1.1 status:** Fully implemented. ChaCha20-Poly1305 AEAD with X25519 ECDH + HKDF-SHA256 key exchange. Both TCP (control) and UDP (voice) paths are now encrypted. Forward secrecy via ephemeral session keys.
> **Status (LNEx v3):** the TCP control plane is protected by **TLS 1.3** (rustls).
> The UDP voice path is protected by per route ChaCha20-Poly1305 keys delivered over the
> TLS control connection. The earlier custom X25519 + HKDF + ChaCha20-Poly1305 layer on
> TCP (LNEx v2) was removed. Design and trust model: [02-protocol/tls.md](../02-protocol/tls.md).
## Goal
## Layers
Replace all plaintext traffic (TCP + UDP) with ChaCha20-Poly1305 AEAD encryption.
X25519 ECDH ephemeral key exchange during handshake for forward secrecy.
| Path | Protection | Keys |
|------|------------|------|
| TCP control (chat, channels, auth) | TLS 1.3, ALPN `vnox-lnex/3`, no fallback | TLS handshake, server cert pinned by SPKI SHA-256 (TOFU) or a public CA |
| Server authenticity | Ed25519 server identity signs HELLO over the TLS exporter (channel binding) | `server_identity.json` |
| Client authenticity | Ed25519 client key signs AUTH over the same exporter | client identity |
| UDP voice | ChaCha20-Poly1305 AEAD per route | random `c2s_key` / `s2c_key` sent in `VoiceSession` over TLS |
| Direct messages E2EE (optional) | X25519 + HKDF + ChaCha20-Poly1305 between clients | per conversation keys, unchanged |
✅ **COMPLETED in Phase 1.1**
## What changed from v2
## Key exchange (during HELLO handshake)
- Removed: ephemeral X25519 exchange in HELLO/AUTH, HKDF session key derivation for TCP,
per frame ChaCha20-Poly1305 with the `ENCRYPTED` flag, `SessionCrypto` in gateway and client.
- Added: mandatory TLS 1.3 listener and connector, certificate management, client trust store,
channel bound Ed25519 signatures.
- Unchanged: UDP voice packet format, voice node, E2EE for direct messages, Ed25519 identities.
1. Server generates ephemeral X25519 keypair per session
2. Server sends public key in `HELLO` packet
3. Client generates own ephemeral X25519 keypair
4. Both compute shared secret via X25519 ECDH
5. Shared secret → HKDF-SHA256 → two keys:
- `client→server` encryption key
- `server→client` encryption key
6. Ephemeral keys discarded after session (forward secrecy)
## Why TLS instead of a custom layer
## Packet encryption
- Reviewed, widely deployed handshake and record layer instead of a protocol we maintain.
- Standard tooling and key lifecycle (Let's Encrypt works out of the box).
- Forward secrecy, key updates and replay protection are provided by TLS 1.3.
- Algorithm: **ChaCha20-Poly1305** (AEAD)
- 96-bit nonce: `session_id || packet_sequence`
- 16-byte Poly1305 authentication tag per packet
- Applied to ALL packets on both TCP and UDP
## Voice keys
## Why ChaCha20-Poly1305 over AES-GCM
- Constant-time on all platforms (no hardware AES requirement)
- Faster in software on ARM (common for mobile — Phase 3)
- Simpler nonce management (no IV collision risk)
## Implementation plan
### ✅ Client (DONE)
- `client/src/net/crypto.rs` — SessionCrypto with ChaCha20-Poly1305
- `client/src/net/voice.rs` — `build_packet()` encrypts voice payloads with c2s_key
- `client/src/net/voice.rs` — `spawn_recv()` decrypts incoming voice with s2c_key
- `client/src/net/session/session_loop.rs` — voice_seq counter for encryption nonces
### ✅ Gateway (DONE)
- `gateway/src/proto/crypto.rs` — X25519 ECDH, HKDF-SHA256, ChaCha20-Poly1305
- `gateway/src/net/handshake.rs` — ephemeral key exchange in HELLO/AUTH
- `gateway/src/net/io.rs` — TCP framing with encryption
### ✅ Voice
- `client/src/net/voice.rs` — encrypted voice packets on UDP (plaintext at rest in voice-node, encrypted on wire)
- Voice-node treats packets as opaque bytes (transparent relay)
- End-to-end encryption: client A → encrypted → voice-node → encrypted → client B
## Nonce management
Each session has a monotonic sequence counter:
- Start at 0 on session establishment
- Increment per packet (both directions independently)
- Nonce = `session_id (8 bytes) || sequence (4 bytes)`
- 12-byte nonce fits ChaCha20-Poly1305 standard
## Key dependencies
Already in `Cargo.toml` (workspace):
- `chacha20poly1305 = "0.10"`
- `x25519-dalek = { version = "2", features = ["static_secrets"] }`
Need to add:
- `hkdf = "0.12"` for key derivation
- `sha2 = "0.10"` (HKDF dependency, likely already transitive)
`VoiceSession` is delivered after the channel authorization check. Keys are random per
route and never derived from the TCP session, so the UDP implementation did not need to
change when the TCP layer was replaced.
## Testing
- ✅ Unit test: encrypt → decrypt round-trip with known keys (`client/src/net/crypto.rs`)
- ✅ Unit test: tampered ciphertext fails authentication
- ✅ Unit test: build_packet creates valid encrypted packets
- Manual test: Run client + gateway + voice-node, join voice channel, verify packets encrypted
- Wireshark: Capture UDP traffic, confirm it's not readable plaintext
- Unit: SPKI fingerprint extraction, pin match and mismatch, unknown server, TLS 1.2 client
rejected, plaintext/v2 client gets an explicit error, channel binding signature replay rejected.
- Integration: `VNOX_GATEWAY_BIN=... cargo test --test gateway_interop -- --ignored`
in `VNOX-Client`, including the first trust flow.
- Voice: `cargo run --bin vnox-e2e-voice -- 127.0.0.1:7600 --trust-first-use` against `vnox-serverd`.

View file

@ -36,7 +36,7 @@ Goal: production-safe for small private communities.
### Encryption (Priority 1) ✅ DONE
- [x] Replace plaintext with ChaCha20-Poly1305 on all packets
- [x] X25519 ECDH key exchange during HELLO handshake
- [x] X25519 ECDH key exchange during HELLO handshake (UDP/E2EE only; TCP moved to TLS 1.3 in LNEx v3)
- [x] HKDF-SHA256 key derivation (client→server / server→client keys)
- [x] Encrypted TCP (control) + UDP (voice) paths
- [x] Forward secrecy via ephemeral session keys
@ -152,7 +152,7 @@ Goal: typing indicators, read receipts, typing states.
Goal: scalability, federation preparation, advanced security.
### Server
- [ ] TLS 1.3 on TCP control plane
- [x] TLS 1.3 on TCP control plane (LNEx v3, see 02-protocol/tls.md)
- [ ] Permission system enforcement in gateway
- [ ] Rate limiting refinement
- [ ] PostgreSQL backend (sqlx support ready, config not exposed yet)

View file

@ -21,9 +21,7 @@ tokio.workspace = true
serde.workspace = true
serde_json.workspace = true
ed25519-dalek.workspace = true
x25519-dalek.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
tracing.workspace = true
@ -50,3 +48,7 @@ url = "2"
[build-dependencies]
prost-build = "0.14"
[dev-dependencies]
# Test clients: a TLS 1.2 only client needs the `tls12` feature of rustls.
rustls = { version = "0.23", features = ["tls12"] }

View file

@ -19,6 +19,11 @@ impl ServerIdentity {
use ed25519_dalek::Signer;
self.signing_key.sign(message).to_bytes().to_vec()
}
/// Ed25519 seed. Only used to derive the TLS key of the auto generated certificate
/// (see `crate::tls`), so the certificate fingerprint is a function of the identity.
pub(crate) fn signing_seed(&self) -> [u8; 32] {
self.signing_key.to_bytes()
}
pub fn pubkey_hex(&self) -> String {
hex::encode(self.signing_key.verifying_key().to_bytes())
}

View file

@ -90,17 +90,34 @@ pub struct GatewayConfig {
/// Defaults to 10.
#[serde(default)]
pub message_rate_burst: Option<u32>,
/// Enable TLS 1.3 on the TCP listener.
/// Deprecated. TLS 1.3 is always on since LNEx v3. `true` is accepted with a warning,
/// `false` is a startup error because plaintext is no longer supported.
#[serde(default)]
pub tls_enabled: bool,
/// Path to TLS certificate file (PEM).
pub tls_enabled: Option<bool>,
/// Path to the TLS certificate chain (PEM, leaf first). Set together with `tls_key_path`.
/// When both are unset a self-signed certificate is generated in `data_dir/tls/`.
#[serde(default)]
pub tls_cert_path: Option<String>,
/// Path to TLS private key file (PEM).
/// Path to the TLS private key (PEM).
#[serde(default)]
pub tls_key_path: Option<String>,
}
impl GatewayConfig {
/// Reject configurations that would weaken or break the mandatory TLS 1.3 listener.
pub fn validate_tls(&self) -> Result<()> {
if self.tls_enabled == Some(false) {
anyhow::bail!(
"gateway.tls_enabled = false is no longer supported: LNEx v3 requires TLS 1.3; remove the option"
);
}
if self.tls_cert_path.is_some() != self.tls_key_path.is_some() {
anyhow::bail!("gateway.tls_cert_path and gateway.tls_key_path must be set together");
}
Ok(())
}
}
#[derive(Debug, Deserialize)]
pub struct VoiceConfig {
pub bind: String,
@ -125,3 +142,33 @@ pub fn load() -> Result<Config> {
toml::from_str(&text).map_err(|e| anyhow::anyhow!("invalid config: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn gateway(extra: &str) -> GatewayConfig {
toml::from_str(&format!("bind = \"127.0.0.1:0\"\n{extra}")).unwrap()
}
#[test]
fn tls_defaults_to_generated_certificate() {
gateway("").validate_tls().unwrap();
}
#[test]
fn plaintext_opt_out_is_a_startup_error() {
let error = gateway("tls_enabled = false").validate_tls().unwrap_err();
assert!(error.to_string().contains("TLS 1.3"));
gateway("tls_enabled = true").validate_tls().unwrap();
}
#[test]
fn certificate_and_key_must_be_configured_together() {
assert!(gateway("tls_cert_path = \"c.pem\"").validate_tls().is_err());
assert!(gateway("tls_key_path = \"k.pem\"").validate_tls().is_err());
gateway("tls_cert_path = \"c.pem\"\ntls_key_path = \"k.pem\"")
.validate_tls()
.unwrap();
}
}

View file

@ -8,7 +8,7 @@ use crate::{
net::{io, state::State},
proto::{
ChannelCreatePayload, ChannelDeletePayload, ChannelListItem, ChannelListPayload,
ChannelStatePayload, PacketId, SessionCrypto, encode_packet, to_payload,
ChannelStatePayload, PacketId, encode_packet, to_payload,
},
};
@ -19,7 +19,6 @@ pub async fn handle_channel_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelCreatePayload::decode(payload)?;
@ -37,7 +36,7 @@ pub async fn handle_channel_create(
"channel_create from {}: invalid kind '{other}'",
sess.nickname
);
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -45,7 +44,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: format!("invalid channel kind: {other}"),
}),
crypto,
)
.await?;
return Ok(());
@ -65,7 +63,7 @@ pub async fn handle_channel_create(
|| channel_id.chars().any(char::is_control)
|| channel_name.chars().any(char::is_control)
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -73,7 +71,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: "channel_id is required".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -84,7 +81,7 @@ pub async fn handle_channel_create(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited channel_create from {}", sess.nickname);
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -92,7 +89,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::RateLimited as u32,
message: "slow down — too many channel operations".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -101,7 +97,7 @@ pub async fn handle_channel_create(
let access = state.access.write().await;
if !super::may_manage(state, &sess.user_id, req.guild_id.as_deref()).await? {
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
@ -133,7 +129,7 @@ pub async fn handle_channel_create(
drop(access);
if !created {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -141,7 +137,6 @@ pub async fn handle_channel_create(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel already exists".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -164,14 +159,7 @@ pub async fn handle_channel_create(
voice_endpoint: state.config.voice.bind.clone(),
guild_id: req.guild_id.clone(),
};
io::send_encrypted(
stream,
PacketId::ChannelState,
seq,
&to_payload(&sp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&sp)).await?;
super::notify_guild(
state,
@ -200,7 +188,6 @@ pub async fn handle_channel_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelDeletePayload::decode(payload)?;
@ -211,7 +198,7 @@ pub async fn handle_channel_delete(
// Protect default channels from deletion.
if req.channel_id == "general" || req.channel_id == "voice" {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -219,7 +206,6 @@ pub async fn handle_channel_delete(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "cannot delete default channels".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -235,7 +221,7 @@ pub async fn handle_channel_delete(
.await?
{
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
state.storage.delete_channel(&req.channel_id).await?;
@ -244,7 +230,7 @@ pub async fn handle_channel_delete(
drop(access);
if !existed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -252,7 +238,6 @@ pub async fn handle_channel_delete(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel not found".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -288,7 +273,6 @@ pub async fn handle_channel_list(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let Some(sess) = session::get(&state.sessions, session_id).await else {
@ -329,6 +313,6 @@ pub async fn handle_channel_list(
channels: items,
guild_id: None,
};
io::send_encrypted(stream, PacketId::ChannelList, seq, &to_payload(&p), crypto).await?;
io::send_frame(stream, PacketId::ChannelList, seq, &to_payload(&p)).await?;
Ok(())
}

View file

@ -6,7 +6,7 @@ use tracing::info;
use crate::{
domain::{channels, session},
net::{io, state::State},
proto::{ChannelEditPayload, PacketId, SessionCrypto, encode_packet, to_payload},
proto::{ChannelEditPayload, PacketId, encode_packet, to_payload},
};
pub async fn handle_channel_edit(
@ -14,7 +14,6 @@ pub async fn handle_channel_edit(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = ChannelEditPayload::decode(payload)?;
@ -32,7 +31,7 @@ pub async fn handle_channel_edit(
|| channel_name.chars().count() > 100
|| channel_name.chars().any(char::is_control)
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -40,7 +39,6 @@ pub async fn handle_channel_edit(
code: crate::proto::ErrorCode::InvalidPacket as u32,
message: "channel_id and channel_name are required".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -56,7 +54,7 @@ pub async fn handle_channel_edit(
.await?
{
drop(access);
super::denied(stream, seq, crypto).await?;
super::denied(stream, seq).await?;
return Ok(());
}
state
@ -67,7 +65,7 @@ pub async fn handle_channel_edit(
drop(access);
if !renamed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -75,7 +73,6 @@ pub async fn handle_channel_edit(
code: crate::proto::ErrorCode::ChannelNotFound as u32,
message: "channel not found".into(),
}),
crypto,
)
.await?;
return Ok(());

View file

@ -6,8 +6,8 @@ use crate::{
state::{BroadcastMsg, State},
},
proto::{
self, ChannelStatePayload, ChatHistoryPayload, MemberInfo, PacketId, SessionCrypto,
UserJoinPayload, encode_packet, to_payload,
self, ChannelStatePayload, ChatHistoryPayload, MemberInfo, PacketId, UserJoinPayload,
encode_packet, to_payload,
},
};
use anyhow::Result;
@ -20,7 +20,6 @@ pub async fn join(
seq: &mut u32,
session_id: &str,
channel_id: &str,
crypto: &SessionCrypto,
state: &State,
_addr: SocketAddr,
) -> Result<()> {
@ -30,7 +29,7 @@ pub async fn join(
};
let Some(ch) = channels::get_channel(&state.channels, channel_id).await else {
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -38,7 +37,6 @@ pub async fn join(
code: proto::ErrorCode::ChannelNotFound as u32,
message: "not found".into(),
}),
crypto,
)
.await;
};
@ -51,7 +49,7 @@ pub async fn join(
.any(|g| g.id == *guild)
{
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -59,14 +57,13 @@ pub async fn join(
code: proto::ErrorCode::PermissionDenied as u32,
message: "guild membership required".into(),
}),
crypto,
)
.await;
}
let is_voice = ch.kind == channels::ChannelKind::Voice;
if is_voice && state.voice_member_tx.is_none() {
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -74,7 +71,6 @@ pub async fn join(
code: proto::ErrorCode::NodeUnavailable as u32,
message: "voice requires the combined server process".into(),
}),
crypto,
)
.await;
}
@ -93,7 +89,7 @@ pub async fn join(
.has(crate::domain::permissions::Permissions::VOICE_SPEAK)
{
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -101,7 +97,6 @@ pub async fn join(
code: proto::ErrorCode::PermissionDenied as u32,
message: "VOICE_SPEAK permission required".into(),
}),
crypto,
)
.await;
}
@ -149,7 +144,7 @@ pub async fn join(
channels::leave(&state.channels, channel_id, session_id).await;
set_voice_channel(state, session_id, None).await;
drop(guard);
return io::send_encrypted(
return io::send_frame(
stream,
PacketId::Error,
seq,
@ -157,7 +152,6 @@ pub async fn join(
code: proto::ErrorCode::NodeUnavailable as u32,
message: "voice service unavailable".into(),
}),
crypto,
)
.await;
}
@ -203,21 +197,13 @@ pub async fn join(
voice_endpoint: state.config.voice.bind.clone(),
guild_id: ch.guild_id,
};
io::send_encrypted(
stream,
PacketId::ChannelState,
seq,
&to_payload(&payload),
crypto,
)
.await?;
io::send_frame(stream, PacketId::ChannelState, seq, &to_payload(&payload)).await?;
if let Some(credentials) = credentials {
io::send_encrypted(
io::send_frame(
stream,
PacketId::VoiceSession,
seq,
&to_payload(&credentials),
crypto,
)
.await?;
}

View file

@ -38,7 +38,6 @@ async fn attempt_join(state: &State, session_id: &str, channel_id: &str) {
&mut 0,
session_id,
channel_id,
&SessionCrypto::derive(&[7; 32], session_id),
state,
"127.0.0.1:12345".parse().unwrap(),
)
@ -169,29 +168,15 @@ async fn text_navigation_preserves_voice_and_leaving_unrelated_channel_is_noop()
.contains(&sid)
);
let (mut stream, _) = tokio::io::duplex(65536);
super::super::leave(
&mut stream,
&mut 0,
&sid,
"general",
&SessionCrypto::derive(&[7; 32], &sid),
&state,
)
.await
.unwrap();
super::super::leave(&mut stream, &mut 0, &sid, "general", &state)
.await
.unwrap();
let sess = session::get(&state.sessions, &sid).await.unwrap();
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
assert_eq!(sess.voice_channel_id.as_deref(), Some("voice"));
super::super::leave(
&mut stream,
&mut 0,
&sid,
"voice",
&SessionCrypto::derive(&[7; 32], &sid),
&state,
)
.await
.unwrap();
super::super::leave(&mut stream, &mut 0, &sid, "voice", &state)
.await
.unwrap();
let sess = session::get(&state.sessions, &sid).await.unwrap();
assert_eq!(sess.channel_id.as_deref(), Some("other-text"));
assert_eq!(sess.voice_channel_id, None);
@ -220,7 +205,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
.await
.unwrap();
let (mut stream, _peer) = tokio::io::duplex(65536);
let crypto = SessionCrypto::derive(&[7; 32], &sid);
crate::handler::channel::handle_channel_edit(
&mut stream,
&mut 0,
@ -229,7 +213,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
channel_id: "managed".into(),
channel_name: "stolen".into(),
}),
&crypto,
&state,
)
.await
@ -248,7 +231,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
&to_payload(&ChannelDeletePayload {
channel_id: "managed".into(),
}),
&crypto,
&state,
)
.await
@ -275,7 +257,6 @@ async fn channel_mutations_require_guild_authority_and_deletion_revokes_voice_cr
&to_payload(&ChannelDeletePayload {
channel_id: "managed".into(),
}),
&crypto,
&state,
)
.await
@ -324,7 +305,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
.await
.unwrap();
let (mut stream, _peer) = tokio::io::duplex(65536);
let crypto = SessionCrypto::derive(&[7; 32], &sid);
crate::handler::guild::handle_role_assign(
&mut stream,
&mut 0,
@ -334,7 +314,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
user_id: "visitor".into(),
role_id: foreign.clone(),
}),
&crypto,
&state,
)
.await
@ -347,7 +326,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
guild_id: guild.clone(),
role_id: foreign.clone(),
}),
&crypto,
&state,
)
.await
@ -407,7 +385,6 @@ async fn guild_role_handlers_reject_cross_guild_targets_and_privilege_escalation
user_id: "visitor".into(),
role_id: powerful,
}),
&crypto,
&state,
)
.await
@ -476,7 +453,6 @@ async fn removing_voice_role_revokes_existing_udp_membership() {
user_id: "visitor".into(),
role_id: role,
}),
&SessionCrypto::derive(&[7; 32], &owner.session_id),
&state,
)
.await
@ -515,7 +491,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
let member = session::create(&state.sessions, "member".into(), "Member".into()).await;
let outsider = session::create(&state.sessions, "outsider".into(), "Outsider".into()).await;
let mut events = state.broadcast.subscribe();
let crypto = SessionCrypto::derive(&[7; 32], &owner_sid);
let (mut stream, _peer) = tokio::io::duplex(65536);
let creation = ChannelCreatePayload {
channel_id: "private-notification".into(),
@ -528,7 +503,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
&mut 0,
&owner_sid,
&to_payload(&creation),
&crypto,
&state,
)
.await
@ -541,7 +515,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
channel_id: creation.channel_id.clone(),
channel_name: "Renamed privately".into(),
}),
&crypto,
&state,
)
.await
@ -553,7 +526,6 @@ async fn private_channel_notifications_target_members_and_acknowledge_editor() {
&to_payload(&ChannelDeletePayload {
channel_id: creation.channel_id.clone(),
}),
&crypto,
&state,
)
.await
@ -607,7 +579,6 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
use std::time::Duration;
use tokio::io::AsyncReadExt;
let (state, sid) = fixture().await;
let crypto = SessionCrypto::derive(&[7; 32], &sid);
let history = |channel: &str| BroadcastMsg {
channel_id: Some(channel.into()),
exclude_session: None,
@ -624,12 +595,11 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
// The same queued target/channel envelope is deliverable while subscribed.
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 2;
crate::handler::deliver::deliver_encrypted(
crate::handler::deliver::deliver_frame(
&mut stream,
&mut seq,
&sid,
&history("general"),
&crypto,
&state,
)
.await
@ -642,16 +612,15 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
);
assert_eq!(seq, 3);
super::super::leave(&mut stream, &mut seq, &sid, "general", &crypto, &state)
super::super::leave(&mut stream, &mut seq, &sid, "general", &state)
.await
.unwrap();
let (mut stream, mut peer) = tokio::io::duplex(65536);
crate::handler::deliver::deliver_encrypted(
crate::handler::deliver::deliver_frame(
&mut stream,
&mut seq,
&sid,
&history("general"),
&crypto,
&state,
)
.await
@ -696,16 +665,9 @@ async fn queued_targeted_history_is_rechecked_after_leave_or_guild_revoke() {
super::super::revoke_guild_access(&state, &guild, Some("visitor")).await;
}
let (mut stream, mut peer) = tokio::io::duplex(65536);
crate::handler::deliver::deliver_encrypted(
&mut stream,
&mut seq,
&sid,
&queued,
&crypto,
&state,
)
.await
.unwrap();
crate::handler::deliver::deliver_frame(&mut stream, &mut seq, &sid, &queued, &state)
.await
.unwrap();
assert_eq!(seq, 3);
assert!(
tokio::time::timeout(Duration::from_millis(15), peer.read_u8())

View file

@ -5,7 +5,6 @@ use tracing::info;
use crate::{
domain::{channels, session},
net::state::State,
proto::SessionCrypto,
};
use super::{broadcast_leave, set_channel, set_voice_channel};
@ -15,7 +14,6 @@ pub async fn leave(
_seq: &mut u32,
session_id: &str,
channel_id: &str,
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let Some(sess) = session::get(&state.sessions, session_id).await else {

View file

@ -117,9 +117,8 @@ pub(super) async fn may_manage(
pub(super) async fn denied(
stream: &mut (impl tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin),
seq: &mut u32,
crypto: &crate::proto::SessionCrypto,
) -> anyhow::Result<()> {
crate::net::io::send_encrypted(
crate::net::io::send_frame(
stream,
PacketId::Error,
seq,
@ -127,7 +126,6 @@ pub(super) async fn denied(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "guild MANAGE_CHANNELS permission required".into(),
}),
crypto,
)
.await
}

View file

@ -10,7 +10,7 @@ use crate::{
},
proto::{
PacketId, PresenceEventPayload, PresenceInfo, PresenceSyncPayload, PresenceUpdatePayload,
SessionCrypto, encode_packet, to_payload,
encode_packet, to_payload,
},
};
@ -33,7 +33,6 @@ pub async fn handle_presence_update(
seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = PresenceUpdatePayload::decode(payload)?;
@ -99,7 +98,6 @@ pub async fn handle_presence_sync(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let _sess = session::get(&state.sessions, session_id)
@ -108,12 +106,11 @@ pub async fn handle_presence_sync(
let presences: Vec<PresenceInfo> = state.presences.read().await.values().cloned().collect();
io::send_encrypted(
io::send_frame(
stream,
PacketId::PresenceSync,
seq,
&to_payload(&PresenceSyncPayload { presences }),
crypto,
)
.await?;
Ok(())

View file

@ -12,7 +12,6 @@ pub async fn handle_read_receipt(
seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &crate::proto::SessionCrypto,
state: &State,
) -> Result<()> {
let req = ReadReceiptPayload::decode(payload)?;

View file

@ -4,15 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::BroadcastMsg, state::State},
proto::SessionCrypto,
};
pub async fn deliver_encrypted(
pub async fn deliver_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
msg: &BroadcastMsg,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
if msg.exclude_session.as_deref() == Some(session_id)
@ -69,5 +67,5 @@ pub async fn deliver_encrypted(
}
drop(access);
}
io::deliver_encrypted(stream, crypto, seq, &msg.data).await
io::deliver_frame(stream, seq, &msg.data).await
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{DmHistoryPayload, PacketId, SessionCrypto, to_payload},
proto::{DmHistoryPayload, PacketId, to_payload},
};
pub async fn handle_dm_history(
@ -13,7 +13,6 @@ pub async fn handle_dm_history(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = DmHistoryPayload::decode(payload)?;
@ -42,6 +41,6 @@ pub async fn handle_dm_history(
search_query: None,
limit: None,
};
io::send_encrypted(stream, PacketId::DmHistory, seq, &to_payload(&resp), crypto).await?;
io::send_frame(stream, PacketId::DmHistory, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -9,9 +9,7 @@ use crate::{
io,
state::{BroadcastMsg, State},
},
proto::{
self, DmMessagePayload, ErrorCode, PacketId, SessionCrypto, encode_packet, to_payload,
},
proto::{self, DmMessagePayload, ErrorCode, PacketId, encode_packet, to_payload},
};
pub async fn handle_dm_message(
@ -19,7 +17,6 @@ pub async fn handle_dm_message(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = DmMessagePayload::decode(payload)?;
@ -34,7 +31,7 @@ pub async fn handle_dm_message(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited DM session {session_id}");
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -42,7 +39,6 @@ pub async fn handle_dm_message(
code: ErrorCode::RateLimited as u32,
message: "you are sending messages too quickly".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -54,7 +50,7 @@ pub async fn handle_dm_message(
.await?
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -62,7 +58,6 @@ pub async fn handle_dm_message(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -102,13 +97,6 @@ pub async fn handle_dm_message(
warn!("dm recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
stream,
PacketId::DmMessage,
seq,
&to_payload(&saved),
crypto,
)
.await?;
io::send_frame(stream, PacketId::DmMessage, seq, &to_payload(&saved)).await?;
Ok(())
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{self, DmStartPayload, DmStartResponsePayload, PacketId, SessionCrypto, to_payload},
proto::{self, DmStartPayload, DmStartResponsePayload, PacketId, to_payload},
};
pub async fn handle_dm_start(
@ -13,7 +13,6 @@ pub async fn handle_dm_start(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = DmStartPayload::decode(payload)?;
@ -29,7 +28,7 @@ pub async fn handle_dm_start(
.is_blocked(&req.target_user_id, &my_id)
.await?
{
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -37,14 +36,13 @@ pub async fn handle_dm_start(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
}
if req.target_user_id == my_id {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -52,7 +50,6 @@ pub async fn handle_dm_start(
code: proto::ErrorCode::InvalidPacket as u32,
message: "cannot DM yourself".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -84,7 +81,7 @@ pub async fn handle_dm_start(
messages,
unread_count: unread_count as u32,
};
io::send_encrypted(stream, PacketId::DmStart, seq, &to_payload(&resp), crypto).await?;
io::send_frame(stream, PacketId::DmStart, seq, &to_payload(&resp)).await?;
Ok(())
}
@ -93,7 +90,6 @@ pub async fn handle_dm_read_ack(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = crate::proto::DmReadAckPayload::decode(payload)?;
@ -106,6 +102,6 @@ pub async fn handle_dm_read_ack(
state.storage.reset_dm_unread(&req.dm_id, &my_id).await?;
io::send_encrypted(stream, PacketId::DmReadAck, seq, b"{}", crypto).await?;
io::send_frame(stream, PacketId::DmReadAck, seq, b"{}").await?;
Ok(())
}

View file

@ -30,14 +30,13 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
}
PacketId::Ping => {
let ping = PingPayload::decode(payload)?;
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::Pong,
ctx.seq,
&to_payload(&PongPayload {
timestamp: ping.timestamp,
}),
ctx.crypto,
)
.await?;
}
@ -48,7 +47,6 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
ctx.seq,
session_id,
&m.channel_id,
ctx.crypto,
ctx.state,
addr,
)
@ -56,217 +54,140 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
}
PacketId::LeaveChannel => {
let m = LeaveChannelPayload::decode(payload)?;
channel::leave(
ctx.stream,
ctx.seq,
session_id,
&m.channel_id,
ctx.crypto,
ctx.state,
)
.await?;
channel::leave(ctx.stream, ctx.seq, session_id, &m.channel_id, ctx.state).await?;
}
PacketId::ChannelCreate => {
channel::handle_channel_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_create(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelDelete => {
channel::handle_channel_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelEdit => {
channel::handle_channel_edit(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_edit(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChannelList => {
channel::handle_channel_list(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
channel::handle_channel_list(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::ChatMessage => {
let m = ChatMessagePayload::decode(payload)?;
content::chat::handle(session_id, m, ctx.state).await?;
}
PacketId::DmStart => {
direct_message::handle_dm_start(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmMessage => {
direct_message::handle_dm_message(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmHistory => {
direct_message::handle_dm_history(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::DmReadAck => {
direct_message::handle_dm_read_ack(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildCreate => {
guild::handle_guild_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildDelete => {
guild::handle_guild_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}
PacketId::GuildList => {
guild::handle_guild_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
direct_message::handle_dm_start(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmMessage => {
direct_message::handle_dm_message(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmHistory => {
direct_message::handle_dm_history(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::DmReadAck => {
direct_message::handle_dm_read_ack(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildCreate => {
guild::handle_guild_create(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildDelete => {
guild::handle_guild_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildList => {
guild::handle_guild_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::GuildMemberJoin => {
guild::handle_guild_member_join(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_join(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberLeave => {
guild::handle_guild_member_leave(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_leave(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberKick => {
guild::handle_guild_member_kick(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_guild_member_kick(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::RoleCreate => {
guild::handle_role_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_create(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::RoleDelete => {
guild::handle_role_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::InviteCreate => {
guild::handle_invite_create(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_create(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::InviteAccept => {
guild::handle_invite_accept(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_accept(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::InviteDelete => {
guild::handle_invite_delete(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_invite_delete(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildAuditLogFetch => {
guild::handle_audit_log_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_audit_log_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildMemberListFetch => {
guild::handle_member_list_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_member_list_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildRoleAssign => {
guild::handle_role_assign(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_assign(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::GuildRoleUnassign => {
guild::handle_role_unassign(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_unassign(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::GuildRoleListFetch => {
guild::handle_role_list_fetch(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
guild::handle_role_list_fetch(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::PresenceUpdate => {
content::presence::handle_presence_update(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
ctx.stream, ctx.seq, session_id, payload, ctx.state,
)
.await?;
}
PacketId::PresenceSync => {
content::presence::handle_presence_sync(
ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state,
)
.await?;
content::presence::handle_presence_sync(ctx.stream, ctx.seq, session_id, ctx.state)
.await?;
}
PacketId::FriendRequest => {
friends::handle_friend_request(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_request(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendAccept => {
friends::handle_friend_accept(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_accept(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendDecline => {
friends::handle_friend_decline(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_decline(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendRemove => {
friends::handle_friend_remove(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_friend_remove(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::FriendList => {
friends::handle_friend_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
.await?;
friends::handle_friend_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::BlockUser => {
friends::handle_block_user(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_block_user(ctx.stream, ctx.seq, session_id, payload, ctx.state).await?;
}
PacketId::UnblockUser => {
friends::handle_unblock_user(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
friends::handle_unblock_user(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::BlockList => {
friends::handle_block_list(ctx.stream, ctx.seq, session_id, ctx.crypto, ctx.state)
.await?;
friends::handle_block_list(ctx.stream, ctx.seq, session_id, ctx.state).await?;
}
PacketId::MessageReactionAdd => {
let m = ReactionPayload::decode(payload)?;
@ -286,34 +207,24 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
content::handle_typing_start(session_id, payload, ctx.state).await?;
}
PacketId::ReadReceipt => {
content::handle_read_receipt(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
content::handle_read_receipt(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmKeyExchange => {
e2ee::handle_e2ee_key_exchange(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_key_exchange(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmKeyExchangeAck => {
e2ee::handle_e2ee_key_exchange_ack(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_key_exchange_ack(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmMessage => {
e2ee::handle_e2ee_dm_message(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_dm_message(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::E2eeDmHistory => {
e2ee::handle_e2ee_dm_history(
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
e2ee::handle_e2ee_dm_history(ctx.stream, ctx.seq, session_id, payload, ctx.state)
.await?;
}
PacketId::Disconnect => debug!("{addr} DISCONNECT"),
other => debug!("{addr} unhandled {:?}", other),

View file

@ -11,7 +11,7 @@ use crate::{
},
proto::{
self, E2eeDmKeyExchangeAckPayload, E2eeDmKeyExchangePayload, ErrorCode, PacketId,
SessionCrypto, encode_packet, to_payload,
encode_packet, to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_e2ee_key_exchange(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmKeyExchangePayload::decode(payload)?;
@ -38,7 +37,7 @@ pub async fn handle_e2ee_key_exchange(
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -46,7 +45,6 @@ pub async fn handle_e2ee_key_exchange(
code: ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -78,12 +76,11 @@ pub async fn handle_e2ee_key_exchange(
warn!("e2ee key exchange recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::E2eeDmKeyExchange,
seq,
&to_payload(&E2eeDmKeyExchangeAckPayload { dm_id: msg.dm_id }),
crypto,
)
.await?;
Ok(())
@ -94,7 +91,6 @@ pub async fn handle_e2ee_key_exchange_ack(
_seq: &mut u32,
session_id: &str,
payload: &[u8],
_crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmKeyExchangeAckPayload::decode(payload)?;

View file

@ -10,8 +10,8 @@ use crate::{
state::{BroadcastMsg, State},
},
proto::{
self, E2eeDmHistoryPayload, E2eeDmMessagePayload, ErrorCode, PacketId, SessionCrypto,
encode_packet, to_payload,
self, E2eeDmHistoryPayload, E2eeDmMessagePayload, ErrorCode, PacketId, encode_packet,
to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_e2ee_dm_message(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let msg = E2eeDmMessagePayload::decode(payload)?;
@ -34,7 +33,7 @@ pub async fn handle_e2ee_dm_message(
if !state.rate_limiter.try_consume(session_id) {
state.metrics.inc(&state.metrics.rate_limited_events);
warn!("rate-limited e2ee dm session {session_id}");
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -42,7 +41,6 @@ pub async fn handle_e2ee_dm_message(
code: ErrorCode::RateLimited as u32,
message: "you are sending messages too quickly".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -55,7 +53,7 @@ pub async fn handle_e2ee_dm_message(
.ok_or_else(|| anyhow::anyhow!("user not in DM"))?;
if state.storage.is_blocked(&other_id, &my_id).await? {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -63,7 +61,6 @@ pub async fn handle_e2ee_dm_message(
code: proto::ErrorCode::Blocked as u32,
message: "blocked".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -103,14 +100,7 @@ pub async fn handle_e2ee_dm_message(
warn!("e2ee dm recipient offline: {}", &other_id[..8]);
}
io::send_encrypted(
stream,
PacketId::E2eeDmMessage,
seq,
&to_payload(&saved),
crypto,
)
.await?;
io::send_frame(stream, PacketId::E2eeDmMessage, seq, &to_payload(&saved)).await?;
Ok(())
}
@ -119,7 +109,6 @@ pub async fn handle_e2ee_dm_history(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = E2eeDmHistoryPayload::decode(payload)?;
@ -147,13 +136,6 @@ pub async fn handle_e2ee_dm_history(
messages,
limit: None,
};
io::send_encrypted(
stream,
PacketId::E2eeDmHistory,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::E2eeDmHistory, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::io,
proto::{FriendDeclinePayload, PacketId, SessionCrypto, SimpleResponsePayload, to_payload},
proto::{FriendDeclinePayload, PacketId, SimpleResponsePayload, to_payload},
};
pub async fn handle_friend_decline(
@ -13,7 +13,6 @@ pub async fn handle_friend_decline(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &crate::net::state::State,
) -> Result<()> {
let req = FriendDeclinePayload::decode(payload)?;
@ -26,7 +25,7 @@ pub async fn handle_friend_decline(
.decline_friend_request(&req.from_user_id, &sess.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendDecline,
seq,
@ -35,7 +34,6 @@ pub async fn handle_friend_decline(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())

View file

@ -4,14 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{FriendInfo, FriendListPayload, PacketId, SessionCrypto, to_payload},
proto::{FriendInfo, FriendListPayload, PacketId, to_payload},
};
pub async fn handle_friend_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -35,12 +34,11 @@ pub async fn handle_friend_list(
});
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendList,
seq,
&to_payload(&FriendListPayload { friends }),
crypto,
)
.await?;
Ok(())

View file

@ -6,8 +6,8 @@ use crate::{
domain::session,
net::{io, state::State},
proto::{
BlockListPayload, BlockUserPayload, FriendRemovePayload, PacketId, SessionCrypto,
SimpleResponsePayload, UnblockUserPayload, to_payload,
BlockListPayload, BlockUserPayload, FriendRemovePayload, PacketId, SimpleResponsePayload,
UnblockUserPayload, to_payload,
},
};
@ -16,7 +16,6 @@ pub async fn handle_friend_remove(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendRemovePayload::decode(payload)?;
@ -29,7 +28,7 @@ pub async fn handle_friend_remove(
.remove_friend(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendRemove,
seq,
@ -38,7 +37,6 @@ pub async fn handle_friend_remove(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -49,7 +47,6 @@ pub async fn handle_block_user(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = BlockUserPayload::decode(payload)?;
@ -62,7 +59,7 @@ pub async fn handle_block_user(
.block_user(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::BlockUser,
seq,
@ -71,7 +68,6 @@ pub async fn handle_block_user(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -82,7 +78,6 @@ pub async fn handle_unblock_user(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = UnblockUserPayload::decode(payload)?;
@ -95,7 +90,7 @@ pub async fn handle_unblock_user(
.unblock_user(&sess.user_id, &req.user_id)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::UnblockUser,
seq,
@ -104,7 +99,6 @@ pub async fn handle_unblock_user(
user_id: None,
role_id: None,
}),
crypto,
)
.await?;
Ok(())
@ -114,7 +108,6 @@ pub async fn handle_block_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -123,12 +116,11 @@ pub async fn handle_block_list(
let blocked = state.storage.list_blocks(&sess.user_id).await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::BlockList,
seq,
&to_payload(&BlockListPayload { blocked }),
crypto,
)
.await?;
Ok(())

View file

@ -8,7 +8,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
net::io,
proto::{ErrorPayload, PacketId, SessionCrypto, to_payload},
proto::{ErrorPayload, PacketId, to_payload},
};
async fn send_err(
@ -16,9 +16,8 @@ async fn send_err(
seq: &mut u32,
code: crate::proto::ErrorCode,
msg: &str,
crypto: &SessionCrypto,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -26,7 +25,6 @@ async fn send_err(
code: code as u32,
message: msg.into(),
}),
crypto,
)
.await
}

View file

@ -5,10 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{
FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, SessionCrypto,
to_payload,
},
proto::{FriendAcceptPayload, FriendEventPayload, FriendRequestPayload, PacketId, to_payload},
};
use super::send_err;
@ -18,7 +15,6 @@ pub async fn handle_friend_request(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendRequestPayload::decode(payload)?;
@ -36,7 +32,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::Blocked,
"you are blocked by this user",
crypto,
)
.await?;
return Ok(());
@ -52,7 +47,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::InvalidPacket,
"already friends",
crypto,
)
.await?;
return Ok(());
@ -68,7 +62,6 @@ pub async fn handle_friend_request(
seq,
crate::proto::ErrorCode::InvalidPacket,
"already friends or request pending",
crypto,
)
.await?;
return Ok(());
@ -81,14 +74,13 @@ pub async fn handle_friend_request(
};
super::notify_user(state, &req.to_user_id, &ev).await;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendRequest,
seq,
&to_payload(&FriendRequestPayload {
to_user_id: req.to_user_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -99,7 +91,6 @@ pub async fn handle_friend_accept(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = FriendAcceptPayload::decode(payload)?;
@ -117,7 +108,6 @@ pub async fn handle_friend_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"no pending request",
crypto,
)
.await?;
return Ok(());
@ -130,14 +120,13 @@ pub async fn handle_friend_accept(
};
super::notify_user(state, &req.from_user_id, &ev).await;
io::send_encrypted(
io::send_frame(
stream,
PacketId::FriendAccept,
seq,
&to_payload(&FriendAcceptPayload {
from_user_id: req.from_user_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -6,8 +6,7 @@ use crate::{
domain::permissions::Permissions,
net::{io, state::State},
proto::{
AuditLogEntryPayload, GuildAuditLogFetchPayload, GuildAuditLogPayload, PacketId,
SessionCrypto, to_payload,
AuditLogEntryPayload, GuildAuditLogFetchPayload, GuildAuditLogPayload, PacketId, to_payload,
},
};
@ -17,7 +16,6 @@ pub async fn handle_audit_log_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildAuditLogFetchPayload::decode(payload)?;
@ -42,7 +40,7 @@ pub async fn handle_audit_log_fetch(
};
if !allowed {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -50,7 +48,6 @@ pub async fn handle_audit_log_fetch(
code: crate::proto::ErrorCode::PermissionDenied as u32,
message: "audit log access requires MANAGE_GUILD".into(),
}),
crypto,
)
.await?;
return Ok(());
@ -75,13 +72,6 @@ pub async fn handle_audit_log_fetch(
guild_id: req.guild_id,
entries,
};
io::send_encrypted(
stream,
PacketId::GuildAuditLog,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildAuditLog, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -6,7 +6,7 @@ use tracing::debug;
use crate::{
domain::session,
net::{io, state::State},
proto::{GuildCreatePayload, GuildInfo, PacketId, SessionCrypto, to_payload},
proto::{GuildCreatePayload, GuildInfo, PacketId, to_payload},
};
use super::send_err;
@ -16,7 +16,6 @@ pub async fn handle_guild_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildCreatePayload::decode(payload)?;
@ -30,7 +29,6 @@ pub async fn handle_guild_create(
seq,
crate::proto::ErrorCode::InvalidPacket,
"guild name must be 2-100 chars",
crypto,
)
.await?;
return Ok(());
@ -51,14 +49,7 @@ pub async fn handle_guild_create(
created_at: guild.created_at,
};
io::send_encrypted(
stream,
PacketId::GuildCreate,
seq,
&to_payload(&info),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildCreate, seq, &to_payload(&info)).await?;
debug!(
"guild: {} created {} (owner={})",
@ -72,7 +63,6 @@ pub async fn handle_guild_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -93,7 +83,6 @@ pub async fn handle_guild_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"only owner can delete guild",
crypto,
)
.await?;
return Ok(());
@ -114,14 +103,13 @@ pub async fn handle_guild_delete(
.await?;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildDelete,
seq,
&to_payload(&crate::proto::GuildDeletePayload {
guild_id: req.guild_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -7,7 +7,7 @@ use crate::{
net::{io, state::State},
proto::{
InviteAcceptPayload, InviteCreatePayload, InviteDeletePayload, InviteInfo, PacketId,
SessionCrypto, to_payload,
to_payload,
},
};
@ -18,7 +18,6 @@ pub async fn handle_invite_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteCreatePayload::decode(payload)?;
@ -39,7 +38,6 @@ pub async fn handle_invite_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing CREATE_INVITE permission",
crypto,
)
.await?;
return Ok(());
@ -78,14 +76,7 @@ pub async fn handle_invite_create(
expires_at: inv.expires_at,
created_at: inv.created_at,
};
io::send_encrypted(
stream,
PacketId::InviteCreate,
seq,
&to_payload(&info),
crypto,
)
.await?;
io::send_frame(stream, PacketId::InviteCreate, seq, &to_payload(&info)).await?;
Ok(())
}
@ -94,7 +85,6 @@ pub async fn handle_invite_accept(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteAcceptPayload::decode(payload)?;
@ -116,7 +106,6 @@ pub async fn handle_invite_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"invite expired",
crypto,
)
.await?;
return Ok(());
@ -130,7 +119,6 @@ pub async fn handle_invite_accept(
seq,
crate::proto::ErrorCode::InvalidPacket,
"invite max uses reached",
crypto,
)
.await?;
return Ok(());
@ -153,7 +141,7 @@ pub async fn handle_invite_accept(
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::InviteAccept,
seq,
@ -162,7 +150,6 @@ pub async fn handle_invite_accept(
guild_id: inv.guild_id.clone(),
guild_name: inv.guild_name.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -173,7 +160,6 @@ pub async fn handle_invite_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = InviteDeletePayload::decode(payload)?;
@ -194,7 +180,6 @@ pub async fn handle_invite_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_GUILD permission",
crypto,
)
.await?;
return Ok(());
@ -212,7 +197,7 @@ pub async fn handle_invite_delete(
None,
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::InviteDelete,
seq,
@ -220,7 +205,6 @@ pub async fn handle_invite_delete(
guild_id: req.guild_id.clone(),
invite_id: req.invite_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -4,16 +4,13 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::session,
net::{io, state::State},
proto::{
GuildInfo, GuildListPayload, PacketId, SessionCrypto, UserRoleUpdatePayload, to_payload,
},
proto::{GuildInfo, GuildListPayload, PacketId, UserRoleUpdatePayload, to_payload},
};
pub async fn handle_guild_list(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let sess = session::get(&state.sessions, session_id)
@ -39,7 +36,7 @@ pub async fn handle_guild_list(
.max_by_key(|r| r.position)
.map(|r| r.color.clone())
.unwrap_or_else(|| "#ffffff".into());
io::send_encrypted(
io::send_frame(
stream,
PacketId::UserRoleUpdate,
seq,
@ -48,17 +45,15 @@ pub async fn handle_guild_list(
guild_id: g.id.clone(),
color,
}),
crypto,
)
.await?;
}
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildList,
seq,
&to_payload(&GuildListPayload { guilds }),
crypto,
)
.await?;
Ok(())

View file

@ -7,7 +7,7 @@ use crate::{
net::{io, state::State},
proto::{
GuildMemberJoinPayload, GuildMemberKickPayload, GuildMemberLeavePayload, PacketId,
SessionCrypto, to_payload,
to_payload,
},
};
@ -18,7 +18,6 @@ pub async fn handle_guild_member_join(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -40,7 +39,6 @@ pub async fn handle_guild_member_join(
seq,
crate::proto::ErrorCode::PermissionDenied,
"a valid invitation is required",
crypto,
)
.await?;
return Ok(());
@ -61,18 +59,17 @@ pub async fn handle_guild_member_join(
.unwrap_or_else(|| "#ffffff".into());
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberJoin,
seq,
&to_payload(&crate::proto::GuildMemberJoinPayload {
guild_id: req.guild_id.clone(),
}),
crypto,
)
.await?;
io::send_encrypted(
io::send_frame(
stream,
PacketId::UserRoleUpdate,
seq,
@ -81,7 +78,6 @@ pub async fn handle_guild_member_join(
guild_id: req.guild_id.clone(),
color,
}),
crypto,
)
.await?;
Ok(())
@ -92,7 +88,6 @@ pub async fn handle_guild_member_leave(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -118,7 +113,6 @@ pub async fn handle_guild_member_leave(
seq,
crate::proto::ErrorCode::PermissionDenied,
"only a non-owner may leave their own membership",
crypto,
)
.await?;
return Ok(());
@ -129,7 +123,7 @@ pub async fn handle_guild_member_leave(
.await?;
crate::handler::channel::revoke_guild_access(state, &req.guild_id, Some(&target)).await;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberLeave,
seq,
@ -137,7 +131,6 @@ pub async fn handle_guild_member_leave(
guild_id: req.guild_id.clone(),
user_id: target,
}),
crypto,
)
.await?;
Ok(())
@ -148,7 +141,6 @@ pub async fn handle_guild_member_kick(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let guard = state.access.write().await;
@ -171,7 +163,6 @@ pub async fn handle_guild_member_kick(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing KICK_MEMBERS permission",
crypto,
)
.await?;
return Ok(());
@ -189,7 +180,6 @@ pub async fn handle_guild_member_kick(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild owner cannot be kicked",
crypto,
)
.await?;
return Ok(());
@ -211,7 +201,7 @@ pub async fn handle_guild_member_kick(
)
.await?;
drop(guard);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildMemberKick,
seq,
@ -219,7 +209,6 @@ pub async fn handle_guild_member_kick(
guild_id: req.guild_id.clone(),
user_id: req.user_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -8,7 +8,7 @@ use crate::{
proto::{
GuildMemberInfoPayload, GuildMemberListFetchPayload, GuildMemberListPayload,
GuildRoleInfoPayload, GuildRoleListFetchPayload, GuildRoleListPayload, PacketId,
RoleAssignPayload, SessionCrypto, to_payload,
RoleAssignPayload, to_payload,
},
};
@ -20,7 +20,6 @@ pub async fn handle_member_list_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildMemberListFetchPayload::decode(payload)?;
@ -41,7 +40,6 @@ pub async fn handle_member_list_fetch(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild membership required",
crypto,
)
.await?;
return Ok(());
@ -70,14 +68,7 @@ pub async fn handle_member_list_fetch(
guild_id: req.guild_id,
members,
};
io::send_encrypted(
stream,
PacketId::GuildMemberList,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildMemberList, seq, &to_payload(&resp)).await?;
Ok(())
}
@ -87,7 +78,6 @@ pub async fn handle_role_assign(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleAssignPayload::decode(payload)?;
@ -111,7 +101,6 @@ pub async fn handle_role_assign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -137,7 +126,6 @@ pub async fn handle_role_assign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role or target not permitted in this guild",
crypto,
)
.await?;
return Ok(());
@ -160,7 +148,7 @@ pub async fn handle_role_assign(
drop(access);
// Confirm to caller.
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildRoleAssign,
seq,
@ -169,7 +157,6 @@ pub async fn handle_role_assign(
user_id: req.user_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -181,7 +168,6 @@ pub async fn handle_role_unassign(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleAssignPayload::decode(payload)?;
@ -205,7 +191,6 @@ pub async fn handle_role_unassign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -231,7 +216,6 @@ pub async fn handle_role_unassign(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role or target not permitted in this guild",
crypto,
)
.await?;
return Ok(());
@ -255,7 +239,7 @@ pub async fn handle_role_unassign(
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::GuildRoleUnassign,
seq,
@ -264,7 +248,6 @@ pub async fn handle_role_unassign(
user_id: req.user_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())
@ -276,7 +259,6 @@ pub async fn handle_role_list_fetch(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = GuildRoleListFetchPayload::decode(payload)?;
@ -295,7 +277,6 @@ pub async fn handle_role_list_fetch(
seq,
crate::proto::ErrorCode::PermissionDenied,
"guild membership required",
crypto,
)
.await?;
return Ok(());
@ -317,13 +298,6 @@ pub async fn handle_role_list_fetch(
guild_id: req.guild_id,
roles,
};
io::send_encrypted(
stream,
PacketId::GuildRoleList,
seq,
&to_payload(&resp),
crypto,
)
.await?;
io::send_frame(stream, PacketId::GuildRoleList, seq, &to_payload(&resp)).await?;
Ok(())
}

View file

@ -12,7 +12,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::permissions::Permissions,
net::{io, state::State},
proto::{ErrorPayload, PacketId, SessionCrypto, to_payload},
proto::{ErrorPayload, PacketId, to_payload},
};
async fn send_err(
@ -20,9 +20,8 @@ async fn send_err(
seq: &mut u32,
code: crate::proto::ErrorCode,
msg: &str,
crypto: &SessionCrypto,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
stream,
PacketId::Error,
seq,
@ -30,7 +29,6 @@ async fn send_err(
code: code as u32,
message: msg.into(),
}),
crypto,
)
.await
}

View file

@ -5,7 +5,7 @@ use tokio::io::{AsyncRead, AsyncWrite};
use crate::{
domain::{permissions::Permissions, session},
net::{io, state::State},
proto::{PacketId, RoleCreatePayload, RoleDeletePayload, SessionCrypto, to_payload},
proto::{PacketId, RoleCreatePayload, RoleDeletePayload, to_payload},
};
use super::send_err;
@ -15,7 +15,6 @@ pub async fn handle_role_create(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleCreatePayload::decode(payload)?;
@ -38,7 +37,6 @@ pub async fn handle_role_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -57,7 +55,6 @@ pub async fn handle_role_create(
seq,
crate::proto::ErrorCode::PermissionDenied,
"cannot grant requested role",
crypto,
)
.await?;
return Ok(());
@ -79,7 +76,7 @@ pub async fn handle_role_create(
)
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::RoleCreate,
seq,
@ -90,7 +87,6 @@ pub async fn handle_role_create(
permissions: req.permissions,
id: role_id,
}),
crypto,
)
.await?;
Ok(())
@ -101,7 +97,6 @@ pub async fn handle_role_delete(
seq: &mut u32,
session_id: &str,
payload: &[u8],
crypto: &SessionCrypto,
state: &State,
) -> Result<()> {
let req = RoleDeletePayload::decode(payload)?;
@ -124,7 +119,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"missing MANAGE_ROLES permission",
crypto,
)
.await?;
return Ok(());
@ -137,7 +131,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"role is outside this guild",
crypto,
)
.await?;
return Ok(());
@ -149,7 +142,6 @@ pub async fn handle_role_delete(
seq,
crate::proto::ErrorCode::PermissionDenied,
"cannot manage requested role",
crypto,
)
.await?;
return Ok(());
@ -168,7 +160,7 @@ pub async fn handle_role_delete(
)
.await?;
drop(access);
io::send_encrypted(
io::send_frame(
stream,
PacketId::RoleDelete,
seq,
@ -176,7 +168,6 @@ pub async fn handle_role_delete(
guild_id: req.guild_id.clone(),
role_id: req.role_id.clone(),
}),
crypto,
)
.await?;
Ok(())

View file

@ -13,11 +13,10 @@ pub use run::run_session;
use tokio::io::{AsyncRead, AsyncWrite};
use crate::{net::state::State, proto::SessionCrypto};
use crate::net::state::State;
pub struct Ctx<'a, S: AsyncRead + AsyncWrite + Unpin> {
pub stream: &'a mut S,
pub seq: &'a mut u32,
pub crypto: &'a SessionCrypto,
pub state: &'a State,
}

View file

@ -5,39 +5,33 @@ use tracing::warn;
use crate::{
net::{io, state::BroadcastMsg, state::State},
proto::{self, PacketId, SessionCrypto, to_payload},
proto::{self, PacketId, to_payload},
};
use super::{Ctx, deliver::deliver_encrypted, dispatch};
use super::{Ctx, deliver::deliver_frame, dispatch};
pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
stream: &mut S,
addr: std::net::SocketAddr,
seq: &mut u32,
session_id: &str,
crypto: &SessionCrypto,
state: &State,
bcast_rx: &mut broadcast::Receiver<BroadcastMsg>,
) -> Result<()> {
let mut ctx = Ctx {
stream,
seq,
crypto,
state,
};
let mut reader = io::EncryptedReader::default();
let mut ctx = Ctx { stream, seq, state };
let mut reader = io::FrameReader::default();
loop {
tokio::select! {
result = reader.read(ctx.stream, ctx.crypto) => {
result = reader.read(ctx.stream) => {
let (hdr, payload) = result?;
let pid = match PacketId::from_u16(hdr.packet_id) {
Some(p) => p,
None => {
warn!("{addr} unknown 0x{:04X}", hdr.packet_id);
io::send_encrypted(ctx.stream, PacketId::Error, ctx.seq, &to_payload(&proto::ErrorPayload {
io::send_frame(ctx.stream, PacketId::Error, ctx.seq, &to_payload(&proto::ErrorPayload {
code: proto::ErrorCode::InvalidPacket as u32,
message: "unknown packet".into(),
}), ctx.crypto).await?;
})).await?;
continue;
}
};
@ -46,7 +40,7 @@ pub async fn run_session<S: AsyncRead + AsyncWrite + Unpin>(
}
bcast = bcast_rx.recv() => {
match bcast {
Ok(msg) => deliver_encrypted(ctx.stream, ctx.seq, session_id, &msg, ctx.crypto, ctx.state).await?,
Ok(msg) => deliver_frame(ctx.stream, ctx.seq, session_id, &msg, ctx.state).await?,
Err(broadcast::error::RecvError::Lagged(n)) => warn!("{addr} lagged {n}"),
Err(broadcast::error::RecvError::Closed) => return Ok(()),
}

View file

@ -5,6 +5,7 @@ pub mod handler;
pub mod media;
pub mod net;
pub mod proto;
pub mod tls;
pub mod webhooks;
use anyhow::Result;
@ -28,6 +29,10 @@ impl Drop for ConnGuard {
}
pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx>) -> Result<()> {
cfg.gateway.validate_tls()?;
if cfg.gateway.tls_enabled == Some(true) {
warn!("gateway.tls_enabled is deprecated: TLS 1.3 is always on, remove the option");
}
let private_mode = cfg.is_private();
if private_mode {
info!("private mode enabled, federation disabled");
@ -72,6 +77,26 @@ pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx
&server_pubkey[..8.min(server_pubkey.len())]
);
let material = tls::load_material(
&cfg.gateway,
&cfg.storage.data_dir,
&server_identity,
&cfg.node.address,
)?;
info!(
"TLS 1.3 certificate: {} (SPKI SHA-256 fingerprint {})",
if material.self_signed {
"self-signed, key = server identity"
} else {
"operator supplied"
},
tls::fingerprint_hex(&material.fingerprint)
);
if let Err(e) = tls::publish_fingerprint(&cfg.storage.data_dir, &material.fingerprint) {
warn!("could not write tls/fingerprint.txt: {e}");
}
let tls_config = tls::server_config(material)?;
let (tx, _) = broadcast::channel(256);
let metrics = admin::metrics::Metrics::new();
let sessions_count = Arc::new(AtomicUsize::new(0));
@ -130,71 +155,24 @@ pub async fn run(cfg: Arc<config::Config>, voice_member_tx: Option<VoiceMemberTx
tokio::spawn(admin::run(admin_bind, admin_state, state.clone()));
let listener = TcpListener::bind(&cfg.gateway.bind).await?;
info!("listening on {}", cfg.gateway.bind);
if cfg.gateway.tls_enabled {
run_tls(listener, cfg, state, max_connections, conn_count).await
} else {
run_plain(listener, state, max_connections, conn_count).await
}
info!("listening on {} (TLS 1.3)", cfg.gateway.bind);
run_tls(listener, tls_config, state, max_connections, conn_count).await
}
/// Grace period for the first byte of a connection. A TLS client speaks immediately;
/// an LNEx v2 client waits for the server HELLO and gets the explicit upgrade error.
const FIRST_BYTE_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
const TLS_HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
async fn run_tls(
listener: TcpListener,
cfg: Arc<config::Config>,
tls_config: Arc<rustls::ServerConfig>,
state: State,
max_connections: Option<usize>,
conn_count: Arc<AtomicUsize>,
) -> Result<()> {
let (certs, key) = load_or_generate_tls_certs(&cfg.gateway)?;
if cfg.gateway.tls_cert_path.is_none() {
warn!("using self-signed TLS certificate — clients must accept it manually");
}
let server_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key)?;
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server_config));
let acceptor = tokio_rustls::TlsAcceptor::from(tls_config);
loop {
match listener.accept().await {
Ok((stream, addr)) => {
let current = conn_count.load(std::sync::atomic::Ordering::Relaxed);
if let Some(limit) = max_connections
&& current >= limit
{
warn!("connection rejected from {addr}: at max_connections ({limit})");
drop(stream);
continue;
}
conn_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
info!("connection from {addr} (TLS)");
state.metrics.inc(&state.metrics.connections_total);
let s = state.clone();
let acceptor = acceptor.clone();
let conn_count_clone = conn_count.clone();
tokio::spawn(async move {
let _guard = ConnGuard(conn_count_clone);
match acceptor.accept(stream).await {
Ok(tls_stream) => {
if let Err(e) = handle(tls_stream, addr, s).await {
debug!("{addr} closed: {e}");
}
}
Err(e) => error!("TLS accept error from {addr}: {e}"),
}
});
}
Err(e) => error!("accept: {e}"),
}
}
}
async fn run_plain(
listener: TcpListener,
state: State,
max_connections: Option<usize>,
conn_count: Arc<AtomicUsize>,
) -> Result<()> {
loop {
match listener.accept().await {
Ok((stream, addr)) => {
@ -210,11 +188,33 @@ async fn run_plain(
info!("connection from {addr}");
state.metrics.inc(&state.metrics.connections_total);
let s = state.clone();
let acceptor = acceptor.clone();
let conn_count_clone = conn_count.clone();
tokio::spawn(async move {
let _guard = ConnGuard(conn_count_clone);
if let Err(e) = handle(stream, addr, s).await {
debug!("{addr} closed: {e}");
let mut stream = stream;
if !tls::looks_like_tls(&mut stream, FIRST_BYTE_GRACE).await {
s.metrics.inc(&s.metrics.auth_failures);
debug!("{addr} rejected: not a TLS 1.3 client");
return;
}
let accepted = tokio::time::timeout(TLS_HANDSHAKE_TIMEOUT, async {
let tls_stream = acceptor.accept(stream).await?;
let binding = tls::channel_binding(tls_stream.get_ref().1)?;
anyhow::Ok((tls_stream, binding))
})
.await;
match accepted {
Ok(Ok((tls_stream, binding))) => {
if let Err(e) = handle(tls_stream, addr, s, binding).await {
debug!("{addr} closed: {e}");
}
}
Ok(Err(e)) => {
s.metrics.inc(&s.metrics.auth_failures);
warn!("TLS handshake from {addr} failed: {e}");
}
Err(_) => warn!("TLS handshake from {addr} timed out"),
}
});
}
@ -227,11 +227,12 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
mut stream: S,
addr: std::net::SocketAddr,
state: State,
binding: [u8; tls::BINDING_LEN],
) -> Result<()> {
let mut seq = 0u32;
let (sess, crypto) = tokio::time::timeout(
let sess = tokio::time::timeout(
std::time::Duration::from_secs(15),
net::handshake::run(&mut stream, addr, &state, &mut seq),
net::handshake::run(&mut stream, addr, &state, &mut seq, &binding),
)
.await??;
let sid = sess.session_id.clone();
@ -240,26 +241,17 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut bcast_rx = state.broadcast.subscribe();
let result = handler::run_session(
&mut stream,
addr,
&mut seq,
&sid,
&crypto,
&state,
&mut bcast_rx,
)
.await;
let result =
handler::run_session(&mut stream, addr, &mut seq, &sid, &state, &mut bcast_rx).await;
if result.is_err() {
let p = proto::DisconnectPayload {
reason: "session closed".into(),
};
let _ = net::io::send_encrypted(
let _ = net::io::send_frame(
&mut stream,
proto::PacketId::Disconnect,
&mut seq,
&proto::to_payload(&p),
&crypto,
)
.await;
}
@ -327,32 +319,3 @@ async fn handle<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
debug!("{addr} cleaned up");
result
}
fn load_or_generate_tls_certs(
cfg: &config::GatewayConfig,
) -> Result<(
Vec<rustls::pki_types::CertificateDer<'static>>,
rustls::pki_types::PrivateKeyDer<'static>,
)> {
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
match (&cfg.tls_cert_path, &cfg.tls_key_path) {
(Some(cert_path), Some(key_path)) => {
let cert_pem = std::fs::read_to_string(cert_path)?;
let key_pem = std::fs::read_to_string(key_path)?;
let cert = CertificateDer::from_pem_reader(&mut cert_pem.as_bytes())?;
let key = PrivateKeyDer::from_pem_reader(&mut key_pem.as_bytes())?;
Ok((vec![cert], key))
}
_ => {
info!("No TLS cert/key configured, generating self-signed certificate");
let certified_key = rcgen::generate_simple_self_signed(vec!["VNOX Server".into()])?;
let cert_der = certified_key.cert.der().clone();
let key_der = PrivateKeyDer::from(PrivatePkcs8KeyDer::from(
certified_key.signing_key.serialize_der(),
));
Ok((vec![cert_der], key_der))
}
}
}

View file

@ -294,7 +294,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
Ok(())
}
Err(error) => {
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::Error,
ctx.seq,
@ -302,7 +302,6 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
code: proto::ErrorCode::PermissionDenied as u32,
message: format!("media: {error}"),
}),
ctx.crypto,
)
.await
}

View file

@ -7,26 +7,49 @@ use crate::{
domain::{auth, session},
net::io,
net::state::State,
proto::{self, AuthPayload, HelloPayload, PacketId, SessionCrypto, SessionPayload, to_payload},
proto::{self, AuthPayload, HelloPayload, PacketId, SessionPayload, to_payload},
};
const LNEX_VERSION: &str = "v2";
/// LNEx protocol version. v3 runs inside TLS 1.3 (see `docs/02-protocol/tls.md`).
pub const LNEX_VERSION: &str = "v3";
/// Run 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 the server identity signs: context, TLS exporter, HELLO without its 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 the client identity signs: context, TLS exporter, the signed HELLO, AUTH without
/// its signature. The exporter makes the signature valid for this TLS connection only.
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
}
/// Run HELLO, AUTH, SESSION inside an established TLS 1.3 connection.
///
/// Returns the session and the derived crypto context (encryption keys).
/// All subsequent packets must be encrypted with `crypto`.
/// `binding` is the TLS exporter value of this connection; both signatures cover it.
pub async fn run(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
addr: std::net::SocketAddr,
state: &State,
seq: &mut u32,
) -> Result<(session::Session, SessionCrypto)> {
// Generate ephemeral X25519 keypair for forward secrecy
let (eph_sk, eph_pk) = SessionCrypto::new_ephemeral();
let eph_pk_raw = eph_pk.as_bytes();
// HELLO — include server's ephemeral public key + privacy mode
binding: &[u8],
) -> Result<session::Session> {
// HELLO: server key, challenge, privacy mode, signature bound to this TLS connection.
let challenge = auth::new_challenge();
let private_mode = state.config.is_private();
let mut hello = HelloPayload {
@ -34,22 +57,17 @@ pub async fn run(
server_pubkey: hex::decode(state.server_identity.pubkey_hex())?,
challenge_nonce: challenge.to_vec(),
node_name: state.config.node.name.clone(),
server_eph_pubkey: eph_pk_raw.to_vec(),
private_mode,
server_signature: Vec::new(),
};
let mut hello_transcript = b"VNOX-LNEx-v2-server-hello\0".to_vec();
hello_transcript.extend_from_slice(&hello.encode_to_vec());
let hello_transcript = server_hello_transcript(binding, &hello.encode_to_vec());
hello.server_signature = state.server_identity.sign(&hello_transcript);
io::send_packet(stream, PacketId::Hello, seq, &to_payload(&hello)).await?;
debug!("{addr} ← HELLO (eph key included)");
debug!("{addr} HELLO sent");
// AUTH — receive client's ephemeral public key
// AUTH
let (hdr, payload) = io::read_packet(stream).await?;
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth)
|| hdr.flags != 0
|| hdr.sequence != 0
{
if PacketId::from_u16(hdr.packet_id) != Some(PacketId::Auth) || hdr.sequence != 0 {
io::send_error(
stream,
seq,
@ -61,33 +79,32 @@ pub async fn run(
}
let msg = AuthPayload::decode(payload.as_slice())?;
anyhow::ensure!(
!msg.nickname.trim().is_empty() && msg.nickname.chars().count() <= 64,
"invalid nickname"
);
debug!("{addr} → AUTH");
if msg.lnex_version != LNEX_VERSION {
io::send_error(
stream,
seq,
proto::ErrorCode::VersionMismatch,
"unsupported version",
"unsupported version: LNEx v3 required",
)
.await?;
return Err(anyhow::anyhow!("version mismatch"));
}
anyhow::ensure!(
!msg.nickname.trim().is_empty() && msg.nickname.chars().count() <= 64,
"invalid nickname"
);
debug!("{addr} AUTH received");
let pubkey: [u8; 32] = msg.client_pubkey.as_slice().try_into()?;
let sig: [u8; 64] = msg.signature.as_slice().try_into()?;
let mut auth_without_signature = msg.clone();
auth_without_signature.signature.clear();
let hello_bytes = hello.encode_to_vec();
let mut auth_transcript = b"VNOX-LNEx-v2-client-auth\0".to_vec();
auth_transcript.extend_from_slice(&(hello_bytes.len() as u32).to_be_bytes());
auth_transcript.extend_from_slice(&hello_bytes);
auth_transcript.extend_from_slice(&auth_without_signature.encode_to_vec());
let auth_transcript = client_auth_transcript(
binding,
&hello.encode_to_vec(),
&auth_without_signature.encode_to_vec(),
);
if let Err(e) = auth::verify_auth(&auth_transcript, &pubkey, &sig) {
warn!("{addr} auth failed: {e}");
state.metrics.inc(&state.metrics.auth_failures);
@ -116,12 +133,6 @@ pub async fn run(
.upsert_user(&hex::encode(&msg.client_pubkey), &msg.nickname)
.await?;
// ECDH: compute shared secret from server's ephemeral sk + client's ephemeral pk
let client_eph_raw: [u8; 32] = msg.client_eph_pubkey.as_slice().try_into()?;
let client_eph_pk = x25519_dalek::PublicKey::from(client_eph_raw);
let shared_secret = SessionCrypto::ecdh(eph_sk, &client_eph_pk);
anyhow::ensure!(shared_secret.was_contributory(), "invalid ephemeral key");
// SESSION
let sess = session::create(
&state.sessions,
@ -130,9 +141,6 @@ pub async fn run(
)
.await;
// Derive encryption keys from shared secret + session_id
let crypto = SessionCrypto::derive(shared_secret.as_bytes(), &sess.session_id);
let timeout_secs = state.config.gateway.session_timeout.unwrap_or(600);
let expires_at = std::time::SystemTime::now()
.checked_add(std::time::Duration::from_secs(timeout_secs))
@ -146,10 +154,159 @@ pub async fn run(
};
io::send_packet(stream, PacketId::Session, seq, &to_payload(&sp)).await?;
info!(
"{addr} auth ok — nick={} sid={} encrypted",
"{addr} auth ok, nick={} sid={}",
sess.nickname,
&sess.session_id[..8]
);
Ok((sess, crypto))
Ok(sess)
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use std::sync::{Arc, atomic::AtomicUsize};
use tokio::io::{AsyncWriteExt, DuplexStream};
async fn state() -> State {
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:")
.await
.unwrap();
let config = toml::from_str(include_str!("../../../dev/config.toml")).unwrap();
let dir = std::env::temp_dir().join(format!("vnox-hs-test-{}", uuid::Uuid::new_v4()));
let identity =
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir).unwrap();
let _ = std::fs::remove_dir_all(dir);
let (broadcast, _) = tokio::sync::broadcast::channel(16);
State::new(
session::new_store(),
crate::domain::channels::new_store(),
Arc::new(storage),
Arc::new(config),
Arc::new(identity),
broadcast,
crate::admin::metrics::Metrics::new(),
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
None,
)
}
/// Minimal client: reads HELLO, signs AUTH over `client_binding`, sends it.
async fn client_auth(
peer: &mut DuplexStream,
client_binding: &[u8],
version: &str,
) -> HelloPayload {
let (hdr, payload) = io::read_packet(peer).await.unwrap();
assert_eq!(hdr.packet_id, PacketId::Hello as u16);
let hello = HelloPayload::decode(payload.as_slice()).unwrap();
let key = SigningKey::generate(&mut rand::rng());
let mut auth = AuthPayload {
client_pubkey: key.verifying_key().to_bytes().to_vec(),
nickname: "tester".into(),
lnex_version: version.into(),
signature: Vec::new(),
};
let transcript = client_auth_transcript(client_binding, &payload, &auth.encode_to_vec());
auth.signature = key.sign(&transcript).to_bytes().to_vec();
let mut seq = 0;
io::send_packet(peer, PacketId::Auth, &mut seq, &to_payload(&auth))
.await
.unwrap();
hello
}
async fn handshake(
server_binding: &[u8],
client_binding: &[u8],
version: &str,
) -> (Result<session::Session>, proto::ErrorPayload) {
let state = state().await;
let (mut server, mut peer) = tokio::io::duplex(65536);
let server_binding = server_binding.to_vec();
let task = tokio::spawn(async move {
let mut seq = 0;
let result = run(
&mut server,
"127.0.0.1:1".parse().unwrap(),
&state,
&mut seq,
&server_binding,
)
.await;
let _ = server.shutdown().await;
result
});
client_auth(&mut peer, client_binding, version).await;
let (hdr, payload) = io::read_packet(&mut peer).await.unwrap();
let error = if hdr.packet_id == PacketId::Error as u16 {
proto::ErrorPayload::decode(payload.as_slice()).unwrap()
} else {
assert_eq!(hdr.packet_id, PacketId::Session as u16);
proto::ErrorPayload::default()
};
(task.await.unwrap(), error)
}
#[tokio::test]
async fn signature_for_the_same_channel_binding_is_accepted() {
let (result, _) = handshake(&[9; 32], &[9; 32], LNEX_VERSION).await;
result.unwrap();
}
#[tokio::test]
async fn client_signature_cannot_be_replayed_on_another_connection() {
// The AUTH was signed for TLS connection A (binding [1;32]) but arrives on B ([2;32]).
let (result, error) = handshake(&[2; 32], &[1; 32], LNEX_VERSION).await;
assert!(result.is_err());
assert_eq!(error.code, proto::ErrorCode::AuthFailed as u32);
}
#[tokio::test]
async fn old_protocol_version_is_rejected_with_explicit_error() {
let (result, error) = handshake(&[3; 32], &[3; 32], "v2").await;
assert!(result.is_err());
assert_eq!(error.code, proto::ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("v3"));
}
#[tokio::test]
async fn server_hello_signature_is_bound_to_the_connection() {
let state = state().await;
let verifying = ed25519_dalek::VerifyingKey::from_bytes(
&hex::decode(state.server_identity.pubkey_hex())
.unwrap()
.try_into()
.unwrap(),
)
.unwrap();
let (mut server, mut peer) = tokio::io::duplex(65536);
tokio::spawn(async move {
let mut seq = 0;
let _ = run(
&mut server,
"127.0.0.1:1".parse().unwrap(),
&state,
&mut seq,
&[5; 32],
)
.await;
});
let (_, payload) = io::read_packet(&mut peer).await.unwrap();
let mut hello = HelloPayload::decode(payload.as_slice()).unwrap();
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature).unwrap();
hello.server_signature.clear();
let unsigned = hello.encode_to_vec();
verifying
.verify_strict(&server_hello_transcript(&[5; 32], &unsigned), &signature)
.unwrap();
assert!(
verifying
.verify_strict(&server_hello_transcript(&[6; 32], &unsigned), &signature)
.is_err(),
"a relay with a different TLS session cannot reuse the server HELLO"
);
}
}

View file

@ -1,10 +1,10 @@
//! LNEx v3 TCP framing. Frames are written directly into the TLS 1.3 stream, so there is
//! no per frame encryption: the 12 byte header is followed by the protobuf payload and
//! `flags` must be zero on the control plane.
use anyhow::Result;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use crate::proto::{
ErrorCode, ErrorPayload, PacketHeader, PacketId, SessionCrypto, encode_packet, flags,
to_payload,
};
use crate::proto::{ErrorCode, ErrorPayload, PacketHeader, PacketId, encode_packet, to_payload};
const MAX_PAYLOAD: u32 = 4 * 1024 * 1024;
@ -14,6 +14,11 @@ pub async fn send_packet(
seq: &mut u32,
payload: &[u8],
) -> Result<()> {
anyhow::ensure!(
payload.len() <= MAX_PAYLOAD as usize,
"payload too large: {}",
payload.len()
);
let data = encode_packet(id, *seq, payload);
*seq = seq.wrapping_add(1);
stream.write_all(&data).await?;
@ -34,15 +39,18 @@ pub async fn send_error(
send_packet(stream, PacketId::Error, seq, &to_payload(&p)).await
}
/// Read one frame during the handshake (strictly `flags == 0`).
pub async fn read_packet(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
) -> Result<(PacketHeader, Vec<u8>)> {
let mut buf = [0u8; PacketHeader::SIZE];
stream.read_exact(&mut buf).await?;
let hdr = PacketHeader::from_bytes(&buf);
if hdr.flags & !flags::KNOWN_MASK != 0 {
return Err(anyhow::anyhow!("unknown packet flags: 0x{:04X}", hdr.flags));
}
anyhow::ensure!(
hdr.flags == 0,
"unsupported packet flags: 0x{:04X}",
hdr.flags
);
if hdr.payload_length > MAX_PAYLOAD {
return Err(anyhow::anyhow!("payload too large: {}", hdr.payload_length));
}
@ -53,114 +61,68 @@ pub async fn read_packet(
Ok((hdr, payload))
}
pub async fn send_encrypted(
/// Send one session frame. The sequence number never wraps inside a connection.
pub async fn send_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
id: PacketId,
seq: &mut u32,
payload: &[u8],
crypto: &SessionCrypto,
) -> Result<()> {
anyhow::ensure!(*seq < u32::MAX, "session sequence exhausted");
anyhow::ensure!(
payload.len() <= MAX_PAYLOAD as usize - 16,
"payload too large"
);
let flags_val = flags::ENCRYPTED;
let mut hdr_buf = [0u8; PacketHeader::SIZE];
hdr_buf[0..2].copy_from_slice(&(id as u16).to_be_bytes());
hdr_buf[2..4].copy_from_slice(&flags_val.to_be_bytes());
hdr_buf[4..8].copy_from_slice(&seq.to_be_bytes());
hdr_buf[8..12].copy_from_slice(&((payload.len() + 16) as u32).to_be_bytes());
let encrypted = crypto.encrypt_s2c_frame(*seq as u64, payload, &hdr_buf);
*seq += 1;
let mut out = Vec::with_capacity(PacketHeader::SIZE + encrypted.len());
out.extend_from_slice(&hdr_buf);
out.extend_from_slice(&encrypted);
stream.write_all(&out).await?;
Ok(())
send_packet(stream, id, seq, payload).await
}
pub async fn read_encrypted(
/// Forward a pre-encoded broadcast packet (`header || payload`) re-sequenced for this session.
pub async fn deliver_frame(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
crypto: &SessionCrypto,
) -> Result<(PacketHeader, Vec<u8>)> {
let mut buf = [0u8; PacketHeader::SIZE];
stream.read_exact(&mut buf).await?;
let hdr = PacketHeader::from_bytes(&buf);
if hdr.flags & !flags::KNOWN_MASK != 0 {
return Err(anyhow::anyhow!("unknown packet flags: 0x{:04X}", hdr.flags));
}
if hdr.flags & flags::ENCRYPTED == 0 {
return Err(anyhow::anyhow!("packet not encrypted"));
}
if hdr.payload_length > MAX_PAYLOAD {
return Err(anyhow::anyhow!("payload too large: {}", hdr.payload_length));
}
let mut encrypted = vec![0u8; hdr.payload_length as usize];
if !encrypted.is_empty() {
stream.read_exact(&mut encrypted).await?;
}
let payload = crypto.decrypt_c2s_frame(hdr.sequence as u64, &encrypted, &buf)?;
Ok((hdr, payload))
}
pub async fn deliver_encrypted(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
crypto: &SessionCrypto,
seq: &mut u32,
raw_data: &[u8],
) -> Result<()> {
if raw_data.len() < PacketHeader::SIZE {
return Err(anyhow::anyhow!("deliver: packet too short"));
}
let raw_hdr = PacketHeader::from_bytes(raw_data[..PacketHeader::SIZE].try_into().unwrap());
let pid = match PacketId::from_u16(raw_hdr.packet_id) {
Some(p) => p,
None => {
return Err(anyhow::anyhow!(
"deliver: unknown packet id 0x{:04X}",
raw_hdr.packet_id
));
}
};
let payload = &raw_data[PacketHeader::SIZE..];
send_encrypted(stream, pid, seq, payload, crypto).await
let raw_hdr = PacketHeader::from_bytes(
raw_data[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("deliver: bad header"))?,
);
let pid = PacketId::from_u16(raw_hdr.packet_id)
.ok_or_else(|| anyhow::anyhow!("deliver: unknown packet id 0x{:04X}", raw_hdr.packet_id))?;
send_frame(stream, pid, seq, &raw_data[PacketHeader::SIZE..]).await
}
/// Incremental framing state survives cancellation by broadcast delivery.
pub struct EncryptedReader {
pub struct FrameReader {
bytes: Vec<u8>,
expected_sequence: u32,
}
impl Default for EncryptedReader {
impl Default for FrameReader {
fn default() -> Self {
Self {
bytes: Vec::new(),
// The client AUTH used sequence 0, the first session frame is 1.
expected_sequence: 1,
}
}
}
impl EncryptedReader {
impl FrameReader {
pub async fn read(
&mut self,
stream: &mut (impl AsyncRead + Unpin),
crypto: &SessionCrypto,
) -> Result<(PacketHeader, Vec<u8>)> {
loop {
let needed = if self.bytes.len() < PacketHeader::SIZE {
PacketHeader::SIZE
} else {
let header: &[u8; PacketHeader::SIZE] =
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
let hdr = PacketHeader::from_bytes(header);
let header: [u8; PacketHeader::SIZE] = self.bytes[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("short header"))?;
let hdr = PacketHeader::from_bytes(&header);
anyhow::ensure!(hdr.flags == 0, "unsupported frame flags");
anyhow::ensure!(
hdr.flags == flags::ENCRYPTED,
"unsupported encrypted frame flags"
);
anyhow::ensure!(
hdr.payload_length >= 16 && hdr.payload_length <= MAX_PAYLOAD,
"invalid encrypted payload size"
hdr.payload_length <= MAX_PAYLOAD,
"payload too large: {}",
hdr.payload_length
);
anyhow::ensure!(
hdr.sequence == self.expected_sequence && hdr.sequence < u32::MAX,
@ -168,15 +130,12 @@ impl EncryptedReader {
);
PacketHeader::SIZE + hdr.payload_length as usize
};
if self.bytes.len() == needed && needed > PacketHeader::SIZE {
let header: &[u8; PacketHeader::SIZE] =
self.bytes[..PacketHeader::SIZE].try_into().unwrap();
let hdr = PacketHeader::from_bytes(header);
let payload = crypto.decrypt_c2s_frame(
hdr.sequence as u64,
&self.bytes[PacketHeader::SIZE..],
header,
)?;
if self.bytes.len() == needed && self.bytes.len() >= PacketHeader::SIZE {
let header: [u8; PacketHeader::SIZE] = self.bytes[..PacketHeader::SIZE]
.try_into()
.map_err(|_| anyhow::anyhow!("short header"))?;
let hdr = PacketHeader::from_bytes(&header);
let payload = self.bytes[PacketHeader::SIZE..].to_vec();
self.bytes.clear();
self.expected_sequence += 1;
return Ok((hdr, payload));
@ -193,49 +152,52 @@ impl EncryptedReader {
#[cfg(test)]
mod reader_tests {
use super::*;
fn frame(crypto: &SessionCrypto, seq: u32) -> Vec<u8> {
let mut header = [0u8; 12];
header[..2].copy_from_slice(&(PacketId::Ping as u16).to_be_bytes());
header[2..4].copy_from_slice(&flags::ENCRYPTED.to_be_bytes());
header[4..8].copy_from_slice(&seq.to_be_bytes());
header[8..].copy_from_slice(&20u32.to_be_bytes());
let mut bytes = header.to_vec();
bytes.extend_from_slice(&crypto.encrypt_c2s_frame(seq as u64, b"ping", &header));
fn frame(seq: u32, flags: u16, body: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(&(PacketId::Ping as u16).to_be_bytes());
bytes.extend_from_slice(&flags.to_be_bytes());
bytes.extend_from_slice(&seq.to_be_bytes());
bytes.extend_from_slice(&(body.len() as u32).to_be_bytes());
bytes.extend_from_slice(body);
bytes
}
#[tokio::test]
async fn cancelled_partial_read_preserves_framing_and_rejects_replay() {
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
let bytes = frame(&crypto, 1);
let bytes = frame(1, 0, b"ping");
let (mut server, mut peer) = tokio::io::duplex(128);
let mut reader = EncryptedReader::default();
let mut reader = FrameReader::default();
peer.write_all(&bytes[..5]).await.unwrap();
assert!(
tokio::time::timeout(
std::time::Duration::from_millis(2),
reader.read(&mut server, &crypto)
reader.read(&mut server)
)
.await
.is_err()
);
peer.write_all(&bytes[5..]).await.unwrap();
let (_, body) = reader.read(&mut server, &crypto).await.unwrap();
let (_, body) = reader.read(&mut server).await.unwrap();
assert_eq!(body, b"ping");
peer.write_all(&bytes).await.unwrap();
assert!(reader.read(&mut server, &crypto).await.is_err());
assert!(reader.read(&mut server).await.is_err());
}
#[tokio::test]
async fn modifying_authenticated_packet_type_is_rejected() {
let crypto = SessionCrypto::derive(&[7; 32], "fixture");
let mut bytes = frame(&crypto, 1);
bytes[1] ^= 1;
async fn legacy_encrypted_flag_is_rejected() {
let bytes = frame(1, crate::proto::flags::ENCRYPTED, b"0123456789abcdef");
let (mut server, mut peer) = tokio::io::duplex(128);
peer.write_all(&bytes).await.unwrap();
assert!(
EncryptedReader::default()
.read(&mut server, &crypto)
.await
.is_err()
);
let error = FrameReader::default().read(&mut server).await.unwrap_err();
assert!(error.to_string().contains("flags"));
}
#[tokio::test]
async fn out_of_order_sequence_is_rejected() {
let bytes = frame(2, 0, b"");
let (mut server, mut peer) = tokio::io::duplex(128);
peer.write_all(&bytes).await.unwrap();
assert!(FrameReader::default().read(&mut server).await.is_err());
}
}

View file

@ -1,4 +1,3 @@
mod crypto;
mod framing;
mod packet;
@ -8,8 +7,6 @@ pub mod lnex {
pub use lnex::*;
pub use crypto::SessionCrypto;
// Re-export everything so `crate::proto::X` works as before
pub use framing::{encode_packet, to_payload};
pub use packet::{ErrorCode, PacketHeader, PacketId, flags};

388
gateway/src/tls.rs Normal file
View file

@ -0,0 +1,388 @@
//! TLS 1.3 for the TCP control plane (LNEx v3). See `docs/02-protocol/tls.md`.
//!
//! * TLS 1.3 only, ALPN `vnox-lnex/3`, no client certificates, no plaintext fallback.
//! * Certificate: user supplied (PEM chain + key) or auto generated and stored in the data
//! directory. The auto generated certificate is signed with the server identity Ed25519
//! key, so its SPKI fingerprint is a pure function of the identity.
//! * Channel binding: both sides derive a 32 byte TLS exporter value that is signed by the
//! LNEx handshake, so signatures cannot be replayed on another connection.
use std::path::Path;
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use sha2::{Digest, Sha256};
use crate::bootstrap::server_identity::ServerIdentity;
use crate::domain::config::GatewayConfig;
/// Application protocol negotiated through ALPN. A connection without it is dropped.
pub const ALPN: &[u8] = b"vnox-lnex/3";
/// TLS exporter label (RFC 5705 / RFC 8446 section 7.5) used for the channel binding.
pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding";
/// Size of the exported channel binding value.
pub const BINDING_LEN: usize = 32;
/// Message shown to peers that do not speak TLS 1.3 (old LNEx v2 clients, plaintext probes).
pub const LEGACY_MESSAGE: &str = "TLS 1.3 required (LNEx v3): update your client";
/// Certificate chain, private key and the fingerprint of the leaf public key.
pub struct TlsMaterial {
pub chain: Vec<CertificateDer<'static>>,
pub key: PrivateKeyDer<'static>,
/// SHA-256 of the leaf SubjectPublicKeyInfo DER.
pub fingerprint: [u8; 32],
/// `true` when the certificate was generated by the gateway (not supplied by the operator).
pub self_signed: bool,
}
/// Lower-case hex of a fingerprint.
pub fn fingerprint_hex(fingerprint: &[u8; 32]) -> String {
hex::encode(fingerprint)
}
/// Read one DER TLV at the start of `data`: `(tag, header_len, content_len)`.
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))
}
/// Extract the complete SubjectPublicKeyInfo SEQUENCE (header included) from a 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];
// Optional [0] version, then serial, signature, issuer, validity, subject.
let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 };
// `skip` counts fields before SubjectPublicKeyInfo: [version], serial, sigalg, issuer, validity, subject.
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])
}
/// SHA-256 over the SubjectPublicKeyInfo DER of a certificate.
pub fn spki_fingerprint(cert_der: &[u8]) -> Result<[u8; 32]> {
Ok(Sha256::digest(spki_der(cert_der)?).into())
}
/// PKCS#8 v1 wrapper for a raw Ed25519 seed (RFC 8410).
pub fn ed25519_pkcs8(seed: &[u8; 32]) -> Vec<u8> {
let mut der = vec![
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04,
0x20,
];
der.extend_from_slice(seed);
der
}
fn self_signed_pem_path(data_dir: &Path) -> std::path::PathBuf {
data_dir.join("tls").join("self-signed.pem")
}
fn parse_chain(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
CertificateDer::pem_slice_iter(pem)
.collect::<std::result::Result<Vec<_>, _>>()
.context("invalid certificate PEM")
}
/// Generate a self-signed certificate whose key is the server identity key.
fn generate_self_signed(
seed: &[u8; 32],
node_address: &str,
) -> Result<(CertificateDer<'static>, String)> {
use rcgen::{CertificateParams, DnType, KeyPair, PKCS_ED25519, SanType, date_time_ymd};
let pkcs8 = PrivatePkcs8KeyDer::from(ed25519_pkcs8(seed));
let key_pair = KeyPair::from_pkcs8_der_and_sign_algo(&pkcs8, &PKCS_ED25519)
.context("server identity key rejected by rcgen")?;
let mut names = vec!["localhost".to_string()];
let host = node_address.trim();
if !host.is_empty() && host != "localhost" && host.parse::<std::net::IpAddr>().is_err() {
names.push(host.to_string());
}
let mut params = CertificateParams::new(names).context("invalid certificate names")?;
for ip in [
std::net::IpAddr::from([127, 0, 0, 1]),
std::net::IpAddr::from(std::net::Ipv6Addr::LOCALHOST),
] {
params.subject_alt_names.push(SanType::IpAddress(ip));
}
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
params.subject_alt_names.push(SanType::IpAddress(ip));
}
params
.distinguished_name
.push(DnType::CommonName, "VNOX gateway");
// Pinned clients ignore validity; keep it long so tools that check it do not complain.
params.not_before = date_time_ymd(2024, 1, 1);
params.not_after = date_time_ymd(2124, 1, 1);
let cert = params.self_signed(&key_pair)?;
Ok((cert.der().clone(), cert.pem()))
}
fn write_atomically(path: &Path, contents: &str) -> Result<()> {
let parent = path.parent().context("path has no parent")?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(".tls-{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&temporary, contents)?;
std::fs::rename(&temporary, path).inspect_err(|_| {
let _ = std::fs::remove_file(&temporary);
})?;
Ok(())
}
/// Load the operator certificate or the stored self-signed certificate (generating it
/// when missing, unreadable or not matching the server identity).
pub fn load_material(
cfg: &GatewayConfig,
data_dir: &Path,
identity: &ServerIdentity,
node_address: &str,
) -> Result<TlsMaterial> {
match (&cfg.tls_cert_path, &cfg.tls_key_path) {
(Some(cert_path), Some(key_path)) => {
let chain = parse_chain(
&std::fs::read(cert_path).with_context(|| format!("read {cert_path}"))?,
)?;
anyhow::ensure!(!chain.is_empty(), "no certificate found in {cert_path}");
let key = PrivateKeyDer::from_pem_slice(
&std::fs::read(key_path).with_context(|| format!("read {key_path}"))?,
)
.context("invalid private key PEM")?;
let fingerprint = spki_fingerprint(chain[0].as_ref())?;
Ok(TlsMaterial {
chain,
key,
fingerprint,
self_signed: false,
})
}
(None, None) => {
let seed = identity.signing_seed();
let expected = {
let (der, _) = generate_self_signed(&seed, node_address)?;
spki_fingerprint(der.as_ref())?
};
let path = self_signed_pem_path(data_dir);
let stored = std::fs::read(&path)
.ok()
.and_then(|pem| parse_chain(&pem).ok())
.filter(|chain| {
chain
.first()
.and_then(|c| spki_fingerprint(c.as_ref()).ok())
.is_some_and(|f| f == expected)
});
let chain = match stored {
Some(chain) => chain,
None => {
let (der, pem) = generate_self_signed(&seed, node_address)?;
write_atomically(&path, &pem)?;
vec![der]
}
};
let key = PrivateKeyDer::from(PrivatePkcs8KeyDer::from(ed25519_pkcs8(&seed)));
Ok(TlsMaterial {
chain,
key,
fingerprint: expected,
self_signed: true,
})
}
_ => bail!("tls_cert_path and tls_key_path must be set together"),
}
}
/// Write the public fingerprint next to the certificate for operators.
pub fn publish_fingerprint(data_dir: &Path, fingerprint: &[u8; 32]) -> Result<()> {
write_atomically(
&data_dir.join("tls").join("fingerprint.txt"),
&format!("{}\n", fingerprint_hex(fingerprint)),
)
}
/// Server config: TLS 1.3 only with the required ALPN.
pub fn server_config(material: TlsMaterial) -> Result<Arc<rustls::ServerConfig>> {
let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_no_client_auth()
.with_single_cert(material.chain, material.key)
.context("certificate and private key do not match")?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// Channel binding of an established server side session.
pub fn channel_binding(connection: &rustls::ServerConnection) -> Result<[u8; BINDING_LEN]> {
anyhow::ensure!(
connection.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3),
"TLS 1.3 required"
);
anyhow::ensure!(
connection.alpn_protocol() == Some(ALPN),
"ALPN vnox-lnex/3 required"
);
connection
.export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None)
.context("TLS exporter unavailable")
}
/// Reply to a peer that did not start a TLS handshake. This is the only plaintext the
/// gateway writes and it carries no secret.
pub async fn reject_legacy(stream: &mut tokio::net::TcpStream) {
use tokio::io::AsyncWriteExt;
let payload = crate::proto::to_payload(&crate::proto::ErrorPayload {
code: crate::proto::ErrorCode::VersionMismatch as u32,
message: LEGACY_MESSAGE.into(),
});
let frame = crate::proto::encode_packet(crate::proto::PacketId::Error, 0, &payload);
let _ = stream.write_all(&frame).await;
let _ = stream.shutdown().await;
}
/// First byte of a TLS handshake record.
const TLS_HANDSHAKE_RECORD: u8 = 0x16;
/// Wait briefly for the first byte. `true` means "looks like TLS, continue".
/// Anything else (no bytes within the grace period, other first byte) is answered with
/// the legacy error and `false`.
pub async fn looks_like_tls(
stream: &mut tokio::net::TcpStream,
grace: std::time::Duration,
) -> bool {
let mut first = [0u8; 1];
match tokio::time::timeout(grace, stream.peek(&mut first)).await {
Ok(Ok(1)) if first[0] == TLS_HANDSHAKE_RECORD => true,
Ok(Ok(0)) | Ok(Err(_)) => false,
_ => {
reject_legacy(stream).await;
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn identity(dir: &Path) -> ServerIdentity {
ServerIdentity::load_or_generate(dir).unwrap()
}
fn temp_dir() -> std::path::PathBuf {
std::env::temp_dir().join(format!("vnox-tls-{}", uuid::Uuid::new_v4()))
}
fn cfg() -> GatewayConfig {
toml::from_str("bind = \"127.0.0.1:0\"").unwrap()
}
#[test]
fn self_signed_fingerprint_is_sha256_of_identity_spki() {
let dir = temp_dir();
let id = identity(&dir);
let material = load_material(&cfg(), &dir, &id, "chat.example.org").unwrap();
// SPKI of an Ed25519 key is a fixed 12 byte prefix followed by the 32 byte key.
let mut spki = vec![
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
];
spki.extend_from_slice(&hex::decode(id.pubkey_hex()).unwrap());
let expected: [u8; 32] = Sha256::digest(&spki).into();
assert_eq!(material.fingerprint, expected);
assert_eq!(
spki_der(material.chain[0].as_ref()).unwrap(),
spki.as_slice()
);
assert!(material.self_signed);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn self_signed_certificate_is_stored_and_reused() {
let dir = temp_dir();
let id = identity(&dir);
let first = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap();
let path = dir.join("tls").join("self-signed.pem");
let stored = std::fs::read(&path).unwrap();
let second = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap();
assert_eq!(first.chain[0], second.chain[0]);
assert_eq!(std::fs::read(&path).unwrap(), stored);
// A certificate for a different key is replaced.
let other = temp_dir();
let other_id = identity(&other);
let swapped = load_material(&cfg(), &dir, &other_id, "127.0.0.1").unwrap();
assert_ne!(swapped.fingerprint, first.fingerprint);
std::fs::remove_dir_all(dir).unwrap();
std::fs::remove_dir_all(other).unwrap();
}
#[test]
fn operator_certificate_requires_both_paths() {
let dir = temp_dir();
let id = identity(&dir);
let mut partial = cfg();
partial.tls_cert_path = Some("/nonexistent/cert.pem".into());
assert!(load_material(&partial, &dir, &id, "x").is_err());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn operator_certificate_is_loaded_and_fingerprinted() {
let dir = temp_dir();
let id = identity(&dir);
std::fs::create_dir_all(&dir).unwrap();
let key = rcgen::KeyPair::generate().unwrap();
let cert = rcgen::CertificateParams::new(vec!["chat.example.org".into()])
.unwrap()
.self_signed(&key)
.unwrap();
let cert_path = dir.join("cert.pem");
let key_path = dir.join("key.pem");
std::fs::write(&cert_path, cert.pem()).unwrap();
std::fs::write(&key_path, key.serialize_pem()).unwrap();
let mut config = cfg();
config.tls_cert_path = Some(cert_path.to_string_lossy().into());
config.tls_key_path = Some(key_path.to_string_lossy().into());
let material = load_material(&config, &dir, &id, "x").unwrap();
assert!(!material.self_signed);
assert_eq!(
material.fingerprint,
spki_fingerprint(cert.der().as_ref()).unwrap()
);
server_config(material).unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn spki_parser_rejects_garbage() {
assert!(spki_der(&[]).is_err());
assert!(spki_der(&[0x30, 0x03, 0x01, 0x02]).is_err());
assert!(spki_der(b"not a certificate").is_err());
}
}

View file

@ -102,12 +102,11 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
.iter()
.map(info)
.collect();
return io::send_encrypted(
return io::send_frame(
ctx.stream,
PacketId::WebhookListResult,
ctx.seq,
&to_payload(&WebhookListResult { hooks, request_id }),
ctx.crypto,
)
.await;
}
@ -221,7 +220,7 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
}
h
};
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::WebhookResult,
ctx.seq,
@ -230,7 +229,6 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
secret,
request_id,
}),
ctx.crypto,
)
.await
}
@ -240,7 +238,7 @@ async fn error<S: AsyncRead + AsyncWrite + Unpin>(
code: ErrorCode,
msg: &str,
) -> Result<()> {
io::send_encrypted(
io::send_frame(
ctx.stream,
PacketId::WebhookErrorResult,
ctx.seq,
@ -249,7 +247,6 @@ async fn error<S: AsyncRead + AsyncWrite + Unpin>(
code: code as u32,
message: msg.into(),
}),
ctx.crypto,
)
.await
}

View file

@ -327,7 +327,7 @@ fn rate_limit_and_content_boundaries() {
#[tokio::test]
async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
use crate::proto::{PacketId, SessionCrypto, WebhookRequest, flags, to_payload};
use crate::proto::{PacketId, WebhookRequest, to_payload};
let (s, _, _) = fixture().await;
let req = WebhookRequest {
id: String::new(),
@ -343,13 +343,11 @@ async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
("owner", PacketId::WebhookResult),
] {
let session = session::create(&s.sessions, user.into(), user.into()).await;
let crypto = SessionCrypto::derive(&[3; 32], &session.session_id);
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 0;
let mut ctx = crate::handler::Ctx {
stream: &mut stream,
seq: &mut seq,
crypto: &crypto,
state: &s,
};
management::handle(
@ -362,7 +360,10 @@ async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
.unwrap();
let (header, _) = crate::net::io::read_packet(&mut peer).await.unwrap();
assert_eq!(header.packet_id, expected as u16);
assert_ne!(header.flags & flags::ENCRYPTED, 0);
assert_eq!(
header.flags, 0,
"TLS protects the stream; frames carry no flags"
);
}
let hooks = s.storage.hooks("target").await.unwrap();
assert_eq!(hooks.len(), 2);

View file

@ -0,0 +1,321 @@
//! Black box tests of the gateway TCP listener: TLS 1.3 only, ALPN, legacy rejection,
//! certificate fingerprint and the channel bound LNEx v3 handshake.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ed25519_dalek::{Signer, SigningKey};
use prost::Message;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use vnox_gateway::net::handshake::{LNEX_VERSION, client_auth_transcript, server_hello_transcript};
use vnox_gateway::proto::{AuthPayload, ErrorCode, ErrorPayload, HelloPayload, PacketId};
use vnox_gateway::tls::{ALPN, EXPORTER_LABEL, spki_fingerprint};
struct Server {
task: tokio::task::JoinHandle<()>,
port: u16,
directory: std::path::PathBuf,
}
impl Drop for Server {
fn drop(&mut self) {
self.task.abort();
let _ = std::fs::remove_dir_all(&self.directory);
}
}
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port()
}
async fn start() -> Server {
let directory = std::env::temp_dir().join(format!("vnox-tls-it-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let port = free_port();
let config = format!(
r#"
[node]
name = "tls-test"
address = "127.0.0.1"
[gateway]
bind = "127.0.0.1:{port}"
admin_bind = "127.0.0.1:0"
[voice]
bind = "127.0.0.1:0"
[storage]
data_dir = "{dir}"
backend = "sqlite"
sqlite_path = "{dir}/t.db"
[server]
mode = "private"
"#,
dir = directory.display()
);
let cfg: vnox_gateway::domain::config::Config = toml::from_str(&config).unwrap();
let task = tokio::spawn(async move {
let _ = vnox_gateway::run(Arc::new(cfg), None).await;
});
for _ in 0..200 {
if TcpStream::connect(("127.0.0.1", port)).await.is_ok() {
return Server {
task,
port,
directory,
};
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("gateway did not start");
}
/// Accepts every certificate (the tests pin the fingerprint themselves) but still checks
/// the TLS 1.3 handshake signature.
#[derive(Debug)]
struct AcceptAll {
leaf: Mutex<Option<Vec<u8>>>,
}
impl ServerCertVerifier for AcceptAll {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_: &[CertificateDer<'_>],
_: &ServerName<'_>,
_: &[u8],
_: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
*self.leaf.lock().unwrap() = Some(end_entity.to_vec());
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&rustls::crypto::aws_lc_rs::default_provider().signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&rustls::crypto::aws_lc_rs::default_provider().signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
rustls::crypto::aws_lc_rs::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
fn client_config(
versions: &[&'static rustls::SupportedProtocolVersion],
alpn: bool,
) -> (rustls::ClientConfig, Arc<AcceptAll>) {
let verifier = Arc::new(AcceptAll {
leaf: Mutex::new(None),
});
let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_protocol_versions(versions)
.unwrap()
.dangerous()
.with_custom_certificate_verifier(verifier.clone())
.with_no_client_auth();
if alpn {
config.alpn_protocols = vec![ALPN.to_vec()];
}
(config, verifier)
}
async fn connect_tls(
server: &Server,
config: rustls::ClientConfig,
) -> std::io::Result<tokio_rustls::client::TlsStream<TcpStream>> {
let tcp = TcpStream::connect(("127.0.0.1", server.port)).await?;
tokio_rustls::TlsConnector::from(Arc::new(config))
.connect(ServerName::try_from("127.0.0.1").unwrap(), tcp)
.await
}
async fn read_frame<S: tokio::io::AsyncRead + Unpin>(stream: &mut S) -> (u16, u32, Vec<u8>) {
let mut header = [0u8; 12];
stream.read_exact(&mut header).await.unwrap();
let id = u16::from_be_bytes([header[0], header[1]]);
let flags = u16::from_be_bytes([header[2], header[3]]);
assert_eq!(flags, 0);
let sequence = u32::from_be_bytes(header[4..8].try_into().unwrap());
let length = u32::from_be_bytes(header[8..12].try_into().unwrap()) as usize;
let mut payload = vec![0u8; length];
stream.read_exact(&mut payload).await.unwrap();
(id, sequence, payload)
}
fn frame(id: PacketId, sequence: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&(id as u16).to_be_bytes());
out.extend_from_slice(&0u16.to_be_bytes());
out.extend_from_slice(&sequence.to_be_bytes());
out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
out.extend_from_slice(payload);
out
}
#[tokio::test]
async fn tls13_with_alpn_works_and_certificate_fingerprint_matches_the_published_one() {
let server = start().await;
let (config, verifier) = client_config(&[&rustls::version::TLS13], true);
let tls = connect_tls(&server, config).await.unwrap();
assert_eq!(
tls.get_ref().1.protocol_version(),
Some(rustls::ProtocolVersion::TLSv1_3)
);
assert_eq!(tls.get_ref().1.alpn_protocol(), Some(ALPN));
let leaf = verifier.leaf.lock().unwrap().clone().unwrap();
let seen = hex::encode(spki_fingerprint(&leaf).unwrap());
let published =
std::fs::read_to_string(server.directory.join("tls").join("fingerprint.txt")).unwrap();
assert_eq!(seen, published.trim());
}
#[tokio::test]
async fn tls12_only_client_is_rejected() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS12], true);
let result = connect_tls(&server, config).await;
assert!(result.is_err(), "the listener must not negotiate TLS 1.2");
}
#[tokio::test]
async fn client_without_alpn_is_rejected_before_any_lnex_byte() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], false);
match connect_tls(&server, config).await {
Err(_) => {}
Ok(mut tls) => {
let mut byte = [0u8; 1];
let read = tokio::time::timeout(Duration::from_secs(3), tls.read(&mut byte)).await;
assert!(
!matches!(read, Ok(Ok(n)) if n > 0),
"no LNEx data may be sent without ALPN vnox-lnex/3"
);
}
}
}
#[tokio::test]
async fn plaintext_garbage_gets_explicit_version_error() {
let server = start().await;
let mut tcp = TcpStream::connect(("127.0.0.1", server.port))
.await
.unwrap();
tcp.write_all(&frame(PacketId::Auth, 0, b"old client"))
.await
.unwrap();
let (id, _, payload) = tokio::time::timeout(Duration::from_secs(5), read_frame(&mut tcp))
.await
.unwrap();
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("TLS 1.3"));
let mut rest = Vec::new();
tcp.read_to_end(&mut rest).await.unwrap();
assert!(rest.is_empty(), "connection is closed after the error");
}
#[tokio::test]
async fn silent_v2_style_client_gets_explicit_version_error() {
// An LNEx v2 client waits for the server HELLO and sends nothing.
let server = start().await;
let mut tcp = TcpStream::connect(("127.0.0.1", server.port))
.await
.unwrap();
let (id, _, payload) = tokio::time::timeout(Duration::from_secs(8), read_frame(&mut tcp))
.await
.unwrap();
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::VersionMismatch as u32);
assert!(error.message.contains("LNEx v3"));
}
async fn authenticate(
tls: &mut tokio_rustls::client::TlsStream<TcpStream>,
signing_binding: Option<[u8; 32]>,
) -> (u16, Vec<u8>) {
let binding = tls
.get_ref()
.1
.export_keying_material([0u8; 32], EXPORTER_LABEL, None)
.unwrap();
let (id, sequence, payload) = read_frame(tls).await;
assert_eq!((id, sequence), (PacketId::Hello as u16, 0));
let mut hello = HelloPayload::decode(payload.as_slice()).unwrap();
assert_eq!(hello.lnex_version, LNEX_VERSION);
// The server HELLO is signed over this connection's exporter.
let signature = ed25519_dalek::Signature::from_slice(&hello.server_signature).unwrap();
let verifying =
ed25519_dalek::VerifyingKey::from_bytes(&hello.server_pubkey.clone().try_into().unwrap())
.unwrap();
hello.server_signature.clear();
verifying
.verify_strict(
&server_hello_transcript(&binding, &hello.encode_to_vec()),
&signature,
)
.unwrap();
let key = SigningKey::generate(&mut rand::rng());
let mut auth = AuthPayload {
client_pubkey: key.verifying_key().to_bytes().to_vec(),
nickname: "tls-test".into(),
lnex_version: LNEX_VERSION.into(),
signature: Vec::new(),
};
let signed_with = signing_binding.unwrap_or(binding);
let transcript = client_auth_transcript(&signed_with, &payload, &auth.encode_to_vec());
auth.signature = key.sign(&transcript).to_bytes().to_vec();
tls.write_all(&frame(PacketId::Auth, 0, &auth.encode_to_vec()))
.await
.unwrap();
let (id, _, payload) = read_frame(tls).await;
(id, payload)
}
#[tokio::test]
async fn full_handshake_over_tls_creates_a_session() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], true);
let mut tls = connect_tls(&server, config).await.unwrap();
let (id, _) = authenticate(&mut tls, None).await;
assert_eq!(id, PacketId::Session as u16);
}
#[tokio::test]
async fn auth_signed_for_another_tls_connection_is_rejected() {
let server = start().await;
let (config, _) = client_config(&[&rustls::version::TLS13], true);
let mut tls = connect_tls(&server, config).await.unwrap();
let (id, payload) = authenticate(&mut tls, Some([0x42; 32])).await;
assert_eq!(id, PacketId::Error as u16);
let error = ErrorPayload::decode(payload.as_slice()).unwrap();
assert_eq!(error.code, ErrorCode::AuthFailed as u32);
}

View file

@ -8,8 +8,11 @@ message Hello {
bytes server_pubkey = 2;
bytes challenge_nonce = 3;
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;
// Ed25519 over "VNOX-LNEx-v3-server-hello\0" || tls_exporter || Hello(signature empty).
bytes server_signature = 7;
}
@ -17,8 +20,10 @@ message Auth {
bytes client_pubkey = 1;
string nickname = 2;
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 client_eph_pubkey = 5;
reserved 5;
reserved "client_eph_pubkey";
}
message Session {