Merge branch 'worktree-agent-a488594f6a87b6bd4'
# Conflicts: # docs/roadmap/v0.5-minecraft-handshake-hygiene.md
This commit is contained in:
commit
4bc5f5af83
17 changed files with 1251 additions and 157 deletions
56
tests/config_minecraft.rs
Normal file
56
tests/config_minecraft.rs
Normal file
|
|
@ -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> {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
193
tests/protocol_minecraft_handler.rs
Normal file
193
tests/protocol_minecraft_handler.rs
Normal file
|
|
@ -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<u8> {
|
||||
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<u8> {
|
||||
let mut out = varint(body.len() as u32);
|
||||
out.extend_from_slice(body);
|
||||
out
|
||||
}
|
||||
|
||||
fn handshake(version: u32, host: &str, state: u32) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<Vec<u8>> {
|
||||
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<u8>)> = 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(())
|
||||
}
|
||||
219
tests/protocol_minecraft_state.rs
Normal file
219
tests/protocol_minecraft_state.rs
Normal file
|
|
@ -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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue