[control] UI socket: with [ui] socket control also serves the API on a 0660 Unix socket and trusts the proof only there; a socket upstream is refused unless it is the admin host on control's own socket; probes under Caddy reach it too
This commit is contained in:
@@ -345,6 +345,10 @@ pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool {
|
|||||||
.any(|a| a.eq_ignore_ascii_case(host))
|
.any(|a| a.eq_ignore_ascii_case(host))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Marks a request that came in on control's UI socket (`[ui] socket`).
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct ViaUiSocket;
|
||||||
|
|
||||||
enum UiIdentity {
|
enum UiIdentity {
|
||||||
/// No sign-in headers: an API-token request.
|
/// No sign-in headers: an API-token request.
|
||||||
None,
|
None,
|
||||||
@@ -356,7 +360,7 @@ enum UiIdentity {
|
|||||||
User(String, String),
|
User(String, String),
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
|
fn ui_identity(ctl: &Control, headers: &HeaderMap, via_socket: bool) -> UiIdentity {
|
||||||
let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
|
let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-"));
|
||||||
let proof = headers.get("x-ianitor-proof");
|
let proof = headers.get("x-ianitor-proof");
|
||||||
if !names_user && proof.is_none() {
|
if !names_user && proof.is_none() {
|
||||||
@@ -366,7 +370,11 @@ fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity {
|
|||||||
(Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
|
(Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want),
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
if !ok {
|
// With a UI socket (G14 option b) the proof counts only there: the loopback port is open
|
||||||
|
// to every local process, and one that learned the proof (say, by taking control's port
|
||||||
|
// while it restarted and reading what edge sent) must not be able to use it.
|
||||||
|
let socket_only = ctl.cfg.ui.as_ref().is_some_and(|u| u.socket.is_some());
|
||||||
|
if !ok || (socket_only && !via_socket) {
|
||||||
return UiIdentity::Forged;
|
return UiIdentity::Forged;
|
||||||
}
|
}
|
||||||
let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
|
let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect();
|
||||||
@@ -428,7 +436,8 @@ async fn guard(State(st): State<Arc<AppState>>, mut req: Request, next: Next) ->
|
|||||||
// The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
|
// The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request
|
||||||
// with the per-boot proof edge adds is identified by its Remote-User. Any other
|
// with the per-boot proof edge adds is identified by its Remote-User. Any other
|
||||||
// request that names a user is refused, so a local process cannot claim to be one.
|
// request that names a user is refused, so a local process cannot claim to be one.
|
||||||
match ui_identity(&st.ctl, req.headers()) {
|
let via_socket = req.extensions().get::<ViaUiSocket>().is_some();
|
||||||
|
match ui_identity(&st.ctl, req.headers(), via_socket) {
|
||||||
UiIdentity::None => {}
|
UiIdentity::None => {}
|
||||||
UiIdentity::Forged => {
|
UiIdentity::Forged => {
|
||||||
return Err(ApiError::new(
|
return Err(ApiError::new(
|
||||||
|
|||||||
@@ -315,6 +315,21 @@ pub async fn probe_upstream(
|
|||||||
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
|
"GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n"
|
||||||
);
|
);
|
||||||
let run = async {
|
let run = async {
|
||||||
|
if let Some(path) = u.unix_path() {
|
||||||
|
// A socket upstream (the admin host on control's own UI socket): plain HTTP.
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let s = tokio::net::UnixStream::connect(path)
|
||||||
|
.await
|
||||||
|
.map_err(|e| io_kind(&e))?;
|
||||||
|
return ask(s, req.as_bytes()).await.map_err(|e| io_kind(&e));
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
let _ = path;
|
||||||
|
return Err("refused");
|
||||||
|
}
|
||||||
|
}
|
||||||
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
|
let tcp = match tokio::net::TcpStream::connect(u.authority()).await {
|
||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => return Err(io_kind(&e)),
|
Err(e) => return Err(io_kind(&e)),
|
||||||
|
|||||||
@@ -195,6 +195,13 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn check(&self) -> Result<(), ConfigError> {
|
pub fn check(&self) -> Result<(), ConfigError> {
|
||||||
|
if let Some(s) = self.ui.as_ref().and_then(|u| u.socket.as_ref())
|
||||||
|
&& (!s.is_absolute() || s.as_os_str().len() > 100)
|
||||||
|
{
|
||||||
|
return Err(ConfigError::Invalid(
|
||||||
|
"ui.socket must be an absolute path of at most 100 characters".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
if !self.listen.ip().is_loopback() {
|
if !self.listen.ip().is_loopback() {
|
||||||
return Err(ConfigError::Invalid(format!(
|
return Err(ConfigError::Invalid(format!(
|
||||||
"listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1",
|
"listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1",
|
||||||
@@ -346,6 +353,13 @@ pub struct UiConfig {
|
|||||||
pub proof_credential: Option<String>,
|
pub proof_credential: Option<String>,
|
||||||
/// The built web UI (served at `/`).
|
/// The built web UI (served at `/`).
|
||||||
pub static_dir: Option<PathBuf>,
|
pub static_dir: Option<PathBuf>,
|
||||||
|
/// A Unix socket (mode 0660; its directory only for the ianitor group) on which control
|
||||||
|
/// also serves the API for the admin host (G14 option b). With it, the proof signs in only
|
||||||
|
/// on this socket; over the loopback port, which any local process can reach (or take while
|
||||||
|
/// control restarts), only API tokens work. The admin host's upstream is then
|
||||||
|
/// `unix:<this path>`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub socket: Option<PathBuf>,
|
||||||
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
|
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub logout_url: Option<String>,
|
pub logout_url: Option<String>,
|
||||||
|
|||||||
@@ -169,6 +169,7 @@ pub async fn run(args: &[String]) -> Result<(), String> {
|
|||||||
proof_credential: None,
|
proof_credential: None,
|
||||||
static_dir: Some(PathBuf::from(d)),
|
static_dir: Some(PathBuf::from(d)),
|
||||||
logout_url: None,
|
logout_url: None,
|
||||||
|
socket: None,
|
||||||
}),
|
}),
|
||||||
engine: None,
|
engine: None,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -680,6 +680,41 @@ impl Control {
|
|||||||
})?;
|
})?;
|
||||||
// The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
|
// The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
|
||||||
let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
|
let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
|
||||||
|
// A socket upstream likewise: only the [ui] host, and only control's own UI socket (a
|
||||||
|
// route file must not point edge at any other socket on the machine).
|
||||||
|
let ui_socket = self
|
||||||
|
.cfg
|
||||||
|
.ui
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|u| u.socket.as_deref())
|
||||||
|
.and_then(|p| p.to_str());
|
||||||
|
for h in model.hosts() {
|
||||||
|
for (i, u) in h.upstreams.iter().enumerate() {
|
||||||
|
let Some(path) = u.unix_path() else { continue };
|
||||||
|
if ui_host == Some(h.hostname.as_str()) && ui_socket == Some(path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let p = messages::params([
|
||||||
|
("hostname", h.hostname.to_string()),
|
||||||
|
("url", u.to_string()),
|
||||||
|
]);
|
||||||
|
let fe = FieldError {
|
||||||
|
code: "host.upstream.unix_socket".into(),
|
||||||
|
message: message("host.upstream.unix_socket", &p),
|
||||||
|
field: Some(format!("upstreams[{i}]")),
|
||||||
|
params: p.clone(),
|
||||||
|
detail: None,
|
||||||
|
};
|
||||||
|
return Err(Fail {
|
||||||
|
status: 422,
|
||||||
|
reason: reason(
|
||||||
|
"apply.failed.validation",
|
||||||
|
messages::params([("first_error", fe.message.clone())]),
|
||||||
|
),
|
||||||
|
errors: vec![fe],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
for h in model.hosts() {
|
for h in model.hosts() {
|
||||||
let proof = h.request_headers.iter().any(|r| {
|
let proof = h.request_headers.iter().any(|r| {
|
||||||
matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
|
matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
|
||||||
|
|||||||
@@ -123,7 +123,10 @@ impl Control {
|
|||||||
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
|
async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> {
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
for u in &r.upstreams {
|
for u in &r.upstreams {
|
||||||
let host_header = if r.has_check {
|
let host_header = if r.has_check && u.is_unix() {
|
||||||
|
// As edge: a socket has no authority to name.
|
||||||
|
"localhost".to_owned()
|
||||||
|
} else if r.has_check {
|
||||||
u.authority()
|
u.authority()
|
||||||
} else {
|
} else {
|
||||||
hostname.to_owned()
|
hostname.to_owned()
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ pub async fn serve(
|
|||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
cfg.check().map_err(|e| e.to_string())?;
|
cfg.check().map_err(|e| e.to_string())?;
|
||||||
let listen = cfg.listen;
|
let listen = cfg.listen;
|
||||||
|
let ui_socket = cfg.ui.as_ref().and_then(|u| u.socket.clone());
|
||||||
let ctl = Control::open(cfg).await?;
|
let ctl = Control::open(cfg).await?;
|
||||||
tokio::spawn(ctl.clone().worker());
|
tokio::spawn(ctl.clone().worker());
|
||||||
tokio::spawn(ctl.clone().health_poller());
|
tokio::spawn(ctl.clone().health_poller());
|
||||||
@@ -50,14 +51,88 @@ pub async fn serve(
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
|
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
|
||||||
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
|
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
|
||||||
axum::serve(listener, app)
|
|
||||||
.with_graceful_shutdown(shutdown)
|
// One shutdown for both listeners.
|
||||||
.await
|
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
|
||||||
.map_err(|e| e.to_string())?;
|
tokio::spawn(async move {
|
||||||
|
shutdown.await;
|
||||||
|
let _ = stop_tx.send(true);
|
||||||
|
});
|
||||||
|
let stopped = |mut rx: tokio::sync::watch::Receiver<bool>| async move {
|
||||||
|
let _ = rx.wait_for(|s| *s).await;
|
||||||
|
};
|
||||||
|
let tcp = axum::serve(listener, app.clone()).with_graceful_shutdown(stopped(stop_rx.clone()));
|
||||||
|
match ui_socket {
|
||||||
|
None => tcp.await.map_err(|e| e.to_string())?,
|
||||||
|
Some(path) => {
|
||||||
|
let ui = ui_listener(&path)?;
|
||||||
|
log::info!(target: "ianitor::control", "UI API on unix:{}", path.display());
|
||||||
|
let ui_app = app.layer(axum::Extension(api::ViaUiSocket));
|
||||||
|
let ui = serve_ui(ui, ui_app, stopped(stop_rx));
|
||||||
|
let (a, b) = tokio::join!(std::future::IntoFuture::into_future(tcp), ui);
|
||||||
|
a.map_err(|e| e.to_string())?;
|
||||||
|
b?;
|
||||||
|
}
|
||||||
|
}
|
||||||
drop(ctl);
|
drop(ctl);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Control's UI socket: a stale socket file from an earlier run is replaced; the new one is
|
||||||
|
/// 0660 (owner and group: edge and Caddy are in the ianitor group). Its directory is the
|
||||||
|
/// real fence: only the ianitor group may enter it, so no other user can connect or put a
|
||||||
|
/// socket of their own in its place.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn ui_listener(path: &std::path::Path) -> Result<tokio::net::UnixListener, String> {
|
||||||
|
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||||
|
if let Ok(m) = std::fs::symlink_metadata(path) {
|
||||||
|
if !m.file_type().is_socket() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} exists and is not a socket; not replacing it",
|
||||||
|
path.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::remove_file(path).map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
|
||||||
|
}
|
||||||
|
let l = tokio::net::UnixListener::bind(path)
|
||||||
|
.map_err(|e| format!("cannot listen on {}: {e}", path.display()))?;
|
||||||
|
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))
|
||||||
|
.map_err(|e| format!("cannot set the mode of {}: {e}", path.display()))?;
|
||||||
|
Ok(l)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
async fn serve_ui(
|
||||||
|
l: tokio::net::UnixListener,
|
||||||
|
app: axum::Router,
|
||||||
|
stop: impl std::future::Future<Output = ()> + Send + 'static,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
axum::serve(l, app)
|
||||||
|
.with_graceful_shutdown(stop)
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
struct NoUnixListener;
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn ui_listener(path: &std::path::Path) -> Result<NoUnixListener, String> {
|
||||||
|
Err(format!(
|
||||||
|
"ui.socket {}: a Unix socket needs a Unix system",
|
||||||
|
path.display()
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
async fn serve_ui(
|
||||||
|
_l: NoUnixListener,
|
||||||
|
_app: axum::Router,
|
||||||
|
_stop: impl std::future::Future<Output = ()> + Send + 'static,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Wait for Ctrl-C or SIGTERM.
|
/// Wait for Ctrl-C or SIGTERM.
|
||||||
pub async fn stop_signal() {
|
pub async fn stop_signal() {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
|
|||||||
Reference in New Issue
Block a user