From ffc7690e71cc957821f7ce4da4ccb72a758b3f5e Mon Sep 17 00:00:00 2001 From: stsiakal Date: Tue, 27 Oct 2026 12:58:46 +0200 Subject: [PATCH 1/4] fix(login): compare the game-server secret in constant time and close on mismatch Registration compared the shared secret with != (a timing oracle) and left the internal connection open after the error reply, so one connection could keep guessing. Compare with subtle::ConstantTimeEq and, after the existing five-second error reply, close the connection. Proof: new socket test wrong_secret_is_refused_and_the_connection_is_closed failed on the previous handler (error reply then no EOF after 2 s, 7.02 s run) and passes with the fix (5.22 s); full aaemu-login suite 201 lib + 5 network tests passed, 0 failed, 7 ignored. --- rust/crates/aaemu-login/src/handlers.rs | 25 ++++++++----- rust/crates/aaemu-login/src/handlers/tests.rs | 8 +++++ rust/crates/aaemu-login/tests/network.rs | 36 +++++++++++++++++++ 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/rust/crates/aaemu-login/src/handlers.rs b/rust/crates/aaemu-login/src/handlers.rs index 9c01d0d708..d4ed881637 100644 --- a/rust/crates/aaemu-login/src/handlers.rs +++ b/rust/crates/aaemu-login/src/handlers.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use std::time::Duration; use anyhow::Context; +use subtle::ConstantTimeEq; use crate::auth::{ AuthFlow, KoreaAuthFlow, KoreaStep, LoginClient, PasswordAuthFlow, ReconnectAuthFlow, }; -use crate::controllers::game::send_with_delay; use crate::models::{GameServerId, GsRegisterResult}; use crate::network::internal::InternalConnection; use crate::network::login::LoginConnection; @@ -89,6 +89,11 @@ pub async fn handle_c2l( } } +/// Constant-time comparison of the shared game-server secret. +fn secret_matches(given: &str, expected: &str) -> bool { + bool::from(given.as_bytes().ct_eq(expected.as_bytes())) +} + /// Dispatches a game server packet. pub async fn handle_g2l( server: &Arc, @@ -115,15 +120,19 @@ pub async fn handle_g2l( Ok(()) } G2lPacket::RegisterGameServer(p) => { - if p.secret_key != server.config.secret_key { + if !secret_matches(&p.secret_key, &server.config.secret_key) { tracing::error!("Connection {}, bad secret key", conn.ip); - send_with_delay( - conn.clone(), - Duration::from_secs(5), - LgRegisterGameServer { + // Reply after the same delay as before, then close: a peer must not keep + // guessing the secret on the same connection. + let conn = conn.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(5)).await; + conn.send_packet(&LgRegisterGameServer { result: GsRegisterResult::Error, - }, - ); + }); + tokio::time::sleep(Duration::from_millis(200)).await; + conn.close(); + }); return Ok(()); } server.games.add(p.gs_id, p.mirrors, conn); diff --git a/rust/crates/aaemu-login/src/handlers/tests.rs b/rust/crates/aaemu-login/src/handlers/tests.rs index b632baf9d9..fdaf0fa17f 100644 --- a/rust/crates/aaemu-login/src/handlers/tests.rs +++ b/rust/crates/aaemu-login/src/handlers/tests.rs @@ -118,6 +118,14 @@ async fn bad_secret_connection_cannot_seed_reconnect_token() { assert_unauthorized_token_rejected(Some("wrong")).await; } +#[test] +fn secret_comparison_accepts_only_the_exact_secret() { + assert!(secret_matches("test", "test")); + assert!(!secret_matches("tesx", "test")); + assert!(!secret_matches("test ", "test")); + assert!(!secret_matches("", "test")); +} + #[tokio::test] async fn registered_connection_cannot_seed_an_unrelated_world_token() { let server = fixture().await; diff --git a/rust/crates/aaemu-login/tests/network.rs b/rust/crates/aaemu-login/tests/network.rs index 8444fc842a..f20192a8ac 100644 --- a/rust/crates/aaemu-login/tests/network.rs +++ b/rust/crates/aaemu-login/tests/network.rs @@ -448,3 +448,39 @@ async fn replaced_internal_socket_disconnect_does_not_unregister_current_owner() ); shutdown.cancel(); } + +#[tokio::test] +async fn wrong_secret_is_refused_and_the_connection_is_closed() { + let (_server, internal_addr, _login_addr, shutdown) = start_server().await; + let mut rogue = Framed::new(TcpStream::connect(internal_addr).await.unwrap(), FrameCodec); + send( + &mut rogue, + &GlRegisterGameServer { + secret_key: "tesx".into(), + gs_id: GameServerId(1), + mirrors: vec![], + }, + ) + .await; + + // The registration is refused after the five-second delay. + let frame = tokio::time::timeout(Duration::from_secs(8), rogue.next()) + .await + .expect("timely registration error") + .expect("open") + .expect("ok"); + let (op, mut body) = split_opcode(frame).unwrap(); + assert_eq!(op, l2g::opcodes::LG_REGISTER_GAME_SERVER); + assert_eq!( + LgRegisterGameServer::read(&mut body).unwrap().result, + aaemu_login::models::GsRegisterResult::Error + ); + + // Then the login server drops the connection, so the peer cannot keep guessing on it. + let closed = tokio::time::timeout(Duration::from_secs(2), rogue.next()).await; + assert!( + matches!(closed, Ok(None) | Ok(Some(Err(_)))), + "wrong-secret connection stayed open: {closed:?}" + ); + shutdown.cancel(); +} From 9a9f4d5e92df9446bc9d2299d970af96b0deff8e Mon Sep 17 00:00:00 2001 From: stsiakal Date: Tue, 27 Oct 2026 13:01:15 +0200 Subject: [PATCH 2/4] fix(login): bind the shipped internal network to loopback The shipped login config listened on every interface for the game-server protocol, so an exposed host ran the internal unauthenticated surface (and default SecretKey) publicly. Bind 127.0.0.1 by default; the Docker login service explicitly asks for * because the game container reaches it over the compose network and the port is not published. Proof: new shipped_internal_network_binds_loopback test failed on the previous Config.json (left *, right 127.0.0.1) and passes with the loopback default. --- docker-compose.yaml | 3 +++ rust/crates/aaemu-login/app/Config.json | 2 +- rust/crates/aaemu-login/src/config.rs | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index c9cc1caf2d..6556853326 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -54,6 +54,9 @@ services: GameServers__0__Name: AAEmu.Game GameServers__0__Host: 127.0.0.1 GameServers__0__Port: 1239 + # the shipped default is loopback; the game container reaches this port over the + # compose network, and the port is never published on the host + InternalNetwork__Host: "*" ports: - 1237:1237 develop: diff --git a/rust/crates/aaemu-login/app/Config.json b/rust/crates/aaemu-login/app/Config.json index b658301213..04e37009eb 100644 --- a/rust/crates/aaemu-login/app/Config.json +++ b/rust/crates/aaemu-login/app/Config.json @@ -9,7 +9,7 @@ "AutoAccount": true, "SkipHostResolve": false, "InternalNetwork": { - "Host": "*", + "Host": "127.0.0.1", "Port": 1234 }, "Network": { diff --git a/rust/crates/aaemu-login/src/config.rs b/rust/crates/aaemu-login/src/config.rs index 8ed486a1b0..835c05450f 100644 --- a/rust/crates/aaemu-login/src/config.rs +++ b/rust/crates/aaemu-login/src/config.rs @@ -543,6 +543,22 @@ mod tests { assert!(AppConfig::from_value(base()).is_err()); } + #[test] + fn shipped_internal_network_binds_loopback() { + let app = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("app"); + let args: Vec = [ + "--Connections:MySQLProvider:Host=127.0.0.1", + "--Connections:MySQLProvider:Port=3306", + "--Connections:MySQLProvider:User=aaemu", + "--Connections:MySQLProvider:Password=secret", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let cfg = AppConfig::load(&app, &args).unwrap(); + assert_eq!(cfg.internal_network.host, "127.0.0.1"); + } + #[test] fn env_and_args_override() { let mut root = base(); From 58481b71e604111749394e7d3e66aaa36cb5ac2c Mon Sep 17 00:00:00 2001 From: stsiakal Date: Tue, 27 Oct 2026 13:15:29 +0200 Subject: [PATCH 3/4] fix(game): require moderator access for /fly and /teleport AccessLevels.json shipped fly and teleport at level 0, and the command manager enforces exactly that table, so any player could toggle fly mode and teleport across the world. Move both commands to the moderator level (50), like the other moderator commands; the Web API loopback default and its bearer authentication are already upstream. Proof: new fly_and_teleport_require_moderator_access test loads the shipped AccessLevels.json and failed on the old table (level-0 fly was not refused: left [] vs Insufficient privileges) and passes now; the shipped_configuration_binds_every_section test also asserts both levels. Command suite: 164 passed, 0 failed; cargo clippy -p aaemu-game --all-targets -- -D warnings clean. --- .../app/Configurations/AccessLevels.json | 4 +- rust/crates/aaemu-game/src/config.rs | 2 + .../services/commands/scripts/tests.rs | 65 +++++++++++++++++++ 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/rust/crates/aaemu-game/app/Configurations/AccessLevels.json b/rust/crates/aaemu-game/app/Configurations/AccessLevels.json index 356e4fa78d..23739d6470 100644 --- a/rust/crates/aaemu-game/app/Configurations/AccessLevels.json +++ b/rust/crates/aaemu-game/app/Configurations/AccessLevels.json @@ -7,13 +7,13 @@ "collectdominion": 0, "joinsiege": 0, "leavesiege": 0, - "fly": 0, "online": 0, "soloparty": 0, - "teleport": 0, // Moderaters + "fly": 50, + "teleport": 50, "announce": 50, "despawn": 50, "dist": 50, diff --git a/rust/crates/aaemu-game/src/config.rs b/rust/crates/aaemu-game/src/config.rs index 5ca983ad6f..51a04d64f6 100644 --- a/rust/crates/aaemu-game/src/config.rs +++ b/rust/crates/aaemu-game/src/config.rs @@ -1204,6 +1204,8 @@ mod tests { // Specialty.json, AccessLevels.json, CharacterSettings.json assert_eq!(cfg.specialty.trade_pack_mail_delay_in_minutes, 480.0); assert_eq!(cfg.access_level_of("help"), Some(0)); + assert_eq!(cfg.access_level_of("fly"), Some(50)); + assert_eq!(cfg.access_level_of("teleport"), Some(50)); assert_eq!(cfg.access_level_of("announce"), Some(50)); assert_eq!(cfg.access_level_of("Announce"), None); assert!(cfg.account.delete_release_name); diff --git a/rust/crates/aaemu-game/src/systems/services/commands/scripts/tests.rs b/rust/crates/aaemu-game/src/systems/services/commands/scripts/tests.rs index 1eb92c7e37..fe3f7c89a3 100644 --- a/rust/crates/aaemu-game/src/systems/services/commands/scripts/tests.rs +++ b/rust/crates/aaemu-game/src/systems/services/commands/scripts/tests.rs @@ -411,3 +411,68 @@ async fn harness_runs_a_command() { assert!(out.is_empty()); assert_eq!(gm.chat(), ["|cFFFFFFFF[Echo]|r hello world "]); } + +#[tokio::test] +async fn fly_and_teleport_require_moderator_access() { + use crate::config::AppConfig; + + let app = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("app"); + if !app.join("Config.json").exists() { + return; + } + // The shipped Config.json keeps %login_port% / %db_port% placeholders. + let args: Vec = [ + "--LoginNetwork:Port=1234", + "/Connections:MySQLProvider:Port", + "3306", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let config = AppConfig::load_from(&app, None, Vec::new(), &args).unwrap(); + let server = harness::server(); + server + .systems + .services + .commands + .access_levels + .load(&config.access_level); + let mut player = harness::pc(&server, 1, "Player", 100.0, 100.0); + + for command in ["fly", "teleport solis"] { + let (handled, out) = harness::run_at(&server, &player.p, command, 0).await; + assert!(handled, "{command} was not handled"); + assert_eq!(out, ["|cFFFF0000Insufficient privileges.|r"], "{command}"); + // Only the refusal chat may reach the client: no fly/teleport packet. + let frames = player.frames(); + assert!( + frames + .iter() + .all(|(op, _)| *op == crate::opcodes::sc::SCChatMessagePacket), + "{command} ran without access: {frames:?}" + ); + } + + // Moderator level 50 still runs both commands. + let (handled, out) = harness::run_at(&server, &player.p, "teleport solis", 50).await; + assert!(handled); + assert_eq!( + out, + [harness::normal( + "teleport", + "Teleporting to |cFFFFFFFFSolis Headlands, Austera|r" + )] + ); + assert!(player + .frames() + .iter() + .any(|(op, _)| *op == crate::opcodes::sc::SCTeleportUnitPacket)); + + let (handled, out) = harness::run_at(&server, &player.p, "fly", 50).await; + assert!(handled); + assert!(out.is_empty()); + assert!(player + .frames() + .iter() + .any(|(op, _)| *op == crate::opcodes::sc::SCUnitFlyingStateChangedPacket)); +} From 60358661ebc0ccac16d5097eb42de5c760be32ce Mon Sep 17 00:00:00 2001 From: stsiakal Date: Tue, 27 Oct 2026 13:45:58 +0200 Subject: [PATCH 4/4] fix(login): poison the internal connection on a wrong registration secret The delayed reply task left the reader running for five seconds, so a peer could send more guesses, and a wrong secret followed by the correct one in that window registered the connection (the first task then closed it). Set a poisoned flag on the connection before scheduling the reply: handle_g2l ignores every later packet, the delayed Error reply is still sent, and the connection closes 200 ms later. Proof: new socket test wrong_secret_poisons_the_connection_before_a_correct_registration failed on the previous handler (the correct secret returned Success) and passes now; the existing token test now expects Error for the poisoned socket and Success for the unregistered one. Full aaemu-login: 202 lib + 6 network tests passed, 0 failed, 7 ignored. --- rust/crates/aaemu-login/src/handlers.rs | 10 +++ rust/crates/aaemu-login/src/handlers/tests.rs | 7 +- .../aaemu-login/src/network/internal.rs | 13 ++++ rust/crates/aaemu-login/tests/network.rs | 69 ++++++++++++++++++- 4 files changed, 95 insertions(+), 4 deletions(-) diff --git a/rust/crates/aaemu-login/src/handlers.rs b/rust/crates/aaemu-login/src/handlers.rs index d4ed881637..65ba396c2a 100644 --- a/rust/crates/aaemu-login/src/handlers.rs +++ b/rust/crates/aaemu-login/src/handlers.rs @@ -100,6 +100,15 @@ pub async fn handle_g2l( conn: &Arc, packet: G2lPacket, ) -> anyhow::Result<()> { + // A connection that sent a wrong secret stays refused until its delayed error reply and + // close, so a correct secret in that window cannot register it. + if conn.is_poisoned() { + tracing::warn!( + "Connection {}: packet after a failed registration, ignored", + conn.ip + ); + return Ok(()); + } match packet { G2lPacket::GameServerLoad(p) => { let gs_id = authorize_game_server(server, conn, None)?; @@ -122,6 +131,7 @@ pub async fn handle_g2l( G2lPacket::RegisterGameServer(p) => { if !secret_matches(&p.secret_key, &server.config.secret_key) { tracing::error!("Connection {}, bad secret key", conn.ip); + conn.poison(); // Reply after the same delay as before, then close: a peer must not keep // guessing the secret on the same connection. let conn = conn.clone(); diff --git a/rust/crates/aaemu-login/src/handlers/tests.rs b/rust/crates/aaemu-login/src/handlers/tests.rs index fdaf0fa17f..d77bc17b39 100644 --- a/rust/crates/aaemu-login/src/handlers/tests.rs +++ b/rust/crates/aaemu-login/src/handlers/tests.rs @@ -101,7 +101,12 @@ async fn assert_unauthorized_token_rejected(secret: Option<&str>) { ), "unauthenticated internal peer seeded a usable reconnect token" ); - assert!(result.is_err()); + // An unregistered peer gets the authorization error; a wrong-secret peer is poisoned and + // ignored, so neither path may acknowledge the packet. + assert!( + result.is_err() || conn.is_poisoned(), + "unauthorized internal packet was processed" + ); assert!( rx.try_recv().is_err(), "must not acknowledge an unauthorized token" diff --git a/rust/crates/aaemu-login/src/network/internal.rs b/rust/crates/aaemu-login/src/network/internal.rs index 1f05070984..bce2a19d75 100644 --- a/rust/crates/aaemu-login/src/network/internal.rs +++ b/rust/crates/aaemu-login/src/network/internal.rs @@ -33,6 +33,9 @@ pub struct InternalConnection { game_server: Mutex>, /// Never set by the C# code; kept for parity. pub block: AtomicBool, + /// Set by a failed registration: no further packet is handled, only the delayed error + /// reply is sent, then the connection closes. + poisoned: AtomicBool, closed: CancellationToken, } @@ -44,10 +47,20 @@ impl InternalConnection { tx, game_server: Mutex::new(None), block: AtomicBool::new(false), + poisoned: AtomicBool::new(false), closed: CancellationToken::new(), } } + /// Rejects every later packet on this connection (a wrong registration secret poisons it). + pub fn poison(&self) { + self.poisoned.store(true, Ordering::Relaxed); + } + + pub fn is_poisoned(&self) -> bool { + self.poisoned.load(Ordering::Relaxed) + } + pub fn game_server(&self) -> Option { *self.game_server.lock().unwrap() } diff --git a/rust/crates/aaemu-login/tests/network.rs b/rust/crates/aaemu-login/tests/network.rs index f20192a8ac..25151f8606 100644 --- a/rust/crates/aaemu-login/tests/network.rs +++ b/rust/crates/aaemu-login/tests/network.rs @@ -310,7 +310,9 @@ async fn unauthorized_internal_tokens_are_rejected_over_sockets() { .await; // A subsequent valid registration is a processing barrier on this same socket. - // It must not retroactively legitimize a token sent before authentication. + // It must not retroactively legitimize a token sent before authentication. A peer + // that already sent a wrong secret is poisoned instead: the correct registration + // must not run, and the delayed error reply is the last packet on the connection. send( &mut gs, &GlRegisterGameServer { @@ -320,13 +322,23 @@ async fn unauthorized_internal_tokens_are_rejected_over_sockets() { }, ) .await; + let expected = if secret.is_some() { + aaemu_login::models::GsRegisterResult::Error + } else { + aaemu_login::models::GsRegisterResult::Success + }; let mut token_acknowledged = false; loop { - let (op, mut body) = recv(&mut gs).await; + let frame = tokio::time::timeout(Duration::from_secs(8), gs.next()) + .await + .expect("timely registration result") + .expect("open") + .expect("ok"); + let (op, mut body) = split_opcode(frame).unwrap(); if op == l2g::opcodes::LG_REGISTER_GAME_SERVER { assert_eq!( LgRegisterGameServer::read(&mut body).unwrap().result, - aaemu_login::models::GsRegisterResult::Success + expected ); break; } @@ -484,3 +496,54 @@ async fn wrong_secret_is_refused_and_the_connection_is_closed() { ); shutdown.cancel(); } + +#[tokio::test] +async fn wrong_secret_poisons_the_connection_before_a_correct_registration() { + let (_server, internal_addr, _login_addr, shutdown) = start_server().await; + let mut rogue = Framed::new(TcpStream::connect(internal_addr).await.unwrap(), FrameCodec); + send( + &mut rogue, + &GlRegisterGameServer { + secret_key: "tesx".into(), + gs_id: GameServerId(1), + mirrors: vec![], + }, + ) + .await; + // The correct secret on the same connection, still inside the five-second reply window. + send( + &mut rogue, + &GlRegisterGameServer { + secret_key: "test".into(), + gs_id: GameServerId(1), + mirrors: vec![], + }, + ) + .await; + + // Only the delayed Error reply may arrive; the correct registration must never run. + let deadline = tokio::time::Instant::now() + Duration::from_secs(8); + let mut errors = 0; + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + let frame = tokio::time::timeout(left, rogue.next()).await; + match frame { + Ok(Some(Ok(frame))) => { + let (op, mut body) = split_opcode(frame).unwrap(); + if op == l2g::opcodes::LG_REGISTER_GAME_SERVER { + let result = LgRegisterGameServer::read(&mut body).unwrap().result; + assert_ne!( + result, + aaemu_login::models::GsRegisterResult::Success, + "a connection that sent a wrong secret registered" + ); + errors += 1; + } + } + Ok(Some(Err(_))) | Ok(None) => break, + Err(_) => panic!("no error reply and close within the deadline"), + } + } + assert_eq!(errors, 1, "expected exactly one registration error reply"); + shutdown.cancel(); +}