[core] Schema: reject wildcard header names, cap file size and upstreams, require <hostname>.toml
This commit is contained in:
@@ -10,7 +10,7 @@
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::{CompileOptions, join};
|
||||
use super::{CompileOptions, join, strip_headers};
|
||||
use crate::{
|
||||
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
|
||||
Upstream,
|
||||
@@ -204,11 +204,13 @@ fn logging(file: &str) -> Value {
|
||||
fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
|
||||
let mut steps = Vec::new();
|
||||
if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
|
||||
// Client-sent identity headers never reach the auth server or the upstream.
|
||||
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
|
||||
steps.push(json!({ "handle": [forward_auth(fa)] }));
|
||||
}
|
||||
if !h.websockets {
|
||||
steps.push(json!({
|
||||
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)^websocket$" } } }],
|
||||
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } }],
|
||||
"handle": [{ "handler": "static_response", "status_code": 403 }]
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
//! Model → [`EdgeConfig`] for the Pingora data plane.
|
||||
|
||||
use super::{CompileOptions, join};
|
||||
use super::{CompileOptions, join, strip_headers};
|
||||
use crate::edge_config::{
|
||||
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck,
|
||||
EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
|
||||
@@ -30,6 +30,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
|
||||
upstream: upstream(&fa.upstream),
|
||||
path_and_query: fa.path_and_query.clone(),
|
||||
copy_headers: fa.copy_headers.clone(),
|
||||
strip_headers: strip_headers(fa),
|
||||
}),
|
||||
hosts: model
|
||||
.hosts()
|
||||
|
||||
@@ -108,6 +108,21 @@ fn check_path(p: &str) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
|
||||
/// any other configured copy header (case-insensitive, no duplicates).
|
||||
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
|
||||
let mut out: Vec<String> = crate::AUTHELIA_COPY_HEADERS
|
||||
.iter()
|
||||
.map(|h| (*h).to_owned())
|
||||
.collect();
|
||||
for h in &fa.copy_headers {
|
||||
if !out.iter().any(|o| o.eq_ignore_ascii_case(h)) {
|
||||
out.push(h.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Join a validated directory and a validated file name.
|
||||
fn join(dir: &str, file: &str) -> String {
|
||||
format!("{}/{}", dir.trim_end_matches('/'), file)
|
||||
|
||||
@@ -46,6 +46,9 @@ pub struct EdgeForwardAuth {
|
||||
pub upstream: EdgeUpstream,
|
||||
pub path_and_query: String,
|
||||
pub copy_headers: Vec<String>,
|
||||
/// Removed from every client request on a forward-auth host before the auth check:
|
||||
/// Authelia's four identity headers plus the copy headers.
|
||||
pub strip_headers: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -24,6 +24,12 @@ pub enum ValidationError {
|
||||
InvalidValue { file: String, message: String },
|
||||
#[error("{file} appears twice in the routes")]
|
||||
DuplicateFile { file: String },
|
||||
#[error("{file} is larger than {max} bytes")]
|
||||
FileTooLarge { file: String, max: usize },
|
||||
#[error("{file} must be named after its hostname: {hostname}.toml")]
|
||||
FileNameMismatch { file: String, hostname: String },
|
||||
#[error("{file}: at most {max} upstreams per host")]
|
||||
TooManyUpstreams { file: String, max: usize },
|
||||
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
|
||||
InvalidHostname {
|
||||
file: String,
|
||||
|
||||
@@ -221,6 +221,10 @@ impl Model {
|
||||
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
|
||||
/// Let's Encrypt staging directory.
|
||||
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
|
||||
/// Largest route file accepted (site or host).
|
||||
pub const MAX_FILE_BYTES: usize = 1 << 20;
|
||||
/// Most upstreams one host may list.
|
||||
pub const MAX_UPSTREAMS: usize = 64;
|
||||
/// Identity headers Authelia returns on success (Authelia's Caddy integration guide).
|
||||
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = [
|
||||
"Remote-User",
|
||||
|
||||
+53
-25
@@ -14,8 +14,8 @@ use serde::de::DeserializeOwned;
|
||||
use crate::error::{ValidationError as E, ValidationErrors};
|
||||
use crate::model::{
|
||||
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, Model, Scheme, SecretName, Site, TlsMode,
|
||||
Upstream, UpstreamHost,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
|
||||
Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||
};
|
||||
|
||||
/// One route file handed in by the caller (core does no I/O).
|
||||
@@ -192,6 +192,12 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
|
||||
|
||||
fn parse<T: DeserializeOwned>(f: &SourceFile<'_>) -> Result<T, E> {
|
||||
let file = f.name.to_owned();
|
||||
if f.contents.len() > MAX_FILE_BYTES {
|
||||
return Err(E::FileTooLarge {
|
||||
file,
|
||||
max: MAX_FILE_BYTES,
|
||||
});
|
||||
}
|
||||
// A plain table parse first tells syntax errors apart from schema errors.
|
||||
if let Err(e) = toml::from_str::<toml::Table>(f.contents) {
|
||||
return Err(E::Syntax {
|
||||
@@ -362,28 +368,45 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
let before = errors.len();
|
||||
let f = || file.to_owned();
|
||||
|
||||
if let Err(reason) = check_hostname(&raw.hostname) {
|
||||
errors.push(E::InvalidHostname {
|
||||
match check_hostname(&raw.hostname) {
|
||||
Err(reason) => errors.push(E::InvalidHostname {
|
||||
file: f(),
|
||||
hostname: raw.hostname.clone(),
|
||||
reason,
|
||||
});
|
||||
}),
|
||||
Ok(()) => {
|
||||
// One TOML per host, named after it: `hosts/<hostname>.toml`.
|
||||
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
if base != format!("{}.toml", raw.hostname) {
|
||||
errors.push(E::FileNameMismatch {
|
||||
file: f(),
|
||||
hostname: raw.hostname.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if raw.upstreams.is_empty() {
|
||||
errors.push(E::NoUpstreams { file: f() });
|
||||
}
|
||||
if raw.upstreams.len() > MAX_UPSTREAMS {
|
||||
errors.push(E::TooManyUpstreams {
|
||||
file: f(),
|
||||
max: MAX_UPSTREAMS,
|
||||
});
|
||||
}
|
||||
let mut upstreams: Vec<Upstream> = Vec::new();
|
||||
for u in &raw.upstreams {
|
||||
let mut seen_upstreams = BTreeSet::new();
|
||||
for u in raw.upstreams.iter().take(MAX_UPSTREAMS) {
|
||||
match parse_url(u, false) {
|
||||
Ok((up, _)) => {
|
||||
if upstreams.contains(&up) {
|
||||
if seen_upstreams.insert(up.clone()) {
|
||||
upstreams.push(up);
|
||||
} else {
|
||||
errors.push(E::DuplicateUpstream {
|
||||
file: f(),
|
||||
url: u.clone(),
|
||||
});
|
||||
} else {
|
||||
upstreams.push(up);
|
||||
}
|
||||
}
|
||||
Err(reason) => errors.push(E::BadUpstreamUrl {
|
||||
@@ -410,18 +433,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
errors.push(E::ForwardAuthNotConfigured { file: f() });
|
||||
}
|
||||
|
||||
// Identity headers set by forward-auth must not be overridable by a rule.
|
||||
let identity: Vec<String> = match (auth, site.and_then(|s| s.forward_auth.as_ref())) {
|
||||
(AuthMode::ForwardAuth, Some(fa)) => fa
|
||||
.copy_headers
|
||||
.iter()
|
||||
.map(|h| h.to_ascii_lowercase())
|
||||
.collect(),
|
||||
(AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS
|
||||
.iter()
|
||||
.map(|h| h.to_ascii_lowercase())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
// Identity headers (Authelia's four, plus any configured copy header) must not be
|
||||
// overridable by a rule on a forward-auth host.
|
||||
let identity: Vec<String> = match auth {
|
||||
AuthMode::ForwardAuth => {
|
||||
let extra = site
|
||||
.and_then(|s| s.forward_auth.as_ref())
|
||||
.map(|fa| fa.copy_headers.clone())
|
||||
.unwrap_or_default();
|
||||
AUTHELIA_COPY_HEADERS
|
||||
.iter()
|
||||
.map(|h| (*h).to_owned())
|
||||
.chain(extra)
|
||||
.map(|h| h.to_ascii_lowercase())
|
||||
.collect()
|
||||
}
|
||||
AuthMode::None => Vec::new(),
|
||||
};
|
||||
let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors);
|
||||
let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors);
|
||||
@@ -433,10 +460,10 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
&& hc
|
||||
.path
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}');
|
||||
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
|
||||
if !ok_path {
|
||||
errors.push(bad(
|
||||
"path must start with '/' and contain only visible ASCII without '{' or '}'",
|
||||
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'",
|
||||
));
|
||||
return None;
|
||||
}
|
||||
@@ -570,12 +597,13 @@ fn check_rules(
|
||||
out
|
||||
}
|
||||
|
||||
/// RFC 9110 token.
|
||||
/// RFC 9110 token minus `*`, which is a wildcard in Caddy's header operations but a literal
|
||||
/// character in edge; allowing it would let the engines disagree.
|
||||
fn valid_header_name(n: &str) -> bool {
|
||||
!n.is_empty()
|
||||
&& n.len() <= 256
|
||||
&& n.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c))
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&c))
|
||||
}
|
||||
|
||||
fn check_header_value(v: &str) -> Result<(), &'static str> {
|
||||
|
||||
Reference in New Issue
Block a user