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)) (No client certificate requested) by lists.proxmox.com (Postfix) with ESMTPS id 359006B220 for ; Mon, 20 Sep 2021 09:38:56 +0200 (CEST) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id C0A1F1C49E for ; Mon, 20 Sep 2021 09:38:24 +0200 (CEST) Received: from proxmox-new.maurer-it.com (proxmox-new.maurer-it.com [94.136.29.106]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits)) (No client certificate requested) by firstgate.proxmox.com (Proxmox) with ESMTPS id B9BF91C3A1 for ; Mon, 20 Sep 2021 09:38:18 +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 940D3449AD; Mon, 20 Sep 2021 09:38:18 +0200 (CEST) From: Dietmar Maurer To: pbs-devel@lists.proxmox.com Date: Mon, 20 Sep 2021 09:38:05 +0200 Message-Id: <20210920073813.3178009-7-dietmar@proxmox.com> X-Mailer: git-send-email 2.30.2 In-Reply-To: <20210920073813.3178009-1-dietmar@proxmox.com> References: <20210920073813.3178009-1-dietmar@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.648 Adjusted score from AWL reputation of From: address BAYES_00 -1.9 Bayes spam probability is 0 to 1% KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Subject: [pbs-devel] [PATCH proxmox-backup 07/15] move normalize_uri_path and extract_cookie to pbs-server crate 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: Mon, 20 Sep 2021 07:38:56 -0000 --- pbs-server/Cargo.toml | 1 + pbs-server/src/lib.rs | 47 +++++++++++++++++++++++++++++++++++++++++ src/server/auth.rs | 5 ++--- src/server/h2service.rs | 4 ++-- src/server/rest.rs | 6 +++--- src/tools/mod.rs | 46 ---------------------------------------- 6 files changed, 55 insertions(+), 54 deletions(-) diff --git a/pbs-server/Cargo.toml b/pbs-server/Cargo.toml index 9e93fb0e..9f76f720 100644 --- a/pbs-server/Cargo.toml +++ b/pbs-server/Cargo.toml @@ -15,6 +15,7 @@ lazy_static = "1.4" libc = "0.2" log = "0.4" nix = "0.19.1" +percent-encoding = "2.1" serde = { version = "1.0", features = [] } serde_json = "1.0" tokio = { version = "1.6", features = ["signal", "process"] } diff --git a/pbs-server/src/lib.rs b/pbs-server/src/lib.rs index 069d80b4..9107a03f 100644 --- a/pbs-server/src/lib.rs +++ b/pbs-server/src/lib.rs @@ -88,3 +88,50 @@ pub fn socketpair() -> Result<(Fd, Fd), Error> { Ok((Fd(pa), Fd(pb))) } + +/// Extract a specific cookie from cookie header. +/// We assume cookie_name is already url encoded. +pub fn extract_cookie(cookie: &str, cookie_name: &str) -> Option { + for pair in cookie.split(';') { + let (name, value) = match pair.find('=') { + Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()), + None => return None, // Cookie format error + }; + + if name == cookie_name { + use percent_encoding::percent_decode; + if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() { + return Some(value.into()); + } else { + return None; // Cookie format error + } + } + } + + None +} + +/// normalize uri path +/// +/// Do not allow ".", "..", or hidden files ".XXXX" +/// Also remove empty path components +pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> { + let items = path.split('/'); + + let mut path = String::new(); + let mut components = vec![]; + + for name in items { + if name.is_empty() { + continue; + } + if name.starts_with('.') { + bail!("Path contains illegal components."); + } + path.push('/'); + path.push_str(name); + components.push(name); + } + + Ok((path, components)) +} diff --git a/src/server/auth.rs b/src/server/auth.rs index 3e2d0c89..d7fbf511 100644 --- a/src/server/auth.rs +++ b/src/server/auth.rs @@ -6,10 +6,9 @@ use std::sync::Arc; use pbs_tools::ticket::{self, Ticket}; use pbs_config::{token_shadow, CachedUserInfo}; use pbs_api_types::{Authid, Userid}; -use pbs_server::{ApiAuth, AuthError}; +use pbs_server::{ApiAuth, AuthError, extract_cookie}; use crate::auth_helpers::*; -use crate::tools; use hyper::header; use percent_encoding::percent_decode_str; @@ -33,7 +32,7 @@ impl UserApiAuth { fn extract_auth_data(headers: &http::HeaderMap) -> Option { if let Some(raw_cookie) = headers.get(header::COOKIE) { if let Ok(cookie) = raw_cookie.to_str() { - if let Some(ticket) = tools::extract_cookie(cookie, "PBSAuthCookie") { + if let Some(ticket) = extract_cookie(cookie, "PBSAuthCookie") { let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) { Some(Ok(v)) => Some(v.to_owned()), _ => None, diff --git a/src/server/h2service.rs b/src/server/h2service.rs index bc9561d3..9b473bbf 100644 --- a/src/server/h2service.rs +++ b/src/server/h2service.rs @@ -11,9 +11,9 @@ use hyper::{Body, Request, Response, StatusCode}; use proxmox::api::{ApiResponseFuture, HttpError, Router, RpcEnvironment}; use proxmox::http_err; +use pbs_server::normalize_uri_path; use pbs_server::formatter::*; -use crate::tools; use crate::server::WorkerTask; /// Hyper Service implementation to handle stateful H2 connections. @@ -44,7 +44,7 @@ impl H2Service { let method = parts.method.clone(); - let (path, components) = match tools::normalize_uri_path(parts.uri.path()) { + let (path, components) = match normalize_uri_path(parts.uri.path()) { Ok((p,c)) => (p, c), Err(err) => return future::err(http_err!(BAD_REQUEST, "{}", err)).boxed(), }; diff --git a/src/server/rest.rs b/src/server/rest.rs index e1a081b6..a47f0b87 100644 --- a/src/server/rest.rs +++ b/src/server/rest.rs @@ -36,13 +36,13 @@ use pbs_tools::stream::AsyncReaderStream; use pbs_api_types::{Authid, Userid}; use pbs_server::{ ApiConfig, FileLogger, FileLogOptions, AuthError, RestEnvironment, CompressionMethod, + extract_cookie, normalize_uri_path, }; use pbs_server::formatter::*; use pbs_config::CachedUserInfo; use crate::auth_helpers::*; -use crate::tools; extern "C" { fn tzset(); @@ -645,7 +645,7 @@ async fn handle_static_file_download( fn extract_lang_header(headers: &http::HeaderMap) -> Option { if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) { - return tools::extract_cookie(cookie, "PBSLangCookie"); + return extract_cookie(cookie, "PBSLangCookie"); } None } @@ -669,7 +669,7 @@ async fn handle_request( ) -> Result, Error> { let (parts, body) = req.into_parts(); let method = parts.method.clone(); - let (path, components) = tools::normalize_uri_path(parts.uri.path())?; + let (path, components) = normalize_uri_path(parts.uri.path())?; let comp_len = components.len(); diff --git a/src/tools/mod.rs b/src/tools/mod.rs index f2576b08..5dc129f0 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -49,27 +49,6 @@ pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> { Ok(()) } -/// Extract a specific cookie from cookie header. -/// We assume cookie_name is already url encoded. -pub fn extract_cookie(cookie: &str, cookie_name: &str) -> Option { - for pair in cookie.split(';') { - let (name, value) = match pair.find('=') { - Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()), - None => return None, // Cookie format error - }; - - if name == cookie_name { - use percent_encoding::percent_decode; - if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() { - return Some(value.into()); - } else { - return None; // Cookie format error - } - } - } - - None -} /// Detect modified configuration files /// @@ -81,31 +60,6 @@ pub fn detect_modified_configuration_file(digest1: &[u8;32], digest2: &[u8;32]) Ok(()) } -/// normalize uri path -/// -/// Do not allow ".", "..", or hidden files ".XXXX" -/// Also remove empty path components -pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> { - let items = path.split('/'); - - let mut path = String::new(); - let mut components = vec![]; - - for name in items { - if name.is_empty() { - continue; - } - if name.starts_with('.') { - bail!("Path contains illegal components."); - } - path.push('/'); - path.push_str(name); - components.push(name); - } - - Ok((path, components)) -} - /// An easy way to convert types to Any /// /// Mostly useful to downcast trait objects (see RpcEnvironment). -- 2.30.2