Files
ianitor/crates/edge/src/proxy.rs
T

524 lines
18 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The HTTPS reverse proxy. Order per request (same as the Caddy compiler emits):
//! host lookup (unknown → 404) → forward-auth → websocket refusal → upstream with header rules.
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;
use async_trait::async_trait;
use http::header;
use pingora::connectors::http::Connector;
use pingora::http::{RequestHeader, ResponseHeader};
use pingora::proxy::{FailToProxy, ProxyHttp, Session};
use pingora::upstreams::peer::HttpPeer;
use pingora::{Error, ErrorSource, ErrorType, Result};
use crate::fetch;
use crate::forward_auth::{self, Outcome};
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::runtime::{HostRt, Op, Runtime};
use crate::share::{self, Decision};
use crate::shared::Shared;
pub struct EdgeProxy {
pub shared: Arc<Shared>,
pub connector: Connector,
}
pub struct Ctx {
/// The runtime current when the request started; used for the whole request.
rt: Option<Arc<Runtime>>,
host: Option<Arc<HostRt>>,
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
upstream: Option<usize>,
addrs: Vec<std::net::SocketAddr>,
addr_idx: usize,
/// The Host header as the client sent it (with port, if any).
host_header: String,
start: Instant,
}
/// The request's host: the authority of an absolute-form target (or HTTP/2 :authority) wins
/// over the Host header, as RFC 9112 §3.2.2 requires and Go/Caddy do.
pub fn host_header(req: &RequestHeader) -> String {
req.uri
.authority()
.map(|a| a.as_str().to_owned())
.or_else(|| {
req.headers
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
})
.unwrap_or_default()
}
/// Host without port, lowercase. `[v6]:port` keeps the brackets off.
pub fn hostname(host_header: &str) -> String {
let h = host_header.trim();
let name = if let Some(rest) = h.strip_prefix('[') {
rest.split(']').next().unwrap_or("")
} else {
h.rsplit_once(':').map_or(h, |(n, port)| {
if port.bytes().all(|c| c.is_ascii_digit()) {
n
} else {
h
}
})
};
name.to_ascii_lowercase()
}
/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost
/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's
/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored.
pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
let peer = session
.client_addr()
.and_then(|a| a.as_inet())
.map(|a| a.ip())?;
if !trusted.contains(&peer) {
return Some(peer);
}
let mut last = peer;
for v in session
.req_header()
.headers
.get_all("x-forwarded-for")
.iter()
.rev()
{
let Ok(s) = v.to_str() else { return Some(last) };
for part in s.rsplit(',') {
match part.trim().parse::<IpAddr>() {
Ok(ip) if trusted.contains(&ip) => last = ip,
Ok(ip) => return Some(ip),
Err(_) => return Some(last),
}
}
}
Some(last)
}
/// A response with an empty body, like Caddy's `static_response` and error responses.
pub async fn respond_empty(session: &mut Session, code: u16) -> Result<()> {
let mut resp = ResponseHeader::build(code, Some(1))?;
resp.insert_header(header::CONTENT_LENGTH, "0")?;
session.write_response_header(Box::new(resp), true).await
}
fn apply(
ops: &[Op],
mut set: impl FnMut(&http::HeaderName, Option<&http::HeaderValue>) -> Result<()>,
) -> Result<()> {
for op in ops {
match op {
Op::Set(n, v) => set(n, Some(v))?,
Op::Remove(n) => set(n, None)?,
}
}
Ok(())
}
/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive).
pub fn is_websocket_upgrade(req: &RequestHeader) -> bool {
req.headers.get_all(header::UPGRADE).iter().any(|v| {
String::from_utf8_lossy(v.as_bytes())
.split(',')
.any(|t| t.trim().eq_ignore_ascii_case("websocket"))
})
}
#[async_trait]
impl ProxyHttp for EdgeProxy {
type CTX = Ctx;
fn new_ctx(&self) -> Ctx {
Ctx {
rt: None,
host: None,
upstream: None,
addrs: Vec::new(),
addr_idx: 0,
host_header: String::new(),
start: Instant::now(),
}
}
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
let rt = self.shared.current();
ctx.rt = Some(rt.clone());
ctx.host_header = host_header(session.req_header());
if self.shared.devices.current().is_some()
&& sni_mismatch(session, &hostname(&ctx.host_header))
{
// Like Caddy once client certificates are configured: a request for another host
// than the one the TLS connection was opened for is refused, so a connection
// that was never asked for a certificate cannot reach a device host.
respond_empty(session, 421).await?;
return Ok(true);
}
let Some(host) = rt.host(&hostname(&ctx.host_header)).cloned() else {
respond_empty(session, 404).await?;
return Ok(true);
};
ctx.host = Some(host.clone());
if host.cfg.device_certs && !has_allowed_device_cert(session, &self.shared) {
// No certificate on this connection (one that is presented but not allowed never
// gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream.
respond_empty(session, 403).await?;
return Ok(true);
}
let mut shared_access = false;
if !host.cfg.share_links {
share::strip_any_token(session)?;
} else {
let ip = client_ip(session, &rt.trusted_proxies);
let revs = self.shared.revocations();
match share::handle(
session,
&host.cfg.hostname,
rt.share_key.as_deref(),
&revs,
&self.shared.throttle,
ip,
)
.await?
{
Decision::Answered => return Ok(true),
Decision::Allowed => shared_access = true,
Decision::Continue => {}
}
}
if host.sends_proof {
// Control trusts Remote-* only next to its proof; a client never supplies either.
let req = session.req_header_mut();
for name in ianitor_core::AUTHELIA_COPY_HEADERS
.iter()
.chain(&["X-Ianitor-Proof"])
{
req.remove_header(*name);
}
}
if host.cfg.forward_auth {
let fa = rt.forward_auth.as_ref().ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
})?;
// Client-sent identity headers never survive, whatever copy_headers says.
let req = session.req_header_mut();
for name in &fa.strip_headers {
req.remove_header(name);
}
if shared_access {
// A valid share link stands in for the sign-in on its prefix.
return self.after_auth(session, &host).await;
}
let ip = client_ip(session, &rt.trusted_proxies).map(|i| i.to_string());
let outcome = match forward_auth::check(
&self.connector,
fa,
session,
&ctx.host_header,
ip,
)
.await
{
Ok(o) => o,
Err(e) => {
log::error!(target: "ianitor::auth", "forward-auth for {} failed, denying: {e}", host.cfg.hostname);
return Err(Error::explain(
ErrorType::HTTPStatus(502),
"forward-auth unreachable",
));
}
};
match outcome {
Outcome::Deny(resp, body) => {
let head = session.req_header().method == http::Method::HEAD;
let end = head || body.is_empty();
session.write_response_header(resp, end).await?;
if !end {
session.write_response_body(Some(body), true).await?;
}
return Ok(true);
}
Outcome::Allow(copy) => {
let req = session.req_header_mut();
for (name, value) in copy {
req.remove_header(&name);
if let Some(v) = value {
req.insert_header(name, v)?;
}
}
}
}
}
self.after_auth(session, &host).await
}
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
let host = ctx
.host
.clone()
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
let idx = match ctx.upstream {
// A retry after a failed connect: same upstream, next address.
Some(i) => i,
None => {
let n = host.upstreams.len();
let first = host.next.fetch_add(1, Ordering::Relaxed);
let i = (0..n)
.map(|k| (first + k) % n)
.find(|&k| host.upstreams[k].healthy.load(Ordering::Relaxed))
.ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
})?;
let up = &host.upstreams[i];
ctx.addrs = match up.resolve().await {
Ok(a) => a,
Err(e) => {
log::warn!(target: "ianitor::proxy", "{}: cannot resolve upstream {}: {e}", host.cfg.hostname, up.authority);
return Err(Error::explain(
ErrorType::HTTPStatus(502),
"upstream does not resolve",
));
}
};
ctx.upstream = Some(i);
ctx.addr_idx = 0;
i
}
};
let up = &host.upstreams[idx];
let addr = *ctx
.addrs
.get(ctx.addr_idx)
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(502), "no address left"))?;
log::debug!(target: "ianitor::proxy", "{}: upstream {} at {addr}", host.cfg.hostname, up.authority);
Ok(Box::new(fetch::peer(addr, up)))
}
fn fail_to_connect(
&self,
_s: &mut Session,
_p: &HttpPeer,
ctx: &mut Ctx,
mut e: Box<Error>,
) -> Box<Error> {
// Like Caddy's dialer: try every address of the chosen upstream, then 502. Other
// upstreams are not tried (Caddy's default has no lb_try_duration).
if ctx.addr_idx + 1 < ctx.addrs.len() {
ctx.addr_idx += 1;
e.set_retry(true);
} else {
e.set_retry(false);
}
e
}
async fn upstream_request_filter(
&self,
session: &mut Session,
req: &mut RequestHeader,
ctx: &mut Ctx,
) -> Result<()> {
// Origin-form target and the routed host, also for absolute-form requests.
if req.uri.authority().is_some() {
let pq = req
.uri
.path_and_query()
.map_or("/", |p| p.as_str())
.to_owned();
let uri = pq
.parse::<http::Uri>()
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
req.set_uri(uri);
}
req.insert_header(header::HOST, ctx.host_header.as_str())?;
// Forwarding headers are always edge's own; client-supplied values are replaced.
let trusted = ctx
.rt
.as_ref()
.map(|r| r.trusted_proxies.as_slice())
.unwrap_or(&[]);
match client_ip(session, trusted) {
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
None => {
req.remove_header("X-Forwarded-For");
}
}
req.insert_header("X-Forwarded-Proto", "https")?;
req.insert_header("X-Forwarded-Host", ctx.host_header.as_str())?;
if let Some(host) = &ctx.host {
apply(&host.request_ops, |n, v| {
match v {
Some(v) => req.insert_header(n.clone(), v.clone())?,
None => {
req.remove_header(n);
}
}
Ok(())
})?;
}
Ok(())
}
async fn upstream_response_filter(
&self,
_s: &mut Session,
resp: &mut ResponseHeader,
ctx: &mut Ctx,
) -> Result<()> {
let Some(host) = &ctx.host else { return Ok(()) };
apply(&host.response_ops, |n, v| {
match v {
Some(v) => resp.insert_header(n.clone(), v.clone())?,
None => {
resp.remove_header(n);
}
}
Ok(())
})?;
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
if !host.secret_values.is_empty() {
let leaking: Vec<http::HeaderName> = resp
.headers
.iter()
.filter(|(_, v)| host.secret_values.iter().any(|s| contains(v.as_bytes(), s)))
.map(|(n, _)| n.clone())
.collect();
for n in leaking {
log::warn!(target: "ianitor::secrets", "{}: dropped response header `{n}` because it contained a secret", host.cfg.hostname);
resp.remove_header(&n);
}
}
Ok(())
}
async fn fail_to_proxy(&self, session: &mut Session, e: &Error, _ctx: &mut Ctx) -> FailToProxy {
let code = match e.etype() {
ErrorType::HTTPStatus(c) => *c,
_ => match e.esource() {
ErrorSource::Upstream => 502,
ErrorSource::Downstream => match e.etype() {
ErrorType::WriteError | ErrorType::ReadError | ErrorType::ConnectionClosed => 0,
_ => 400,
},
ErrorSource::Internal | ErrorSource::Unset => 500,
},
};
if code > 0
&& session.response_written().is_none()
&& let Err(err) = respond_empty(session, code).await
{
log::debug!(target: "ianitor::proxy", "could not send the error response: {err}");
}
FailToProxy {
error_code: code,
can_reuse_downstream: false,
}
}
async fn logging(&self, session: &mut Session, _e: Option<&Error>, ctx: &mut Ctx) {
let Some(host) = &ctx.host else { return };
if !host.cfg.access_log {
return;
}
let Some(log) = ctx.rt.as_ref().and_then(|rt| rt.access_log.as_ref()) else {
return;
};
let req = session.req_header();
log.write(&AccessRecord {
ts: now_secs(),
host: &host.cfg.hostname,
method: req.method.as_str(),
path: req.uri.path(),
status: session.response_written().map_or(0, |r| r.status.as_u16()),
remote_ip: client_ip(
session,
ctx.rt
.as_ref()
.map_or(&[], |r| r.trusted_proxies.as_slice()),
)
.map(|i| truncate_ip(i).to_string()),
duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
});
}
fn request_summary(&self, session: &Session, ctx: &Ctx) -> String {
// Method, host and path only: no query string, no headers.
let req = session.req_header();
format!("{} {}{}", req.method, ctx.host_header, req.uri.path())
}
}
impl EdgeProxy {
/// The steps after the sign-in check: websocket refusal.
async fn after_auth(&self, session: &mut Session, host: &HostRt) -> Result<bool> {
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
}
}
/// Was this TLS connection opened (by SNI) for another host than the request names?
fn sni_mismatch(session: &Session, host: &str) -> bool {
let Some(s) = session.digest().and_then(|d| d.ssl_digest.as_ref()) else {
return false;
};
match s.extension.get::<crate::tls::ConnSni>() {
Some(crate::tls::ConnSni(Some(sni))) => sni != host,
// TLS without a recorded name: refuse rather than guess.
_ => true,
}
}
/// Did this connection present a device certificate that the current config allows? The
/// handshake already checked the chain and the list; this checks again against the runtime
/// serving the request, so a revocation also ends requests on connections made before it.
fn has_allowed_device_cert(session: &Session, shared: &crate::shared::Shared) -> bool {
let Some(trust) = shared.devices.current() else {
return false;
};
session
.digest()
.and_then(|d| d.ssl_digest.as_ref())
.is_some_and(|s| !s.cert_digest.is_empty() && trust.allows(&s.cert_digest))
}
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hostname_strips_port_and_case() {
assert_eq!(hostname("App.Test:8443"), "app.test");
assert_eq!(hostname("app.test"), "app.test");
assert_eq!(hostname("[::1]:443"), "::1");
assert_eq!(hostname(""), "");
}
#[test]
fn contains_finds_substrings() {
assert!(contains(b"abc-secret-def", b"secret"));
assert!(!contains(b"abc", b""));
assert!(!contains(b"sec", b"secret"));
}
}