forge
Explore
Log in

Don't you dare go Hollow

im: store the session address from client_ip

Browse files at this commit

e61e812ef7481b81f646985b8a3839f35b1c7ba8Ahmet Kaan GümüşParent: 2043642
topcoat 0.9 reports the client through client_ip once one proxy hop is trusted. The old read took the first x-forwarded-for hop — or x-real-ip — from any peer, which a client can spoof. x-real-ip goes with it: the family proxy sets x-forwarded-for, so the fallback never fired.
crates/im-web/src/auth.rsmodified+68 -18
@@ -89,26 +89,13 @@ fn url_origin(raw: &str) -> Option<String> {
8989 }
9090
9191 /// Creation-time facts for the session row: the address the browser came
92-/// through and the agent it claims to be. The accept loop discards the peer
93-/// address, so the proxy headers are the only source — the first
94-/// `x-forwarded-for` hop, else `x-real-ip`, else nothing known.
92+/// through and the agent it claims to be. The address is `client_ip` under
93+/// the router's one trusted hop: the address that hop appended, or the peer
94+/// on a direct connection. A forwarding header a client supplies itself is
95+/// never read.
9596 fn session_meta(cx: &Cx) -> im_core::sessions::SessionMeta {
9697 let headers = topcoat::router::request::headers(cx);
97- let ip = headers
98- .get("x-forwarded-for")
99- .and_then(|value| value.to_str().ok())
100- .and_then(|value| value.split(',').next())
101- .map(str::trim)
102- .filter(|hop| !hop.is_empty())
103- .map(str::to_string)
104- .or_else(|| {
105- headers
106- .get("x-real-ip")
107- .and_then(|value| value.to_str().ok())
108- .map(str::trim)
109- .filter(|ip| !ip.is_empty())
110- .map(str::to_string)
111- });
98+ let ip = topcoat::router::request::client_ip(cx).map(|ip| ip.to_string());
11299 let agent = headers
113100 .get("user-agent")
114101 .and_then(|value| value.to_str().ok())
@@ -752,4 +739,67 @@ mod tests {
752739 // The local-path rule stands beside the origin rule.
753740 assert_eq!(logout_target(Some("/\\in.example"), &services), "/");
754741 }
742+
743+ mod session_meta_ip {
744+ use std::net::SocketAddr;
745+
746+ use topcoat::context::Cx;
747+ use topcoat::router::response::IntoResponse as _;
748+ use topcoat::router::{
749+ Body, Method, RemoteAddr, RouteFn, RouteFuture, Router, request::Request, to_bytes,
750+ };
751+
752+ use super::session_meta;
753+ use crate::server::trusted_proxies;
754+
755+ fn echo(cx: &Cx, _body: Body) -> RouteFuture<'_> {
756+ Box::pin(async move {
757+ session_meta(cx)
758+ .ip
759+ .unwrap_or_else(|| "none".to_string())
760+ .into_response(cx)
761+ })
762+ }
763+
764+ fn router(trust_one_hop: bool) -> Router {
765+ let builder = Router::builder().route(RouteFn::new(Method::GET, "/meta", echo));
766+ if trust_one_hop {
767+ builder.trusted_proxies(trusted_proxies()).build()
768+ } else {
769+ builder.build()
770+ }
771+ }
772+
773+ async fn ip(trust_one_hop: bool, peer: &str, forwarded: Option<&str>) -> String {
774+ let mut builder = Request::builder()
775+ .method(Method::GET)
776+ .uri("/meta")
777+ .extension(RemoteAddr(peer.parse::<SocketAddr>().unwrap()));
778+ if let Some(value) = forwarded {
779+ builder = builder.header("x-forwarded-for", value);
780+ }
781+ let response = router(trust_one_hop)
782+ .handle(builder.body(Body::empty()).unwrap())
783+ .await;
784+ String::from_utf8(to_bytes(response.into_body(), 64).await.unwrap().to_vec()).unwrap()
785+ }
786+
787+ #[tokio::test]
788+ async fn one_trusted_hop_reports_the_client_not_the_proxy() {
789+ let got = ip(true, "10.0.0.1:4242", Some("198.51.100.1")).await;
790+ assert_eq!(got, "198.51.100.1");
791+ }
792+
793+ #[tokio::test]
794+ async fn a_missing_header_falls_back_to_the_peer() {
795+ let got = ip(true, "203.0.113.9:4242", None).await;
796+ assert_eq!(got, "203.0.113.9");
797+ }
798+
799+ #[tokio::test]
800+ async fn an_untrusted_peer_cannot_spoof_the_forwarded_header() {
801+ let got = ip(false, "203.0.113.9:4242", Some("198.51.100.1")).await;
802+ assert_eq!(got, "203.0.113.9");
803+ }
804+ }
755805 }
crates/im-web/src/main.rsmodified+1 -0
@@ -435,6 +435,7 @@ async fn serve(config: Config) {
435435 .layer(BodyLimit::max(photo::PHOTO_LIMIT_BYTES as usize + 4096).at("/api/profile_photo"))
436436 .cookies()
437437 .assets(bundle)
438+ .trusted_proxies(server::trusted_proxies())
438439 .app_context(app)
439440 .app_context(live::Shutdown(stopping))
440441 .build();
crates/im-web/src/server.rsmodified+6 -0
@@ -26,6 +26,12 @@ pub const PENDING_COOKIE: &str = "im_pending";
2626 /// short enough to not be a session.
2727 pub const PENDING_MINUTES: i64 = 10;
2828
29+/// One proxy hop in front of the process. `im` is reached through that hop,
30+/// so `client_ip` reads the address it appended rather than the hop's own.
31+/// A direct connection, with no hop in front, is its own address.
32+pub fn trusted_proxies() -> topcoat::router::TrustedProxies {
33+ topcoat::router::TrustedProxies::new().nearest(1)
34+}
2935 pub struct App {
3036 pub store: Arc<Store>,
3137 pub config: Config,