v0.42.2
This commit is contained in:
1 parent
aa0a271a1c
commit
f38a2b9e5e
38 files changed
+1098
-160
No files matched your search
@@ -9,6 +9,28 @@ impl Php {
|
||||
"Web Service PHP extension",
|
||||
)?;
|
||||
self.endpoint = self.endpoint.trim().to_owned();
|
||||
self.script_name_prefix = self.script_name_prefix.trim().to_owned();
|
||||
if !self.script_name_prefix.is_empty() {
|
||||
ensure!(
|
||||
self.script_name_prefix.starts_with('/')
|
||||
&& !self.script_name_prefix.ends_with('/')
|
||||
&& self.script_name_prefix.len() <= 256
|
||||
&& self.script_name_prefix.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'-' | b'.')
|
||||
})
|
||||
&& self.script_name_prefix.split('/').skip(1).all(|part| {
|
||||
!part.is_empty() && part != "." && part != ".."
|
||||
}),
|
||||
"Web Service FastCGI SCRIPT_NAME prefix must be /path (no trailing slash, dot segments or special characters)"
|
||||
);
|
||||
}
|
||||
if self.handler != FastCgiHandler::PhpFpm {
|
||||
ensure!(self.php_values.is_empty() && self.php_admin_values.is_empty(),
|
||||
"PHP_VALUE and PHP_ADMIN_VALUE require handler=php_fpm");
|
||||
ensure!(self.extensions.iter().all(|ext| !matches!(ext.as_str(),
|
||||
"php" | "phtml" | "phar" | "php3" | "php4" | "php5" | "php7" | "php8")),
|
||||
"non-PHP FastCGI handlers cannot execute PHP extensions; use php_fpm");
|
||||
}
|
||||
ensure!(
|
||||
self.connect_timeout_ms >= 50 && self.connect_timeout_ms <= 60_000,
|
||||
"Web Service PHP connect timeout must be 50..60000 ms"
|
||||
@@ -57,7 +79,7 @@ impl Php {
|
||||
if self.enabled {
|
||||
ensure!(
|
||||
!self.extensions.is_empty(),
|
||||
"PHP-FPM needs executable extensions"
|
||||
"FastCGI needs at least one executable extension"
|
||||
);
|
||||
FastCgiEndpoint::parse(&self.endpoint)?;
|
||||
}
|
||||
@@ -304,12 +326,12 @@ impl Service {
|
||||
if self.php.enabled {
|
||||
ensure!(
|
||||
!self.php.extensions.is_empty(),
|
||||
"Web Service PHP needs at least one executable extension"
|
||||
"Web Service FastCGI needs at least one executable extension"
|
||||
);
|
||||
FastCgiEndpoint::parse(&self.php.endpoint)?;
|
||||
ensure!(
|
||||
self.symlink_policy == SymlinkPolicy::Deny,
|
||||
"PHP-FPM currently requires symlink_policy=deny to avoid script-path races"
|
||||
"FastCGI script execution requires symlink_policy=deny to avoid script-path races"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -348,7 +370,8 @@ impl Service {
|
||||
let htaccess = htaccess::compile(&root, &self.htaccess)?;
|
||||
if let Some(compiled) = &htaccess {
|
||||
ensure!(
|
||||
self.php.enabled || !htaccess::adds_php_extensions(Some(compiled)),
|
||||
(self.php.enabled && self.php.handler == FastCgiHandler::PhpFpm)
|
||||
|| !htaccess::adds_php_extensions(Some(compiled)),
|
||||
".htaccess AddHandler for PHP requires PHP-FPM to be enabled on the Web Service"
|
||||
);
|
||||
tracing::debug!(service = %self.id, files = compiled.files_loaded, ".htaccess compatibility compiled");
|
||||
@@ -397,6 +420,7 @@ impl Service {
|
||||
script_extensions.extend(
|
||||
[
|
||||
"php", "phtml", "phar", "php3", "php4", "php5", "php7", "php8",
|
||||
"cgi", "fcgi", "pl", "py", "sh",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned),
|
||||
@@ -406,6 +430,8 @@ impl Service {
|
||||
extensions: self.php.extensions.iter().cloned().collect(),
|
||||
path_info: self.php.path_info,
|
||||
endpoint: FastCgiEndpoint::parse(&self.php.endpoint)?,
|
||||
handler: self.php.handler,
|
||||
script_name_prefix: self.php.script_name_prefix.clone(),
|
||||
connect_timeout: Duration::from_millis(self.php.connect_timeout_ms),
|
||||
request_timeout: Duration::from_millis(self.php.request_timeout_ms),
|
||||
permits: Arc::new(Semaphore::new(self.php.max_concurrent_requests)),
|
||||
|
||||
@@ -112,6 +112,8 @@ fn reserved_fastcgi_param(name: &str) -> bool {
|
||||
| "SERVER_PORT"
|
||||
| "REMOTE_ADDR"
|
||||
| "REMOTE_PORT"
|
||||
| "REMOTE_USER"
|
||||
| "AUTH_USER"
|
||||
| "HTTPS"
|
||||
| "GATEWAY_INTERFACE"
|
||||
| "SERVER_SOFTWARE"
|
||||
@@ -259,6 +261,15 @@ impl Default for Precompressed {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FastCgiHandler {
|
||||
#[default]
|
||||
PhpFpm,
|
||||
Fcgiwrap,
|
||||
Fastcgi,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Php {
|
||||
@@ -267,6 +278,11 @@ pub struct Php {
|
||||
#[serde(default = "default_php_extensions")]
|
||||
pub extensions: Vec<String>,
|
||||
pub endpoint: String,
|
||||
/// Existing configurations default to PHP-FPM; fcgiwrap runs installed CGI scripts.
|
||||
pub handler: FastCgiHandler,
|
||||
/// Public URL prefix when a Vhost location rewrites a mount path.
|
||||
/// SCRIPT_FILENAME stays confined to document_root; SCRIPT_NAME gains this prefix.
|
||||
pub script_name_prefix: String,
|
||||
#[serde(default = "default_php_connect_timeout_ms")]
|
||||
pub connect_timeout_ms: u64,
|
||||
#[serde(default = "default_php_request_timeout_ms")]
|
||||
@@ -292,6 +308,8 @@ impl Default for Php {
|
||||
path_info: false,
|
||||
extensions: default_php_extensions(),
|
||||
endpoint: "unix:/run/php/php-fpm.sock".into(),
|
||||
handler: FastCgiHandler::PhpFpm,
|
||||
script_name_prefix: String::new(),
|
||||
connect_timeout_ms: default_php_connect_timeout_ms(),
|
||||
request_timeout_ms: default_php_request_timeout_ms(),
|
||||
max_concurrent_requests: default_php_max_concurrent_requests(),
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
impl FastCgiEndpoint {
|
||||
pub(super) fn parse(value: &str) -> Result<Self> {
|
||||
if let Some(path) = value.strip_prefix("unix:") {
|
||||
ensure!(!path.trim().is_empty(), "PHP-FPM unix socket path is empty");
|
||||
ensure!(!path.trim().is_empty(), "FastCGI Unix socket path is empty");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
return Ok(Self::Unix(PathBuf::from(path)));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
anyhow::bail!("PHP-FPM unix sockets require a Unix platform");
|
||||
anyhow::bail!("FastCGI Unix sockets require a Unix platform");
|
||||
}
|
||||
if let Some(address) = value.strip_prefix("tcp:") {
|
||||
let address = address
|
||||
.parse::<std::net::SocketAddr>()
|
||||
.context("PHP-FPM TCP endpoint must be an IP socket address")?;
|
||||
.context("FastCGI TCP endpoint must be an IP socket address")?;
|
||||
ensure!(
|
||||
address.ip().is_loopback(),
|
||||
"PHP-FPM TCP endpoint must use a loopback address"
|
||||
"FastCGI TCP endpoint must use a loopback address"
|
||||
);
|
||||
return Ok(Self::Tcp(address));
|
||||
}
|
||||
anyhow::bail!("PHP-FPM endpoint must start with unix: or tcp:")
|
||||
anyhow::bail!("FastCGI endpoint must start with unix: or tcp:")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,8 @@ pub(crate) struct CompiledPhp {
|
||||
pub(super) extensions: HashSet<String>,
|
||||
pub(super) path_info: bool,
|
||||
pub(super) endpoint: FastCgiEndpoint,
|
||||
pub(super) handler: FastCgiHandler,
|
||||
pub(super) script_name_prefix: String,
|
||||
pub(super) connect_timeout: Duration,
|
||||
pub(super) request_timeout: Duration,
|
||||
pub(crate) permits: Arc<Semaphore>,
|
||||
@@ -69,3 +71,11 @@ pub struct CompiledService {
|
||||
#[cfg(unix)]
|
||||
pub(super) root_handle: Arc<File>,
|
||||
}
|
||||
|
||||
impl CompiledService {
|
||||
// Read-only diagnostics for the authenticated administration UI. Warnings
|
||||
// come from the active compiled snapshot, not from another filesystem scan.
|
||||
pub fn htaccess_diagnostics(&self) -> Option<(usize, &[String])> {
|
||||
self.htaccess.as_ref().map(|compiled| (compiled.files_loaded, compiled.warnings.as_slice()))
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,11 @@ pub(super) fn fastcgi_params(
|
||||
let mut params = BTreeMap::<String, String>::new();
|
||||
params.insert("REQUEST_METHOD".into(), method.as_str().into());
|
||||
params.insert("SCRIPT_FILENAME".into(), script_filename);
|
||||
params.insert("SCRIPT_NAME".into(), script_path.into());
|
||||
params.insert("SCRIPT_NAME".into(), format!("{}{}", php.script_name_prefix, script_path));
|
||||
if let Some(username) = context.authenticated_user.as_deref() {
|
||||
params.insert("REMOTE_USER".into(), username.to_owned());
|
||||
params.insert("AUTH_USER".into(), username.to_owned());
|
||||
}
|
||||
if let Some(path_info) = path_info.filter(|value| !value.is_empty()) {
|
||||
params.insert("PATH_INFO".into(), path_info.into());
|
||||
}
|
||||
@@ -208,7 +212,7 @@ pub(super) fn fastcgi_params(
|
||||
for (name, value) in &php.custom_params {
|
||||
params.insert(name.clone(), value.clone());
|
||||
}
|
||||
if !php.php_values.is_empty() {
|
||||
if php.handler == super::config::FastCgiHandler::PhpFpm && !php.php_values.is_empty() {
|
||||
let mut value = String::new();
|
||||
for (name, item) in &php.php_values {
|
||||
if !value.is_empty() {
|
||||
@@ -220,7 +224,7 @@ pub(super) fn fastcgi_params(
|
||||
}
|
||||
params.insert("PHP_VALUE".into(), value);
|
||||
}
|
||||
if !php.php_admin_values.is_empty() {
|
||||
if php.handler == super::config::FastCgiHandler::PhpFpm && !php.php_admin_values.is_empty() {
|
||||
let value = php
|
||||
.php_admin_values
|
||||
.iter()
|
||||
@@ -375,7 +379,7 @@ async fn drain_fastcgi_body(
|
||||
if !stderr.is_empty() {
|
||||
tracing::warn!(
|
||||
stderr = %String::from_utf8_lossy(&stderr),
|
||||
"PHP-FPM FastCGI stderr"
|
||||
"FastCGI stderr"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn php_response_inner(
|
||||
Ok(Ok(io)) => io,
|
||||
Ok(Err(error)) => {
|
||||
php.metrics.failure(2);
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM connection failed");
|
||||
tracing::warn!(%error, service = %service.id, "FastCGI connection failed");
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -94,7 +94,7 @@ async fn php_response_inner(
|
||||
) {
|
||||
Ok(params) => params,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM parameter preparation failed");
|
||||
tracing::warn!(%error, service = %service.id, "FastCGI parameter preparation failed");
|
||||
php.metrics.failure(4);
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
@@ -136,7 +136,7 @@ async fn php_response_inner(
|
||||
}
|
||||
Ok(Err(FastCgiRequestWriteError::Io(error))) => {
|
||||
php.metrics.failure(4);
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM request write failed");
|
||||
tracing::warn!(%error, service = %service.id, "FastCGI request write failed");
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -156,7 +156,7 @@ async fn php_response_inner(
|
||||
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM response read failed");
|
||||
tracing::warn!(%error, service = %service.id, "FastCGI response read failed");
|
||||
php.metrics.failure(6);
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
@@ -174,7 +174,7 @@ async fn php_response_inner(
|
||||
match parsed {
|
||||
Ok((status, headers)) => break (status, headers, body),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, service = %service.id, "PHP-FPM CGI headers rejected");
|
||||
tracing::warn!(%error, service = %service.id, "FastCGI CGI headers rejected");
|
||||
php.metrics.failure(7);
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
@@ -188,7 +188,7 @@ async fn php_response_inner(
|
||||
FCGI_END_REQUEST => {
|
||||
php.metrics.failure(7);
|
||||
if !stderr.is_empty() {
|
||||
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "PHP-FPM FastCGI stderr");
|
||||
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
|
||||
}
|
||||
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
||||
}
|
||||
@@ -196,7 +196,7 @@ async fn php_response_inner(
|
||||
}
|
||||
};
|
||||
if !stderr.is_empty() {
|
||||
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "PHP-FPM FastCGI stderr");
|
||||
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
|
||||
}
|
||||
let send_body = method != Method::HEAD
|
||||
&& status != StatusCode::NO_CONTENT
|
||||
@@ -258,9 +258,6 @@ pub(super) fn php_for_path<'a>(
|
||||
}
|
||||
|
||||
pub(super) fn protected_script_without_handler(service: &CompiledService, path: &Path) -> bool {
|
||||
if service.php.is_some() {
|
||||
return false;
|
||||
}
|
||||
path.extension()
|
||||
.and_then(|value| value.to_str())
|
||||
.map(|value| value.to_ascii_lowercase())
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
routing::open_components,
|
||||
};
|
||||
use anyhow::{bail, ensure, Context, Result};
|
||||
use ipnet::IpNet;
|
||||
use axum::{body::Body, response::Response};
|
||||
use http::{
|
||||
header::{CACHE_CONTROL, EXPIRES, LOCATION},
|
||||
@@ -14,6 +15,7 @@ use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
fs,
|
||||
io::Read,
|
||||
net::IpAddr,
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
time::{Duration, SystemTime},
|
||||
@@ -27,6 +29,8 @@ const MAX_HTACCESS_RULES: usize = 256;
|
||||
const MAX_HTACCESS_CONDITIONS: usize = 512;
|
||||
const MAX_HTACCESS_HEADERS: usize = 64;
|
||||
const MAX_HTACCESS_MIME_TYPES: usize = 128;
|
||||
const MAX_HTACCESS_ACCESS_SELECTORS: usize = 128;
|
||||
const MAX_HTACCESS_FILE_RULES: usize = 64;
|
||||
|
||||
fn default_filename() -> String {
|
||||
".htaccess".into()
|
||||
@@ -85,6 +89,7 @@ pub struct Compiled {
|
||||
struct Scope {
|
||||
components: Vec<String>,
|
||||
rewrites: Vec<RewriteRule>,
|
||||
redirects: Vec<SimpleRedirect>,
|
||||
directory_index: Option<Vec<String>>,
|
||||
directory_listing: Option<bool>,
|
||||
mime_types: BTreeMap<String, HeaderValue>,
|
||||
@@ -94,6 +99,83 @@ struct Scope {
|
||||
expires_default: Option<Duration>,
|
||||
expires_by_type: Vec<(String, Duration)>,
|
||||
deny_all: Option<bool>,
|
||||
legacy_access: Option<LegacyAccess>,
|
||||
file_rules: Vec<FileAccessRule>,
|
||||
}
|
||||
|
||||
// Apache Files / FilesMatch rules apply to filenames below their directory.
|
||||
// Only bounded access-control directives are accepted inside these blocks.
|
||||
#[derive(Debug, Clone)]
|
||||
struct FileAccessRule {
|
||||
matcher: Regex,
|
||||
deny_all: Option<bool>,
|
||||
legacy_access: Option<LegacyAccess>,
|
||||
}
|
||||
impl FileAccessRule {
|
||||
fn denied(&self, client_ip: IpAddr) -> Option<bool> {
|
||||
if let Some(legacy) = &self.legacy_access {
|
||||
Some(self.deny_all.unwrap_or(false) || legacy.denied(client_ip))
|
||||
} else {
|
||||
self.deny_all
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apache 2.2 mod_access_compat's Order/Allow/Deny are access rules, not
|
||||
// harmless unsupported directives. Evaluate them instead of silently skipping
|
||||
// them and accidentally publishing protected files.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
enum LegacyOrder {
|
||||
#[default]
|
||||
DenyAllow,
|
||||
AllowDeny,
|
||||
MutualFailure,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum AccessSelector {
|
||||
All,
|
||||
Network(IpNet),
|
||||
}
|
||||
|
||||
impl AccessSelector {
|
||||
fn matches(&self, client_ip: IpAddr) -> bool {
|
||||
match self {
|
||||
Self::All => true,
|
||||
Self::Network(network) => network.contains(&client_ip),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct LegacyAccess {
|
||||
order: LegacyOrder,
|
||||
allow: Vec<AccessSelector>,
|
||||
deny: Vec<AccessSelector>,
|
||||
}
|
||||
|
||||
impl LegacyAccess {
|
||||
fn denied(&self, client_ip: IpAddr) -> bool {
|
||||
let allowed = self.allow.iter().any(|selector| selector.matches(client_ip));
|
||||
let denied = self.deny.iter().any(|selector| selector.matches(client_ip));
|
||||
match self.order {
|
||||
LegacyOrder::DenyAllow => denied && !allowed,
|
||||
LegacyOrder::AllowDeny | LegacyOrder::MutualFailure => !allowed || denied,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct SimpleRedirect {
|
||||
matcher: RedirectMatcher,
|
||||
replacement: String,
|
||||
status: StatusCode,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum RedirectMatcher {
|
||||
Prefix(String),
|
||||
Regex(Regex),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -158,7 +240,7 @@ struct ParseState {
|
||||
rewrite_engine: bool,
|
||||
pending_conditions: Vec<RewriteCondition>,
|
||||
skip_next_rule: bool,
|
||||
in_files_block: usize,
|
||||
file_block: Option<FileAccessRule>,
|
||||
unsupported: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -395,6 +477,37 @@ fn normalize_extension(value: &str) -> Result<String> {
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn legacy_access_selectors(parts: &[String], path: &Path, line_no: usize) -> Result<Vec<AccessSelector>> {
|
||||
ensure!(
|
||||
parts.len() >= 3 && parts[1].eq_ignore_ascii_case("from"),
|
||||
"{}:{line_no}: {} expects 'from all' or 'from IP/CIDR'",
|
||||
path.display(),
|
||||
parts[0]
|
||||
);
|
||||
ensure!(
|
||||
parts.len() - 2 <= MAX_HTACCESS_ACCESS_SELECTORS,
|
||||
"{}:{line_no}: too many access-control selectors",
|
||||
path.display()
|
||||
);
|
||||
let mut selectors = Vec::with_capacity(parts.len() - 2);
|
||||
for value in &parts[2..] {
|
||||
if value.eq_ignore_ascii_case("all") {
|
||||
selectors.push(AccessSelector::All);
|
||||
} else {
|
||||
let network = if let Ok(ip) = value.parse::<IpAddr>() {
|
||||
IpNet::from(ip)
|
||||
} else {
|
||||
value.parse::<IpNet>().with_context(|| format!(
|
||||
"{}:{line_no}: unsupported {} source {value:?}; only all, IP and CIDR are supported to avoid weakening access control",
|
||||
path.display(), parts[0]
|
||||
))?
|
||||
};
|
||||
selectors.push(AccessSelector::Network(network));
|
||||
}
|
||||
}
|
||||
Ok(selectors)
|
||||
}
|
||||
|
||||
fn unsupported(
|
||||
state: &mut ParseState,
|
||||
config: &Config,
|
||||
|
||||
@@ -1,3 +1,115 @@
|
||||
fn redirect_status(value: &str) -> Option<StatusCode> {
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"permanent" | "301" => Some(StatusCode::MOVED_PERMANENTLY),
|
||||
"temp" | "temporary" | "302" => Some(StatusCode::FOUND),
|
||||
"seeother" | "303" => Some(StatusCode::SEE_OTHER),
|
||||
"307" => Some(StatusCode::TEMPORARY_REDIRECT),
|
||||
"308" => Some(StatusCode::PERMANENT_REDIRECT),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
|
||||
let (status, source_index) = if parts.len() == 4 {
|
||||
(redirect_status(&parts[1]).context("unsupported Redirect status")?, 2)
|
||||
} else {
|
||||
ensure!(parts.len() == 3, "Redirect / RedirectMatch expects [status] source target");
|
||||
(StatusCode::FOUND, 1)
|
||||
};
|
||||
let source = &parts[source_index];
|
||||
let replacement = &parts[source_index + 1];
|
||||
ensure!(!source.is_empty() && source.len() <= 512 && replacement.len() <= 1024,
|
||||
"Redirect source/target is invalid");
|
||||
ensure!((replacement.starts_with('/') && !replacement.starts_with("//"))
|
||||
|| replacement.starts_with("http://") || replacement.starts_with("https://"),
|
||||
"Redirect target must be a local absolute path or an explicit http(s) URL");
|
||||
ensure!(!replacement.contains('\\') && !replacement.contains('\r') && !replacement.contains('\n'),
|
||||
"Redirect target contains unsafe characters");
|
||||
HeaderValue::from_str(replacement).context("invalid Redirect target")?;
|
||||
let matcher = if regex {
|
||||
RedirectMatcher::Regex(Regex::new(source).context("invalid RedirectMatch regex")?)
|
||||
} else {
|
||||
ensure!(source.starts_with('/') && !source.starts_with("//")
|
||||
&& !source.contains('\r') && !source.contains('\n') && !source.contains('?')
|
||||
&& !source.contains('#') && !source.contains('\\'), "invalid Redirect path prefix");
|
||||
RedirectMatcher::Prefix(source.to_owned())
|
||||
};
|
||||
Ok(SimpleRedirect { matcher, replacement: replacement.to_owned(), status })
|
||||
}
|
||||
|
||||
// Only a safe, deterministic subset of Apache access rules is allowed in
|
||||
// <Files> and <FilesMatch>. Unknown directives inside a security scope must
|
||||
// fail closed, including when the general "ignore unsupported" option is off.
|
||||
fn file_rule_start(line: &str) -> Result<FileAccessRule> {
|
||||
let inner = line.trim().strip_prefix('<').and_then(|s| s.strip_suffix('>'))
|
||||
.context("unterminated Files or FilesMatch tag")?;
|
||||
let (tag, value) = inner.split_once(char::is_whitespace)
|
||||
.context("Files or FilesMatch requires a filename/pattern")?;
|
||||
let values = tokens(value)?;
|
||||
let regex_pattern = if tag.eq_ignore_ascii_case("filesmatch") {
|
||||
ensure!(values.len() == 1, "FilesMatch needs one quoted regex");
|
||||
values[0].clone()
|
||||
} else {
|
||||
// Apache also accepts <Files ~ "regex"> as an alias of FilesMatch.
|
||||
if values.len() == 2 && values[0] == "~" {
|
||||
values[1].clone()
|
||||
} else {
|
||||
ensure!(values.len() == 1, "Files needs a single filename/glob");
|
||||
let mut pattern = String::from("^");
|
||||
for ch in values[0].chars() {
|
||||
match ch {
|
||||
'*' => pattern.push_str(".*"),
|
||||
'?' => pattern.push('.'),
|
||||
_ => pattern.push_str(®ex::escape(&ch.to_string())),
|
||||
}
|
||||
}
|
||||
pattern.push('$');
|
||||
pattern
|
||||
}
|
||||
};
|
||||
ensure!(regex_pattern.len() <= 512, "Files/FilesMatch pattern exceeds 512 bytes");
|
||||
Ok(FileAccessRule { matcher: Regex::new(®ex_pattern)
|
||||
.context("invalid Files/FilesMatch regular expression")?,
|
||||
deny_all: None, legacy_access: None })
|
||||
}
|
||||
|
||||
fn apply_access_directive(
|
||||
directive: &str, parts: &[String], path: &Path, line_no: usize,
|
||||
deny_all: &mut Option<bool>, legacy_access: &mut Option<LegacyAccess>,
|
||||
) -> Result<()> {
|
||||
match directive {
|
||||
"require" => {
|
||||
if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("denied") {
|
||||
*deny_all = Some(true);
|
||||
} else if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("granted") {
|
||||
*deny_all = Some(false);
|
||||
} else {
|
||||
bail!("{}:{line_no}: unsupported Require; refusing to ignore access control", path.display());
|
||||
}
|
||||
}
|
||||
"order" => {
|
||||
ensure!(parts.len() == 2, "{}:{line_no}: Order expects allow,deny or deny,allow", path.display());
|
||||
let order = match parts[1].to_ascii_lowercase().as_str() {
|
||||
"deny,allow" => LegacyOrder::DenyAllow,
|
||||
"allow,deny" => LegacyOrder::AllowDeny,
|
||||
"mutual-failure" => LegacyOrder::MutualFailure,
|
||||
_ => bail!("{}:{line_no}: unsupported Order value {:?}", path.display(), parts[1]),
|
||||
};
|
||||
legacy_access.get_or_insert_with(LegacyAccess::default).order = order;
|
||||
}
|
||||
"allow" | "deny" => {
|
||||
let selectors = legacy_access_selectors(parts, path, line_no)?;
|
||||
let access = legacy_access.get_or_insert_with(LegacyAccess::default);
|
||||
let dest = if directive == "allow" { &mut access.allow } else { &mut access.deny };
|
||||
ensure!(dest.len() + selectors.len() <= MAX_HTACCESS_ACCESS_SELECTORS,
|
||||
"{}:{line_no}: too many access-control selectors", path.display());
|
||||
dest.extend(selectors);
|
||||
}
|
||||
_ => bail!("{}:{line_no}: unsupported access directive", path.display()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(Scope, Vec<String>)> {
|
||||
let content = read_htaccess_nofollow(path)?;
|
||||
let mut scope = Scope { components, ..Scope::default() };
|
||||
@@ -11,21 +123,33 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
if line.is_empty() || line.starts_with('#') { continue; }
|
||||
let lower_line = line.to_ascii_lowercase();
|
||||
if lower_line.starts_with("<ifmodule") || lower_line == "</ifmodule>" { continue; }
|
||||
if lower_line.starts_with("<files") || lower_line.starts_with("<filesmatch") {
|
||||
if lower_line.contains(".htaccess") || lower_line.contains(".htpasswd") || lower_line.contains("^\\.ht") {
|
||||
state.in_files_block = state.in_files_block.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
bail!("{}:{line_no}: general Files/FilesMatch semantics are not supported; refusing to ignore an access/handler scope", path.display());
|
||||
}
|
||||
if line.eq_ignore_ascii_case("</Files>") || line.eq_ignore_ascii_case("</FilesMatch>") {
|
||||
state.in_files_block = state.in_files_block.saturating_sub(1);
|
||||
if lower_line == "</files>" || lower_line == "</filesmatch>" {
|
||||
let rule = state.file_block.take()
|
||||
.with_context(|| format!("{}:{line_no}: unmatched Files/FilesMatch closing tag", path.display()))?;
|
||||
ensure!(rule.deny_all.is_some() || rule.legacy_access.is_some(),
|
||||
"{}:{line_no}: Files/FilesMatch block has no supported access rule", path.display());
|
||||
scope.file_rules.push(rule);
|
||||
continue;
|
||||
}
|
||||
if state.in_files_block != 0 {
|
||||
if lower_line.starts_with("<files ") || lower_line.starts_with("<filesmatch ") {
|
||||
ensure!(state.file_block.is_none(), "{}:{line_no}: nested Files/FilesMatch blocks are unsupported", path.display());
|
||||
ensure!(scope.file_rules.len() < MAX_HTACCESS_FILE_RULES,
|
||||
"{}:{line_no}: too many Files/FilesMatch rules", path.display());
|
||||
state.file_block = Some(file_rule_start(line)
|
||||
.with_context(|| format!("{}:{line_no}", path.display()))?);
|
||||
continue;
|
||||
}
|
||||
let parts = tokens(line).with_context(|| format!("{}:{line_no}", path.display()))?;
|
||||
if let Some(rule) = state.file_block.as_mut() {
|
||||
let directive = parts.first().map(|s| s.to_ascii_lowercase()).unwrap_or_default();
|
||||
if !matches!(directive.as_str(), "require" | "order" | "allow" | "deny") {
|
||||
bail!("{}:{line_no}: unsupported {} inside Files/FilesMatch; refusing unsafe ignore",
|
||||
path.display(), parts.first().map(String::as_str).unwrap_or("directive"));
|
||||
}
|
||||
apply_access_directive(&directive, &parts, path, line_no,
|
||||
&mut rule.deny_all, &mut rule.legacy_access)?;
|
||||
continue;
|
||||
}
|
||||
if parts.is_empty() { continue; }
|
||||
let directive = parts[0].to_ascii_lowercase();
|
||||
match directive.as_str() {
|
||||
@@ -127,20 +251,25 @@ fn parse_file(path: &Path, components: Vec<String>, config: &Config) -> Result<(
|
||||
ensure!(parts.len() >= 3, "{}:{line_no}: ExpiresByType needs media type and duration", path.display());
|
||||
scope.expires_by_type.push((parts[1].to_ascii_lowercase(), parse_duration(&parts[2..].join(" "))?));
|
||||
}
|
||||
"require" => {
|
||||
if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("denied") { scope.deny_all = Some(true); }
|
||||
else if parts.len() == 3 && parts[1].eq_ignore_ascii_case("all") && parts[2].eq_ignore_ascii_case("granted") { scope.deny_all = Some(false); }
|
||||
else { bail!("{}:{line_no}: only 'Require all granted/denied' is supported; refusing to ignore an access-control directive", path.display()); }
|
||||
"require" | "order" | "allow" | "deny" => {
|
||||
apply_access_directive(&directive, &parts, path, line_no,
|
||||
&mut scope.deny_all, &mut scope.legacy_access)?;
|
||||
}
|
||||
"sethandler" | "removehandler" | "authtype" | "authname" | "authuserfile" | "authgroupfile" | "order" | "allow" | "deny" => {
|
||||
"sethandler" | "removehandler" | "authtype" | "authname" | "authuserfile" | "authgroupfile" => {
|
||||
bail!("{}:{line_no}: security/handler directive {} is not supported and cannot be ignored safely", path.display(), parts[0]);
|
||||
}
|
||||
"errordocument" | "setenvif" | "redirect" | "redirectmatch" | "fallbackresource" => {
|
||||
"redirect" | "redirectmatch" => {
|
||||
ensure!(scope.redirects.len() < 64, "{}:{line_no}: at most 64 Redirect/RedirectMatch rules per file", path.display());
|
||||
scope.redirects.push(redirect_rule(&parts, directive == "redirectmatch")
|
||||
.with_context(|| format!("{}:{line_no}", path.display()))?);
|
||||
}
|
||||
"errordocument" | "setenvif" | "fallbackresource" => {
|
||||
unsupported(&mut state, config, path, line_no, format!("directive {} is not in the RustProxy compatibility subset", parts[0]))?;
|
||||
}
|
||||
_ => unsupported(&mut state, config, path, line_no, format!("unsupported directive {}", parts[0]))?,
|
||||
}
|
||||
}
|
||||
ensure!(state.file_block.is_none(), "{}: unclosed Files/FilesMatch block", path.display());
|
||||
ensure!(state.pending_conditions.is_empty(), "{}: RewriteCond without following RewriteRule", path.display());
|
||||
Ok((scope, state.unsupported))
|
||||
}
|
||||
@@ -215,9 +344,28 @@ fn matching_scopes<'a>(compiled: &'a Compiled, path: &str) -> Vec<&'a Scope> {
|
||||
compiled.scopes.iter().filter(|scope| scope_matches(scope, &components)).collect()
|
||||
}
|
||||
|
||||
pub fn denied(compiled: Option<&Compiled>, path: &str) -> bool {
|
||||
pub fn denied(compiled: Option<&Compiled>, path: &str, client_ip: IpAddr) -> bool {
|
||||
let Some(compiled) = compiled else { return false; };
|
||||
matching_scopes(compiled, path).into_iter().filter_map(|scope| scope.deny_all).next_back().unwrap_or(false)
|
||||
let scopes = matching_scopes(compiled, path);
|
||||
// A matching <Files>/<FilesMatch> denial is additive. A narrower file
|
||||
// grant must not cancel a directory denial or another matched file rule.
|
||||
let basename = path_components(path).ok().and_then(|parts| parts.last().cloned());
|
||||
if let Some(name) = basename {
|
||||
for scope in &scopes {
|
||||
for rule in &scope.file_rules {
|
||||
if rule.matcher.is_match(&name) && rule.denied(client_ip) == Some(true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scopes.into_iter().filter_map(|scope| {
|
||||
if let Some(legacy) = &scope.legacy_access {
|
||||
Some(scope.deny_all.unwrap_or(false) || legacy.denied(client_ip))
|
||||
} else {
|
||||
scope.deny_all
|
||||
}
|
||||
}).next_back().unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn index_files<'a>(compiled: Option<&'a Compiled>, directory_components: &[String], fallback: &'a [String]) -> &'a [String] {
|
||||
|
||||
@@ -22,6 +22,37 @@ pub async fn apply_rewrites(
|
||||
let mut changed = false;
|
||||
let mut end = false;
|
||||
'scope: for scope in scopes {
|
||||
// Apache mod_alias Redirect / RedirectMatch, independently of RewriteEngine.
|
||||
for rule in &scope.redirects {
|
||||
let tail = match &rule.matcher {
|
||||
RedirectMatcher::Prefix(prefix) => {
|
||||
if path == *prefix { Some("") }
|
||||
else if prefix.ends_with('/') && path.starts_with(prefix) {
|
||||
Some(&path[prefix.len()..])
|
||||
} else { path.strip_prefix(prefix).filter(|tail| tail.starts_with('/')) }
|
||||
}
|
||||
RedirectMatcher::Regex(_) => None,
|
||||
};
|
||||
let target = match &rule.matcher {
|
||||
RedirectMatcher::Prefix(_) => tail.map(|tail| format!("{}{}", rule.replacement, tail)),
|
||||
RedirectMatcher::Regex(regex) => regex.captures(&path).map(|captures| {
|
||||
let mut target = String::new();
|
||||
captures.expand(&rule.replacement, &mut target);
|
||||
target
|
||||
}),
|
||||
};
|
||||
if let Some(mut target) = target {
|
||||
ensure!((target.starts_with('/') && !target.starts_with("//"))
|
||||
|| target.starts_with("http://") || target.starts_with("https://"),
|
||||
"unsafe .htaccess Redirect expansion");
|
||||
ensure!(!target.contains('\\') && !target.contains('\r') && !target.contains('\n'),
|
||||
"unsafe .htaccess Redirect expansion");
|
||||
if let Some(query) = query.as_deref().filter(|q| !q.is_empty()) {
|
||||
if !target.contains('?') { target.push('?'); target.push_str(query); }
|
||||
}
|
||||
return Ok(RewriteOutcome::Redirect(redirect_response(rule.status, &target)?));
|
||||
}
|
||||
}
|
||||
for rule in &scope.rewrites {
|
||||
let relative = scope_relative_path(scope, &path);
|
||||
if !rule.pattern.is_match(&relative) {
|
||||
|
||||
@@ -10,7 +10,7 @@ mod security;
|
||||
mod serve;
|
||||
|
||||
pub use config::{
|
||||
CacheRule, CompiledService, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
|
||||
CacheRule, CompiledService, FastCgiHandler, Hardening, Php, PhpFpmProfile, Precompressed, RewriteRule,
|
||||
SendfileMode, Service, SymlinkPolicy,
|
||||
};
|
||||
pub use htaccess::Config as HtaccessConfig;
|
||||
|
||||
@@ -8,6 +8,8 @@ pub struct RequestContext {
|
||||
pub server_port: u16,
|
||||
pub tls: bool,
|
||||
pub version: Version,
|
||||
/// Set only after Vhost Basic authentication has succeeded.
|
||||
pub authenticated_user: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn server_protocol(version: http::Version) -> &'static str {
|
||||
|
||||
+21
-12
@@ -4,6 +4,7 @@ use super::{
|
||||
},
|
||||
filesystem::{list_directory_sync, path_components, FilesystemRoot},
|
||||
htaccess,
|
||||
config::FastCgiHandler,
|
||||
response::{
|
||||
add_service_headers, builtin_error_response, directory_listing, directory_redirect,
|
||||
file_response, io_response, status_response,
|
||||
@@ -22,7 +23,7 @@ use http::{
|
||||
};
|
||||
use std::{io, path::PathBuf};
|
||||
|
||||
async fn resolve_php_path_info(
|
||||
async fn resolve_script_path_info(
|
||||
service: &CompiledService,
|
||||
components: &[String],
|
||||
) -> Option<(String, String)> {
|
||||
@@ -77,7 +78,7 @@ async fn serve_inner(
|
||||
components
|
||||
.iter()
|
||||
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
|
||||
}) || htaccess::denied(service.htaccess.as_ref(), path)
|
||||
}) || htaccess::denied(service.htaccess.as_ref(), path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
@@ -125,18 +126,18 @@ async fn serve_inner(
|
||||
htaccess::protected_component(service.htaccess.as_ref(), component)
|
||||
})
|
||||
})
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path)
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &rewritten_path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
if let Ok(components) = path_components(&rewritten_path) {
|
||||
if let Some((script_path, path_info)) = resolve_php_path_info(service, &components).await {
|
||||
if let Some((script_path, path_info)) = resolve_script_path_info(service, &components).await {
|
||||
let script_components = path_components(&script_path).unwrap_or_default();
|
||||
if hardening_denied_path(service, &script_path)
|
||||
|| script_components.iter().any(|component| {
|
||||
htaccess::protected_component(service.htaccess.as_ref(), component)
|
||||
})
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &script_path)
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
@@ -178,7 +179,7 @@ async fn serve_inner(
|
||||
|| components
|
||||
.iter()
|
||||
.any(|component| htaccess::protected_component(service.htaccess.as_ref(), component))
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &effective_path)
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &effective_path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
@@ -192,14 +193,14 @@ async fn serve_inner(
|
||||
) =>
|
||||
{
|
||||
if let Some((script_path, path_info)) =
|
||||
resolve_php_path_info(service, &components).await
|
||||
resolve_script_path_info(service, &components).await
|
||||
{
|
||||
let script_components = path_components(&script_path).unwrap_or_default();
|
||||
if hardening_denied_path(service, &script_path)
|
||||
|| script_components.iter().any(|component| {
|
||||
htaccess::protected_component(service.htaccess.as_ref(), component)
|
||||
})
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &script_path)
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
@@ -242,7 +243,10 @@ async fn serve_inner(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if protected_script_without_handler(service, &public_path) {
|
||||
if protected_script_without_handler(service, &public_path)
|
||||
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|
||||
{
|
||||
// A CGI-only root must never expose any non-executed file.
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
@@ -276,7 +280,9 @@ async fn serve_inner(
|
||||
let mut script_path = effective_path.trim_end_matches('/').to_owned();
|
||||
script_path.push('/');
|
||||
script_path.push_str(index);
|
||||
if hardening_denied_path(service, &script_path) {
|
||||
if hardening_denied_path(service, &script_path)
|
||||
|| htaccess::denied(service.htaccess.as_ref(), &script_path, context.client_ip)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
let public_path = PathBuf::from(&script_path);
|
||||
@@ -295,7 +301,9 @@ async fn serve_inner(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if protected_script_without_handler(service, &public_path) {
|
||||
if protected_script_without_handler(service, &public_path)
|
||||
|| service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|
||||
{
|
||||
return builtin_error_response(StatusCode::FORBIDDEN, &method);
|
||||
}
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
@@ -333,7 +341,8 @@ async fn serve_inner(
|
||||
if method != Method::GET && method != Method::HEAD {
|
||||
return method_not_allowed_response();
|
||||
}
|
||||
if !htaccess::directory_listing(
|
||||
if service.php.as_ref().is_some_and(|php| php.handler == FastCgiHandler::Fcgiwrap)
|
||||
|| !htaccess::directory_listing(
|
||||
service.htaccess.as_ref(),
|
||||
&components,
|
||||
service.directory_listing,
|
||||
|
||||
@@ -68,6 +68,7 @@ async fn serve_body_request(
|
||||
server_port: 80,
|
||||
tls: false,
|
||||
version: Version::HTTP_11,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -1126,6 +1127,62 @@ SetHandler application/x-httpd-php
|
||||
assert!(error.contains("Files/FilesMatch"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_legacy_deny_from_all_is_enforced_even_in_non_strict_mode() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("private")).unwrap();
|
||||
std::fs::write(tmp.path().join("index.html"), b"public").unwrap();
|
||||
std::fs::write(tmp.path().join("private/secret.txt"), b"secret").unwrap();
|
||||
std::fs::write(
|
||||
tmp.path().join("private/.htaccess"),
|
||||
b"Order allow,deny\nDeny from all\nErrorDocument 403 /denied.html\nOptions +FollowSymLinks\n",
|
||||
).unwrap();
|
||||
let mut configured = Service {
|
||||
id: "htaccess-deny-all".into(),
|
||||
name: "htaccess deny all".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
let service = configured.compile().unwrap();
|
||||
assert_eq!(service.htaccess.as_ref().unwrap().warnings.len(), 2);
|
||||
assert_eq!(serve_request(&service, &request(Method::GET, "/index.html"), "/index.html").await.status(), StatusCode::OK);
|
||||
assert_eq!(serve_request(&service, &request(Method::GET, "/private/secret.txt"), "/private/secret.txt").await.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_legacy_order_and_ip_rules_follow_apache_22_precedence() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let ht = tmp.path().join(".htaccess");
|
||||
let config = htaccess::Config { enabled: true, strict: true, ..Default::default() };
|
||||
|
||||
std::fs::write(&ht, b"Order deny,allow\nDeny from all\nAllow from 192.0.2.0/24\n").unwrap();
|
||||
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
|
||||
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
|
||||
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
|
||||
|
||||
std::fs::write(&ht, b"Order allow,deny\nAllow from 192.0.2.0/24\nDeny from 192.0.2.42\n").unwrap();
|
||||
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
|
||||
assert!(!htaccess::denied(Some(&compiled), "/index.html", "192.0.2.41".parse().unwrap()));
|
||||
assert!(htaccess::denied(Some(&compiled), "/index.html", "192.0.2.42".parse().unwrap()));
|
||||
assert!(htaccess::denied(Some(&compiled), "/index.html", "198.51.100.1".parse().unwrap()));
|
||||
|
||||
std::fs::write(&ht, b"Order allow,deny\nAllow from 2001:db8::/32\nDeny from 2001:db8::bad\n").unwrap();
|
||||
let compiled = htaccess::compile(tmp.path(), &config).unwrap().unwrap();
|
||||
assert!(!htaccess::denied(Some(&compiled), "/index.html", "2001:db8::1".parse().unwrap()));
|
||||
assert!(htaccess::denied(Some(&compiled), "/index.html", "2001:db8::bad".parse().unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_legacy_unsupported_hostnames_fail_closed_with_strict_disabled() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), b"Deny from protected.example\n").unwrap();
|
||||
let config = htaccess::Config { enabled: true, strict: false, ..Default::default() };
|
||||
let error = htaccess::compile(tmp.path(), &config).unwrap_err().to_string();
|
||||
assert!(error.contains("only all, IP and CIDR are supported"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn htaccess_strict_mode_rejects_unsupported_directives() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
@@ -1221,6 +1278,7 @@ fn fastcgi_never_forwards_proxy_header_as_http_proxy() {
|
||||
server_port: 80,
|
||||
tls: false,
|
||||
version: Version::HTTP_11,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1272,6 +1330,7 @@ fn php_custom_fastcgi_params_and_php_values_are_validated() {
|
||||
server_port: 443,
|
||||
tls: true,
|
||||
version: Version::HTTP_2,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1327,6 +1386,7 @@ fn fastcgi_path_info_keeps_script_filename_separate() {
|
||||
server_port: 80,
|
||||
tls: false,
|
||||
version: Version::HTTP_11,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1539,6 +1599,7 @@ fn php_admin_values_are_operator_only_and_serialized() {
|
||||
server_port: 8589,
|
||||
tls: false,
|
||||
version: Version::HTTP_11,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1596,6 +1657,7 @@ fn fastcgi_always_sets_http_host_for_http2_http3_wordpress_requests() {
|
||||
server_port: 443,
|
||||
tls: true,
|
||||
version,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1645,6 +1707,7 @@ fn fastcgi_http_host_keeps_explicit_host_and_port() {
|
||||
server_port: 443,
|
||||
tls: true,
|
||||
version: Version::HTTP_11,
|
||||
authenticated_user: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -2454,3 +2517,171 @@ fn sendfile_mode_is_backward_compatible_and_rejects_unknown_values() {
|
||||
SendfileMode::Off
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fastcgi_handler_is_backward_compatible_and_prevents_php_as_cgi() {
|
||||
let legacy: Php = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
|
||||
assert_eq!(legacy.handler, FastCgiHandler::PhpFpm);
|
||||
assert_eq!(legacy.script_name_prefix, "");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<FastCgiHandler>(r#""fcgiwrap""#).unwrap(),
|
||||
FastCgiHandler::Fcgiwrap
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<FastCgiHandler>(r#""fastcgi""#).unwrap(),
|
||||
FastCgiHandler::Fastcgi
|
||||
);
|
||||
for handler in [FastCgiHandler::Fcgiwrap, FastCgiHandler::Fastcgi] {
|
||||
let mut unsafe_php = Php {
|
||||
enabled: true,
|
||||
handler,
|
||||
extensions: vec!["php".into()],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(unsafe_php.validate().is_err());
|
||||
let mut unsafe_ini = Php {
|
||||
enabled: true,
|
||||
handler,
|
||||
extensions: vec!["cgi".into()],
|
||||
php_values: BTreeMap::from([("memory_limit".into(), "128M".into())]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(unsafe_ini.validate().is_err());
|
||||
}
|
||||
let mut bad_prefix = Php {
|
||||
enabled: true,
|
||||
handler: FastCgiHandler::Fcgiwrap,
|
||||
extensions: vec!["cgi".into()],
|
||||
script_name_prefix: "/app/../admin".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(bad_prefix.validate().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generic_fcgiwrap_mount_passes_public_script_name_without_exposing_other_files() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("health.cgi"), b"#!/bin/sh\necho ok\n").unwrap();
|
||||
std::fs::write(tmp.path().join("configuration.txt"), b"private CGI settings").unwrap();
|
||||
let (address, received) = fastcgi_fixture_record_params().await;
|
||||
let mut config = Service {
|
||||
id: "cgi-app".into(),
|
||||
name: "CGI app".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
php: Php {
|
||||
enabled: true,
|
||||
handler: FastCgiHandler::Fcgiwrap,
|
||||
extensions: vec!["cgi".into()],
|
||||
endpoint: format!("tcp:{address}"),
|
||||
path_info: true,
|
||||
script_name_prefix: "/app/cgi-bin".into(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
// The Vhost strips /app/cgi-bin before invoking the mounted Web Service.
|
||||
let uri = "/app/cgi-bin/health.cgi/more?query=1";
|
||||
let response = serve_request(&service, &request(Method::GET, uri), "/health.cgi/more").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let params = received.await.unwrap();
|
||||
assert_eq!(params["SCRIPT_FILENAME"].as_str(), tmp.path().join("health.cgi").to_string_lossy().as_ref());
|
||||
assert_eq!(params["SCRIPT_NAME"], "/app/cgi-bin/health.cgi");
|
||||
assert_eq!(params["PATH_INFO"], "/more");
|
||||
assert_eq!(params["REQUEST_URI"], uri);
|
||||
assert_eq!(params["QUERY_STRING"], "query=1");
|
||||
let forbidden = serve_request(
|
||||
&service,
|
||||
&request(Method::GET, "/app/cgi-bin/configuration.txt"),
|
||||
"/configuration.txt",
|
||||
).await;
|
||||
assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generic_fastcgi_responder_executes_only_configured_script_extensions() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("handler.fcgi"), b"script").unwrap();
|
||||
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
|
||||
let (address, received) = fastcgi_fixture_record_params().await;
|
||||
let mut config = Service {
|
||||
id: "responder".into(),
|
||||
name: "FastCGI responder".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
php: Php {
|
||||
enabled: true,
|
||||
handler: FastCgiHandler::Fastcgi,
|
||||
extensions: vec!["fcgi".into()],
|
||||
endpoint: format!("tcp:{address}"),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
let executed = serve_request(&service, &request(Method::GET, "/handler.fcgi"), "/handler.fcgi").await;
|
||||
assert_eq!(executed.status(), StatusCode::OK);
|
||||
assert_eq!(received.await.unwrap()["SCRIPT_NAME"], "/handler.fcgi");
|
||||
let static_file = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
|
||||
assert_eq!(static_file.status(), StatusCode::OK);
|
||||
assert_eq!(static_file.into_body().collect().await.unwrap().to_bytes(), "public");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_filesmatch_enforces_denial_including_directory_index() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join("index.html"), b"index").unwrap();
|
||||
std::fs::write(tmp.path().join("secret.env"), b"secret").unwrap();
|
||||
std::fs::write(tmp.path().join("public.txt"), b"public").unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), r#"
|
||||
<FilesMatch "^secret\.env$">
|
||||
Require all denied
|
||||
</FilesMatch>
|
||||
<Files "index.html">
|
||||
Deny from all
|
||||
</Files>
|
||||
"#).unwrap();
|
||||
let mut config = Service {
|
||||
id: "files-rule".into(),
|
||||
name: "Files rule".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
for path in ["/secret.env", "/", "/index.html"] {
|
||||
let response = serve_request(&service, &request(Method::GET, path), path).await;
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{path}");
|
||||
}
|
||||
let good = serve_request(&service, &request(Method::GET, "/public.txt"), "/public.txt").await;
|
||||
assert_eq!(good.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn htaccess_redirect_and_redirectmatch_are_applied_without_rewriteengine() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::fs::write(tmp.path().join(".htaccess"), r#"
|
||||
Redirect permanent /old /new
|
||||
RedirectMatch 302 ^/old-files/(.*)$ /archive/$1
|
||||
ErrorDocument 404 /error.html
|
||||
"#).unwrap();
|
||||
let mut config = Service {
|
||||
id: "redirects".into(),
|
||||
name: "Redirects".into(),
|
||||
document_root: tmp.path().to_path_buf(),
|
||||
htaccess: htaccess::Config { enabled: true, strict: false, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
config.validate().unwrap();
|
||||
let service = config.compile().unwrap();
|
||||
let (_, warnings) = service.htaccess_diagnostics().unwrap();
|
||||
assert_eq!(warnings.len(), 1); // ErrorDocument ignored in non-strict mode.
|
||||
let redirect = serve_request(&service, &request(Method::GET, "/old/docs?a=1"), "/old/docs").await;
|
||||
assert_eq!(redirect.status(), StatusCode::MOVED_PERMANENTLY);
|
||||
assert_eq!(redirect.headers()[LOCATION], "/new/docs?a=1");
|
||||
let regex = serve_request(&service, &request(Method::GET, "/old-files/file.txt"), "/old-files/file.txt").await;
|
||||
assert_eq!(regex.status(), StatusCode::FOUND);
|
||||
assert_eq!(regex.headers()[LOCATION], "/archive/file.txt");
|
||||
}
|
||||
Reference in new issue
Block a user