609 lines
34 KiB
Rust
609 lines
34 KiB
Rust
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),
|
|
"404" => Some(StatusCode::NOT_FOUND),
|
|
"gone" | "410" => Some(StatusCode::GONE),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn redirect_rule(parts: &[String], regex: bool) -> Result<SimpleRedirect> {
|
|
let explicit = parts.get(1).and_then(|value| redirect_status(value));
|
|
let (status, source_index) = explicit.map_or((StatusCode::FOUND, 1), |status| (status, 2));
|
|
let status_only = matches!(status, StatusCode::NOT_FOUND | StatusCode::GONE);
|
|
ensure!(parts.len() == source_index + if status_only { 1 } else { 2 },
|
|
"Redirect / RedirectMatch expects [status] source target, or 404/gone source without target");
|
|
let source = &parts[source_index];
|
|
ensure!(!source.is_empty() && source.len() <= 512, "Redirect source is invalid");
|
|
let replacement = if status_only {
|
|
None
|
|
} else {
|
|
let replacement = &parts[source_index + 1];
|
|
ensure!(replacement.len() <= 1024, "Redirect target is too long");
|
|
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")?;
|
|
Some(replacement.to_owned())
|
|
};
|
|
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, 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() };
|
|
let mut state = ParseState { rewrite_engine: false, ..ParseState::default() };
|
|
let mut rule_count = 0usize;
|
|
let mut condition_count = 0usize;
|
|
|
|
for (line_no, raw) in content.lines().enumerate() {
|
|
let line_no = line_no + 1;
|
|
let line = raw.trim();
|
|
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 == "</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 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() {
|
|
"rewriteengine" => {
|
|
ensure!(parts.len() == 2, "{}:{line_no}: RewriteEngine expects On or Off", path.display());
|
|
state.rewrite_engine = if parts[1].eq_ignore_ascii_case("on") { true } else if parts[1].eq_ignore_ascii_case("off") { false } else { bail!("{}:{line_no}: RewriteEngine expects On or Off", path.display()) };
|
|
if !state.rewrite_engine { state.pending_conditions.clear(); state.skip_next_rule = false; }
|
|
}
|
|
"rewritebase" => {
|
|
ensure!(parts.len() == 2, "{}:{line_no}: RewriteBase expects one absolute URL prefix", path.display());
|
|
let base = &parts[1];
|
|
ensure!(base.starts_with('/') && !base.starts_with("//")
|
|
&& !base.contains('\\') && !base.contains('?') && !base.contains('#')
|
|
&& !base.chars().any(char::is_control),
|
|
"{}:{line_no}: RewriteBase must be a safe absolute URL path", path.display());
|
|
crate::acl::validate_decoded_routing_path(base)
|
|
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid RewriteBase path", path.display()))?;
|
|
scope.rewrite_base = Some(if base.ends_with('/') { base.to_owned() } else { format!("{base}/") });
|
|
}
|
|
"acceptpathinfo" => {
|
|
ensure!(parts.len() == 2, "{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
|
scope.accept_path_info = if parts[1].eq_ignore_ascii_case("on") {
|
|
Some(AcceptPathInfoMode::On)
|
|
} else if parts[1].eq_ignore_ascii_case("off") {
|
|
Some(AcceptPathInfoMode::Off)
|
|
} else if parts[1].eq_ignore_ascii_case("default") {
|
|
Some(AcceptPathInfoMode::Default)
|
|
} else {
|
|
bail!("{}:{line_no}: AcceptPathInfo expects On, Off or Default", path.display());
|
|
};
|
|
}
|
|
"errordocument" => {
|
|
ensure!(parts.len() == 3, "{}:{line_no}: ErrorDocument expects an HTTP error status and a local URL", path.display());
|
|
let status: u16 = parts[1].parse().context("ErrorDocument status must be numeric")?;
|
|
ensure!((400..600).contains(&status), "{}:{line_no}: ErrorDocument status must be 400..599", path.display());
|
|
let target = &parts[2];
|
|
ensure!(target.len() <= 1024 && target.starts_with('/') && !target.starts_with("//")
|
|
&& !target.contains('\\') && !target.contains('#')
|
|
&& !target.chars().any(char::is_control),
|
|
"{}:{line_no}: ErrorDocument requires a safe local URL, not an external redirect or literal response", path.display());
|
|
let path_only = target.split('?').next().unwrap_or_default();
|
|
crate::acl::validate_decoded_routing_path(path_only)
|
|
.map_err(|_| anyhow::anyhow!("{}:{line_no}: invalid ErrorDocument URL path", path.display()))?;
|
|
target.parse::<Uri>().context("invalid ErrorDocument URL")?;
|
|
scope.error_documents.insert(status, target.to_owned());
|
|
}
|
|
"rewritecond" if state.rewrite_engine => {
|
|
condition_count += 1;
|
|
ensure!(condition_count <= MAX_HTACCESS_CONDITIONS, "too many RewriteCond entries across one .htaccess file");
|
|
match parse_condition(&parts) {
|
|
Ok(condition) => state.pending_conditions.push(condition),
|
|
Err(error) => {
|
|
unsupported(&mut state, config, path, line_no, error.to_string())?;
|
|
state.skip_next_rule = true;
|
|
}
|
|
}
|
|
}
|
|
"rewriterule" if state.rewrite_engine => {
|
|
rule_count += 1;
|
|
ensure!(rule_count <= MAX_HTACCESS_RULES, "too many RewriteRule entries across one .htaccess file");
|
|
let conditions = std::mem::take(&mut state.pending_conditions);
|
|
if state.skip_next_rule {
|
|
state.skip_next_rule = false;
|
|
state.unsupported.push(format!("{}:{line_no}: RewriteRule skipped because a preceding RewriteCond was unsupported", path.display()));
|
|
continue;
|
|
}
|
|
match parse_rewrite_rule(&parts, conditions, &mut state) {
|
|
Ok(rule) => scope.rewrites.push(rule),
|
|
Err(error) => unsupported(&mut state, config, path, line_no, error.to_string())?,
|
|
}
|
|
}
|
|
"directoryindex" => {
|
|
ensure!(parts.len() >= 2, "{}:{line_no}: DirectoryIndex needs at least one file", path.display());
|
|
let mut index = Vec::new();
|
|
for value in &parts[1..] {
|
|
if value.eq_ignore_ascii_case("disabled") { index.clear(); break; }
|
|
ensure!(!value.contains('/') && !value.contains('\\') && value != "." && value != "..", "{}:{line_no}: DirectoryIndex entries must be plain file names", path.display());
|
|
index.push(value.clone());
|
|
}
|
|
ensure!(index.len() <= 16, "{}:{line_no}: DirectoryIndex allows at most 16 files", path.display());
|
|
scope.directory_index = Some(index);
|
|
}
|
|
"options" => {
|
|
for option in &parts[1..] {
|
|
if option.eq_ignore_ascii_case("+Indexes") || option.eq_ignore_ascii_case("Indexes") { scope.directory_listing = Some(true); }
|
|
else if option.eq_ignore_ascii_case("-Indexes") { scope.directory_listing = Some(false); }
|
|
else if option.eq_ignore_ascii_case("-MultiViews") { }
|
|
else { unsupported(&mut state, config, path, line_no, format!("unsupported Options token {option}"))?; }
|
|
}
|
|
}
|
|
"addtype" => {
|
|
ensure!(parts.len() >= 3, "{}:{line_no}: AddType expects media/type and extension(s)", path.display());
|
|
let mime = HeaderValue::from_str(&parts[1]).context("invalid AddType media type")?;
|
|
for extension in &parts[2..] {
|
|
ensure!(scope.mime_types.len() < MAX_HTACCESS_MIME_TYPES, "too many AddType extensions in .htaccess");
|
|
scope.mime_types.insert(normalize_extension(extension)?, mime.clone());
|
|
}
|
|
}
|
|
"addhandler" => {
|
|
ensure!(parts.len() >= 3, "{}:{line_no}: AddHandler expects handler and extension(s)", path.display());
|
|
if parts[1].to_ascii_lowercase().contains("php") {
|
|
for extension in &parts[2..] { scope.php_extensions.insert(normalize_extension(extension)?); }
|
|
} else {
|
|
bail!("{}:{line_no}: non-PHP AddHandler is not supported and cannot be ignored safely", path.display());
|
|
}
|
|
}
|
|
"header" => {
|
|
ensure!(parts.len() >= 3, "{}:{line_no}: Header expects an action and name", path.display());
|
|
ensure!(scope.headers.len() < MAX_HTACCESS_HEADERS, "too many Header directives in .htaccess");
|
|
let mut action_index = 1usize;
|
|
if parts[action_index].eq_ignore_ascii_case("always") || parts[action_index].eq_ignore_ascii_case("onsuccess") { action_index += 1; }
|
|
ensure!(parts.len() > action_index + 1, "{}:{line_no}: Header expects an action and name", path.display());
|
|
let action = parts[action_index].to_ascii_lowercase();
|
|
let name = HeaderName::from_str(&parts[action_index + 1]).context("invalid Header name")?;
|
|
ensure!(supported_response_header(&name), "protected response header cannot be set from .htaccess");
|
|
match action.as_str() {
|
|
"unset" => scope.headers.push(HeaderOp::Unset(name)),
|
|
"set" | "add" => {
|
|
ensure!(parts.len() > action_index + 2, "{}:{line_no}: Header {action} needs a value", path.display());
|
|
let value = HeaderValue::from_str(&parts[action_index + 2..].join(" ")).context("invalid Header value")?;
|
|
if action == "set" { scope.headers.push(HeaderOp::Set(name, value)); } else { scope.headers.push(HeaderOp::Add(name, value)); }
|
|
}
|
|
_ => unsupported(&mut state, config, path, line_no, format!("unsupported Header action {action}"))?,
|
|
}
|
|
}
|
|
"expiresactive" => {
|
|
ensure!(parts.len() == 2, "{}:{line_no}: ExpiresActive expects On or Off", path.display());
|
|
scope.expires_active = parts[1].eq_ignore_ascii_case("on");
|
|
}
|
|
"expiresdefault" => {
|
|
ensure!(parts.len() >= 2, "{}:{line_no}: ExpiresDefault needs a duration", path.display());
|
|
scope.expires_default = Some(parse_duration(&parts[1..].join(" "))?);
|
|
}
|
|
"expiresbytype" => {
|
|
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" | "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" => {
|
|
bail!("{}:{line_no}: security/handler directive {} is not supported and cannot be ignored safely", path.display(), parts[0]);
|
|
}
|
|
"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()))?);
|
|
}
|
|
"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))
|
|
}
|
|
|
|
fn discover(root: &Path, filename: &str, recursive: bool) -> Result<Vec<(PathBuf, Vec<String>)>> {
|
|
let mut result = Vec::new();
|
|
let mut stack = vec![(root.to_path_buf(), Vec::<String>::new(), 0usize)];
|
|
while let Some((directory, components, depth)) = stack.pop() {
|
|
let directory = fs::canonicalize(&directory)
|
|
.with_context(|| format!("cannot canonicalize {} during .htaccess scan", directory.display()))?;
|
|
ensure!(directory.starts_with(root), ".htaccess scan escaped the Web Service document root");
|
|
let candidate = directory.join(filename);
|
|
match fs::symlink_metadata(&candidate) {
|
|
Ok(metadata) => {
|
|
ensure!(!metadata.file_type().is_symlink(), "{} must not be a symlink", candidate.display());
|
|
if metadata.is_file() {
|
|
result.push((candidate, components.clone()));
|
|
ensure!(result.len() <= MAX_HTACCESS_FILES, "Web Service .htaccess scan exceeds 128 files");
|
|
}
|
|
}
|
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
|
Err(error) => return Err(error).with_context(|| format!("cannot inspect {}", candidate.display())),
|
|
}
|
|
if !recursive || depth >= MAX_HTACCESS_DEPTH { continue; }
|
|
for entry in fs::read_dir(&directory).with_context(|| format!("cannot scan {} for .htaccess", directory.display()))? {
|
|
let entry = entry?;
|
|
let file_type = entry.file_type()?;
|
|
if !file_type.is_dir() || file_type.is_symlink() { continue; }
|
|
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue; };
|
|
if name == ".git" || name == "node_modules" { continue; }
|
|
let mut child = components.clone();
|
|
child.push(name);
|
|
stack.push((entry.path(), child, depth + 1));
|
|
}
|
|
}
|
|
result.sort_by(|a, b| a.1.len().cmp(&b.1.len()).then_with(|| a.1.cmp(&b.1)));
|
|
Ok(result)
|
|
}
|
|
|
|
pub fn compile(root: &Path, config: &Config) -> Result<Option<Compiled>> {
|
|
if !config.enabled { return Ok(None); }
|
|
let files = discover(root, &config.filename, config.scan_subdirectories)?;
|
|
let mut scopes = Vec::new();
|
|
let mut warnings = Vec::new();
|
|
let mut total = 0u64;
|
|
for (file, components) in files {
|
|
total = total.saturating_add(fs::metadata(&file)?.len());
|
|
ensure!(total <= MAX_HTACCESS_TOTAL_BYTES, "Web Service .htaccess files exceed 1 MiB total");
|
|
let (scope, mut file_warnings) = parse_file(&file, components, config)?;
|
|
scopes.push(scope);
|
|
warnings.append(&mut file_warnings);
|
|
}
|
|
Ok(Some(Compiled { filename: config.filename.clone(), files_loaded: scopes.len(), scopes, warnings }))
|
|
}
|
|
|
|
pub fn adds_php_extensions(compiled: Option<&Compiled>) -> bool {
|
|
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.php_extensions.is_empty()))
|
|
}
|
|
|
|
pub fn rewrites_to_php(compiled: Option<&Compiled>) -> bool {
|
|
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| {
|
|
scope.rewrites.iter().any(|rule| rule.replacement.to_ascii_lowercase().contains(".php"))
|
|
}))
|
|
}
|
|
|
|
pub fn protected_component(compiled: Option<&Compiled>, value: &str) -> bool {
|
|
let lower = value.to_ascii_lowercase();
|
|
if lower == ".htaccess" || lower == ".htpasswd" || lower.starts_with(".ht") { return true; }
|
|
compiled.is_some_and(|compiled| value.eq_ignore_ascii_case(&compiled.filename))
|
|
}
|
|
|
|
fn scope_matches(scope: &Scope, components: &[String]) -> bool {
|
|
components.len() >= scope.components.len() && components[..scope.components.len()] == scope.components[..]
|
|
}
|
|
|
|
fn matching_scopes<'a>(compiled: &'a Compiled, path: &str) -> Vec<&'a Scope> {
|
|
let Ok(components) = path_components(path) else { return Vec::new(); };
|
|
compiled.scopes.iter().filter(|scope| scope_matches(scope, &components)).collect()
|
|
}
|
|
|
|
pub fn denied(compiled: Option<&Compiled>, path: &str, client_ip: IpAddr) -> bool {
|
|
let Some(compiled) = compiled else { return 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] {
|
|
let Some(compiled) = compiled else { return fallback; };
|
|
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_index.as_deref()).next_back().unwrap_or(fallback)
|
|
}
|
|
|
|
pub fn accept_path_info(compiled: Option<&Compiled>, script_path: &str, fallback: bool) -> bool {
|
|
match compiled.and_then(|compiled| matching_scopes(compiled, script_path).into_iter()
|
|
.filter_map(|scope| scope.accept_path_info).next_back()) {
|
|
Some(AcceptPathInfoMode::On) => true,
|
|
Some(AcceptPathInfoMode::Off) => false,
|
|
Some(AcceptPathInfoMode::Default) | None => fallback,
|
|
}
|
|
}
|
|
|
|
pub fn has_error_documents(compiled: Option<&Compiled>) -> bool {
|
|
compiled.is_some_and(|compiled| compiled.scopes.iter().any(|scope| !scope.error_documents.is_empty()))
|
|
}
|
|
|
|
pub fn error_document<'a>(compiled: Option<&'a Compiled>, path: &str, status: StatusCode) -> Option<&'a str> {
|
|
compiled?.scopes.iter().filter(|scope| {
|
|
path_components(path).ok().is_some_and(|parts| scope_matches(scope, &parts))
|
|
}).filter_map(|scope| scope.error_documents.get(&status.as_u16()).map(String::as_str)).next_back()
|
|
}
|
|
|
|
pub fn directory_listing(compiled: Option<&Compiled>, directory_components: &[String], fallback: bool) -> bool {
|
|
let Some(compiled) = compiled else { return fallback; };
|
|
compiled.scopes.iter().filter(|scope| scope_matches(scope, directory_components)).filter_map(|scope| scope.directory_listing).next_back().unwrap_or(fallback)
|
|
}
|
|
|
|
pub fn mime_type(compiled: Option<&Compiled>, path: &Path) -> Option<HeaderValue> {
|
|
let compiled = compiled?;
|
|
let extension = path.extension()?.to_str()?.to_ascii_lowercase();
|
|
let path_text = path.to_string_lossy();
|
|
matching_scopes(compiled, &path_text).into_iter().filter_map(|scope| scope.mime_types.get(&extension).cloned()).next_back()
|
|
}
|
|
|
|
pub fn php_extension(compiled: Option<&Compiled>, path: &Path) -> bool {
|
|
let Some(compiled) = compiled else { return false; };
|
|
let Some(extension) = path.extension().and_then(|v| v.to_str()).map(|v| v.to_ascii_lowercase()) else { return false; };
|
|
let path_text = path.to_string_lossy();
|
|
matching_scopes(compiled, &path_text).into_iter().any(|scope| scope.php_extensions.contains(&extension))
|
|
}
|
|
|
|
pub fn apply_response(compiled: Option<&Compiled>, response: &mut Response, path: &str) {
|
|
let Some(compiled) = compiled else { return; };
|
|
let scopes = matching_scopes(compiled, path);
|
|
for scope in &scopes {
|
|
for op in &scope.headers {
|
|
match op {
|
|
HeaderOp::Set(name, value) => { response.headers_mut().insert(name.clone(), value.clone()); }
|
|
HeaderOp::Add(name, value) => { response.headers_mut().append(name.clone(), value.clone()); }
|
|
HeaderOp::Unset(name) => { response.headers_mut().remove(name); }
|
|
}
|
|
}
|
|
}
|
|
let Some(content_type) = response.headers().get(http::header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).map(|v| v.to_ascii_lowercase()) else { return; };
|
|
let mut expiry = None;
|
|
for scope in scopes {
|
|
if !scope.expires_active { continue; }
|
|
let specific = scope.expires_by_type.iter().find(|(mime, _)| content_type.starts_with(mime)).map(|(_, duration)| *duration);
|
|
expiry = specific.or(scope.expires_default).or(expiry);
|
|
}
|
|
if let Some(duration) = expiry {
|
|
let seconds = duration.as_secs();
|
|
if let Ok(value) = HeaderValue::from_str(&format!("public, max-age={seconds}")) { response.headers_mut().insert(CACHE_CONTROL, value); }
|
|
if let Ok(value) = HeaderValue::from_str(&httpdate::fmt_http_date(SystemTime::now() + duration)) { response.headers_mut().insert(EXPIRES, value); }
|
|
}
|
|
}
|
|
|
|
fn scope_relative_path(scope: &Scope, path: &str) -> String {
|
|
let prefix = if scope.components.is_empty() { "/".to_owned() } else { format!("/{}/", scope.components.join("/")) };
|
|
if scope.components.is_empty() { return path.trim_start_matches('/').to_owned(); }
|
|
if path == prefix.trim_end_matches('/') { return String::new(); }
|
|
path.strip_prefix(&prefix).unwrap_or(path.trim_start_matches('/')).to_owned()
|
|
}
|
|
|
|
fn expand_condition_input(input: &str, service: &CompiledService, method: &Method, headers: &HeaderMap, path: &str, query: Option<&str>, uri: &Uri, context: &RequestContext, captures: &[String]) -> String {
|
|
let mut value = input.to_owned();
|
|
let request_filename = service.root.join(path.trim_start_matches('/')).to_string_lossy().to_string();
|
|
let pairs = [
|
|
("%{REQUEST_FILENAME}", request_filename),
|
|
("%{REQUEST_URI}", path.to_owned()),
|
|
("%{REQUEST_METHOD}", method.as_str().to_owned()),
|
|
("%{QUERY_STRING}", query.unwrap_or("").to_owned()),
|
|
("%{HTTP_HOST}", headers.get(http::header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(&context.server_name).to_owned()),
|
|
("%{HTTPS}", if context.tls { "on" } else { "off" }.to_owned()),
|
|
("%{REQUEST_SCHEME}", if context.tls { "https" } else { "http" }.to_owned()),
|
|
("%{SERVER_NAME}", context.server_name.clone()),
|
|
("%{SERVER_PORT}", context.server_port.to_string()),
|
|
("%{REMOTE_ADDR}", context.client_ip.to_string()),
|
|
("%{HTTP_USER_AGENT}", headers.get(http::header::USER_AGENT).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned()),
|
|
("%{HTTP_REFERER}", headers.get(http::header::REFERER).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned()),
|
|
("%{HTTP_COOKIE}", headers.get(http::header::COOKIE).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned()),
|
|
("%{DOCUMENT_ROOT}", service.root.to_string_lossy().to_string()),
|
|
("%{THE_REQUEST}", format!("{} {} {}", method, uri.path_and_query().map(|v| v.as_str()).unwrap_or(path), super::request::server_protocol(context.version))),
|
|
];
|
|
for (needle, replacement) in pairs { value = value.replace(needle, &replacement); }
|
|
let mut offset = 0usize;
|
|
while let Some(start) = value[offset..].find("%{HTTP:") {
|
|
let start = offset + start;
|
|
let Some(end_rel) = value[start..].find('}') else { break; };
|
|
let end = start + end_rel;
|
|
let name = &value[start + 7..end];
|
|
let replacement = HeaderName::from_str(name).ok().and_then(|name| headers.get(&name)).and_then(|v| v.to_str().ok()).unwrap_or("").to_owned();
|
|
value.replace_range(start..=end, &replacement);
|
|
offset = start + replacement.len();
|
|
}
|
|
for index in 1..=9 { value = value.replace(&format!("%{index}"), captures.get(index).map(String::as_str).unwrap_or("")); }
|
|
value
|
|
}
|
|
|
|
async fn file_test(service: &CompiledService, value: &str, kind: FileTest) -> bool {
|
|
let path = PathBuf::from(value);
|
|
let relative = if path.is_absolute() {
|
|
match path.strip_prefix(&service.root) { Ok(value) => value, Err(_) => return false }
|
|
} else { path.as_path() };
|
|
let mut components = Vec::new();
|
|
for part in relative.components() {
|
|
match part {
|
|
std::path::Component::Normal(value) => { let Some(value) = value.to_str() else { return false; }; components.push(value.to_owned()); }
|
|
std::path::Component::CurDir => {}
|
|
_ => return false,
|
|
}
|
|
}
|
|
match open_components(service, components).await {
|
|
Ok(opened) => match kind { FileTest::File => opened.metadata.is_file(), FileTest::Directory => opened.metadata.is_dir(), FileTest::NonEmptyFile => opened.metadata.is_file() && opened.metadata.len() > 0 },
|
|
Err(_) => false,
|
|
}
|
|
}
|
|
|
|
async fn condition_matches(condition: &RewriteCondition, service: &CompiledService, method: &Method, headers: &HeaderMap, path: &str, query: Option<&str>, uri: &Uri, context: &RequestContext, prior_captures: &[String]) -> (bool, Vec<String>) {
|
|
let value = expand_condition_input(&condition.input, service, method, headers, path, query, uri, context, prior_captures);
|
|
match &condition.matcher {
|
|
ConditionMatcher::File { kind, negate } => {
|
|
let matched = file_test(service, &value, *kind).await;
|
|
(if *negate { !matched } else { matched }, Vec::new())
|
|
}
|
|
ConditionMatcher::Exact { value: wanted, negate, insensitive } => {
|
|
let equal = if *insensitive { value.eq_ignore_ascii_case(wanted) } else { value.as_str() == wanted.as_str() };
|
|
(if *negate { !equal } else { equal }, Vec::new())
|
|
}
|
|
ConditionMatcher::Regex { regex, negate } => {
|
|
if let Some(captures) = regex.captures(&value) {
|
|
let values = captures.iter().map(|value| value.map(|v| v.as_str().to_owned()).unwrap_or_default()).collect::<Vec<_>>();
|
|
(!*negate, if *negate { Vec::new() } else { values })
|
|
} else { (*negate, Vec::new()) }
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn conditions_match(rule: &RewriteRule, service: &CompiledService, method: &Method, headers: &HeaderMap, path: &str, query: Option<&str>, uri: &Uri, context: &RequestContext) -> (bool, Vec<String>) {
|
|
let mut i = 0usize;
|
|
let mut captures = Vec::new();
|
|
while i < rule.conditions.len() {
|
|
let mut group_ok = false;
|
|
loop {
|
|
let condition = &rule.conditions[i];
|
|
let (matched, current) = condition_matches(condition, service, method, headers, path, query, uri, context, &captures).await;
|
|
if matched {
|
|
group_ok = true;
|
|
if !current.is_empty() { captures = current; }
|
|
}
|
|
let chained = condition.or_next;
|
|
i += 1;
|
|
if !chained || i >= rule.conditions.len() { break; }
|
|
}
|
|
if !group_ok { return (false, Vec::new()); }
|
|
}
|
|
(true, captures)
|
|
}
|
|
|
|
fn replacement_with_captures(rule: &RewriteRule, captures: ®ex::Captures<'_>, condition_captures: &[String]) -> String {
|
|
let mut replacement = String::new();
|
|
captures.expand(&rule.replacement, &mut replacement);
|
|
for index in 1..=9 { replacement = replacement.replace(&format!("%{index}"), condition_captures.get(index).map(String::as_str).unwrap_or("")); }
|
|
replacement
|
|
}
|
|
|
|
fn scoped_target(scope: &Scope, replacement: &str) -> String {
|
|
if replacement.starts_with('/') { return replacement.to_owned(); }
|
|
if let Some(base) = &scope.rewrite_base { return format!("{base}{replacement}"); }
|
|
if scope.components.is_empty() { format!("/{replacement}") } else if replacement.is_empty() { format!("/{}/", scope.components.join("/")) } else { format!("/{}/{}", scope.components.join("/"), replacement) }
|
|
}
|
|
|
|
fn redirect_response(status: StatusCode, location: &str) -> Result<Response> {
|
|
let mut response = Response::new(Body::empty());
|
|
*response.status_mut() = status;
|
|
response.headers_mut().insert(LOCATION, HeaderValue::from_str(location).context("invalid .htaccess redirect location")?);
|
|
Ok(response)
|
|
}
|