From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by lists.proxmox.com (Postfix) with ESMTPS id 263E96090E for ; Thu, 15 Oct 2020 17:44:22 +0200 (CEST) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id 0F806143C0 for ; Thu, 15 Oct 2020 17:43:52 +0200 (CEST) Received: from proxmox-new.maurer-it.com (proxmox-new.maurer-it.com [212.186.127.180]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by firstgate.proxmox.com (Proxmox) with ESMTPS id B6E8C142E9 for ; Thu, 15 Oct 2020 17:43:50 +0200 (CEST) Received: from proxmox-new.maurer-it.com (localhost.localdomain [127.0.0.1]) by proxmox-new.maurer-it.com (Proxmox) with ESMTP id 7C96C45DB5 for ; Thu, 15 Oct 2020 17:43:50 +0200 (CEST) From: Thomas Lamprecht To: pbs-devel@lists.proxmox.com Date: Thu, 15 Oct 2020 17:43:42 +0200 Message-Id: <20201015154342.11210-1-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.27.0 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL -0.135 Adjusted score from AWL reputation of From: address KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record URIBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to URIBL was blocked. See http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block for more information. [access.rs, environment.rs, rest.rs] Subject: [pbs-devel] [PATCH backup] server/rest: forward real client IP on proxied request X-BeenThere: pbs-devel@lists.proxmox.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Proxmox Backup Server development discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Thu, 15 Oct 2020 15:44:22 -0000 needs new proxmox dependency to get the RpcEnvironment changes, adding client_ip getter and setter. Signed-off-by: Thomas Lamprecht --- NOTE: needs new (not yet bumped) proxmox crate for the client_ip setter/getter src/api2/access.rs | 7 ++++++- src/server/environment.rs | 10 ++++++++++ src/server/rest.rs | 38 ++++++++++++++++++++++++++++++++------ 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/api2/access.rs b/src/api2/access.rs index 81666bda..19b128b1 100644 --- a/src/api2/access.rs +++ b/src/api2/access.rs @@ -138,6 +138,7 @@ fn create_ticket( path: Option, privs: Option, port: Option, + rpcenv: &mut dyn RpcEnvironment, ) -> Result { match authenticate_user(&username, &password, path, privs, port) { Ok(true) => { @@ -157,7 +158,11 @@ fn create_ticket( "username": username, })), Err(err) => { - let client_ip = "unknown"; // $rpcenv->get_client_ip() || ''; + let client_ip = match rpcenv.get_client_ip().map(|addr| addr.ip()) { + Some(ip) => format!("{}", ip), + None => "unknown".into(), + }; + log::error!("authentication failure; rhost={} user={} msg={}", client_ip, username, err.to_string()); Err(http_err!(UNAUTHORIZED, "permission check failed.")) } diff --git a/src/server/environment.rs b/src/server/environment.rs index 10ff958c..5fbff307 100644 --- a/src/server/environment.rs +++ b/src/server/environment.rs @@ -7,6 +7,7 @@ pub struct RestEnvironment { env_type: RpcEnvironmentType, result_attributes: Value, user: Option, + client_ip: Option, } impl RestEnvironment { @@ -14,6 +15,7 @@ impl RestEnvironment { Self { result_attributes: json!({}), user: None, + client_ip: None, env_type, } } @@ -40,4 +42,12 @@ impl RpcEnvironment for RestEnvironment { fn get_user(&self) -> Option { self.user.clone() } + + fn set_client_ip(&mut self, client_ip: Option) { + self.client_ip = client_ip; + } + + fn get_client_ip(&self) -> Option { + self.client_ip.clone() + } } diff --git a/src/server/rest.rs b/src/server/rest.rs index d145573f..98e56039 100644 --- a/src/server/rest.rs +++ b/src/server/rest.rs @@ -9,13 +9,15 @@ use std::task::{Context, Poll}; use anyhow::{bail, format_err, Error}; use futures::future::{self, FutureExt, TryFutureExt}; use futures::stream::TryStreamExt; -use hyper::header; +use hyper::header::{self, HeaderMap}; use hyper::http::request::Parts; use hyper::{Body, Request, Response, StatusCode}; +use lazy_static::lazy_static; use serde_json::{json, Value}; use tokio::fs::File; use tokio::time::Instant; use url::form_urlencoded; +use regex::Regex; use proxmox::http_err; use proxmox::api::{ @@ -127,6 +129,17 @@ fn log_response( } } +fn get_proxied_peer(headers: &HeaderMap) -> Option { + lazy_static! { + static ref RE: Regex = Regex::new(r#"for="([^"]+)""#).unwrap(); + } + let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?; + let capture = RE.captures(&forwarded)?; + let rhost = capture.get(1)?.as_str(); + + rhost.parse().ok() +} + impl tower_service::Service> for ApiService { type Response = Response; type Error = Error; @@ -141,9 +154,12 @@ impl tower_service::Service> for ApiService { let method = req.method().clone(); let config = Arc::clone(&self.api_config); - let peer = self.peer; + let peer = match get_proxied_peer(req.headers()) { + Some(proxied_peer) => proxied_peer, + None => self.peer, + }; async move { - let response = match handle_request(config, req).await { + let response = match handle_request(config, req, &peer).await { Ok(response) => response, Err(err) => { let (err, code) = match err.downcast_ref::() { @@ -246,6 +262,7 @@ async fn proxy_protected_request( info: &'static ApiMethod, mut parts: Parts, req_body: Body, + peer: &std::net::SocketAddr, ) -> Result, Error> { let mut uri_parts = parts.uri.clone().into_parts(); @@ -256,7 +273,10 @@ async fn proxy_protected_request( parts.uri = new_uri; - let request = Request::from_parts(parts, req_body); + let mut request = Request::from_parts(parts, req_body); + request + .headers_mut() + .insert(header::FORWARDED, format!("for=\"{}\";", peer).parse().unwrap()); let reload_timezone = info.reload_timezone; @@ -505,7 +525,11 @@ fn check_auth( Ok(userid) } -async fn handle_request(api: Arc, req: Request) -> Result, Error> { +async fn handle_request( + api: Arc, + req: Request, + peer: &std::net::SocketAddr, +) -> Result, Error> { let (parts, body) = req.into_parts(); @@ -517,6 +541,8 @@ async fn handle_request(api: Arc, req: Request) -> Result, req: Request) -> Result