This commit is contained in:
Mateusz Gruszczyński committed 2026-10-04 11:15:58 +02:00
1 parent 87e571c170
commit fa7abc9e53
308 files changed
+49746 -50237

No files matched your search

+395
View File
@@ -0,0 +1,395 @@
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.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);
continue;
}
if state.in_files_block != 0 {
// RustProxy always blocks .htaccess/.htpasswd directly. More general Files/FilesMatch
// access semantics remain intentionally outside the compatibility subset.
continue;
}
let parts = tokens(line).with_context(|| format!("{}:{line_no}", path.display()))?;
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" => {
// Per-directory substitutions are already resolved relative to the containing scope.
}
"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") { /* RustProxy has no content negotiation; already effectively off. */ }
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" => {
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()); }
}
"sethandler" | "removehandler" | "authtype" | "authname" | "authuserfile" | "authgroupfile" | "order" | "allow" | "deny" => {
bail!("{}:{line_no}: security/handler directive {} is not supported and cannot be ignored safely", path.display(), parts[0]);
}
"errordocument" | "setenvif" | "redirect" | "redirectmatch" | "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.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 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) -> bool {
let Some(compiled) = compiled else { return false; };
matching_scopes(compiled, path).into_iter().filter_map(|scope| scope.deny_all).last().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()).last().unwrap_or(fallback)
}
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).last().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()).last()
}
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<_>>();
(if *negate { false } else { true }, if *negate { Vec::new() } else { values })
} else { (if *negate { true } else { false }, 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: &regex::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 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)
}