Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix: derive separate authenticated tunnel bootstrap keys

Steven Enamakel3aa1bc4a218d
diff --git a/app/src/lib/tunnel/crypto.test.ts b/app/src/lib/tunnel/crypto.test.ts
index 1f3e98a620..390f9b06e5 100644
--- a/app/src/lib/tunnel/crypto.test.ts
+++ b/app/src/lib/tunnel/crypto.test.ts
@@ -146,10 +146,10 @@ describe('sealHandshake / openHandshake', () => {
expect(Array.from(recovered)).toEqual(Array.from(payload));
});
- it('frame starts with version byte 0x01', () => {
+ it('frame starts with version byte 0x03', () => {
const core = generateKeypair();
const frame = sealHandshake(core.publicKey, new Uint8Array(16));
- expect(frame[0]).toBe(0x01);
+ expect(frame[0]).toBe(0x03);
});
it('rejects tampered handshake frame', () => {
diff --git a/app/src/lib/tunnel/crypto.ts b/app/src/lib/tunnel/crypto.ts
index 2bc9f9712b..f297a297e5 100644
--- a/app/src/lib/tunnel/crypto.ts
+++ b/app/src/lib/tunnel/crypto.ts
@@ -10,9 +10,9 @@
* see a distinctive "re-pair required" error instead of a generic AEAD
* authentication failure.
*
- * Sealed-handshake format (device → core, first frame) keeps the v1 byte
- * because that flow uses raw XChaCha20Poly1305 outside the post-pairing
- * `TunnelCipher` — it's the bootstrap, not the session.
+ * Sealed-handshake format (device → core, first frame) uses marker 0x03,
+ * an HKDF-derived key and authenticated header. The acknowledgement uses
+ * marker 0x04 and a separate key.
*
* Mirrors crates/openhuman-core/src/security/devices/crypto.rs — keep in sync.
*/
@@ -32,6 +32,8 @@ const cryptoErr = debug('crypto:error');
export const FRAME_VERSION = 0x02;
/** Previous frame version. Surfaced so callers can recognise the legacy shape. */
export const LEGACY_FRAME_VERSION_V1 = 0x01;
+export const HANDSHAKE_VERSION = 0x03;
+export const HANDSHAKE_ACK_VERSION = 0x04;
const NONCE_LEN = 24; // XChaCha20-Poly1305 nonce
const EPH_PUB_LEN = 32; // X25519 public key
const REPLAY_WINDOW = 128;
@@ -40,6 +42,14 @@ const REPLAY_WINDOW = 128;
* byte-identical values. */
export const HKDF_INFO_C2S = new TextEncoder().encode('openhuman-tunnel/v1/c2s');
export const HKDF_INFO_S2C = new TextEncoder().encode('openhuman-tunnel/v1/s2c');
+const HKDF_INFO_HANDSHAKE = new TextEncoder().encode('openhuman-tunnel/v3/handshake');
+const HKDF_INFO_HANDSHAKE_ACK = new TextEncoder().encode('openhuman-tunnel/v3/handshake-ack');
+const HKDF_COMPAT_SALT = new TextEncoder().encode('openhuman-tunnel/compat');
+const HKDF_INFO_COMPAT = new TextEncoder().encode('openhuman-tunnel/compat/symmetric');
+
+function bootstrapKey(dh: Uint8Array, salt: Uint8Array, info: Uint8Array): Uint8Array {
+ return hkdf(sha256, dh, salt, info, 32);
+}
// -- base64url helpers -------------------------------------------------------
@@ -242,19 +252,18 @@ function openWithKey(key: Uint8Array, frame: Uint8Array, tracker: ReplayTracker)
}
/**
- * Legacy single-key seal — kept for non-session bootstrap callers (e.g. the
- * device-pubkey handshake path in `transport.ts`). New session frames go
- * through `TunnelCipher#seal` so they pick up directional subkeys.
+ * Compatibility single-key helpers for local fixtures. Production session
+ * frames go through `TunnelCipher` with directional subkeys.
*/
export function seal(key: Uint8Array, plaintext: Uint8Array): Uint8Array {
- return sealWithKey(key, plaintext);
+ return sealWithKey(bootstrapKey(key, HKDF_COMPAT_SALT, HKDF_INFO_COMPAT), plaintext);
}
/**
* Legacy single-key open. See {@link seal} for the rationale.
*/
export function open(key: Uint8Array, frame: Uint8Array, tracker: ReplayTracker): Uint8Array {
- return openWithKey(key, frame, tracker);
+ return openWithKey(bootstrapKey(key, HKDF_COMPAT_SALT, HKDF_INFO_COMPAT), frame, tracker);
}
// -- sealed handshake --------------------------------------------------------
@@ -263,26 +272,30 @@ export function open(key: Uint8Array, frame: Uint8Array, tracker: ReplayTracker)
* Seal a handshake payload to the core's static public key using an ephemeral
* X25519 keypair + XChaCha20-Poly1305.
*
- * Output: 0x01 || eph_pub(32) || nonce(24) || ciphertext+tag
+ * Output: 0x03 || eph_pub(32) || nonce(24) || ciphertext+tag
*
* Mirrors the wire format expected by bus.rs handle_tunnel_frame.
*/
export function sealHandshake(corePubkey: Uint8Array, payload: Uint8Array): Uint8Array {
+ if (corePubkey.length !== 32) {
+ throw new Error('[crypto] core public key must be 32 bytes');
+ }
const eph = generateKeypair();
- const sharedKey = deriveSharedSecret(eph.secretKey, corePubkey);
+ const dh = deriveSharedSecret(eph.secretKey, corePubkey);
+ const salt = new Uint8Array(64);
+ salt.set(eph.publicKey);
+ salt.set(corePubkey, 32);
+ const key = bootstrapKey(dh, salt, HKDF_INFO_HANDSHAKE);
const nonce = randomBytes(NONCE_LEN);
- const cipher = xchacha20poly1305(sharedKey, nonce);
+ const header = new Uint8Array(1 + EPH_PUB_LEN);
+ header[0] = HANDSHAKE_VERSION;
+ header.set(eph.publicKey, 1);
+ const cipher = xchacha20poly1305(key, nonce, header);
const ciphertext = cipher.encrypt(payload);
- // 0x01 || eph_pub(32) || nonce(24) || ciphertext+tag
- // NOTE: the layer-2 sealed-handshake byte is intentionally pinned to
- // 0x01 (LEGACY_FRAME_VERSION_V1), NOT the current FRAME_VERSION. The
- // handshake lives outside the post-pairing session and uses raw
- // XChaCha20Poly1305 on the device-pubkey-bearing first frame; the byte
- // is a wire marker for `devices/bus.rs::handle_tunnel_frame`, not a
- // signal of the post-session key schedule.
+ // 0x03 || eph_pub(32) || nonce(24) || ciphertext+tag
const frame = new Uint8Array(1 + EPH_PUB_LEN + NONCE_LEN + ciphertext.length);
- frame[0] = LEGACY_FRAME_VERSION_V1;
+ frame[0] = HANDSHAKE_VERSION;
frame.set(eph.publicKey, 1);
frame.set(nonce, 1 + EPH_PUB_LEN);
frame.set(ciphertext, 1 + EPH_PUB_LEN + NONCE_LEN);
@@ -299,23 +312,74 @@ export function openHandshake(myPriv: Uint8Array, frame: Uint8Array): Uint8Array
if (frame.length < 1 + EPH_PUB_LEN + NONCE_LEN + 16) {
throw new Error('[crypto] sealed-handshake frame too short');
}
- // The layer-2 sealed-handshake byte is pinned to 0x01 — see sealHandshake.
- if (frame[0] !== LEGACY_FRAME_VERSION_V1) {
+ if (frame[0] !== HANDSHAKE_VERSION) {
throw new Error(`[crypto] bad handshake version: 0x${frame[0].toString(16)}`);
}
const ephPub = frame.slice(1, 1 + EPH_PUB_LEN);
const nonce = frame.slice(1 + EPH_PUB_LEN, 1 + EPH_PUB_LEN + NONCE_LEN);
const ciphertext = frame.slice(1 + EPH_PUB_LEN + NONCE_LEN);
- const sharedKey = deriveSharedSecret(myPriv, ephPub);
+ const dh = deriveSharedSecret(myPriv, ephPub);
+ const salt = new Uint8Array(64);
+ salt.set(ephPub);
+ salt.set(x25519.getPublicKey(myPriv), 32);
+ const key = bootstrapKey(dh, salt, HKDF_INFO_HANDSHAKE);
try {
- const cipher = xchacha20poly1305(sharedKey, nonce);
+ const cipher = xchacha20poly1305(key, nonce, frame.slice(0, 1 + EPH_PUB_LEN));
return cipher.decrypt(ciphertext);
} catch {
throw new Error('[crypto] handshake authentication failed');
}
}
+/** Open the core's bootstrap acknowledgement using a key distinct from both
+ * the device handshake key and the directional session keys. */
+export function openHandshakeAck(
+ staticDh: Uint8Array,
+ clientEphPub: Uint8Array,
+ frame: Uint8Array
+): Uint8Array {
+ if (staticDh.length !== 32 || clientEphPub.length !== 32) {
+ throw new Error('[crypto] acknowledgement key inputs must be 32 bytes');
+ }
+ if (frame.length < 1 + NONCE_LEN + 16 || frame[0] !== HANDSHAKE_ACK_VERSION) {
+ throw new Error('[crypto] unsupported handshake acknowledgement');
+ }
+ const aad = new Uint8Array(33);
+ aad[0] = HANDSHAKE_ACK_VERSION;
+ aad.set(clientEphPub, 1);
+ const key = bootstrapKey(staticDh, clientEphPub, HKDF_INFO_HANDSHAKE_ACK);
+ try {
+ return xchacha20poly1305(key, frame.slice(1, 1 + NONCE_LEN), aad).decrypt(
+ frame.slice(1 + NONCE_LEN)
+ );
+ } catch {
+ throw new Error('[crypto] handshake acknowledgement authentication failed');
+ }
+}
+
+/** Encode an acknowledgement for a core-side peer or local protocol fixture. */
+export function sealHandshakeAck(
+ staticDh: Uint8Array,
+ clientEphPub: Uint8Array,
+ plaintext: Uint8Array
+): Uint8Array {
+ if (staticDh.length !== 32 || clientEphPub.length !== 32) {
+ throw new Error('[crypto] acknowledgement key inputs must be 32 bytes');
+ }
+ const aad = new Uint8Array(33);
+ aad[0] = HANDSHAKE_ACK_VERSION;
+ aad.set(clientEphPub, 1);
+ const key = bootstrapKey(staticDh, clientEphPub, HKDF_INFO_HANDSHAKE_ACK);
+ const nonce = randomBytes(NONCE_LEN);
+ const ciphertext = xchacha20poly1305(key, nonce, aad).encrypt(plaintext);
+ const frame = new Uint8Array(1 + NONCE_LEN + ciphertext.length);
+ frame[0] = HANDSHAKE_ACK_VERSION;
+ frame.set(nonce, 1);
+ frame.set(ciphertext, 1 + NONCE_LEN);
+ return frame;
+}
+
// -- replay tracker ----------------------------------------------------------
/** Sliding-window replay tracker over raw nonce bytes. */
diff --git a/app/src/services/transport/TunnelTransport.test.ts b/app/src/services/transport/TunnelTransport.test.ts
index 1c731e9364..cf6597f252 100644
--- a/app/src/services/transport/TunnelTransport.test.ts
+++ b/app/src/services/transport/TunnelTransport.test.ts
@@ -14,6 +14,7 @@ import {
open,
ReplayTracker,
seal,
+ sealHandshakeAck,
TunnelCipher,
type TunnelKeypair,
} from '../../lib/tunnel/crypto';
@@ -86,7 +87,11 @@ async function connectTransport(
server_ephemeral_pubkey: base64urlEncode(serverEphemeral.publicKey),
})
);
- fire('tunnel:frame', { payload: base64urlEncode(seal(internals.staticDhKey!, ack)) });
+ fire('tunnel:frame', {
+ payload: base64urlEncode(
+ sealHandshakeAck(internals.staticDhKey!, internals.clientEphemeralKeypair!.publicKey, ack)
+ ),
+ });
await connectP;
return new TunnelCipher('server', keys);
}
@@ -260,12 +265,21 @@ describe('TunnelTransport', () => {
fire('tunnel:connected');
await Promise.resolve();
- type HandshakeInternals = { staticDhKey: Uint8Array | null };
+ type HandshakeInternals = {
+ staticDhKey: Uint8Array | null;
+ clientEphemeralKeypair: TunnelKeypair | null;
+ };
const internals = transport as unknown as HandshakeInternals;
expect(internals.staticDhKey).toBeTruthy();
fire('tunnel:frame', {
- payload: base64urlEncode(seal(internals.staticDhKey!, new TextEncoder().encode('not json'))),
+ payload: base64urlEncode(
+ sealHandshakeAck(
+ internals.staticDhKey!,
+ internals.clientEphemeralKeypair!.publicKey,
+ new TextEncoder().encode('not json')
+ )
+ ),
});
await expect(connectP).rejects.toThrow();
@@ -290,13 +304,20 @@ describe('TunnelTransport', () => {
fire('tunnel:connected');
await Promise.resolve();
- type HandshakeInternals = { staticDhKey: Uint8Array | null };
+ type HandshakeInternals = {
+ staticDhKey: Uint8Array | null;
+ clientEphemeralKeypair: TunnelKeypair | null;
+ };
const internals = transport as unknown as HandshakeInternals;
expect(internals.staticDhKey).toBeTruthy();
fire('tunnel:frame', {
payload: base64urlEncode(
- seal(internals.staticDhKey!, new TextEncoder().encode(JSON.stringify({ kind: 'nope' })))
+ sealHandshakeAck(
+ internals.staticDhKey!,
+ internals.clientEphemeralKeypair!.publicKey,
+ new TextEncoder().encode(JSON.stringify({ kind: 'nope' }))
+ )
),
});
await expect(connectP).rejects.toThrow(/invalid handshake ack/i);
diff --git a/app/src/services/transport/TunnelTransport.ts b/app/src/services/transport/TunnelTransport.ts
index 79407bc7a9..3c05330619 100644
--- a/app/src/services/transport/TunnelTransport.ts
+++ b/app/src/services/transport/TunnelTransport.ts
@@ -20,7 +20,7 @@ import {
deriveSharedSecret,
generateKeypair,
keypairFromSecretKey,
- open,
+ openHandshakeAck,
ReplayTracker,
sealHandshake,
TunnelCipher,
@@ -61,7 +61,7 @@ export class TunnelTransport implements CoreTransport {
reject: (err: Error) => void;
timeoutId: ReturnType<typeof setTimeout>;
} | null = null;
- private readonly replayTracker = new ReplayTracker();
+ private replayTracker = new ReplayTracker();
private readonly reassembler = new Reassembler();
private readonly rateLimiter = new TokenBucket(100, 100);
@@ -138,6 +138,7 @@ export class TunnelTransport implements CoreTransport {
this.staticDhKey = null;
this.clientEphemeralKeypair = null;
this.cipher = null;
+ this.replayTracker = new ReplayTracker();
this._connectPromise = null;
});
@@ -233,7 +234,11 @@ export class TunnelTransport implements CoreTransport {
let plaintext: Uint8Array;
try {
- plaintext = open(this.staticDhKey, frameBytes, this.replayTracker);
+ plaintext = openHandshakeAck(
+ this.staticDhKey,
+ this.clientEphemeralKeypair.publicKey,
+ frameBytes
+ );
} catch (err) {
this.handshakeAck?.reject(err as Error);
logErr('[tunnel] handshake ack open failed: %s', (err as Error).message);
diff --git a/crates/openhuman-core/src/security/devices/bus.rs b/crates/openhuman-core/src/security/devices/bus.rs
index d2dc9ef608..704da13bc2 100644
--- a/crates/openhuman-core/src/security/devices/bus.rs
+++ b/crates/openhuman-core/src/security/devices/bus.rs
@@ -12,7 +12,9 @@ use std::sync::{Arc, OnceLock};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::security::devices::crypto::{
- base64url_decode, base64url_encode, derive_session_keys, TunnelCipher, TunnelRole,
+ base64url_decode, base64url_encode, derive_bootstrap_key, derive_session_keys, TunnelCipher,
+ TunnelRole, HANDSHAKE_ACK_VERSION, HANDSHAKE_VERSION, HKDF_INFO_HANDSHAKE,
+ HKDF_INFO_HANDSHAKE_ACK,
};
use crate::security::devices::rpc::{
ACTIVE_CIPHERS, PEER_STATUS, PENDING_KEYPAIRS, PENDING_SESSIONS,
@@ -207,9 +209,9 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
// Wire format for the handshake frame:
//
- // 0x01 || eph_pub(32) || nonce(24) || ciphertext+tag
+ // 0x03 || eph_pub(32) || nonce(24) || ciphertext+tag
//
- // Version byte 0x01 = "sealed-handshake". The device generates an ephemeral
+ // Version byte 0x03 = "sealed-handshake". The device generates an ephemeral
// X25519 keypair, performs DH with corePubkey, then seals its static pubkey
// (32 bytes) with XChaCha20-Poly1305. The core decrypts using the same
// ephemeral DH to recover the device's static public key, then performs a
@@ -217,10 +219,16 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
//
// Version byte 0x02 = "encrypted-frame" (used post-handshake, handled later).
//
- // Fallback: if the frame begins with a printable ASCII character other than
- // 0x01/0x02, treat the entire payload as a base64url(device_pubkey) string
- // for backward compat with any pre-Layer-2 devices.
- let handshake_payload = if frame_bytes.first() == Some(&0x01) {
+ // Old raw-DH handshakes and plaintext pubkeys are rejected. The peer must
+ // upgrade its tunnel implementation before connecting again.
+ if frame_bytes.first() != Some(&HANDSHAKE_VERSION) {
+ log::warn!(
+ "[devices/bus] unsupported handshake version channel_id={}",
+ channel_id
+ );
+ return;
+ }
+ let handshake_payload = {
// Sealed handshake: eph_pub(32) || nonce(24) || ciphertext+tag
if frame_bytes.len() < 1 + 32 + 24 + 16 {
log::warn!(
@@ -264,6 +272,15 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
return;
}
};
+ // Bind both public keys and the wire marker to the bootstrap key.
+ let mut salt = [0u8; 64];
+ salt[..32].copy_from_slice(&eph_pub_bytes);
+ let core_pub = match base64url_decode(&core_keypair.pubkey_b64) {
+ Ok(pubkey) if pubkey.len() == 32 => pubkey,
+ _ => return,
+ };
+ salt[32..].copy_from_slice(&core_pub);
+ let handshake_key = derive_bootstrap_key(&dh_key, &salt, HKDF_INFO_HANDSHAKE);
// Decrypt: nonce(24) || ciphertext+tag at offset 33.
let inner_frame = &frame_bytes[33..];
let res = {
@@ -271,16 +288,22 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
// stripped the eph_pub prefix. Reconstruct a plain open call by using
// XChaCha20 directly on nonce||ct (inner_frame).
use chacha20poly1305::{
- aead::{Aead, KeyInit},
+ aead::{Aead, KeyInit, Payload},
XChaCha20Poly1305, XNonce,
};
if inner_frame.len() < 24 {
Err("[devices/bus] inner_frame too short for nonce".to_string())
} else {
let nonce = XNonce::from_slice(&inner_frame[..24]);
- let aead = XChaCha20Poly1305::new((&dh_key).into());
- aead.decrypt(nonce, &inner_frame[24..])
- .map_err(|_| "[devices/bus] AEAD decrypt failed on handshake frame".to_string())
+ let aead = XChaCha20Poly1305::new((&handshake_key).into());
+ aead.decrypt(
+ nonce,
+ Payload {
+ msg: &inner_frame[24..],
+ aad: &frame_bytes[..33],
+ },
+ )
+ .map_err(|_| "[devices/bus] AEAD decrypt failed on handshake frame".to_string())
}
};
match res {
@@ -302,22 +325,6 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
return;
}
}
- } else {
- // Fallback: plaintext base64url-encoded device pubkey (pre-Layer-2 compat).
- log::debug!(
- "[devices/bus] fallback plaintext handshake channel_id={}",
- channel_id
- );
- match String::from_utf8(frame_bytes) {
- Ok(s) => parse_handshake_payload(&s),
- Err(_) => {
- log::warn!(
- "[devices/bus] tunnel:frame payload not valid UTF-8 for channel_id={}",
- channel_id
- );
- return;
- }
- }
};
let device_pubkey_b64 = handshake_payload.device_pubkey;
@@ -339,15 +346,19 @@ async fn handle_tunnel_frame(channel_id: &str, payload_b64: &str) {
}
};
- if let Some(client_eph_pubkey) = handshake_payload.client_ephemeral_pubkey {
- if let Err(e) = install_v2_cipher_and_ack(channel_id, &static_dh, &client_eph_pubkey).await
- {
- log::error!(
- "[devices/bus] v2 handshake ack failed channel_id={}: {e}",
- channel_id
- );
- return;
- }
+ let Some(client_eph_pubkey) = handshake_payload.client_ephemeral_pubkey else {
+ log::warn!(
+ "[devices/bus] handshake missing client ephemeral key channel_id={}",
+ channel_id
+ );
+ return;
+ };
+ if let Err(e) = install_v2_cipher_and_ack(channel_id, &static_dh, &client_eph_pubkey).await {
+ log::error!(
+ "[devices/bus] v2 handshake ack failed channel_id={}: {e}",
+ channel_id
+ );
+ return;
}
// Persist the paired device. The pending session holds both the label
@@ -472,10 +483,28 @@ async fn install_v2_cipher_and_ack(
});
let ack_bytes = serde_json::to_vec(&ack)
.map_err(|e| format!("[devices/bus] handshake ack serialize failed: {e}"))?;
- let bootstrap_cipher = TunnelCipher::new(static_dh);
- let ack_frame = bootstrap_cipher
- .seal(&ack_bytes)
+ use chacha20poly1305::{
+ aead::{Aead, AeadCore, KeyInit, OsRng, Payload},
+ XChaCha20Poly1305,
+ };
+ let ack_key = derive_bootstrap_key(static_dh, &client_eph_arr, HKDF_INFO_HANDSHAKE_ACK);
+ let ack_nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
+ let mut ack_aad = [0u8; 33];
+ ack_aad[0] = HANDSHAKE_ACK_VERSION;
+ ack_aad[1..].copy_from_slice(&client_eph_arr);
+ let ack_ciphertext = XChaCha20Poly1305::new((&ack_key).into())
+ .encrypt(
+ &ack_nonce,
+ Payload {
+ msg: &ack_bytes,
+ aad: &ack_aad,
+ },
+ )
.map_err(|e| format!("[devices/bus] handshake ack seal failed: {e}"))?;
+ let mut ack_frame = Vec::with_capacity(1 + 24 + ack_ciphertext.len());
+ ack_frame.push(HANDSHAKE_ACK_VERSION);
+ ack_frame.extend_from_slice(&ack_nonce);
+ ack_frame.extend_from_slice(&ack_ciphertext);
let ack_b64 = base64url_encode(&ack_frame);
emit_frame(channel_id, &ack_b64).await?;
log::info!(
diff --git a/crates/openhuman-core/src/security/devices/crypto.rs b/crates/openhuman-core/src/security/devices/crypto.rs
index 063ae6f395..b0eb5b75fe 100644
--- a/crates/openhuman-core/src/security/devices/crypto.rs
+++ b/crates/openhuman-core/src/security/devices/crypto.rs
@@ -19,6 +19,14 @@
//! authenticate the peer via the paired QR-code provenance; the ephemeral
//! DH provides forward secrecy.
//!
+//! Bootstrap messages use separate wire markers and HKDF domains:
+//! `0x03 || client_handshake_eph_pub || nonce || ciphertext` authenticates
+//! its 33-byte header and derives its key from the ephemeral-to-core DH,
+//! salted by `client_handshake_eph_pub || core_static_pub`.
+//! `0x04 || nonce || ciphertext` authenticates `0x04 || client_session_eph_pub`
+//! and derives its key from static DH, salted by `client_session_eph_pub`.
+//! Pre-upgrade raw-DH and plaintext handshakes are rejected.
+//!
//! Replay protection still uses a sliding window over the last
//! `WINDOW_SIZE` raw nonces, applied per opener.
@@ -38,6 +46,12 @@ pub const FRAME_VERSION: u8 = 0x02;
/// Previous frame version. Surfaced so callers can build a stable error
/// message when an older peer sends a v1 frame post-upgrade.
pub const LEGACY_FRAME_VERSION_V1: u8 = 0x01;
+/// Bootstrap messages use distinct wire markers so a legacy handshake cannot
+/// silently bypass the new key schedule.
+pub const HANDSHAKE_VERSION: u8 = 0x03;
+pub const HANDSHAKE_ACK_VERSION: u8 = 0x04;
+pub const HKDF_INFO_HANDSHAKE: &[u8] = b"openhuman-tunnel/v3/handshake";
+pub const HKDF_INFO_HANDSHAKE_ACK: &[u8] = b"openhuman-tunnel/v3/handshake-ack";
const NONCE_LEN: usize = 24; // XChaCha20-Poly1305 nonce = 192 bits
const WINDOW_SIZE: usize = 128; // replay protection window
@@ -48,6 +62,17 @@ const WINDOW_SIZE: usize = 128; // replay protection window
pub const HKDF_INFO_C2S: &[u8] = b"openhuman-tunnel/v1/c2s";
pub const HKDF_INFO_S2C: &[u8] = b"openhuman-tunnel/v1/s2c";
+/// Extract and expand bootstrap DH material before using it with an AEAD.
+/// The public salt binds the key to the exchange's ephemeral public key;
+/// the info tag separates the two bootstrap directions and session traffic.
+pub fn derive_bootstrap_key(dh: &[u8; 32], salt: &[u8], info: &[u8]) -> [u8; 32] {
+ let mut key = [0u8; 32];
+ Hkdf::<Sha256>::new(Some(salt), dh)
+ .expand(info, &mut key)
+ .expect("32-byte HKDF output fits SHA-256 limit");
+ key
+}
+
// ---------------------------------------------------------------------------
// Key material
// ---------------------------------------------------------------------------
@@ -76,9 +101,10 @@ impl DeviceKeypair {
}
}
- /// Perform X25519 DH with the peer's public key and derive a symmetric key.
+ /// Perform X25519 DH with the peer's public key.
///
- /// Returns the 32-byte shared secret (suitable for XChaCha20-Poly1305 key init).
+ /// Returns raw DH material for an HKDF key schedule; it must never be
+ /// passed directly to an AEAD constructor.
pub fn derive_shared_secret(&self, peer_pubkey_b64: &str) -> Result<[u8; 32], String> {
let peer_bytes = base64url_decode(peer_pubkey_b64)
.map_err(|e| format!("[devices/crypto] bad peer pubkey: {e}"))?;
@@ -91,6 +117,9 @@ impl DeviceKeypair {
let peer_arr: [u8; 32] = peer_bytes.try_into().unwrap();
let peer_public = PublicKey::from(peer_arr);
let dh = self.private.diffie_hellman(&peer_public);
+ if dh.as_bytes().iter().all(|&byte| byte == 0) {
+ return Err("[devices/crypto] non-contributory peer public key".into());
+ }
log::debug!("[devices/crypto] DH completed, shared secret derived");
Ok(*dh.as_bytes())
}
@@ -189,14 +218,16 @@ pub struct TunnelCipher {
}
impl TunnelCipher {
- /// LEGACY: construct from a single 32-byte symmetric key. Both seal
- /// and open use the same key — preserved for the layer-2 sealed
- /// handshake path in `devices/bus.rs` that lives outside the
- /// post-pairing session. New session callers MUST go through
- /// [`Self::for_role`] which holds directional subkeys.
+ /// Compatibility constructor for older unit fixtures. Production
+ /// sessions use [`Self::for_role`] with directional subkeys.
+ #[cfg(test)]
pub fn new(key: &[u8; 32]) -> Self {
- log::debug!("[devices/crypto] TunnelCipher created (legacy single-key mode)");
- let cipher = XChaCha20Poly1305::new(key.into());
+ let derived = derive_bootstrap_key(
+ key,
+ b"openhuman-tunnel/compat",
+ b"openhuman-tunnel/compat/symmetric",
+ );
+ let cipher = XChaCha20Poly1305::new((&derived).into());
Self {
seal_cipher: cipher.clone(),
open_cipher: cipher,