use crate::{cli::ServeArgs, pki};
use indicatrix_net::messages::PeerRole;
use std::{
net::{SocketAddr, TcpStream},
path::PathBuf,
sync::Arc,
time::Instant,
};
#[derive(Debug, Clone)]
pub struct Auth {
pub role: PeerRole,
pub allowlist: Option<PathBuf>,
}
#[derive(Debug)]
pub enum Transport {
Tls {
config: Arc<rustls::ServerConfig>,
auth: Auth,
},
Insecure,
}
pub fn build_transport(args: &ServeArgs, bind_addr: SocketAddr) -> Result<Transport, String> {
if args.insecure_no_tls {
if !bind_addr.ip().is_loopback() {
return Err(format!(
"refusing --insecure-no-tls on non-loopback bind address {bind_addr} -- serving plaintext with no \
TLS and no authentication beyond localhost is not allowed; see --help"
));
}
tracing::warn!(
"indicatrix-worker serve: --insecure-no-tls -- serving PLAINTEXT with no TLS and no authentication. For \
local debugging only; every connection accepted this way is logged."
);
return Ok(Transport::Insecure);
}
let ca_path = args.ca.clone().ok_or_else(|| {
"\"serve\" requires --ca <path> unless --insecure-no-tls is set (see --help)".to_string()
})?;
let cert_path = args.cert.clone().ok_or_else(|| {
"\"serve\" requires --cert <path> unless --insecure-no-tls is set (see --help)".to_string()
})?;
let key_path = args.key.clone().ok_or_else(|| {
"\"serve\" requires --key <path> unless --insecure-no-tls is set (see --help)".to_string()
})?;
let ca = indicatrix_net::tls::load_ca(&ca_path)
.map_err(|e| format!("--ca {}: {e}", ca_path.display()))?;
let cert_chain = indicatrix_net::tls::load_certs(&cert_path)
.map_err(|e| format!("--cert {}: {e}", cert_path.display()))?;
let key = indicatrix_net::tls::load_private_key(&key_path)
.map_err(|e| format!("--key {}: {e}", key_path.display()))?;
let config = indicatrix_net::tls::server_config(ca, cert_chain, key)
.map_err(|e| format!("failed to build TLS config: {e}"))?;
let allowlist = if args.trust_any_client_cert {
tracing::warn!(
"indicatrix-worker serve: --trust-any-client-cert -- the fingerprint allowlists are DISABLED; any client \
certificate signed by {} (and carrying the port's role) will be accepted",
ca_path.display()
);
None
} else {
let allowlist_path = args
.allowlist
.clone()
.unwrap_or_else(|| pki::default_viewer_allowlist_path(&ca_path));
let preflight = indicatrix_net::tls::Allowlist::load(&allowlist_path).map_err(|e| {
format!(
"--allowlist {}: {e} (run `indicatrix-worker cert issue-client` to trust a viewer, or pass \
--trust-any-client-cert to skip this check)",
allowlist_path.display()
)
})?;
tracing::info!(
"indicatrix-worker serve: {} trusted viewer certificate(s) in {}",
preflight.len(),
allowlist_path.display()
);
Some(allowlist_path)
};
Ok(Transport::Tls {
config,
auth: Auth {
role: PeerRole::Viewer,
allowlist,
},
})
}
#[cfg(feature = "worker")]
pub fn worker_auth(args: &ServeArgs) -> Result<Auth, String> {
if args.trust_any_client_cert {
return Ok(Auth {
role: PeerRole::Worker,
allowlist: None,
});
}
let path = match (&args.worker_allowlist, &args.ca) {
(Some(path), _) => path.clone(),
(None, Some(ca)) => pki::default_worker_allowlist_path(ca),
(None, None) => return Err("\"serve\" requires --ca <path> for the worker port".into()),
};
if path.exists() {
let list = indicatrix_net::tls::Allowlist::load(&path)
.map_err(|e| format!("--worker-allowlist {}: {e}", path.display()))?;
tracing::info!(
"indicatrix-worker serve: {} trusted worker certificate(s) in {}",
list.len(),
path.display()
);
} else {
tracing::info!(
"indicatrix-worker serve: no worker allowlist at {} yet -- every joining worker is refused until one \
is enrolled (`cert issue-client --role worker` or `cert issue-token --role worker`)",
path.display()
);
}
Ok(Auth {
role: PeerRole::Worker,
allowlist: Some(path),
})
}
pub fn accept_tls(
stream: TcpStream,
config: &Arc<rustls::ServerConfig>,
auth: &Auth,
peer: Option<SocketAddr>,
) -> Option<(TlsStream, PeerRole)> {
let conn = match rustls::ServerConnection::new(Arc::clone(config)) {
Ok(c) => c,
Err(e) => {
tracing::warn!("connection {peer:?}: could not start TLS: {e}");
return None;
}
};
let mut tls_stream = rustls::StreamOwned::new(conn, stream);
let deadline = Instant::now() + super::HANDSHAKE_TIMEOUT;
let handshake_result = {
let mut io = super::DeadlineSocket::new(&tls_stream.sock, deadline);
tls_stream.conn.complete_io(&mut io)
};
if let Err(e) = handshake_result {
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) {
tracing::debug!(
"connection {peer:?}: TLS handshake timed out after {:?} -- dropping (see \
serve::HANDSHAKE_TIMEOUT)",
super::HANDSHAKE_TIMEOUT
);
} else {
tracing::warn!("connection {peer:?}: TLS handshake failed: {e}");
}
return None;
}
match check_auth(&tls_stream, auth) {
Ok(role) => Some((tls_stream, role)),
Err(msg) => {
tracing::warn!("connection {peer:?}: {msg}");
None
}
}
}
pub type TlsStream = rustls::StreamOwned<rustls::ServerConnection, TcpStream>;
fn check_auth(stream: &TlsStream, auth: &Auth) -> Result<PeerRole, String> {
let peer_certs = stream
.conn
.peer_certificates()
.filter(|certs| !certs.is_empty())
.ok_or_else(|| {
"TLS handshake succeeded but the peer presented no client certificate".to_string()
})?;
let fingerprint = indicatrix_net::tls::fingerprint(&peer_certs[0]);
let fingerprint_hex = indicatrix_net::tls::fingerprint_to_hex(&fingerprint);
let role = pki::role_of_certificate(&peer_certs[0])
.map_err(|e| format!("rejecting client certificate {fingerprint_hex}: {e}"))?;
if role != auth.role {
return Ok(role);
}
let Some(path) = &auth.allowlist else {
return Ok(role); };
let allowlist = indicatrix_net::tls::Allowlist::load(path).map_err(|e| {
format!(
"rejecting {} certificate {fingerprint_hex}: could not (re-)load allowlist {}: {e}",
pki::role::role_name(role),
path.display()
)
})?;
if allowlist.contains(&fingerprint) {
Ok(role)
} else {
Err(format!(
"rejecting {} certificate {fingerprint_hex}: not present in {} (run `indicatrix-worker cert \
issue-client --role {}` to trust it, or add this exact fingerprint by hand)",
pki::role::role_name(role),
path.display(),
pki::role::role_name(role)
))
}
}