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:
@@ -295,11 +295,14 @@ impl ApiHandler {
|
||||
from_pubkey: Option<String>,
|
||||
message: Option<String>,
|
||||
signature: Option<String>,
|
||||
#[serde(default)]
|
||||
encrypted: bool,
|
||||
}
|
||||
let incoming: Incoming = serde_json::from_slice(&body).unwrap_or(Incoming {
|
||||
from_pubkey: None,
|
||||
message: None,
|
||||
signature: None,
|
||||
encrypted: false,
|
||||
});
|
||||
if let (Some(from), Some(msg)) = (incoming.from_pubkey.as_ref(), incoming.message.as_ref()) {
|
||||
// Validate from_pubkey is a valid hex ed25519 pubkey
|
||||
@@ -322,17 +325,44 @@ impl ApiHandler {
|
||||
.unwrap());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No signature — accept but mark as unverified
|
||||
tracing::warn!("Node message from {} has no signature — unverified", &from[..16.min(from.len())]);
|
||||
}
|
||||
// Sanitize log output to prevent log injection
|
||||
|
||||
// Decrypt if the message is E2E encrypted
|
||||
let plaintext = if incoming.encrypted {
|
||||
// Load our identity to derive shared secret
|
||||
let data_dir = std::path::Path::new("/var/lib/archipelago");
|
||||
let identity_dir = data_dir.join("identity");
|
||||
match crate::identity::NodeIdentity::load_or_create(&identity_dir).await {
|
||||
Ok(node_id) => {
|
||||
match node_msg::decrypt_from_peer(node_id.signing_key(), from, msg) {
|
||||
Ok(decrypted) => {
|
||||
tracing::info!("Decrypted E2E message from {}...", &from[..16.min(from.len())]);
|
||||
decrypted
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("E2E decryption failed from {}: {}", &from[..16.min(from.len())], e);
|
||||
return Ok(Response::builder()
|
||||
.status(StatusCode::BAD_REQUEST)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(hyper::Body::from(r#"{"error":"Decryption failed"}"#))
|
||||
.unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Cannot decrypt: identity load failed: {}", e);
|
||||
msg.clone()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
msg.clone()
|
||||
};
|
||||
|
||||
let safe_from = sanitize_log_string(from);
|
||||
let safe_msg = sanitize_log_string(msg);
|
||||
let safe_msg = sanitize_log_string(&plaintext);
|
||||
tracing::info!("Received message from {}: {}", safe_from, safe_msg);
|
||||
// Sanitize stored message content (strip HTML entities)
|
||||
let clean_from = sanitize_html(from);
|
||||
let clean_msg = sanitize_html(msg);
|
||||
let clean_msg = sanitize_html(&plaintext);
|
||||
node_msg::store_received(&clean_from, &clean_msg).await;
|
||||
}
|
||||
Ok(Response::builder()
|
||||
|
||||
@@ -89,7 +89,25 @@ impl RpcHandler {
|
||||
|
||||
let (data, _) = self.state_manager.get_snapshot().await;
|
||||
let pubkey = data.server_info.pubkey.clone();
|
||||
node_message::send_to_peer(onion, &pubkey, message).await?;
|
||||
|
||||
// Load signing key for E2E encryption
|
||||
let identity_dir = self.config.data_dir.join("identity");
|
||||
let node_id = crate::identity::NodeIdentity::load_or_create(&identity_dir).await?;
|
||||
|
||||
// Look up recipient's pubkey from federation nodes
|
||||
let fed_nodes = federation::load_nodes(&self.config.data_dir).await.unwrap_or_default();
|
||||
let recipient_pubkey = fed_nodes.iter()
|
||||
.find(|n| n.onion == onion || n.onion == format!("{}.onion", onion)
|
||||
|| format!("{}.onion", n.onion) == onion)
|
||||
.map(|n| n.pubkey.clone());
|
||||
|
||||
node_message::send_to_peer(
|
||||
onion,
|
||||
&pubkey,
|
||||
message,
|
||||
Some(node_id.signing_key()),
|
||||
recipient_pubkey.as_deref(),
|
||||
).await?;
|
||||
Ok(serde_json::json!({ "ok": true, "sent_to": onion }))
|
||||
}
|
||||
|
||||
|
||||
@@ -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")?;
|
||||
|
||||
Reference in New Issue
Block a user