diff --git a/Cargo.toml b/Cargo.toml index 56360e7..37b1b10 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] } diff --git a/dev/config.toml b/dev/config.toml index 9cc91d4..e2be742 100644 --- a/dev/config.toml +++ b/dev/config.toml @@ -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 /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" diff --git a/gateway/Cargo.toml b/gateway/Cargo.toml index 8636aa8..0120eed 100644 --- a/gateway/Cargo.toml +++ b/gateway/Cargo.toml @@ -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"] } diff --git a/gateway/src/bootstrap/server_identity.rs b/gateway/src/bootstrap/server_identity.rs index ff0382d..0cc6806 100644 --- a/gateway/src/bootstrap/server_identity.rs +++ b/gateway/src/bootstrap/server_identity.rs @@ -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()) } diff --git a/gateway/src/domain/config.rs b/gateway/src/domain/config.rs index 2289b34..0e9cf9b 100644 --- a/gateway/src/domain/config.rs +++ b/gateway/src/domain/config.rs @@ -90,17 +90,34 @@ pub struct GatewayConfig { /// Defaults to 10. #[serde(default)] pub message_rate_burst: Option, - /// 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, + /// 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, - /// Path to TLS private key file (PEM). + /// Path to the TLS private key (PEM). #[serde(default)] pub tls_key_path: Option, } +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 { 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(); + } +} diff --git a/gateway/src/handler/channel/create.rs b/gateway/src/handler/channel/create.rs index 728961e..d622aa5 100644 --- a/gateway/src/handler/channel/create.rs +++ b/gateway/src/handler/channel/create.rs @@ -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(()) } diff --git a/gateway/src/handler/channel/edit.rs b/gateway/src/handler/channel/edit.rs index 4649703..a75fe00 100644 --- a/gateway/src/handler/channel/edit.rs +++ b/gateway/src/handler/channel/edit.rs @@ -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(()); diff --git a/gateway/src/handler/channel/join.rs b/gateway/src/handler/channel/join.rs index 6975f5f..717c75d 100644 --- a/gateway/src/handler/channel/join.rs +++ b/gateway/src/handler/channel/join.rs @@ -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?; } diff --git a/gateway/src/handler/channel/join/tests.rs b/gateway/src/handler/channel/join/tests.rs index 0a865a1..bf69259 100644 --- a/gateway/src/handler/channel/join/tests.rs +++ b/gateway/src/handler/channel/join/tests.rs @@ -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()) diff --git a/gateway/src/handler/channel/leave.rs b/gateway/src/handler/channel/leave.rs index b3c4638..262f065 100644 --- a/gateway/src/handler/channel/leave.rs +++ b/gateway/src/handler/channel/leave.rs @@ -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 { diff --git a/gateway/src/handler/channel/mod.rs b/gateway/src/handler/channel/mod.rs index 3418049..11ebf57 100644 --- a/gateway/src/handler/channel/mod.rs +++ b/gateway/src/handler/channel/mod.rs @@ -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 } diff --git a/gateway/src/handler/content/presence.rs b/gateway/src/handler/content/presence.rs index 2029a69..a5a405c 100644 --- a/gateway/src/handler/content/presence.rs +++ b/gateway/src/handler/content/presence.rs @@ -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 = state.presences.read().await.values().cloned().collect(); - io::send_encrypted( + io::send_frame( stream, PacketId::PresenceSync, seq, &to_payload(&PresenceSyncPayload { presences }), - crypto, ) .await?; Ok(()) diff --git a/gateway/src/handler/content/read_receipt.rs b/gateway/src/handler/content/read_receipt.rs index 69c2210..9b2044d 100644 --- a/gateway/src/handler/content/read_receipt.rs +++ b/gateway/src/handler/content/read_receipt.rs @@ -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)?; diff --git a/gateway/src/handler/deliver.rs b/gateway/src/handler/deliver.rs index f360e3b..a74fb53 100644 --- a/gateway/src/handler/deliver.rs +++ b/gateway/src/handler/deliver.rs @@ -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 } diff --git a/gateway/src/handler/direct_message/history.rs b/gateway/src/handler/direct_message/history.rs index e34ff50..bfa8c4e 100644 --- a/gateway/src/handler/direct_message/history.rs +++ b/gateway/src/handler/direct_message/history.rs @@ -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(()) } diff --git a/gateway/src/handler/direct_message/send.rs b/gateway/src/handler/direct_message/send.rs index 2de0bd3..ae090a3 100644 --- a/gateway/src/handler/direct_message/send.rs +++ b/gateway/src/handler/direct_message/send.rs @@ -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(()) } diff --git a/gateway/src/handler/direct_message/start.rs b/gateway/src/handler/direct_message/start.rs index c624b12..783ea5c 100644 --- a/gateway/src/handler/direct_message/start.rs +++ b/gateway/src/handler/direct_message/start.rs @@ -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(()) } diff --git a/gateway/src/handler/dispatch.rs b/gateway/src/handler/dispatch.rs index 0d29843..69f52b8 100644 --- a/gateway/src/handler/dispatch.rs +++ b/gateway/src/handler/dispatch.rs @@ -30,14 +30,13 @@ pub async fn dispatch( } 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( ctx.seq, session_id, &m.channel_id, - ctx.crypto, ctx.state, addr, ) @@ -56,217 +54,140 @@ pub async fn dispatch( } 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( 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), diff --git a/gateway/src/handler/e2ee/key_exchange.rs b/gateway/src/handler/e2ee/key_exchange.rs index c44476b..b01eefe 100644 --- a/gateway/src/handler/e2ee/key_exchange.rs +++ b/gateway/src/handler/e2ee/key_exchange.rs @@ -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)?; diff --git a/gateway/src/handler/e2ee/message.rs b/gateway/src/handler/e2ee/message.rs index 57bcd05..54bc0a3 100644 --- a/gateway/src/handler/e2ee/message.rs +++ b/gateway/src/handler/e2ee/message.rs @@ -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(()) } diff --git a/gateway/src/handler/friends/decline.rs b/gateway/src/handler/friends/decline.rs index 102360c..71f57cf 100644 --- a/gateway/src/handler/friends/decline.rs +++ b/gateway/src/handler/friends/decline.rs @@ -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(()) diff --git a/gateway/src/handler/friends/list.rs b/gateway/src/handler/friends/list.rs index f2844fb..ebf2c25 100644 --- a/gateway/src/handler/friends/list.rs +++ b/gateway/src/handler/friends/list.rs @@ -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(()) diff --git a/gateway/src/handler/friends/manage.rs b/gateway/src/handler/friends/manage.rs index 9ae4c17..97da7b5 100644 --- a/gateway/src/handler/friends/manage.rs +++ b/gateway/src/handler/friends/manage.rs @@ -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(()) diff --git a/gateway/src/handler/friends/mod.rs b/gateway/src/handler/friends/mod.rs index 35b38d4..bafe386 100644 --- a/gateway/src/handler/friends/mod.rs +++ b/gateway/src/handler/friends/mod.rs @@ -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 } diff --git a/gateway/src/handler/friends/requests.rs b/gateway/src/handler/friends/requests.rs index eeef291..c309e62 100644 --- a/gateway/src/handler/friends/requests.rs +++ b/gateway/src/handler/friends/requests.rs @@ -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(()) diff --git a/gateway/src/handler/guild/audit.rs b/gateway/src/handler/guild/audit.rs index 80b66a4..ca065c6 100644 --- a/gateway/src/handler/guild/audit.rs +++ b/gateway/src/handler/guild/audit.rs @@ -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(()) } diff --git a/gateway/src/handler/guild/crud.rs b/gateway/src/handler/guild/crud.rs index 51fff93..22e9f36 100644 --- a/gateway/src/handler/guild/crud.rs +++ b/gateway/src/handler/guild/crud.rs @@ -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(()) diff --git a/gateway/src/handler/guild/invites.rs b/gateway/src/handler/guild/invites.rs index 98bc480..6434343 100644 --- a/gateway/src/handler/guild/invites.rs +++ b/gateway/src/handler/guild/invites.rs @@ -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(()) diff --git a/gateway/src/handler/guild/list.rs b/gateway/src/handler/guild/list.rs index f36d79b..b92d562 100644 --- a/gateway/src/handler/guild/list.rs +++ b/gateway/src/handler/guild/list.rs @@ -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(()) diff --git a/gateway/src/handler/guild/members.rs b/gateway/src/handler/guild/members.rs index aa6f562..f8d98c3 100644 --- a/gateway/src/handler/guild/members.rs +++ b/gateway/src/handler/guild/members.rs @@ -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(()) diff --git a/gateway/src/handler/guild/members_list.rs b/gateway/src/handler/guild/members_list.rs index af7efef..9b6d9fd 100644 --- a/gateway/src/handler/guild/members_list.rs +++ b/gateway/src/handler/guild/members_list.rs @@ -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(()) } diff --git a/gateway/src/handler/guild/mod.rs b/gateway/src/handler/guild/mod.rs index aeb7706..2e2cf45 100644 --- a/gateway/src/handler/guild/mod.rs +++ b/gateway/src/handler/guild/mod.rs @@ -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 } diff --git a/gateway/src/handler/guild/roles.rs b/gateway/src/handler/guild/roles.rs index f87d6bc..78f359c 100644 --- a/gateway/src/handler/guild/roles.rs +++ b/gateway/src/handler/guild/roles.rs @@ -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(()) diff --git a/gateway/src/handler/mod.rs b/gateway/src/handler/mod.rs index d179a7f..1a88920 100644 --- a/gateway/src/handler/mod.rs +++ b/gateway/src/handler/mod.rs @@ -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, } diff --git a/gateway/src/handler/run.rs b/gateway/src/handler/run.rs index cf97664..fc46869 100644 --- a/gateway/src/handler/run.rs +++ b/gateway/src/handler/run.rs @@ -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( stream: &mut S, addr: std::net::SocketAddr, seq: &mut u32, session_id: &str, - crypto: &SessionCrypto, state: &State, bcast_rx: &mut broadcast::Receiver, ) -> 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( } 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(()), } diff --git a/gateway/src/lib.rs b/gateway/src/lib.rs index 81ad8ed..7fe0a4a 100644 --- a/gateway/src/lib.rs +++ b/gateway/src/lib.rs @@ -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, voice_member_tx: Option) -> 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, voice_member_tx: Option, voice_member_tx: Option, + tls_config: Arc, state: State, max_connections: Option, conn_count: Arc, ) -> 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, - conn_count: Arc, -) -> 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( 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( .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( debug!("{addr} cleaned up"); result } - -fn load_or_generate_tls_certs( - cfg: &config::GatewayConfig, -) -> Result<( - Vec>, - 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)) - } - } -} diff --git a/gateway/src/media/mod.rs b/gateway/src/media/mod.rs index 924a0a1..4fc4a66 100644 --- a/gateway/src/media/mod.rs +++ b/gateway/src/media/mod.rs @@ -294,7 +294,7 @@ pub async fn handle( Ok(()) } Err(error) => { - io::send_encrypted( + io::send_frame( ctx.stream, PacketId::Error, ctx.seq, @@ -302,7 +302,6 @@ pub async fn handle( code: proto::ErrorCode::PermissionDenied as u32, message: format!("media: {error}"), }), - ctx.crypto, ) .await } diff --git a/gateway/src/net/handshake.rs b/gateway/src/net/handshake.rs index 2ade92d..0adbd9a 100644 --- a/gateway/src/net/handshake.rs +++ b/gateway/src/net/handshake.rs @@ -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 { + 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 { + 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 { + // 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, 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" + ); + } } diff --git a/gateway/src/net/io.rs b/gateway/src/net/io.rs index 1169d7c..aef6256 100644 --- a/gateway/src/net/io.rs +++ b/gateway/src/net/io.rs @@ -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)> { 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)> { - 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, 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)> { 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 { - 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 { + 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()); } } diff --git a/gateway/src/proto/mod.rs b/gateway/src/proto/mod.rs index 1aaffde..f8eeb23 100644 --- a/gateway/src/proto/mod.rs +++ b/gateway/src/proto/mod.rs @@ -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}; diff --git a/gateway/src/tls.rs b/gateway/src/tls.rs new file mode 100644 index 0000000..66e5a36 --- /dev/null +++ b/gateway/src/tls.rs @@ -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>, + 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 { + 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>> { + CertificateDer::pem_slice_iter(pem) + .collect::, _>>() + .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::().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::() { + 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 { + 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> { + 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()); + } +} diff --git a/gateway/src/webhooks/management.rs b/gateway/src/webhooks/management.rs index 6eb3c17..25aeb29 100644 --- a/gateway/src/webhooks/management.rs +++ b/gateway/src/webhooks/management.rs @@ -102,12 +102,11 @@ pub async fn handle( .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( } h }; - io::send_encrypted( + io::send_frame( ctx.stream, PacketId::WebhookResult, ctx.seq, @@ -230,7 +229,6 @@ pub async fn handle( secret, request_id, }), - ctx.crypto, ) .await } @@ -240,7 +238,7 @@ async fn error( code: ErrorCode, msg: &str, ) -> Result<()> { - io::send_encrypted( + io::send_frame( ctx.stream, PacketId::WebhookErrorResult, ctx.seq, @@ -249,7 +247,6 @@ async fn error( code: code as u32, message: msg.into(), }), - ctx.crypto, ) .await } diff --git a/gateway/src/webhooks/tests.rs b/gateway/src/webhooks/tests.rs index 1d99dd0..b8ed909 100644 --- a/gateway/src/webhooks/tests.rs +++ b/gateway/src/webhooks/tests.rs @@ -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); diff --git a/gateway/tests/tls_listener.rs b/gateway/tests/tls_listener.rs new file mode 100644 index 0000000..a0e4ec6 --- /dev/null +++ b/gateway/tests/tls_listener.rs @@ -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>>, +} +impl ServerCertVerifier for AcceptAll { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + _: &[CertificateDer<'_>], + _: &ServerName<'_>, + _: &[u8], + _: UnixTime, + ) -> Result { + *self.leaf.lock().unwrap() = Some(end_entity.to_vec()); + Ok(ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + 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 { + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &rustls::crypto::aws_lc_rs::default_provider().signature_verification_algorithms, + ) + } + fn supported_verify_schemes(&self) -> Vec { + rustls::crypto::aws_lc_rs::default_provider() + .signature_verification_algorithms + .supported_schemes() + } +} + +fn client_config( + versions: &[&'static rustls::SupportedProtocolVersion], + alpn: bool, +) -> (rustls::ClientConfig, Arc) { + 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> { + 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(stream: &mut S) -> (u16, u32, Vec) { + 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 { + 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, + signing_binding: Option<[u8; 32]>, +) -> (u16, Vec) { + 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); +} diff --git a/protocol/lnex.proto b/protocol/lnex.proto index 3b18f62..84fb355 100644 --- a/protocol/lnex.proto +++ b/protocol/lnex.proto @@ -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 {