diff --git a/docs/configuration.md b/docs/configuration.md index d0b8c9b..2cc2f67 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -185,6 +185,14 @@ enabled = true max_frame_bytes = 8192 timeout_secs = 5 send_proxy_protocol = false +max_handshake_bytes = 2048 +max_login_start_bytes = 5120 +max_status_request_bytes = 64 +# min_protocol_version = 47 +# max_protocol_version = 772 +deny_protocol_versions = [] +username_max_len = 16 +username_charset = "standard" [logging] level = "info" @@ -210,6 +218,14 @@ clickhouse_url = "" | `protocol.minecraft.max_frame_bytes` | `8192` | Лимит кадра; > 0 | | `protocol.minecraft.timeout_secs` | `5` | Таймаут handshake; > 0 | | `protocol.minecraft.send_proxy_protocol` | `false` | Отправлять PROXY v2 на Paper; alias — `proxy_protocol` | +| `protocol.minecraft.max_handshake_bytes` | `2048` | Лимит кадра handshake (длина проверяется до буферизации); `16..=8192`, дополнительно ограничен `max_frame_bytes` | +| `protocol.minecraft.max_login_start_bytes` | `5120` | Лимит кадра login-start; `16..=8192` | +| `protocol.minecraft.max_status_request_bytes` | `64` | Лимит кадра status request; `1..=1024` | +| `protocol.minecraft.min_protocol_version` | не задан | Нижняя граница protocol id; `>= 0`, не больше `max_protocol_version` | +| `protocol.minecraft.max_protocol_version` | не задан | Верхняя граница protocol id; `>= 0` | +| `protocol.minecraft.deny_protocol_versions` | `[]` | Запрещённые protocol id (например `340`); `>= 0` | +| `protocol.minecraft.username_max_len` | `16` | Максимум символов в нике; `1..=64` | +| `protocol.minecraft.username_charset` | `"standard"` | `standard` (`A-Za-z0-9_.-`), `ascii` (печатный ASCII без пробела) или `any` (UTF-8 без управляющих символов) | | `logging.level` | `info` | `trace`, `debug`, `info`, `warn`, `error` | | `logging.format` | `text` | `text` или `json` | | `metrics.enabled` | `true` | Prometheus endpoint | diff --git a/docs/minecraft-java.md b/docs/minecraft-java.md index 769ab77..3889c0c 100644 --- a/docs/minecraft-java.md +++ b/docs/minecraft-java.md @@ -42,6 +42,51 @@ text and is not part of the Minecraft protocol. Configure the edge firewall to allow public TCP `25565`, and keep Prometheus `9090` and the Paper backend port private. +## Handshake hygiene + +Handshake и login-start идут открытым текстом, поэтому Rampart проверяет их до +подключения к Paper. Любое нарушение — тихое закрытие соединения без ответа. +Handler читает handshake и следующий за ним кадр (status request или login-start) +и пересылает оба на backend байт-в-байт. + +Что отклоняется: + +- пустой или длиннее 255 символов hostname; hostname не UTF-8; +- второй handshake, login-start до handshake, второй login-start; +- `next_state` не из `{1, 2, 3}` (3 — transfer, обрабатывается как login); +- неправдоподобный protocol id (меньше 4 или больше 65535, кроме снапшотов с битом 30); +- версия вне `min_protocol_version`/`max_protocol_version` или из `deny_protocol_versions`; +- ник длиной вне `1..=username_max_len` или с символами вне `username_charset` + (по умолчанию `A-Za-z0-9_.-`, длина до 16); +- status request не равный пустому пакету `0x00`. + +Размер кадра проверяется сразу после декодирования VarInt длины, до чтения тела: +handshake до `max_handshake_bytes` (2048), login-start до `max_login_start_bytes` +(5120), status request до `max_status_request_bytes` (64); общий потолок — +`max_frame_bytes`. + +```toml +[protocol.minecraft] +min_protocol_version = 47 +deny_protocol_versions = [340] +username_max_len = 16 +username_charset = "standard" +``` + +Метрики (`/metrics`): + +- `rampart_mc_handshake_total{result,reason}` — `result` это `accepted` или `rejected`; + `reason` из закрытого набора: `ok`, `frame_length`, `frame_too_large`, `malformed`, + `unexpected_packet`, `empty_hostname`, `oversized_hostname`, `bad_hostname`, + `duplicate_handshake`, `login_before_handshake`, `duplicate_login_start`, + `bad_next_state`, `implausible_version`, `version_below_min`, `version_above_max`, + `version_denied`, `bad_username`, `bad_status_request`, `timeout`, `io`. +- `rampart_mc_protocol_version_total{version}` — имя релиза из встроенной таблицы + (например `1.20.3-4`), всё остальное — `other`. + +Ограничения: второй login-start виден только если клиент прислал его сразу следом +за первым; после ответа сервера трафик шифруется и не разбирается. + ## Preserve player IPs safely When `send_proxy_protocol` is enabled, Rampart prepends a PROXY protocol v2 header diff --git a/docs/roadmap/v0.5-minecraft-handshake-hygiene.md b/docs/roadmap/v0.5-minecraft-handshake-hygiene.md new file mode 100644 index 0000000..4c71224 --- /dev/null +++ b/docs/roadmap/v0.5-minecraft-handshake-hygiene.md @@ -0,0 +1,68 @@ +# v0.5 — Minecraft: гигиена handshake/login и метрики + +| | | +|---|---| +| Milestone | v0.5 | +| Status | in progress (часть 1: state machine, лимиты, версии, метрики) | +| Priority | P1 | +| Depends on | — | + +## Цель + +Минимальные проверки, доступные прокси без расшифровки: плохие клиенты отсекаются до +upstream, а оператор видит причины отказов. + +## Зачем + +Rampart — прозрачный прокси и не читает зашифрованный трафик, но handshake и login-start +идут открытым текстом. Разбор sonar (GPL — только идеи) и Infrarust (AGPL — только идеи) +показал дешёвые проверки; реальное покрытие нашего `src/protocol/minecraft/` нужно сверить. + +## Scope + +- Конечный автомат handshake→login: пустой hostname, второй handshake, второй login-start, + login до handshake, неизвестный protocol id → тихий дроп; username по regex/длине. +- Лимиты размера кадра по фазе до буферизации (около 2 КиБ handshake, 5 КиБ login-start, + 64 байта status request); handshake декодируется независимо от версии протокола. +- Таблица версий протокола `(id → имя)`; конфигурируемые min/max и deny-список; метрика по + версиям с ограниченной кардинальностью. +- Метрики: `rampart_mc_handshake_total{result,reason}` (reason — закрытый enum), логины/с как + отдельный сигнал от cps. +- Лимиты, учитывающие login: считать только соединения, дошедшие до login-start, и число + разных username с одного IP за окно; отдельный бюджет для status-ping (ключ — IPv4 или + IPv6 `/64`). +- Fail-score по IP с затуханием (интеграция с `IpReputation`/`TrafficHook`): аномалии + handshake — события с весами, порог → `ban`/`ban_cidr`. +- Проверки «только под атакой» (тайминг NEVER/DURING_ATTACK/ALWAYS по состоянию + `AttackDetector`); сводка по атаке в webhook. +- Status: single-flight на upstream и негативный кэш на несколько секунд (флуд ping в + мёртвый backend не открывает соединение на каждый ping) — дополняет кэш из + v0.6-hot-path-perf.md (задача пока не в репозитории). + +## Non-goals + +- Проверки гравитации/коллизий/капча (нужен фейковый сервер); brand-проверки (зашифровано + в online-mode); обработка Geyser/Eaglercraft. + +## Критерии приёмки + +- [x] Каждый вид аномалии покрыт тестом (порядок пакетов, размеры, версии, username): `tests/protocol_minecraft_state.rs`, `tests/protocol_minecraft_handler.rs`. +- [x] Метрики видны в `/metrics` с закрытым набором label (`rampart_mc_handshake_total`, `rampart_mc_protocol_version_total`). +- [ ] Строгие проверки под атакой включаются автоматически и логируются. +- [ ] Валидный клиент не затронут (e2e-тест через `tests/edge_e2e`). + +## Верификация + +e2e с набором «плохих» клиентов (скрипт на сыром TCP) и стресс-прогон под флудом ping. + +## Прогресс + +Сделано (часть 1): конечный автомат handshake→status/login, лимиты кадра по фазе до +буферизации, таблица версий + min/max/deny, username-валидация, метрики +`rampart_mc_handshake_total` / `rampart_mc_protocol_version_total`. + +Не сделано (остаётся открытым): логины/с как отдельный сигнал, лимиты по login-start и +числу username с IP, бюджет status-ping, fail-score по IP, проверки «только под атакой» +(третий и четвёртый пункты приёмки), single-flight и негативный кэш status, e2e через +`tests/edge_e2e` (он собирается только с `protocol-http`; пока покрыто loopback-тестом +handler'а), обнаружение второго login-start после ответа сервера (нужен инспектор в relay). diff --git a/src/config/mod.rs b/src/config/mod.rs index 727d0e4..b5f12a5 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -7,14 +7,14 @@ mod trusted; #[cfg(feature = "protocol-http")] pub use sections::HttpProtocolConfig; -#[cfg(feature = "protocol-minecraft")] -pub use sections::MinecraftProtocolConfig; #[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))] pub use sections::ProtocolConfig; pub use sections::{ BackendConfig, BanConfig, BindConfig, DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig, LimitsConfig, LoggingConfig, MetricsConfig, PowConfig, ProxyProtocolConfig, StoreConfig, WorkerConfig, XdpConfig, }; +#[cfg(feature = "protocol-minecraft")] +pub use sections::{MinecraftProtocolConfig, UsernameCharset}; pub use trusted::TrustedProxyCidr; use serde::Deserialize; @@ -165,12 +165,7 @@ impl Config { if self.backend.upstreams.len() != 1 { anyhow::bail!("protocol.minecraft requires exactly one backend.upstreams entry"); } - if self.protocol.minecraft.max_frame_bytes == 0 { - anyhow::bail!("protocol.minecraft.max_frame_bytes must be positive"); - } - if self.protocol.minecraft.timeout_secs == 0 { - anyhow::bail!("protocol.minecraft.timeout_secs must be positive"); - } + self.protocol.minecraft.validate()?; } Ok(()) } diff --git a/src/config/sections/detect.rs b/src/config/sections/detect.rs index 11204af..d656de7 100644 --- a/src/config/sections/detect.rs +++ b/src/config/sections/detect.rs @@ -89,48 +89,7 @@ pub struct ProtocolConfig { pub http: HttpProtocolConfig, #[cfg(feature = "protocol-minecraft")] #[serde(default)] - pub minecraft: MinecraftProtocolConfig, -} - -/// `[protocol.minecraft]` section: Minecraft handshake handler policy. -#[cfg(feature = "protocol-minecraft")] -#[derive(Debug, Clone, Deserialize)] -pub struct MinecraftProtocolConfig { - #[serde(default = "default_minecraft_enabled")] - pub enabled: bool, - #[serde(default = "default_minecraft_max_frame_bytes")] - pub max_frame_bytes: usize, - #[serde(default = "default_minecraft_timeout_secs")] - pub timeout_secs: u64, - #[serde(default, alias = "proxy_protocol")] - pub send_proxy_protocol: bool, -} - -#[cfg(feature = "protocol-minecraft")] -impl Default for MinecraftProtocolConfig { - fn default() -> Self { - Self { - enabled: default_minecraft_enabled(), - max_frame_bytes: default_minecraft_max_frame_bytes(), - timeout_secs: default_minecraft_timeout_secs(), - send_proxy_protocol: false, - } - } -} - -#[cfg(feature = "protocol-minecraft")] -fn default_minecraft_enabled() -> bool { - !cfg!(feature = "protocol-http") -} - -#[cfg(feature = "protocol-minecraft")] -fn default_minecraft_max_frame_bytes() -> usize { - 8192 -} - -#[cfg(feature = "protocol-minecraft")] -fn default_minecraft_timeout_secs() -> u64 { - 5 + pub minecraft: super::minecraft::MinecraftProtocolConfig, } /// `[protocol.http]` section: HTTP/1.1 handler policy on the edge node. diff --git a/src/config/sections/minecraft/mod.rs b/src/config/sections/minecraft/mod.rs new file mode 100644 index 0000000..ae19521 --- /dev/null +++ b/src/config/sections/minecraft/mod.rs @@ -0,0 +1,135 @@ +//! `[protocol.minecraft]` section: Minecraft handshake handler policy. + +use serde::Deserialize; + +/// Character set accepted in login-start usernames. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsernameCharset { + /// ASCII letters, digits, `_`, `.` and `-` (`.` covers Floodgate prefixes). + #[default] + Standard, + /// Any printable ASCII character except space. + Ascii, + /// Any UTF-8 text without control characters (length limit still applies). + Any, +} + +/// `[protocol.minecraft]` section. +#[derive(Debug, Clone, Deserialize)] +pub struct MinecraftProtocolConfig { + #[serde(default = "default_enabled")] + pub enabled: bool, + /// Global ceiling for any single frame; per-phase caps are clamped to it. + #[serde(default = "default_max_frame_bytes")] + pub max_frame_bytes: usize, + #[serde(default = "default_timeout_secs")] + pub timeout_secs: u64, + #[serde(default, alias = "proxy_protocol")] + pub send_proxy_protocol: bool, + #[serde(default = "default_max_handshake_bytes")] + pub max_handshake_bytes: usize, + #[serde(default = "default_max_login_start_bytes")] + pub max_login_start_bytes: usize, + #[serde(default = "default_max_status_request_bytes")] + pub max_status_request_bytes: usize, + /// Lowest accepted protocol id; `None` means no lower bound. + #[serde(default)] + pub min_protocol_version: Option, + /// Highest accepted protocol id; `None` means no upper bound. + #[serde(default)] + pub max_protocol_version: Option, + #[serde(default)] + pub deny_protocol_versions: Vec, + #[serde(default = "default_username_max_len")] + pub username_max_len: usize, + #[serde(default)] + pub username_charset: UsernameCharset, +} + +impl Default for MinecraftProtocolConfig { + fn default() -> Self { + Self { + enabled: default_enabled(), + max_frame_bytes: default_max_frame_bytes(), + timeout_secs: default_timeout_secs(), + send_proxy_protocol: false, + max_handshake_bytes: default_max_handshake_bytes(), + max_login_start_bytes: default_max_login_start_bytes(), + max_status_request_bytes: default_max_status_request_bytes(), + min_protocol_version: None, + max_protocol_version: None, + deny_protocol_versions: Vec::new(), + username_max_len: default_username_max_len(), + username_charset: UsernameCharset::default(), + } + } +} + +impl MinecraftProtocolConfig { + /// Checks the invariants of an enabled handler. + /// + /// # Errors + /// Returns an error naming the first out-of-range key. + pub fn validate(&self) -> anyhow::Result<()> { + if self.max_frame_bytes == 0 { + anyhow::bail!("protocol.minecraft.max_frame_bytes must be positive"); + } + if self.timeout_secs == 0 { + anyhow::bail!("protocol.minecraft.timeout_secs must be positive"); + } + check_range("max_handshake_bytes", self.max_handshake_bytes, 16, 8192)?; + check_range("max_login_start_bytes", self.max_login_start_bytes, 16, 8192)?; + check_range("max_status_request_bytes", self.max_status_request_bytes, 1, 1024)?; + check_range("username_max_len", self.username_max_len, 1, 64)?; + let lo = self.min_protocol_version; + let hi = self.max_protocol_version; + if lo.is_some_and(|v| v < 0) || hi.is_some_and(|v| v < 0) { + anyhow::bail!("protocol.minecraft min/max_protocol_version must be non-negative"); + } + if let (Some(lo), Some(hi)) = (lo, hi) + && lo > hi + { + anyhow::bail!("protocol.minecraft.min_protocol_version exceeds max_protocol_version"); + } + if self.deny_protocol_versions.iter().any(|v| *v < 0) { + anyhow::bail!("protocol.minecraft.deny_protocol_versions must be non-negative"); + } + Ok(()) + } +} + +fn check_range(key: &str, value: usize, min: usize, max: usize) -> anyhow::Result<()> { + if !(min..=max).contains(&value) { + anyhow::bail!("protocol.minecraft.{key} must be in {min}..={max}"); + } + Ok(()) +} + +fn default_enabled() -> bool { + !cfg!(feature = "protocol-http") +} + +fn default_max_frame_bytes() -> usize { + 8192 +} + +fn default_timeout_secs() -> u64 { + 5 +} + +fn default_max_handshake_bytes() -> usize { + 2048 +} + +fn default_max_login_start_bytes() -> usize { + 5120 +} + +fn default_max_status_request_bytes() -> usize { + 64 +} + +fn default_username_max_len() -> usize { + 16 +} diff --git a/src/config/sections/mod.rs b/src/config/sections/mod.rs index 142cf8e..9fd51a4 100644 --- a/src/config/sections/mod.rs +++ b/src/config/sections/mod.rs @@ -2,14 +2,16 @@ mod detect; mod edge; +#[cfg(feature = "protocol-minecraft")] +mod minecraft; mod platform; #[cfg(feature = "protocol-http")] pub use detect::HttpProtocolConfig; -#[cfg(feature = "protocol-minecraft")] -pub use detect::MinecraftProtocolConfig; #[cfg(any(feature = "protocol-http", feature = "protocol-minecraft"))] pub use detect::ProtocolConfig; pub use detect::{DetectAlertConfig, DetectAutobanConfig, DetectConfig, DetectPrefixConfig}; pub use edge::{BackendConfig, BanConfig, BindConfig, LimitsConfig, PowConfig, ProxyProtocolConfig, WorkerConfig}; +#[cfg(feature = "protocol-minecraft")] +pub use minecraft::{MinecraftProtocolConfig, UsernameCharset}; pub use platform::{LoggingConfig, MetricsConfig, StoreConfig, XdpConfig}; diff --git a/src/metrics.rs b/src/metrics.rs index 1d613a4..4f65f55 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -71,6 +71,26 @@ pub static INTEL_ALERTS_TOTAL: LazyLock = LazyLock::new(|| { .expect("INTEL_ALERTS_TOTAL") }); +/// Minecraft handshake outcomes; `reason` is a closed enum, never client input. +pub static MC_HANDSHAKE_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "rampart_mc_handshake_total", + "Minecraft handshakes by result and closed reason", + &["result", "reason"] + ) + .expect("MC_HANDSHAKE_TOTAL") +}); + +/// Minecraft protocol versions seen; label is a table name or `other`. +pub static MC_PROTOCOL_VERSION_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "rampart_mc_protocol_version_total", + "Minecraft handshakes by known protocol version (unknown ids are other)", + &["version"] + ) + .expect("MC_PROTOCOL_VERSION_TOTAL") +}); + /// Serves the Prometheus registry over a minimal HTTP endpoint. /// /// Runs until the task is dropped; a failed connection is logged and never diff --git a/src/protocol/minecraft/mod.rs b/src/protocol/minecraft/mod.rs index 6907621..5cd0242 100644 --- a/src/protocol/minecraft/mod.rs +++ b/src/protocol/minecraft/mod.rs @@ -1,18 +1,28 @@ //! Minecraft Java TCP handshake validation (feature `protocol-minecraft`). +//! +//! Reads the handshake and the first status/login frame, validates both against +//! [`policy::Policy`] and replays the raw bytes to the upstream unchanged. -mod parser; +pub mod parser; +pub mod policy; +pub mod reason; +pub mod state; use crate::config::MinecraftProtocolConfig; +use crate::metrics; use crate::protocol::{HandshakeResult, ProtocolHandler, Upstream}; +use policy::{Policy, versions}; +use reason::Reason; +use state::{Session, Step}; use std::future::Future; use std::pin::Pin; use std::time::Duration; -use tokio::io::AsyncReadExt; +use tokio::io::{AsyncRead, AsyncReadExt}; use tokio::net::TcpStream; pub struct MinecraftProtocolHandler { upstream: String, - max_frame_bytes: usize, + policy: Policy, timeout: Duration, } @@ -22,47 +32,66 @@ impl MinecraftProtocolHandler { Self { // Config validation requires exactly one backend when this handler is enabled. upstream: upstreams.first().cloned().unwrap_or_default(), - max_frame_bytes: config.max_frame_bytes, + policy: Policy::from_config(config), timeout: Duration::from_secs(config.timeout_secs), } } - async fn read_handshake(&self, stream: &mut TcpStream) -> anyhow::Result> { - let mut frame = Vec::with_capacity(64); - let mut frame_len = 0usize; - for index in 0..5 { - let mut byte = [0u8; 1]; - stream.read_exact(&mut byte).await?; - frame.push(byte[0]); - if index == 4 && byte[0] & 0xf0 != 0 { - anyhow::bail!("Minecraft frame length VarInt exceeds 32 bits"); - } - if byte[0] & 0x80 == 0 { - let (decoded, prefix_len) = parser::decode_frame_length(&frame)?; - frame_len = decoded; - if frame_len == 0 || frame_len > self.max_frame_bytes { - anyhow::bail!("Minecraft handshake frame length {frame_len} is outside allowed range"); - } - if prefix_len != frame.len() { - anyhow::bail!("invalid Minecraft frame length prefix"); - } - break; - } - if index == 4 { - anyhow::bail!("Minecraft frame length VarInt exceeds five bytes"); + async fn read_frames(&self, stream: &mut R) -> Result, Reason> { + let mut session = Session::new(&self.policy); + let mut raw = Vec::new(); + // Handshake, then the status request or login-start that follows at once. + for _ in 0..2 { + let (frame, prefix_len) = read_frame(stream, session.frame_cap()).await?; + if let Step::Handshake(handshake) = session.feed(&frame[prefix_len..])? { + metrics::MC_PROTOCOL_VERSION_TOTAL + .with_label_values(&[versions::label(handshake.protocol_version)]) + .inc(); } + raw.extend_from_slice(&frame); } - if frame_len == 0 { - anyhow::bail!("invalid empty Minecraft handshake frame"); - } - let prefix_len = frame.len(); - frame.resize(prefix_len + frame_len, 0); - stream.read_exact(&mut frame[prefix_len..]).await?; - parser::parse_frame(&frame, self.max_frame_bytes)?; - Ok(frame) + Ok(raw) } } +/// Reads one length-prefixed frame, enforcing `cap` as soon as the length +/// VarInt is decoded so oversized bodies are never buffered. +/// +/// Returns the raw bytes (prefix included) and the prefix length. +/// +/// # Errors +/// Returns the [`Reason`] for a bad length, an oversized frame or an I/O error. +pub async fn read_frame(stream: &mut R, cap: usize) -> Result<(Vec, usize), Reason> { + let mut frame = Vec::with_capacity(32); + for _ in 0..5 { + let mut byte = [0u8; 1]; + stream.read_exact(&mut byte).await.map_err(|_| Reason::Io)?; + frame.push(byte[0]); + if byte[0] & 0x80 == 0 { + break; + } + } + let (frame_len, prefix_len) = parser::decode_frame_length(&frame)?; + if frame_len == 0 { + return Err(Reason::FrameLength); + } + if frame_len > cap { + return Err(Reason::FrameTooLarge); + } + frame.resize(prefix_len + frame_len, 0); + stream + .read_exact(&mut frame[prefix_len..]) + .await + .map_err(|_| Reason::Io)?; + Ok((frame, prefix_len)) +} + +fn record(reason: Reason) { + metrics::MC_HANDSHAKE_TOTAL + .with_label_values(&[reason.result(), reason.as_str()]) + .inc(); +} + impl ProtocolHandler for MinecraftProtocolHandler { fn name(&self) -> &'static str { "minecraft" @@ -73,9 +102,11 @@ impl ProtocolHandler for MinecraftProtocolHandler { stream: &'a mut TcpStream, ) -> Pin> + Send + 'a>> { Box::pin(async move { - let frame = tokio::time::timeout(self.timeout, self.read_handshake(stream)) + let outcome = tokio::time::timeout(self.timeout, self.read_frames(stream)) .await - .map_err(|_| anyhow::anyhow!("timed out reading Minecraft handshake"))??; + .unwrap_or(Err(Reason::Timeout)); + record(outcome.as_ref().err().copied().unwrap_or(Reason::Ok)); + let frame = outcome.map_err(|reason| anyhow::anyhow!("Minecraft handshake rejected: {reason}"))?; Ok(HandshakeResult::with_initial_data( Upstream::new(self.upstream.clone()), frame, diff --git a/src/protocol/minecraft/parser.rs b/src/protocol/minecraft/parser.rs index 5a9fa61..5628764 100644 --- a/src/protocol/minecraft/parser.rs +++ b/src/protocol/minecraft/parser.rs @@ -1,94 +1,125 @@ -//! Bounded parser for the Minecraft Java handshake packet. +//! Bounded parsers for the Minecraft Java handshake and login-start packets. +//! +//! Parsers take the frame body (packet id onward, without the length prefix) and +//! never allocate based on client-declared lengths. + +use super::policy::Policy; +use super::reason::Reason; -const HANDSHAKE_PACKET_ID: i32 = 0; const MAX_VARINT_BYTES: usize = 5; -const MAX_HOST_BYTES: usize = 255; +const MAX_HOST_CHARS: usize = 255; +/// A UTF-8 character takes at most four bytes. +const MAX_UTF8_BYTES: usize = 4; #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum NextState { +pub enum NextState { Status, Login, + /// Protocol 766+ transfer intent; handled like login. + Transfer, } -pub(super) fn decode_frame_length(prefix: &[u8]) -> anyhow::Result<(usize, usize)> { - let (length, bytes_read) = decode_varint(prefix, 0)?; - let length = usize::try_from(length).map_err(|_| anyhow::anyhow!("negative frame length"))?; - Ok((length, bytes_read)) +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Handshake { + pub protocol_version: i32, + pub next_state: NextState, } -/// Validates a complete length-prefixed handshake frame and returns its state. -pub(super) fn parse_frame(frame: &[u8], max_frame_bytes: usize) -> anyhow::Result { - let (frame_len, prefix_len) = decode_varint(frame, 0)?; - let frame_len = usize::try_from(frame_len).map_err(|_| anyhow::anyhow!("negative frame length"))?; - if frame_len == 0 || frame_len > max_frame_bytes { - anyhow::bail!("Minecraft handshake frame length {frame_len} is outside allowed range"); - } - if frame.len() != prefix_len + frame_len { - anyhow::bail!("Minecraft handshake frame length does not match packet"); - } +/// Decodes the frame length prefix, returning `(length, prefix bytes)`. +/// +/// # Errors +/// Returns [`Reason::Malformed`] for an over-long or negative VarInt. +pub fn decode_frame_length(prefix: &[u8]) -> Result<(usize, usize), Reason> { + let (length, read) = decode_varint(prefix, 0)?; + let length = usize::try_from(length).map_err(|_| Reason::Malformed)?; + Ok((length, read)) +} - let body = &frame[prefix_len..]; - let (packet_id, mut cursor) = decode_varint(body, 0)?; - if packet_id != HANDSHAKE_PACKET_ID { - anyhow::bail!("unexpected Minecraft packet id {packet_id} in handshake state"); +/// Parses a handshake body. Independent of the protocol version. +/// +/// # Errors +/// Returns the [`Reason`] for the first structural violation. +pub fn parse_handshake(body: &[u8]) -> Result { + let (packet_id, cursor) = decode_varint(body, 0)?; + if packet_id != 0 { + return Err(Reason::UnexpectedPacket); } - - let (protocol_version, next) = decode_varint(body, cursor)?; + let (protocol_version, cursor) = decode_varint(body, cursor)?; if protocol_version < 0 { - anyhow::bail!("Minecraft protocol version must be non-negative"); + return Err(Reason::ImplausibleVersion); } - cursor = next; - - let (host_len, next) = decode_varint(body, cursor)?; - let host_len = usize::try_from(host_len).map_err(|_| anyhow::anyhow!("negative host length"))?; - if host_len == 0 || host_len > MAX_HOST_BYTES { - anyhow::bail!("Minecraft handshake hostname length is outside allowed range"); + let (host_len, cursor) = decode_varint(body, cursor)?; + let host_len = usize::try_from(host_len).map_err(|_| Reason::OversizedHostname)?; + if host_len == 0 { + return Err(Reason::EmptyHostname); } - cursor = next; - let host_end = cursor - .checked_add(host_len) - .ok_or_else(|| anyhow::anyhow!("hostname length overflow"))?; - let host_bytes = body - .get(cursor..host_end) - .ok_or_else(|| anyhow::anyhow!("truncated Minecraft handshake hostname"))?; - std::str::from_utf8(host_bytes).map_err(|_| anyhow::anyhow!("Minecraft handshake hostname is not UTF-8"))?; - cursor = host_end; - - let port_end = cursor - .checked_add(2) - .ok_or_else(|| anyhow::anyhow!("port length overflow"))?; - if body.get(cursor..port_end).is_none() { - anyhow::bail!("truncated Minecraft handshake port"); + if host_len > MAX_HOST_CHARS * MAX_UTF8_BYTES { + return Err(Reason::OversizedHostname); } - cursor = port_end; - - let (state, next) = decode_varint(body, cursor)?; - cursor = next; + let host_end = cursor.checked_add(host_len).ok_or(Reason::Malformed)?; + let host = body.get(cursor..host_end).ok_or(Reason::Malformed)?; + let host = std::str::from_utf8(host).map_err(|_| Reason::BadHostname)?; + if host.chars().count() > MAX_HOST_CHARS { + return Err(Reason::OversizedHostname); + } + let port_end = host_end.checked_add(2).ok_or(Reason::Malformed)?; + if body.get(host_end..port_end).is_none() { + return Err(Reason::Malformed); + } + let (state, cursor) = decode_varint(body, port_end)?; if cursor != body.len() { - anyhow::bail!("unexpected trailing bytes in Minecraft handshake"); - } - - match state { - 1 => Ok(NextState::Status), - 2 => Ok(NextState::Login), - _ => anyhow::bail!("unsupported Minecraft next state {state}; expected status or login"), + return Err(Reason::Malformed); } + let next_state = match state { + 1 => NextState::Status, + 2 => NextState::Login, + 3 => NextState::Transfer, + _ => return Err(Reason::BadNextState), + }; + Ok(Handshake { + protocol_version, + next_state, + }) } -/// Decodes signed Minecraft VarInt from a packet, returning value and next offset. -fn decode_varint(bytes: &[u8], start: usize) -> anyhow::Result<(i32, usize)> { +/// Parses a login-start body and validates the username. +/// +/// Bytes after the name (UUID, signature data) differ per protocol version and +/// are bounded only by the frame cap. +/// +/// # Errors +/// Returns the [`Reason`] for the first violation. +pub fn parse_login_start(body: &[u8], policy: &Policy) -> Result<(), Reason> { + let (packet_id, cursor) = decode_varint(body, 0)?; + if packet_id != 0 { + return Err(Reason::UnexpectedPacket); + } + let (name_len, cursor) = decode_varint(body, cursor)?; + let name_len = usize::try_from(name_len).map_err(|_| Reason::BadUsername)?; + if name_len == 0 || name_len > policy.username_max_len * MAX_UTF8_BYTES { + return Err(Reason::BadUsername); + } + let end = cursor.checked_add(name_len).ok_or(Reason::Malformed)?; + let name = body.get(cursor..end).ok_or(Reason::Malformed)?; + let name = std::str::from_utf8(name).map_err(|_| Reason::BadUsername)?; + policy.check_username(name) +} + +/// Decodes a signed Minecraft VarInt, returning the value and the next offset. +/// +/// # Errors +/// Returns [`Reason::Malformed`] when truncated or longer than 32 bits. +pub fn decode_varint(bytes: &[u8], start: usize) -> Result<(i32, usize), Reason> { let mut value = 0u32; for index in 0..MAX_VARINT_BYTES { - let byte = *bytes - .get(start + index) - .ok_or_else(|| anyhow::anyhow!("truncated Minecraft VarInt"))?; + let byte = *bytes.get(start + index).ok_or(Reason::Malformed)?; if index == 4 && byte & 0xf0 != 0 { - anyhow::bail!("Minecraft VarInt exceeds 32 bits"); + return Err(Reason::Malformed); } value |= u32::from(byte & 0x7f) << (index * 7); if byte & 0x80 == 0 { return Ok((value as i32, start + index + 1)); } } - anyhow::bail!("Minecraft VarInt exceeds five bytes") + Err(Reason::Malformed) } diff --git a/src/protocol/minecraft/policy/mod.rs b/src/protocol/minecraft/policy/mod.rs new file mode 100644 index 0000000..d70d77e --- /dev/null +++ b/src/protocol/minecraft/policy/mod.rs @@ -0,0 +1,77 @@ +//! Runtime policy derived from `[protocol.minecraft]`: frame caps, version +//! bounds and username rules. + +pub mod versions; + +use super::reason::Reason; +use crate::config::{MinecraftProtocolConfig, UsernameCharset}; + +#[derive(Debug, Clone)] +pub struct Policy { + pub max_frame_bytes: usize, + pub handshake_cap: usize, + pub login_start_cap: usize, + pub status_request_cap: usize, + pub min_version: Option, + pub max_version: Option, + pub deny_versions: Vec, + pub username_max_len: usize, + pub username_charset: UsernameCharset, +} + +impl Policy { + #[must_use] + pub fn from_config(config: &MinecraftProtocolConfig) -> Self { + let ceiling = config.max_frame_bytes; + Self { + max_frame_bytes: ceiling, + handshake_cap: config.max_handshake_bytes.min(ceiling), + login_start_cap: config.max_login_start_bytes.min(ceiling), + status_request_cap: config.max_status_request_bytes.min(ceiling), + min_version: config.min_protocol_version, + max_version: config.max_protocol_version, + deny_versions: config.deny_protocol_versions.clone(), + username_max_len: config.username_max_len, + username_charset: config.username_charset, + } + } + + /// Applies plausibility, min/max and deny-list rules to a protocol id. + /// + /// # Errors + /// Returns the matching [`Reason`] when the version is refused. + pub fn check_version(&self, id: i32) -> Result<(), Reason> { + if !versions::is_plausible(id) { + return Err(Reason::ImplausibleVersion); + } + if self.min_version.is_some_and(|min| id < min) { + return Err(Reason::VersionBelowMin); + } + if self.max_version.is_some_and(|max| id > max) { + return Err(Reason::VersionAboveMax); + } + if self.deny_versions.contains(&id) { + return Err(Reason::VersionDenied); + } + Ok(()) + } + + /// Validates a login-start username against length and charset. + /// + /// # Errors + /// Returns [`Reason::BadUsername`] when the name is not acceptable. + pub fn check_username(&self, name: &str) -> Result<(), Reason> { + let chars = name.chars().count(); + if chars == 0 || chars > self.username_max_len { + return Err(Reason::BadUsername); + } + let ok = match self.username_charset { + UsernameCharset::Standard => name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')), + UsernameCharset::Ascii => name.bytes().all(|b| b.is_ascii_graphic()), + UsernameCharset::Any => !name.chars().any(char::is_control), + }; + if ok { Ok(()) } else { Err(Reason::BadUsername) } + } +} diff --git a/src/protocol/minecraft/policy/versions.rs b/src/protocol/minecraft/policy/versions.rs new file mode 100644 index 0000000..4063556 --- /dev/null +++ b/src/protocol/minecraft/policy/versions.rs @@ -0,0 +1,77 @@ +//! Known Minecraft Java protocol ids. +//! +//! Only ids verified against the public protocol version list are included. +//! Newer or snapshot ids are valid but unnamed: they are labelled `other` in +//! metrics so label cardinality stays bounded. + +/// `(protocol id, release name)` sorted by id. +pub const VERSIONS: &[(i32, &str)] = &[ + (47, "1.8.x"), + (107, "1.9"), + (108, "1.9.1"), + (109, "1.9.2"), + (110, "1.9.3-4"), + (210, "1.10.x"), + (315, "1.11"), + (316, "1.11.1-2"), + (335, "1.12"), + (338, "1.12.1"), + (340, "1.12.2"), + (393, "1.13"), + (401, "1.13.1"), + (404, "1.13.2"), + (477, "1.14"), + (480, "1.14.1"), + (485, "1.14.2"), + (490, "1.14.3"), + (498, "1.14.4"), + (573, "1.15"), + (575, "1.15.1"), + (578, "1.15.2"), + (735, "1.16"), + (736, "1.16.1"), + (751, "1.16.2"), + (753, "1.16.3"), + (754, "1.16.4-5"), + (755, "1.17"), + (756, "1.17.1"), + (757, "1.18-1.18.1"), + (758, "1.18.2"), + (759, "1.19"), + (760, "1.19.1-2"), + (761, "1.19.3"), + (762, "1.19.4"), + (763, "1.20-1.20.1"), + (764, "1.20.2"), + (765, "1.20.3-4"), + (766, "1.20.5-6"), + (767, "1.21-1.21.1"), + (768, "1.21.2-3"), + (769, "1.21.4"), + (770, "1.21.5"), + (771, "1.21.6"), + (772, "1.21.7-8"), +]; + +/// Release name for a known id. +#[must_use] +pub fn name(id: i32) -> Option<&'static str> { + VERSIONS.iter().find(|(known, _)| *known == id).map(|(_, name)| *name) +} + +/// Bounded metrics label: the release name, or `other` for unknown ids. +#[must_use] +pub fn label(id: i32) -> &'static str { + name(id).unwrap_or("other") +} + +/// Whether `id` is a protocol id a real client can send. +/// +/// Releases use small ids; development snapshots set bit 30 on top of a small +/// number. Anything else is a malformed or probing client. +#[must_use] +pub fn is_plausible(id: i32) -> bool { + const SNAPSHOT_BIT: i32 = 0x4000_0000; + const MAX_SMALL: i32 = 0xFFFF; + id >= 0 && ((4..=MAX_SMALL).contains(&id) || (id & SNAPSHOT_BIT != 0 && (id & !SNAPSHOT_BIT) <= MAX_SMALL)) +} diff --git a/src/protocol/minecraft/reason.rs b/src/protocol/minecraft/reason.rs new file mode 100644 index 0000000..4074fa2 --- /dev/null +++ b/src/protocol/minecraft/reason.rs @@ -0,0 +1,97 @@ +//! Closed set of reasons a Minecraft handshake is accepted or rejected. +//! +//! The `as_str` values are used as Prometheus label values, so the set must stay +//! small and must never be built from client input. + +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Reason { + Ok, + FrameLength, + FrameTooLarge, + Malformed, + UnexpectedPacket, + EmptyHostname, + OversizedHostname, + BadHostname, + DuplicateHandshake, + LoginBeforeHandshake, + DuplicateLoginStart, + BadNextState, + ImplausibleVersion, + VersionBelowMin, + VersionAboveMax, + VersionDenied, + BadUsername, + BadStatusRequest, + Timeout, + Io, +} + +impl Reason { + /// Every reason, for exhaustive tests and documentation. + pub const ALL: [Reason; 20] = [ + Reason::Ok, + Reason::FrameLength, + Reason::FrameTooLarge, + Reason::Malformed, + Reason::UnexpectedPacket, + Reason::EmptyHostname, + Reason::OversizedHostname, + Reason::BadHostname, + Reason::DuplicateHandshake, + Reason::LoginBeforeHandshake, + Reason::DuplicateLoginStart, + Reason::BadNextState, + Reason::ImplausibleVersion, + Reason::VersionBelowMin, + Reason::VersionAboveMax, + Reason::VersionDenied, + Reason::BadUsername, + Reason::BadStatusRequest, + Reason::Timeout, + Reason::Io, + ]; + + /// Stable label value for metrics and logs. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Reason::Ok => "ok", + Reason::FrameLength => "frame_length", + Reason::FrameTooLarge => "frame_too_large", + Reason::Malformed => "malformed", + Reason::UnexpectedPacket => "unexpected_packet", + Reason::EmptyHostname => "empty_hostname", + Reason::OversizedHostname => "oversized_hostname", + Reason::BadHostname => "bad_hostname", + Reason::DuplicateHandshake => "duplicate_handshake", + Reason::LoginBeforeHandshake => "login_before_handshake", + Reason::DuplicateLoginStart => "duplicate_login_start", + Reason::BadNextState => "bad_next_state", + Reason::ImplausibleVersion => "implausible_version", + Reason::VersionBelowMin => "version_below_min", + Reason::VersionAboveMax => "version_above_max", + Reason::VersionDenied => "version_denied", + Reason::BadUsername => "bad_username", + Reason::BadStatusRequest => "bad_status_request", + Reason::Timeout => "timeout", + Reason::Io => "io", + } + } + + /// Metrics `result` label: `accepted` only for [`Reason::Ok`]. + #[must_use] + pub fn result(self) -> &'static str { + if self == Reason::Ok { "accepted" } else { "rejected" } + } +} + +impl fmt::Display for Reason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl std::error::Error for Reason {} diff --git a/src/protocol/minecraft/state.rs b/src/protocol/minecraft/state.rs new file mode 100644 index 0000000..17b7c6c --- /dev/null +++ b/src/protocol/minecraft/state.rs @@ -0,0 +1,129 @@ +//! Handshake -> status/login state machine. +//! +//! Fed one frame body at a time; it decides which packet shapes are legal in the +//! current phase and reports a closed [`Reason`] for everything else. + +use super::parser::{self, Handshake, NextState}; +use super::policy::Policy; +use super::reason::Reason; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + Handshake, + /// Handshake done, waiting for the status request. + Status, + /// Handshake done, waiting for login-start. + Login, + /// Status request or login-start seen; later packets are not inspected. + Established, +} + +/// What a successfully validated frame was. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Step { + Handshake(Handshake), + StatusRequest, + LoginStart, + /// A later packet that this proxy does not inspect (encrypted or opaque). + Passthrough, +} + +pub struct Session<'a> { + policy: &'a Policy, + phase: Phase, + started: Option, +} + +impl<'a> Session<'a> { + #[must_use] + pub fn new(policy: &'a Policy) -> Self { + Self { + policy, + phase: Phase::Handshake, + started: None, + } + } + + #[must_use] + pub fn phase(&self) -> Phase { + self.phase + } + + /// Maximum frame length the next frame may declare in this phase. + #[must_use] + pub fn frame_cap(&self) -> usize { + match self.phase { + Phase::Handshake => self.policy.handshake_cap, + Phase::Status => self.policy.status_request_cap, + Phase::Login => self.policy.login_start_cap, + Phase::Established => self.policy.max_frame_bytes, + } + } + + /// Validates one frame body and advances the phase. + /// + /// # Errors + /// Returns the [`Reason`] the connection must be dropped for. + pub fn feed(&mut self, body: &[u8]) -> Result { + match self.phase { + Phase::Handshake => self.on_handshake(body), + Phase::Status => self.on_status(body), + Phase::Login => self.on_login(body), + Phase::Established => self.on_established(body), + } + } + + fn on_handshake(&mut self, body: &[u8]) -> Result { + let handshake = match parser::parse_handshake(body) { + Ok(handshake) => handshake, + Err(_) if parser::parse_login_start(body, self.policy).is_ok() => return Err(Reason::LoginBeforeHandshake), + Err(reason) => return Err(reason), + }; + self.policy.check_version(handshake.protocol_version)?; + self.phase = match handshake.next_state { + NextState::Status => Phase::Status, + NextState::Login | NextState::Transfer => Phase::Login, + }; + self.started = Some(handshake.next_state); + Ok(Step::Handshake(handshake)) + } + + fn on_status(&mut self, body: &[u8]) -> Result { + if body == [0] { + self.phase = Phase::Established; + return Ok(Step::StatusRequest); + } + Err(self.misplaced(body).unwrap_or(Reason::BadStatusRequest)) + } + + fn on_login(&mut self, body: &[u8]) -> Result { + match parser::parse_login_start(body, self.policy) { + Ok(()) => { + self.phase = Phase::Established; + Ok(Step::LoginStart) + }, + Err(reason) => Err(self.misplaced(body).unwrap_or(reason)), + } + } + + fn on_established(&mut self, body: &[u8]) -> Result { + if let Some(reason) = self.misplaced(body) { + return Err(reason); + } + let is_packet_zero = parser::decode_varint(body, 0).is_ok_and(|(id, _)| id == 0); + match (self.started, is_packet_zero) { + (Some(NextState::Login | NextState::Transfer), true) + if parser::parse_login_start(body, self.policy).is_ok() => + { + Err(Reason::DuplicateLoginStart) + }, + (Some(NextState::Status), true) if body == [0] => Err(Reason::BadStatusRequest), + _ => Ok(Step::Passthrough), + } + } + + /// Detects a handshake sent in a later phase. + fn misplaced(&self, body: &[u8]) -> Option { + parser::parse_handshake(body).ok().map(|_| Reason::DuplicateHandshake) + } +} diff --git a/tests/config_minecraft.rs b/tests/config_minecraft.rs new file mode 100644 index 0000000..84fc8bd --- /dev/null +++ b/tests/config_minecraft.rs @@ -0,0 +1,56 @@ +//! `[protocol.minecraft]` hygiene options: defaults, parsing and clamps. +#![cfg(feature = "protocol-minecraft")] + +use rampart::config::{Config, UsernameCharset}; + +fn parse(extra: &str) -> anyhow::Result { + Config::parse_str(&format!("[protocol.minecraft]\nenabled = true\n{extra}")) +} + +#[test] +fn defaults_match_the_documented_values() -> anyhow::Result<()> { + let mc = parse("")?.protocol.minecraft; + assert_eq!(mc.max_handshake_bytes, 2048); + assert_eq!(mc.max_login_start_bytes, 5120); + assert_eq!(mc.max_status_request_bytes, 64); + assert_eq!(mc.username_max_len, 16); + assert_eq!(mc.username_charset, UsernameCharset::Standard); + assert_eq!(mc.min_protocol_version, None); + assert_eq!(mc.max_protocol_version, None); + assert!(mc.deny_protocol_versions.is_empty()); + Ok(()) +} + +#[test] +fn custom_values_parse() -> anyhow::Result<()> { + let mc = parse( + "min_protocol_version = 47\nmax_protocol_version = 772\ndeny_protocol_versions = [340, 754]\n\ + username_max_len = 32\nusername_charset = \"any\"\nmax_handshake_bytes = 512\n", + )? + .protocol + .minecraft; + assert_eq!(mc.min_protocol_version, Some(47)); + assert_eq!(mc.deny_protocol_versions, vec![340, 754]); + assert_eq!(mc.username_charset, UsernameCharset::Any); + assert_eq!(mc.max_handshake_bytes, 512); + Ok(()) +} + +#[test] +fn out_of_range_values_are_rejected() { + for bad in [ + "max_handshake_bytes = 8", + "max_handshake_bytes = 100000", + "max_login_start_bytes = 0", + "max_status_request_bytes = 0", + "max_status_request_bytes = 4096", + "username_max_len = 0", + "username_max_len = 65", + "min_protocol_version = 800\nmax_protocol_version = 700", + "min_protocol_version = -1", + "deny_protocol_versions = [-5]", + "username_charset = \"regex\"", + ] { + assert!(parse(bad).is_err(), "{bad}"); + } +} diff --git a/tests/protocol_minecraft_handler.rs b/tests/protocol_minecraft_handler.rs new file mode 100644 index 0000000..4e0c2c5 --- /dev/null +++ b/tests/protocol_minecraft_handler.rs @@ -0,0 +1,193 @@ +//! Minecraft handler over loopback: byte-exact replay, rejects, per-phase frame +//! caps enforced before buffering, and the handshake metrics. +#![cfg(feature = "protocol-minecraft")] + +use rampart::config::MinecraftProtocolConfig; +use rampart::metrics::{MC_HANDSHAKE_TOTAL, MC_PROTOCOL_VERSION_TOTAL}; +use rampart::protocol::ProtocolHandler; +use rampart::protocol::minecraft::MinecraftProtocolHandler; +use rampart::protocol::minecraft::read_frame; +use rampart::protocol::minecraft::reason::Reason; +use std::time::Duration; +use tokio::io::AsyncWriteExt; +use tokio::net::{TcpListener, TcpStream}; + +fn varint(mut value: u32) -> Vec { + let mut out = Vec::new(); + loop { + let byte = (value & 0x7f) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + return out; + } + out.push(byte | 0x80); + } +} + +fn frame(body: &[u8]) -> Vec { + let mut out = varint(body.len() as u32); + out.extend_from_slice(body); + out +} + +fn handshake(version: u32, host: &str, state: u32) -> Vec { + let mut body = varint(0); + body.extend(varint(version)); + body.extend(varint(host.len() as u32)); + body.extend(host.as_bytes()); + body.extend(25565u16.to_be_bytes()); + body.extend(varint(state)); + frame(&body) +} + +fn login(name: &str) -> Vec { + let mut body = varint(0); + body.extend(varint(name.len() as u32)); + body.extend(name.as_bytes()); + body.extend([9u8; 16]); + frame(&body) +} + +fn handler(tune: impl FnOnce(&mut MinecraftProtocolConfig)) -> MinecraftProtocolHandler { + let mut config = MinecraftProtocolConfig { + timeout_secs: 5, + ..MinecraftProtocolConfig::default() + }; + tune(&mut config); + MinecraftProtocolHandler::new(&config, &["127.0.0.1:25566".to_string()]) +} + +/// Sends `payload` from a client, runs the handler on the accepted side and +/// returns its outcome (the client stays open while the handler runs). +async fn run(handler: &MinecraftProtocolHandler, payload: &[u8]) -> anyhow::Result> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let mut client = TcpStream::connect(listener.local_addr()?).await?; + let (mut server, _) = listener.accept().await?; + client.write_all(payload).await?; + let result = handler.handshake(&mut server).await; + drop(client); + result.map(|r| r.initial_backend_data) +} + +fn counter(result: &str, reason: &str) -> u64 { + MC_HANDSHAKE_TOTAL.with_label_values(&[result, reason]).get() +} + +#[tokio::test] +async fn valid_login_is_replayed_byte_for_byte() -> anyhow::Result<()> { + let mut payload = handshake(765, "mc.example.com", 2); + payload.extend(login("Steve_01")); + let before = counter("accepted", "ok"); + let replay = run(&handler(|_| {}), &payload).await?; + assert_eq!(replay, payload); + assert!(counter("accepted", "ok") > before); + Ok(()) +} + +#[tokio::test] +async fn valid_status_request_is_replayed() -> anyhow::Result<()> { + let mut payload = handshake(47, "mc.example.com", 1); + payload.extend(frame(&[0])); + assert_eq!(run(&handler(|_| {}), &payload).await?, payload); + Ok(()) +} + +#[tokio::test] +async fn bad_clients_are_rejected_and_counted_by_reason() -> anyhow::Result<()> { + let cases: Vec<(&str, Vec)> = vec![ + ("empty_hostname", [handshake(765, "", 2), login("Steve")].concat()), + ("bad_next_state", [handshake(765, "h", 9), login("Steve")].concat()), + ("bad_username", [handshake(765, "h", 2), login("bad name!")].concat()), + ( + "duplicate_handshake", + [handshake(765, "h", 2), handshake(765, "h", 2)].concat(), + ), + ("login_before_handshake", login("Steve")), + ("implausible_version", [handshake(0, "h", 2), login("Steve")].concat()), + ("bad_status_request", [handshake(765, "h", 1), frame(&[0, 0])].concat()), + ]; + for (reason, payload) in cases { + let before = counter("rejected", reason); + assert!(run(&handler(|_| {}), &payload).await.is_err(), "{reason}"); + assert!(counter("rejected", reason) > before, "{reason}"); + } + Ok(()) +} + +#[tokio::test] +async fn denied_version_is_rejected_and_version_label_is_bounded() -> anyhow::Result<()> { + let strict = handler(|c| c.deny_protocol_versions = vec![765]); + let mut payload = handshake(765, "h", 2); + payload.extend(login("Steve")); + assert!(run(&strict, &payload).await.is_err()); + let known = MC_PROTOCOL_VERSION_TOTAL.with_label_values(&["1.20.3-4"]).get(); + assert!(known >= 1); + let other_before = MC_PROTOCOL_VERSION_TOTAL.with_label_values(&["other"]).get(); + let mut unknown = handshake(31_337, "h", 2); + unknown.extend(login("Steve")); + assert!(run(&handler(|_| {}), &unknown).await.is_ok()); + assert!(MC_PROTOCOL_VERSION_TOTAL.with_label_values(&["other"]).get() > other_before); + Ok(()) +} + +#[tokio::test] +async fn oversized_declared_frames_are_rejected_without_a_body() -> anyhow::Result<()> { + // Only the length prefix is sent: rejection must not wait for the body. + let handler = handler(|c| c.timeout_secs = 30); + let started = std::time::Instant::now(); + let before = counter("rejected", "frame_too_large"); + let result = run(&handler, &varint(2049)).await; + assert!(result.is_err()); + let mut login_phase = handshake(765, "h", 2); + login_phase.extend(varint(5121)); + assert!(run(&handler, &login_phase).await.is_err()); + let mut status_phase = handshake(765, "h", 1); + status_phase.extend(varint(65)); + assert!(run(&handler, &status_phase).await.is_err()); + assert!(started.elapsed() < Duration::from_secs(5)); + // Counters are process-global and other tests run in parallel. + assert!(counter("rejected", "frame_too_large") >= before + 3); + Ok(()) +} + +#[tokio::test] +async fn frame_caps_are_configurable_and_clamped_to_the_global_ceiling() -> anyhow::Result<()> { + let mut long_host = handshake(765, &"a".repeat(200), 2); + long_host.extend(login("Steve")); + assert!(run(&handler(|_| {}), &long_host).await.is_ok()); + let tight = handler(|c| c.max_handshake_bytes = 32); + assert!(run(&tight, &long_host).await.is_err()); + let ceiling = handler(|c| c.max_frame_bytes = 40); + assert!(run(&ceiling, &long_host).await.is_err()); + Ok(()) +} + +#[tokio::test] +async fn read_frame_checks_cap_before_reading_the_body() { + let (mut writer, mut reader) = tokio::io::duplex(64); + writer.write_all(&varint(100)).await.expect("write prefix"); + assert_eq!( + read_frame(&mut reader, 99).await.expect_err("must be rejected"), + Reason::FrameTooLarge + ); + let mut zero = &[0u8][..]; + assert_eq!( + read_frame(&mut zero, 10).await.expect_err("must be rejected"), + Reason::FrameLength + ); + let mut overlong = &[0x80u8, 0x80, 0x80, 0x80, 0x80, 0x01][..]; + assert_eq!( + read_frame(&mut overlong, 10).await.expect_err("must be rejected"), + Reason::Malformed + ); +} + +#[tokio::test] +async fn silent_client_times_out_and_is_counted() -> anyhow::Result<()> { + let quick = handler(|c| c.timeout_secs = 1); + let before = counter("rejected", "timeout"); + assert!(run(&quick, &[]).await.is_err()); + assert!(counter("rejected", "timeout") > before); + Ok(()) +} diff --git a/tests/protocol_minecraft_state.rs b/tests/protocol_minecraft_state.rs new file mode 100644 index 0000000..32d39c0 --- /dev/null +++ b/tests/protocol_minecraft_state.rs @@ -0,0 +1,219 @@ +//! Minecraft handshake/login state machine, parsers, version policy and the +//! closed reason set. +#![cfg(feature = "protocol-minecraft")] + +use rampart::config::{MinecraftProtocolConfig, UsernameCharset}; +use rampart::protocol::minecraft::parser::{NextState, parse_handshake}; +use rampart::protocol::minecraft::policy::{Policy, versions}; +use rampart::protocol::minecraft::reason::Reason; +use rampart::protocol::minecraft::state::{Phase, Session, Step}; + +fn varint(mut value: u32) -> Vec { + let mut out = Vec::new(); + loop { + let byte = (value & 0x7f) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + return out; + } + out.push(byte | 0x80); + } +} + +fn handshake_body(version: u32, host: &str, state: u32) -> Vec { + let mut body = varint(0); + body.extend(varint(version)); + body.extend(varint(host.len() as u32)); + body.extend(host.as_bytes()); + body.extend(25565u16.to_be_bytes()); + body.extend(varint(state)); + body +} + +fn login_body(name: &str) -> Vec { + let mut body = varint(0); + body.extend(varint(name.len() as u32)); + body.extend(name.as_bytes()); + body.extend([7u8; 16]); + body +} + +fn policy_with(tune: impl FnOnce(&mut MinecraftProtocolConfig)) -> Policy { + let mut config = MinecraftProtocolConfig::default(); + tune(&mut config); + Policy::from_config(&config) +} + +fn default_policy() -> Policy { + policy_with(|_| {}) +} + +#[test] +fn valid_login_flow_is_accepted() { + let policy = default_policy(); + let mut session = Session::new(&policy); + assert!(matches!( + session.feed(&handshake_body(765, "mc.example.com", 2)), + Ok(Step::Handshake(_)) + )); + assert_eq!(session.phase(), Phase::Login); + assert_eq!(session.feed(&login_body("Steve_01")), Ok(Step::LoginStart)); + assert_eq!(session.phase(), Phase::Established); +} + +#[test] +fn valid_status_flow_and_transfer_state_are_accepted() { + let policy = default_policy(); + let mut session = Session::new(&policy); + assert!(session.feed(&handshake_body(47, "h", 1)).is_ok()); + assert_eq!(session.feed(&[0]), Ok(Step::StatusRequest)); + let mut transfer = Session::new(&policy); + assert!(transfer.feed(&handshake_body(766, "h", 3)).is_ok()); + assert_eq!(transfer.phase(), Phase::Login); +} + +#[test] +fn handshake_hostname_bounds() { + assert_eq!(parse_handshake(&handshake_body(765, "", 2)), Err(Reason::EmptyHostname)); + let long = "a".repeat(256); + assert_eq!( + parse_handshake(&handshake_body(765, &long, 2)), + Err(Reason::OversizedHostname) + ); + let max = "a".repeat(255); + assert!(parse_handshake(&handshake_body(765, &max, 2)).is_ok()); +} + +#[test] +fn next_state_must_be_status_login_or_transfer() { + for state in [0, 4, 99] { + assert_eq!( + parse_handshake(&handshake_body(765, "h", state)), + Err(Reason::BadNextState) + ); + } + assert_eq!( + parse_handshake(&handshake_body(765, "h", 3)).map(|h| h.next_state), + Ok(NextState::Transfer) + ); +} + +#[test] +fn login_start_before_handshake_is_rejected() { + let policy = default_policy(); + let mut session = Session::new(&policy); + assert_eq!(session.feed(&login_body("Steve")), Err(Reason::LoginBeforeHandshake)); +} + +#[test] +fn second_handshake_is_rejected_in_every_phase() { + let policy = default_policy(); + let again = handshake_body(765, "mc.example.com", 2); + let mut login = Session::new(&policy); + login.feed(&again).expect("first handshake"); + assert_eq!(login.feed(&again), Err(Reason::DuplicateHandshake)); + let mut status = Session::new(&policy); + status.feed(&handshake_body(765, "h", 1)).expect("first handshake"); + assert_eq!(status.feed(&again), Err(Reason::DuplicateHandshake)); + let mut done = Session::new(&policy); + done.feed(&again).expect("first handshake"); + done.feed(&login_body("Steve")).expect("login"); + assert_eq!(done.feed(&again), Err(Reason::DuplicateHandshake)); +} + +#[test] +fn second_login_start_is_rejected_but_encryption_response_passes() { + let policy = default_policy(); + let mut session = Session::new(&policy); + session.feed(&handshake_body(765, "h", 2)).expect("handshake"); + session.feed(&login_body("Steve")).expect("login"); + assert_eq!(session.feed(&login_body("Alex")), Err(Reason::DuplicateLoginStart)); + assert_eq!(session.feed(&[1, 0, 0]), Ok(Step::Passthrough)); +} + +#[test] +fn bad_status_requests_are_rejected() { + let policy = default_policy(); + let mut session = Session::new(&policy); + session.feed(&handshake_body(765, "h", 1)).expect("handshake"); + assert_eq!(session.feed(&[0, 0]), Err(Reason::BadStatusRequest)); + let mut twice = Session::new(&policy); + twice.feed(&handshake_body(765, "h", 1)).expect("handshake"); + twice.feed(&[0]).expect("status request"); + assert_eq!(twice.feed(&[0]), Err(Reason::BadStatusRequest)); + assert_eq!(twice.feed(&[1, 0, 0, 0, 0, 0, 0, 0, 1]), Ok(Step::Passthrough)); +} + +#[test] +fn usernames_are_validated() { + let policy = default_policy(); + for good in ["Steve", "a", "Player_123", "x_y_z_0123456789", ".Floodgate"] { + assert_eq!(policy.check_username(good), Ok(()), "{good}"); + } + for bad in ["", "seventeen_chars_ab", "has space", "tab\t", "caf\u{e9}"] { + assert_eq!(policy.check_username(bad), Err(Reason::BadUsername), "{bad:?}"); + } + let mut session = Session::new(&policy); + session.feed(&handshake_body(765, "h", 2)).expect("handshake"); + assert_eq!( + session.feed(&login_body("seventeen_chars_ab")), + Err(Reason::BadUsername) + ); +} + +#[test] +fn username_policy_is_configurable() { + let any = policy_with(|c| { + c.username_charset = UsernameCharset::Any; + c.username_max_len = 32; + }); + assert_eq!(any.check_username("caf\u{e9}"), Ok(())); + assert_eq!(any.check_username(&"a".repeat(32)), Ok(())); + assert_eq!(any.check_username("bell\u{7}"), Err(Reason::BadUsername)); + let ascii = policy_with(|c| c.username_charset = UsernameCharset::Ascii); + assert_eq!(ascii.check_username("a!b#"), Ok(())); +} + +#[test] +fn version_policy_min_max_deny_and_plausibility() { + let policy = policy_with(|c| { + c.min_protocol_version = Some(47); + c.max_protocol_version = Some(770); + c.deny_protocol_versions = vec![340]; + }); + assert_eq!(policy.check_version(765), Ok(())); + assert_eq!(policy.check_version(340), Err(Reason::VersionDenied)); + assert_eq!(policy.check_version(5), Err(Reason::VersionBelowMin)); + assert_eq!(policy.check_version(771), Err(Reason::VersionAboveMax)); + let open = default_policy(); + assert_eq!(open.check_version(0), Err(Reason::ImplausibleVersion)); + assert_eq!(open.check_version(1_000_000), Err(Reason::ImplausibleVersion)); + assert_eq!(open.check_version(i32::MAX), Err(Reason::ImplausibleVersion)); + assert_eq!(open.check_version(0x4000_0000 | 200), Ok(())); + let mut session = Session::new(&policy); + assert_eq!(session.feed(&handshake_body(340, "h", 2)), Err(Reason::VersionDenied)); +} + +#[test] +fn version_table_covers_required_ids_and_labels_are_bounded() { + for id in [47, 340, 754, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767] { + assert!(versions::name(id).is_some(), "{id}"); + } + assert!(versions::VERSIONS.windows(2).all(|pair| pair[0].0 < pair[1].0)); + assert_eq!(versions::label(765), "1.20.3-4"); + assert_eq!(versions::label(123_456), "other"); + assert_eq!(versions::label(-1), "other"); +} + +#[test] +fn reasons_are_a_closed_label_set() { + let mut seen = std::collections::HashSet::new(); + for reason in Reason::ALL { + let label = reason.as_str(); + assert!(label.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')); + assert!(seen.insert(label), "duplicate label {label}"); + let expected = if reason == Reason::Ok { "accepted" } else { "rejected" }; + assert_eq!(reason.result(), expected); + } +}