Merge branch 'worktree-agent-a488594f6a87b6bd4'

# Conflicts:
#	docs/roadmap/v0.5-minecraft-handshake-hygiene.md
This commit is contained in:
Loki 2026-11-21 20:20:37 +01:00
commit 4bc5f5af83
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
17 changed files with 1251 additions and 157 deletions

View file

@ -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(())
}

View file

@ -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.

View file

@ -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<i32>,
/// Highest accepted protocol id; `None` means no upper bound.
#[serde(default)]
pub max_protocol_version: Option<i32>,
#[serde(default)]
pub deny_protocol_versions: Vec<i32>,
#[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
}

View file

@ -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};

View file

@ -71,6 +71,26 @@ pub static INTEL_ALERTS_TOTAL: LazyLock<IntCounter> = LazyLock::new(|| {
.expect("INTEL_ALERTS_TOTAL")
});
/// Minecraft handshake outcomes; `reason` is a closed enum, never client input.
pub static MC_HANDSHAKE_TOTAL: LazyLock<IntCounterVec> = 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<IntCounterVec> = 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

View file

@ -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<Vec<u8>> {
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<R: AsyncRead + Unpin>(&self, stream: &mut R) -> Result<Vec<u8>, 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<R: AsyncRead + Unpin>(stream: &mut R, cap: usize) -> Result<(Vec<u8>, 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<Box<dyn Future<Output = anyhow::Result<HandshakeResult>> + 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,

View file

@ -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<NextState> {
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<Handshake, Reason> {
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)
}

View file

@ -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<i32>,
pub max_version: Option<i32>,
pub deny_versions: Vec<i32>,
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) }
}
}

View file

@ -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))
}

View file

@ -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 {}

View file

@ -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<NextState>,
}
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<Step, Reason> {
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<Step, Reason> {
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<Step, Reason> {
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<Step, Reason> {
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<Step, Reason> {
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<Reason> {
parser::parse_handshake(body).ok().map(|_| Reason::DuplicateHandshake)
}
}