move normalize_uri_path and extract_cookie to proxmox-rest-server crate

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Dietmar Maurer 2021-09-21 07:58:45 +02:00 committed by Thomas Lamprecht
parent 605fe2e7e7
commit 778c7d954b
6 changed files with 55 additions and 54 deletions

View File

@ -15,6 +15,7 @@ lazy_static = "1.4"
libc = "0.2" libc = "0.2"
log = "0.4" log = "0.4"
nix = "0.19.1" nix = "0.19.1"
percent-encoding = "2.1"
serde = { version = "1.0", features = [] } serde = { version = "1.0", features = [] }
serde_json = "1.0" serde_json = "1.0"
tokio = { version = "1.6", features = ["signal", "process"] } tokio = { version = "1.6", features = ["signal", "process"] }

View File

@ -88,3 +88,50 @@ pub fn socketpair() -> Result<(Fd, Fd), Error> {
Ok((Fd(pa), Fd(pb))) 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<String> {
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))
}

View File

@ -6,10 +6,9 @@ use std::sync::Arc;
use pbs_tools::ticket::{self, Ticket}; use pbs_tools::ticket::{self, Ticket};
use pbs_config::{token_shadow, CachedUserInfo}; use pbs_config::{token_shadow, CachedUserInfo};
use pbs_api_types::{Authid, Userid}; use pbs_api_types::{Authid, Userid};
use proxmox_rest_server::{ApiAuth, AuthError}; use proxmox_rest_server::{ApiAuth, AuthError, extract_cookie};
use crate::auth_helpers::*; use crate::auth_helpers::*;
use crate::tools;
use hyper::header; use hyper::header;
use percent_encoding::percent_decode_str; use percent_encoding::percent_decode_str;
@ -33,7 +32,7 @@ impl UserApiAuth {
fn extract_auth_data(headers: &http::HeaderMap) -> Option<AuthData> { fn extract_auth_data(headers: &http::HeaderMap) -> Option<AuthData> {
if let Some(raw_cookie) = headers.get(header::COOKIE) { if let Some(raw_cookie) = headers.get(header::COOKIE) {
if let Ok(cookie) = raw_cookie.to_str() { 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()) { let csrf_token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
Some(Ok(v)) => Some(v.to_owned()), Some(Ok(v)) => Some(v.to_owned()),
_ => None, _ => None,

View File

@ -11,9 +11,9 @@ use hyper::{Body, Request, Response, StatusCode};
use proxmox::api::{ApiResponseFuture, HttpError, Router, RpcEnvironment}; use proxmox::api::{ApiResponseFuture, HttpError, Router, RpcEnvironment};
use proxmox::http_err; use proxmox::http_err;
use proxmox_rest_server::normalize_uri_path;
use proxmox_rest_server::formatter::*; use proxmox_rest_server::formatter::*;
use crate::tools;
use crate::server::WorkerTask; use crate::server::WorkerTask;
/// Hyper Service implementation to handle stateful H2 connections. /// Hyper Service implementation to handle stateful H2 connections.
@ -44,7 +44,7 @@ impl <E: RpcEnvironment + Clone> H2Service<E> {
let method = parts.method.clone(); 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), Ok((p,c)) => (p, c),
Err(err) => return future::err(http_err!(BAD_REQUEST, "{}", err)).boxed(), Err(err) => return future::err(http_err!(BAD_REQUEST, "{}", err)).boxed(),
}; };

View File

@ -36,13 +36,13 @@ use pbs_tools::stream::AsyncReaderStream;
use pbs_api_types::{Authid, Userid}; use pbs_api_types::{Authid, Userid};
use proxmox_rest_server::{ use proxmox_rest_server::{
ApiConfig, FileLogger, FileLogOptions, AuthError, RestEnvironment, CompressionMethod, ApiConfig, FileLogger, FileLogOptions, AuthError, RestEnvironment, CompressionMethod,
extract_cookie, normalize_uri_path,
}; };
use proxmox_rest_server::formatter::*; use proxmox_rest_server::formatter::*;
use pbs_config::CachedUserInfo; use pbs_config::CachedUserInfo;
use crate::auth_helpers::*; use crate::auth_helpers::*;
use crate::tools;
extern "C" { extern "C" {
fn tzset(); fn tzset();
@ -645,7 +645,7 @@ async fn handle_static_file_download(
fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> { fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) { 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 None
} }
@ -669,7 +669,7 @@ async fn handle_request(
) -> Result<Response<Body>, Error> { ) -> Result<Response<Body>, Error> {
let (parts, body) = req.into_parts(); let (parts, body) = req.into_parts();
let method = parts.method.clone(); 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(); let comp_len = components.len();

View File

@ -49,27 +49,6 @@ pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
Ok(()) 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<String> {
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 /// Detect modified configuration files
/// ///
@ -81,31 +60,6 @@ pub fn detect_modified_configuration_file(digest1: &[u8;32], digest2: &[u8;32])
Ok(()) 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 /// An easy way to convert types to Any
/// ///
/// Mostly useful to downcast trait objects (see RpcEnvironment). /// Mostly useful to downcast trait objects (see RpcEnvironment).