Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/aaemu-game/app/Configurations/AccessLevels.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/aaemu-game/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = [
"--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));
}
2 changes: 1 addition & 1 deletion rust/crates/aaemu-login/app/Config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"AutoAccount": true,
"SkipHostResolve": false,
"InternalNetwork": {
"Host": "*",
"Host": "127.0.0.1",
"Port": 1234
},
"Network": {
Expand Down
16 changes: 16 additions & 0 deletions rust/crates/aaemu-login/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = [
"--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();
Expand Down
35 changes: 27 additions & 8 deletions rust/crates/aaemu-login/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<LoginServer>,
conn: &Arc<InternalConnection>,
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)?;
Expand All @@ -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);
Expand Down
15 changes: 14 additions & 1 deletion rust/crates/aaemu-login/src/handlers/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions rust/crates/aaemu-login/src/network/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ pub struct InternalConnection {
game_server: Mutex<Option<GameServerId>>,
/// 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,
}

Expand All @@ -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<GameServerId> {
*self.game_server.lock().unwrap()
}
Expand Down
105 changes: 102 additions & 3 deletions rust/crates/aaemu-login/tests/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
}
Expand Down Expand Up @@ -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();
}
Loading