v0.42.2
This commit is contained in:
1 parent
aa0a271a1c
commit
f38a2b9e5e
38 files changed
+1098
-160
No files matched your search
@@ -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] {
|
||||
|
||||
Reference in new issue
Block a user