fix: harden channel access and refresh server dependencies

This commit is contained in:
Loki 2026-10-24 13:57:29 +02:00
parent 84df32a9de
commit b14f036bdb
Signed by: boba
GPG key ID: 253067914055423B
23 changed files with 1242 additions and 720 deletions

View file

@ -3,6 +3,7 @@ name = "vnox-gateway"
description = "VNOX gateway — auth, channels, sessions, permissions"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
@ -24,27 +25,23 @@ x25519-dalek.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
argon2.workspace = true
rand.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
anyhow.workspace = true
thiserror.workspace = true
toml.workspace = true
uuid.workspace = true
hex.workspace = true
axum = { version = "0.8", features = ["ws"] }
tower = "0.5"
axum = "0.8"
sqlx = { version = "0.9", features = ["sqlite", "postgres", "runtime-tokio", "tls-rustls"] }
bitflags = "2"
prost = "0.13"
prost = "0.14"
# TLS 1.3 support
rustls-pki-types = "1"
rustls = "0.23"
tokio-rustls = "0.26"
rcgen = "0.13"
rcgen = "0.14"
[build-dependencies]
prost-build = "0.13"
prost-build = "0.14"

View file

@ -1,6 +1,5 @@
use anyhow::Result;
use ed25519_dalek::SigningKey;
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
use std::path::Path;
@ -41,7 +40,7 @@ impl ServerIdentity {
return Ok(Self { signing_key });
}
let signing_key = SigningKey::generate(&mut OsRng);
let signing_key = SigningKey::generate(&mut rand::rng());
let verifying_key = signing_key.verifying_key();
let pubkey_hex = hex::encode(verifying_key.to_bytes());

View file

@ -11,9 +11,9 @@ pub fn verify_auth(challenge: &[u8; 32], pubkey: &[u8; 32], signature: &[u8; 64]
/// Random 32-byte challenge nonce for HELLO.
pub fn new_challenge() -> [u8; 32] {
use rand::RngCore;
use rand::Rng;
let mut n = [0u8; 32];
rand::thread_rng().fill_bytes(&mut n);
rand::rng().fill_bytes(&mut n);
n
}
@ -21,11 +21,10 @@ pub fn new_challenge() -> [u8; 32] {
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use rand::rngs::OsRng;
#[test]
fn verify_auth_accepts_valid_signature() {
let sk = SigningKey::generate(&mut OsRng);
let sk = SigningKey::generate(&mut rand::rng());
let vk = sk.verifying_key();
let challenge = [7u8; 32];
let sig = sk.sign(&challenge);
@ -34,7 +33,7 @@ mod tests {
#[test]
fn verify_auth_rejects_tampered_challenge() {
let sk = SigningKey::generate(&mut OsRng);
let sk = SigningKey::generate(&mut rand::rng());
let vk = sk.verifying_key();
let challenge = [7u8; 32];
let sig = sk.sign(&challenge);

View file

@ -445,7 +445,13 @@ pub struct ChannelRecord {
}
impl Storage {
pub async fn create_channel(&self, id: &str, name: &str, kind: &str, guild_id: Option<&str>) -> Result<bool> {
pub async fn create_channel(
&self,
id: &str,
name: &str,
kind: &str,
guild_id: Option<&str>,
) -> Result<bool> {
match &self.pool {
Pool::Sqlite(p) => {
let result = sqlx::query(
@ -552,7 +558,8 @@ impl Storage {
"voice" => ChannelKind::Voice,
_ => ChannelKind::Text,
};
crate::domain::channels::create(channel_store, &ch.id, &ch.name, kind, ch.guild_id).await;
crate::domain::channels::create(channel_store, &ch.id, &ch.name, kind, ch.guild_id)
.await;
}
Ok(())
}

View file

@ -98,14 +98,26 @@ pub async fn handle_channel_create(
let guild_id = req.guild_id.clone();
let created = channels::create(&state.channels, &channel_id, &channel_name, kind.clone(), guild_id.clone()).await;
let created = channels::create(
&state.channels,
&channel_id,
&channel_name,
kind.clone(),
guild_id.clone(),
)
.await;
// Persist to DB (best-effort, log and continue on failure).
#[allow(clippy::collapsible_if)]
if created {
if let Err(e) = state
.storage
.create_channel(&channel_id, &channel_name, kind.as_str(), guild_id.as_deref())
.create_channel(
&channel_id,
&channel_name,
kind.as_str(),
guild_id.as_deref(),
)
.await
{
warn!("failed to persist channel to storage: {e}");

View file

@ -29,18 +29,10 @@ pub async fn join(
state: &State,
addr: SocketAddr,
) -> Result<()> {
let prev_channel = session::get(&state.sessions, session_id)
.await
.and_then(|s| s.channel_id);
if prev_channel.as_deref() == Some(channel_id) {
let Some(sess) = session::get(&state.sessions, session_id).await else {
return Ok(());
}
if let Some(prev) = prev_channel {
channels::leave(&state.channels, &prev, session_id).await;
broadcast_leave(state, &prev, session_id).await;
}
};
let prev_channel = sess.channel_id;
let ch = match channels::get_channel(&state.channels, channel_id).await {
Some(c) => c,
@ -60,6 +52,40 @@ pub async fn join(
}
};
// Validate the destination before changing membership or exposing its history.
// Role assignments alone are insufficient: a kicked user can retain stale roles.
if let Some(guild_id) = ch.guild_id.as_deref() {
let is_member = state
.storage
.list_user_guilds(&sess.user_id)
.await?
.iter()
.any(|guild| guild.id == guild_id);
if !is_member {
io::send_encrypted(
stream,
PacketId::Error,
seq,
&to_payload(&proto::ErrorPayload {
code: proto::ErrorCode::PermissionDenied as u32,
message: "guild membership required".into(),
}),
crypto,
)
.await?;
return Ok(());
}
}
if prev_channel.as_deref() == Some(channel_id) {
return Ok(());
}
if let Some(prev) = prev_channel {
channels::leave(&state.channels, &prev, session_id).await;
broadcast_leave(state, &prev, session_id).await;
}
channels::join(&state.channels, channel_id, session_id).await;
set_channel(state, session_id, Some(channel_id.into())).await;
@ -130,3 +156,6 @@ pub async fn join(
info!("session {} joined {channel_id}", &session_id[..8]);
Ok(())
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,145 @@
use super::*;
use std::sync::{Arc, atomic::AtomicUsize};
async fn fixture() -> (State, String) {
let storage = crate::domain::storage::Storage::connect_sqlite(":memory:")
.await
.unwrap();
let config = toml::from_str(include_str!("../../../../../dev/config.toml")).unwrap();
let identity_dir =
std::env::temp_dir().join(format!("vnox-join-test-{}", uuid::Uuid::new_v4()));
let identity =
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&identity_dir).unwrap();
std::fs::remove_file(identity_dir.join("server_identity.json")).unwrap();
std::fs::remove_dir(identity_dir).unwrap();
let (broadcast, _) = tokio::sync::broadcast::channel(16);
let state = State::new(
session::new_store(),
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,
);
let sess = session::create(&state.sessions, "visitor".into(), "Visitor".into()).await;
channels::join(&state.channels, "general", &sess.session_id).await;
set_channel(&state, &sess.session_id, Some("general".into())).await;
(state, sess.session_id)
}
async fn attempt_join(state: &State, session_id: &str, channel_id: &str) {
let (mut stream, _peer) = tokio::io::duplex(65536);
join(
&mut stream,
&mut 0,
session_id,
channel_id,
&SessionCrypto::derive(&[7; 32], session_id),
state,
"127.0.0.1:12345".parse().unwrap(),
)
.await
.unwrap();
}
#[tokio::test]
async fn missing_channel_keeps_previous_membership() {
let (state, sid) = fixture().await;
attempt_join(&state, &sid, "missing").await;
assert!(
channels::members(&state.channels, "general")
.await
.contains(&sid)
);
assert_eq!(
session::get(&state.sessions, &sid)
.await
.unwrap()
.channel_id
.as_deref(),
Some("general")
);
}
#[tokio::test]
async fn outsider_cannot_join_guild_channel_or_lose_previous_membership() {
let (state, sid) = fixture().await;
let guild_id = state
.storage
.create_guild("owner", "Private guild")
.await
.unwrap();
channels::create(
&state.channels,
"private",
"Private",
channels::ChannelKind::Text,
Some(guild_id),
)
.await;
attempt_join(&state, &sid, "private").await;
assert!(
!channels::members(&state.channels, "private")
.await
.contains(&sid)
);
assert!(
channels::members(&state.channels, "general")
.await
.contains(&sid)
);
assert_eq!(
session::get(&state.sessions, &sid)
.await
.unwrap()
.channel_id
.as_deref(),
Some("general")
);
}
#[tokio::test]
async fn guild_member_can_switch_channels() {
let (state, sid) = fixture().await;
let guild_id = state
.storage
.create_guild("owner", "Private guild")
.await
.unwrap();
state
.storage
.add_guild_member(&guild_id, "visitor")
.await
.unwrap();
channels::create(
&state.channels,
"private",
"Private",
channels::ChannelKind::Text,
Some(guild_id),
)
.await;
attempt_join(&state, &sid, "private").await;
assert!(
channels::members(&state.channels, "private")
.await
.contains(&sid)
);
assert!(
!channels::members(&state.channels, "general")
.await
.contains(&sid)
);
assert_eq!(
session::get(&state.sessions, &sid)
.await
.unwrap()
.channel_id
.as_deref(),
Some("private")
);
}

View file

@ -79,12 +79,7 @@ pub async fn dispatch<S: AsyncRead + AsyncWrite + Unpin>(
}
PacketId::ChannelList => {
channel::handle_channel_list(
ctx.stream,
ctx.seq,
session_id,
payload,
ctx.crypto,
ctx.state,
ctx.stream, ctx.seq, session_id, payload, ctx.crypto, ctx.state,
)
.await?;
}

View file

@ -150,7 +150,9 @@ async fn run_tls(
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 {
if let Some(limit) = max_connections
&& current >= limit
{
warn!("connection rejected from {addr}: at max_connections ({limit})");
drop(stream);
continue;
@ -188,7 +190,9 @@ async fn run_plain(
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 {
if let Some(limit) = max_connections
&& current >= limit
{
warn!("connection rejected from {addr}: at max_connections ({limit})");
drop(stream);
continue;
@ -335,7 +339,7 @@ fn load_or_generate_tls_certs(
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.key_pair.serialize_der(),
certified_key.signing_key.serialize_der(),
));
Ok((vec![cert_der], key_der))
}

View file

@ -16,12 +16,12 @@ pub(super) fn encrypt_with_key(
seq: u64,
plaintext: &[u8],
) -> Vec<u8> {
let cipher = ChaCha20Poly1305::new(Key::from_slice(key));
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
let nonce_bytes = make_nonce(cid, seq);
let nonce = Nonce::from_slice(&nonce_bytes);
let nonce = Nonce::from(nonce_bytes);
cipher
.encrypt(
nonce,
&nonce,
Payload {
msg: plaintext,
aad: &[],
@ -36,12 +36,12 @@ pub(super) fn decrypt_with_key(
seq: u64,
ciphertext: &[u8],
) -> anyhow::Result<Vec<u8>> {
let cipher = ChaCha20Poly1305::new(Key::from_slice(key));
let cipher = ChaCha20Poly1305::new(&Key::from(*key));
let nonce_bytes = make_nonce(cid, seq);
let nonce = Nonce::from_slice(&nonce_bytes);
let nonce = Nonce::from(nonce_bytes);
cipher
.decrypt(
nonce,
&nonce,
Payload {
msg: ciphertext,
aad: &[],
@ -49,3 +49,36 @@ pub(super) fn decrypt_with_key(
)
.map_err(|e| anyhow::anyhow!("decryption failed: {e:?}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wire_ciphertext_matches_independent_chacha20_poly1305_vector() {
let key = std::array::from_fn(|index| index as u8);
let cid = [0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43];
let seq = 0x4746_4544;
let plaintext = b"VNOX dependency migration";
// Cross-checked with Python cryptography's ChaCha20Poly1305 implementation,
// IETF nonce 070000004041424344454647, and empty associated data.
let expected = hex::decode(
"1fa23e7a312509b0fc8729521811348ff880daa5598c43a57635975f81278abdf4461b25af86aee1c3",
)
.unwrap();
assert_eq!(encrypt_with_key(&key, &cid, seq, plaintext), expected);
assert_eq!(
decrypt_with_key(&key, &cid, seq, &expected).unwrap(),
plaintext
);
}
#[test]
fn tampered_ciphertext_is_rejected() {
let key = [7; 32];
let cid = [9; 8];
let mut ciphertext = encrypt_with_key(&key, &cid, 42, b"authenticated");
ciphertext[0] ^= 1;
assert!(decrypt_with_key(&key, &cid, 42, &ciphertext).is_err());
}
}

View file

@ -43,7 +43,7 @@ impl SessionCrypto {
}
pub fn new_ephemeral() -> (EphemeralSecret, PublicKey) {
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let sk = EphemeralSecret::random_from_rng(&mut rng);
let pk = PublicKey::from(&sk);
(sk, pk)
@ -96,7 +96,7 @@ mod tests {
#[test]
fn ecdh_derives_same_secret_on_both_sides() {
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let alice_sk = EphemeralSecret::random_from_rng(&mut rng);
let alice_pk = PublicKey::from(&alice_sk);