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-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)); +} 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(); diff --git a/rust/crates/aaemu-login/src/handlers.rs b/rust/crates/aaemu-login/src/handlers.rs index 9c01d0d708..65ba396c2a 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,12 +89,26 @@ 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, 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)?; @@ -115,15 +129,20 @@ 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 { + 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(); + 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..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" @@ -118,6 +123,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/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 8444fc842a..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; } @@ -448,3 +460,90 @@ 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(); +} + +#[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(); +}