diff --git a/crates/sixm-server/src/app.rs b/crates/sixm-server/src/app.rs index 8305ec2..45b25c7 100644 --- a/crates/sixm-server/src/app.rs +++ b/crates/sixm-server/src/app.rs @@ -83,6 +83,9 @@ impl App { if let Some(v) = s.stream_distance { server_options.stream_distance = v; } + if let Some(v) = s.trusted_proxies { + server_options.trusted_proxies = v; + } if let Some(v) = s.tags { server_options.tags = v; } diff --git a/crates/sixm-server/src/config.rs b/crates/sixm-server/src/config.rs index e0b5c52..2054dab 100644 --- a/crates/sixm-server/src/config.rs +++ b/crates/sixm-server/src/config.rs @@ -45,6 +45,8 @@ pub struct Settings { pub host: Option, pub tick_rate: Option, pub stream_distance: Option, + /// Proxies whose `X-Forwarded-For` is believed, by address. + pub trusted_proxies: Option>, pub tags: Option>, } @@ -249,6 +251,22 @@ fn apply_setting(settings: &mut Settings, key: &str, value: &str) -> Option { + let mut proxies = Vec::new(); + for part in value.split([',', ' ']).filter(|p| !p.trim().is_empty()) { + match part.trim().parse::() { + Ok(ip) => proxies.push(ip), + Err(_) => { + return Some(Err(format!( + "sv_proxies must be IP addresses (got \"{}\")", + part.trim() + ))) + } + } + } + settings.trusted_proxies = Some(proxies); + Ok(()) + } _ => return None, }; Some(result) @@ -263,6 +281,7 @@ fn is_setting_convar(key: &str) -> bool { | "sv_host" | "sv_tickrate" | "sv_streamdistance" + | "sv_proxies" ) } diff --git a/crates/sixm-server/src/core.rs b/crates/sixm-server/src/core.rs index 355b59a..638909c 100644 --- a/crates/sixm-server/src/core.rs +++ b/crates/sixm-server/src/core.rs @@ -77,6 +77,8 @@ pub struct ServerOptions { pub tick_rate: u32, /// Players further apart than this do not see each other; `<= 0` means unlimited. pub stream_distance: f32, + /// Proxies whose `X-Forwarded-For` is believed, by address. + pub trusted_proxies: Vec, /// Version string shown in `/info.json` and on the status page. pub build: String, pub tags: Vec, @@ -115,6 +117,7 @@ impl Default for ServerOptions { max_players: 32, tick_rate: 20, stream_distance: 500.0, + trusted_proxies: Vec::new(), build: env!("CARGO_PKG_VERSION").to_string(), tags: Vec::new(), vars: BTreeMap::new(), @@ -224,6 +227,7 @@ impl Server { max_players: options.max_players, tick_rate: options.tick_rate, stream_distance: options.stream_distance, + trusted_proxies: options.trusted_proxies, build: options.build, tags: options.tags, limits, @@ -665,6 +669,7 @@ struct Inner { max_players: u32, tick_rate: u32, stream_distance: f32, + trusted_proxies: Vec, build: String, tags: Vec, limits: Limits, @@ -1496,7 +1501,7 @@ impl Inner { }; // An IPv4 client on a dual-stack socket shows up as ::ffff:a.b.c.d. - let ip = remote.ip().to_canonical(); + let ip = client_ip(remote.ip().to_canonical(), headers, &self.trusted_proxies); let endpoint = SocketAddr::new(ip, remote.port()).to_string(); let (tx, rx) = mpsc::unbounded_channel(); let conn = { @@ -1727,6 +1732,49 @@ fn json_response(status: StatusCode, body: &impl Serialize) -> HttpResponse { res } +/// The client's address: its own, or the right-most address in `X-Forwarded-For` +/// that is not one of our proxies when the peer itself is one. The header from any +/// other peer is forged by definition and ignored. +/// +/// Every `X-Forwarded-For` line counts, in order: a proxy may add a line of its own +/// instead of appending to the client's, and the client's line comes first. The walk +/// stops at the first hop that is not an address and falls back to the peer, because +/// everything to the left of it is only as trustworthy as that hop. +fn client_ip( + peer: std::net::IpAddr, + headers: &hyper::HeaderMap, + trusted: &[std::net::IpAddr], +) -> std::net::IpAddr { + if !trusted.contains(&peer) { + return peer; + } + let mut hops = Vec::new(); + for line in headers.get_all("x-forwarded-for") { + let Ok(line) = line.to_str() else { + return peer; + }; + hops.extend(line.split(',').map(str::trim).filter(|hop| !hop.is_empty())); + } + for hop in hops.into_iter().rev() { + let Some(ip) = forwarded_hop(hop) else { + return peer; + }; + if !trusted.contains(&ip) { + return ip; + } + } + peer +} + +/// One `X-Forwarded-For` entry as an address. Some proxies add the port +/// (`203.0.113.9:51234`, `[2001:db8::1]:51234`), which is dropped. +fn forwarded_hop(hop: &str) -> Option { + hop.parse::() + .or_else(|_| hop.parse::().map(|addr| addr.ip())) + .ok() + .map(|ip| ip.to_canonical()) +} + /// An upgrade request is refused with a bare status and the connection closed. fn refusal(status: StatusCode) -> HttpResponse { let mut res = Response::new(Full::default()); diff --git a/crates/sixm-server/tests/config.rs b/crates/sixm-server/tests/config.rs index 9a816bc..fb489b9 100644 --- a/crates/sixm-server/tests/config.rs +++ b/crates/sixm-server/tests/config.rs @@ -106,6 +106,7 @@ sv_hostname "Leonida Nights" sv_maxclients 48 set sv_tickrate 30 set sv_streamdistance 350.5 +sv_proxies "127.0.0.1, 10.0.0.5" sets tags "roleplay, eu ,, drift" sets locale en-GB setr voice_enabled true @@ -130,6 +131,10 @@ frobnicate 1 2 max_players: Some(48), tick_rate: Some(30), stream_distance: Some(350.5), + trusted_proxies: Some(vec![ + "127.0.0.1".parse().unwrap(), + "10.0.0.5".parse().unwrap() + ]), tags: Some(vec![ "roleplay".to_string(), "eu".to_string(), @@ -148,7 +153,7 @@ frobnicate 1 2 assert_eq!(cfg.convars["sv_hostname"], "Leonida Nights"); assert_eq!(cfg.convars["locale"], "en-GB"); assert_eq!(cfg.replicated, ["voice_enabled"]); - assert_eq!(cfg.unknown, [cmd("frobnicate", &["1", "2"], 17)]); + assert_eq!(cfg.unknown, [cmd("frobnicate", &["1", "2"], 18)]); assert!( !cfg.info_vars.contains_key("mysql_string"), "private convars are not public" diff --git a/crates/sixm-server/tests/core.rs b/crates/sixm-server/tests/core.rs index ad277ae..4807421 100644 --- a/crates/sixm-server/tests/core.rs +++ b/crates/sixm-server/tests/core.rs @@ -191,9 +191,26 @@ impl Client { } async fn connect_to(port: u16, path: &str) -> Client { + Client::connect_with(port, path, &[]).await + } + + /// A client whose upgrade request carries extra headers, the way a proxy forwards one. + async fn connect_with(port: u16, path: &str, headers: &[(&str, &str)]) -> Client { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); - let url = format!("ws://127.0.0.1:{port}{path}"); - let (mut ws, _) = tokio_tungstenite::client_async(url, stream).await.unwrap(); + let mut request = format!("ws://127.0.0.1:{port}{path}") + .into_client_request() + .unwrap(); + for (name, value) in headers { + request.headers_mut().append( + tokio_tungstenite::tungstenite::http::HeaderName::from_bytes(name.as_bytes()) + .unwrap(), + value.parse().unwrap(), + ); + } + let (mut ws, _) = tokio_tungstenite::client_async(request, stream) + .await + .unwrap(); let (commands, mut rx) = mpsc::unbounded_channel(); let received = Rc::new(Received::default()); let seen = received.clone(); @@ -232,7 +249,11 @@ impl Client { /// Connect, say hello and wait for the WELCOME. async fn join(port: u16, name: &str) -> Client { - let mut client = Client::connect(port).await; + Client::join_with(port, name, &[]).await + } + + async fn join_with(port: u16, name: &str, headers: &[(&str, &str)]) -> Client { + let mut client = Client::connect_with(port, "/", headers).await; client.hello(name); client.welcome = client.next("welcome").await; client.id = client.welcome["id"].as_u64().unwrap() as u16; @@ -1116,6 +1137,123 @@ fn state_flood_is_dropped_silently_not_kicked() { // ----------------------------------------------------------- player_connecting +#[test] +fn a_trusted_proxy_hands_over_the_client_address_from_x_forwarded_for() { + run(async { + let (server, port) = start(ServerOptions { + trusted_proxies: vec!["127.0.0.1".parse().unwrap()], + ..options() + }) + .await; + let recorder = Recorder::install(&server); + let _client = + Client::join_with(port, "Via Proxy", &[("x-forwarded-for", "203.0.113.9")]).await; + + let seen = recorder.connecting.borrow(); + assert!( + seen[0].endpoint.starts_with("203.0.113.9:"), + "endpoint was {}", + seen[0].endpoint + ); + assert_eq!(seen[0].identifiers, ["ip:203.0.113.9"]); + }); +} + +#[test] +fn an_untrusted_peer_cannot_forge_x_forwarded_for() { + run(async { + let (server, port) = start(options()).await; + let recorder = Recorder::install(&server); + let _client = + Client::join_with(port, "Forger", &[("x-forwarded-for", "203.0.113.9")]).await; + + let seen = recorder.connecting.borrow(); + assert!(seen[0].endpoint.starts_with("127.0.0.1:")); + assert_eq!(seen[0].identifiers, ["ip:127.0.0.1"]); + }); +} + +#[test] +fn a_chain_of_two_proxies_yields_the_address_before_the_trusted_ones() { + run(async { + let (server, port) = start(ServerOptions { + trusted_proxies: vec!["127.0.0.1".parse().unwrap(), "10.0.0.5".parse().unwrap()], + ..options() + }) + .await; + let recorder = Recorder::install(&server); + let _client = Client::join_with( + port, + "Behind Two", + &[("x-forwarded-for", "198.51.100.7, 10.0.0.5")], + ) + .await; + + let seen = recorder.connecting.borrow(); + assert!( + seen[0].endpoint.starts_with("198.51.100.7:"), + "endpoint was {}", + seen[0].endpoint + ); + assert_eq!(seen[0].identifiers, ["ip:198.51.100.7"]); + }); +} + +/// The `ip:` identifier a player gets when the peer is the trusted proxy 127.0.0.1 +/// and the upgrade request carries these headers. +async fn identifiers_behind_local_proxy(headers: &[(&str, &str)]) -> Vec { + let (server, port) = start(ServerOptions { + trusted_proxies: vec!["127.0.0.1".parse().unwrap()], + ..options() + }) + .await; + let recorder = Recorder::install(&server); + let _client = Client::join_with(port, "Behind Proxy", headers).await; + let seen = recorder.connecting.borrow(); + seen[0].identifiers.clone() +} + +#[test] +fn a_forged_x_forwarded_for_line_does_not_hide_the_proxys_own_line() { + run(async { + // The client sent the first line; the proxy added the second instead of appending. + let identifiers = identifiers_behind_local_proxy(&[ + ("x-forwarded-for", "203.0.113.9"), + ("x-forwarded-for", "198.51.100.7"), + ]) + .await; + assert_eq!(identifiers, ["ip:198.51.100.7"]); + }); +} + +#[test] +fn a_hop_with_a_port_is_read_as_its_address() { + run(async { + let v4 = identifiers_behind_local_proxy(&[( + "x-forwarded-for", + "203.0.113.9, 198.51.100.7:51234", + )]) + .await; + assert_eq!(v4, ["ip:198.51.100.7"]); + let v6 = identifiers_behind_local_proxy(&[( + "x-forwarded-for", + "203.0.113.9, [2001:db8::1]:51234", + )]) + .await; + assert_eq!(v6, ["ip:2001:db8::1"]); + }); +} + +#[test] +fn a_hop_that_is_not_an_address_ends_the_walk_at_the_proxy() { + run(async { + // "unknown" is what the proxy saw; the entry to its left is the client's own claim. + let identifiers = + identifiers_behind_local_proxy(&[("x-forwarded-for", "203.0.113.9, unknown")]).await; + assert_eq!(identifiers, ["ip:127.0.0.1"]); + }); +} + #[test] fn player_connecting_synchronous_reject() { run(async { diff --git a/docs/configuration.md b/docs/configuration.md index d07357b..d02647e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -40,6 +40,7 @@ If there is no configuration file, the server logs a warning, uses the defaults | `endpoint_add_tcp` | `endpoint_add_tcp "0.0.0.0:30120"` | `0.0.0.0:30120` | Address and port to listen on. Also accepts a port alone, or `[v6-address]:port` | | `sv_tickrate` | `sv_tickrate 20` | `20` | Ticks per second, 1 to 240: how often snapshots are sent and sleeping script threads are woken | | `sv_streamdistance` | `sv_streamdistance 500` | `500` | Players further apart than this are not sent to each other. `0` or less means no limit | +| `sv_proxies` | `sv_proxies "127.0.0.1, 10.0.0.5"` | none | Reverse proxies whose `X-Forwarded-For` is believed. The header from any other peer is ignored | | `ensure` | `ensure hello` | | Start the resource named `hello`. `start` means the same | | `stop` | `stop hello` | | Take a resource back off the start list | | `set` | `set mykey value` | | Set a convar | diff --git a/docs/hosting.md b/docs/hosting.md index 28957d9..2dc49af 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -122,9 +122,20 @@ Players then connect with `--secure` on the proxy's port: .\sixm-client.exe --host play.example.com --port 443 --secure --name Alice ``` -Behind a proxy the server sees every player coming from the proxy's address, because it does not read -`X-Forwarded-For` ([#10](https://github.com/CodingRule/SixM/issues/10)). `GetPlayerEndpoint` and the `ip:` -identifier are therefore the same for everyone. +Behind a proxy the server would otherwise see every player coming from the proxy's address. Name the proxy +addresses in `server.cfg` and the server believes `X-Forwarded-For` from them, and nobody else: + +``` +sv_proxies "127.0.0.1, 10.0.0.5" +``` + +The client address is the right-most one in the header that is not itself a listed proxy, so a chain of two +proxies works. `GetPlayerEndpoint` and the `ip:` identifier then show the player, not the proxy. + +Entries are single addresses, not ranges. A proxy that adds its own `X-Forwarded-For` line instead of appending +to the client's is read correctly, and so is an entry with a port (`203.0.113.9:51234`). If the entry a proxy +added is not an address at all, the server stops there and uses the proxy's address, rather than believe +whatever the client wrote before it. ## Run it as a service on Linux