feat: E2E encrypted Tor channel messages (ChaCha20-Poly1305)

Messages between federated nodes are now end-to-end encrypted:
- X25519 ECDH key agreement from existing ed25519 node identities
- HKDF-SHA256 key derivation with domain separation
- ChaCha20-Poly1305 authenticated encryption per message
- Random 12-byte nonce per message via OsRng (CSPRNG)
- Graceful fallback to plaintext if encryption fails
- Receiver auto-detects encrypted vs plaintext messages

The Tor transport was already encrypted (onion routing), this adds
application-layer E2E encryption so even a compromised receiving
backend can't read messages without the node's private key.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-03-20 09:04:43 +00:00
parent f0a403b224
commit 9b6adfc42d
3 changed files with 147 additions and 11 deletions

View File

@@ -135,6 +135,70 @@ fn within_seconds(ts1: &str, ts2: &str, secs: i64) -> bool {
}
}
// ─── E2E Encryption ─────────────────────────────────────────────
use crate::mesh::crypto;
use base64::Engine;
/// Encrypt a message for a recipient using X25519 ECDH + ChaCha20-Poly1305.
/// Returns base64-encoded ciphertext (nonce + encrypted data).
fn encrypt_for_peer(
our_signing_key: &ed25519_dalek::SigningKey,
their_pubkey_hex: &str,
plaintext: &str,
) -> Result<String> {
let their_pubkey_bytes: [u8; 32] = hex::decode(their_pubkey_hex)
.context("Invalid peer pubkey hex")?
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid peer pubkey length"))?;
let their_x25519 = crypto::ed25519_pubkey_to_x25519(&their_pubkey_bytes)?;
let our_x25519 = crypto::ed25519_secret_to_x25519(our_signing_key);
let shared = crypto::x25519_shared_secret(&our_x25519, &their_x25519);
// HKDF to derive message key (domain separation for Tor messages)
let msg_key_bytes = crypto::hkdf_sha256(
b"archipelago-tor-msg-v1",
&shared,
b"message-encryption",
32,
)?;
let msg_key: [u8; 32] = msg_key_bytes.try_into()
.map_err(|_| anyhow::anyhow!("HKDF key length mismatch"))?;
let encrypted = crypto::encrypt(&msg_key, plaintext.as_bytes())?;
Ok(base64::engine::general_purpose::STANDARD.encode(&encrypted))
}
/// Decrypt a message from a sender using X25519 ECDH + ChaCha20-Poly1305.
pub fn decrypt_from_peer(
our_signing_key: &ed25519_dalek::SigningKey,
sender_pubkey_hex: &str,
encrypted_b64: &str,
) -> Result<String> {
let sender_pubkey_bytes: [u8; 32] = hex::decode(sender_pubkey_hex)
.context("Invalid sender pubkey hex")?
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid sender pubkey length"))?;
let sender_x25519 = crypto::ed25519_pubkey_to_x25519(&sender_pubkey_bytes)?;
let our_x25519 = crypto::ed25519_secret_to_x25519(our_signing_key);
let shared = crypto::x25519_shared_secret(&our_x25519, &sender_x25519);
let msg_key_bytes = crypto::hkdf_sha256(
b"archipelago-tor-msg-v1",
&shared,
b"message-encryption",
32,
)?;
let msg_key: [u8; 32] = msg_key_bytes.try_into()
.map_err(|_| anyhow::anyhow!("HKDF key length mismatch"))?;
let encrypted = base64::engine::general_purpose::STANDARD.decode(encrypted_b64).context("Invalid base64 ciphertext")?;
let plaintext_bytes = crypto::decrypt(&msg_key, &encrypted)?;
String::from_utf8(plaintext_bytes).context("Decrypted message is not valid UTF-8")
}
// ─── Tor Messaging ──────────────────────────────────────────────
/// Tor v3 onion hostname is 56 base32 chars (a-z, 2-7). Reject invalid formats.
@@ -153,8 +217,16 @@ fn validate_onion(onion: &str) -> Result<()> {
Ok(())
}
/// Send a message to a peer over Tor.
pub async fn send_to_peer(onion: &str, from_pubkey: &str, message: &str) -> Result<()> {
/// Send an encrypted message to a peer over Tor.
/// The message is encrypted with ChaCha20-Poly1305 using an X25519 shared secret
/// derived from both nodes' ed25519 keys.
pub async fn send_to_peer(
onion: &str,
from_pubkey: &str,
message: &str,
signing_key: Option<&ed25519_dalek::SigningKey>,
recipient_pubkey: Option<&str>,
) -> Result<()> {
validate_onion(onion)?;
let host = if onion.ends_with(".onion") {
@@ -163,10 +235,26 @@ pub async fn send_to_peer(onion: &str, from_pubkey: &str, message: &str) -> Resu
format!("{}.onion", onion)
};
let url = format!("http://{}/archipelago/node-message", host);
// Encrypt message if we have both keys
let (payload_message, encrypted) = match (signing_key, recipient_pubkey) {
(Some(sk), Some(rpk)) => {
match encrypt_for_peer(sk, rpk, message) {
Ok(enc) => (enc, true),
Err(e) => {
tracing::warn!("Encryption failed, sending plaintext: {}", e);
(message.to_string(), false)
}
}
}
_ => (message.to_string(), false),
};
let body = serde_json::json!({
"from_pubkey": from_pubkey,
"message": message,
"message": payload_message,
"timestamp": chrono::Utc::now().to_rfc3339(),
"encrypted": encrypted,
});
let proxy = reqwest::Proxy::all(TOR_SOCKS).context("Invalid Tor proxy")?;