use super::registry::{EnrollRegistry, ZeroizeLocal};
use indicatrix_net::{
enroll::{EnrollRequest, EnrollResponse},
messages::PeerRole,
};
use std::{
io::{Read, Write},
net::{SocketAddr, TcpStream},
path::Path,
sync::Arc,
};
pub(super) type EnrollTlsStream = rustls::StreamOwned<rustls::ServerConnection, TcpStream>;
const MAX_ENROLL_REQUEST_LEN: u32 = 4096;
pub(super) fn accept_enroll_tls(
stream: TcpStream,
config: &Arc<rustls::ServerConfig>,
peer: Option<SocketAddr>,
) -> Option<EnrollTlsStream> {
if let Err(e) = stream.set_read_timeout(Some(crate::serve::HANDSHAKE_TIMEOUT)) {
tracing::debug!(
"enrollment connection {peer:?}: failed to set handshake read timeout: {e}"
);
}
if let Err(e) = stream.set_write_timeout(Some(crate::serve::HANDSHAKE_TIMEOUT)) {
tracing::debug!(
"enrollment connection {peer:?}: failed to set handshake write timeout: {e}"
);
}
let conn = match rustls::ServerConnection::new(Arc::clone(config)) {
Ok(c) => c,
Err(e) => {
tracing::warn!("enrollment connection {peer:?}: could not start TLS: {e}");
return None;
}
};
let mut tls_stream = rustls::StreamOwned::new(conn, stream);
let deadline = std::time::Instant::now() + crate::serve::HANDSHAKE_TIMEOUT;
let handshake_result = {
let mut io = crate::serve::DeadlineSocket::new(&tls_stream.sock, deadline);
tls_stream.conn.complete_io(&mut io)
};
if let Err(e) = handshake_result {
tracing::warn!("enrollment connection {peer:?}: TLS handshake failed: {e}");
return None;
}
Some(tls_stream)
}
fn issue_label_for_role(name: &str, role: PeerRole) -> Result<&str, String> {
match (role, name.strip_prefix(crate::pki::WORKER_CN_PREFIX)) {
(PeerRole::Viewer, None) => Ok(name),
(PeerRole::Worker, Some(label)) => Ok(label),
(PeerRole::Viewer, Some(_)) => Err(
"this is the VIEWER enrollment listener -- a worker token must be issued on the coordinator's \
WORKER enrollment listener (default port 7881)"
.to_string(),
),
(PeerRole::Worker, None) => Err(
"this is the WORKER enrollment listener -- pass `cert issue-token --role worker` for a worker \
token, or use the viewer enrollment listener (default port 7879) for a viewer"
.to_string(),
),
}
}
fn issue_response(
name: &str,
authorised: bool,
registry: &EnrollRegistry,
pki_dir: &Path,
peer: Option<SocketAddr>,
) -> EnrollResponse {
if !peer.is_some_and(|p| p.ip().is_loopback()) {
tracing::warn!("enrollment connection {peer:?}: refused Issue from a non-loopback peer");
return EnrollResponse::IssueRefused {
reason: "issuing enrollment tokens is only permitted from loopback".to_string(),
};
}
if !authorised {
tracing::warn!("enrollment connection {peer:?}: refused Issue without the operator secret");
return EnrollResponse::IssueRefused {
reason: format!(
"issuing enrollment tokens needs the operator secret ({} in the PKI directory)",
indicatrix_net::enroll::OPERATOR_SECRET_FILE
),
};
}
match issue_label_for_role(name, registry.role()) {
Ok(label) => match registry.issue(pki_dir, label) {
Ok((token, expires_in_secs)) => EnrollResponse::Issued {
token,
expires_in_secs,
},
Err(reason) => EnrollResponse::IssueRefused {
reason: reason.to_string(),
},
},
Err(reason) => EnrollResponse::IssueRefused { reason },
}
}
pub(super) fn handle_enroll_connection<S: Read + Write>(
mut stream: S,
registry: &EnrollRegistry,
pki_dir: &Path,
allowlist_path: Option<&Path>,
peer: Option<SocketAddr>,
) -> Result<(), String> {
let deadline = std::time::Instant::now() + crate::serve::HANDSHAKE_TIMEOUT;
let request: EnrollRequest = {
let mut guarded = crate::serve::DeadlineIo::new(&mut stream, deadline);
indicatrix_net::messages::read_message_bounded(&mut guarded, MAX_ENROLL_REQUEST_LEN)
.map_err(|e| e.to_string())?
};
match request {
EnrollRequest::Issue { .. } => {
tracing::warn!(
"enrollment connection {peer:?}: refused an Issue without the operator secret"
);
let response = EnrollResponse::IssueRefused {
reason: "this listener requires the operator secret to issue a token -- update \
`indicatrix-worker cert issue-token`"
.to_string(),
};
indicatrix_net::messages::write_message(&mut stream, &response)
.map_err(|e| e.to_string())
}
EnrollRequest::IssueAuthorized {
name,
mut operator_secret,
} => {
let authorised = registry.operator_secret_matches(&operator_secret);
operator_secret.zeroize_local();
let response = issue_response(&name, authorised, registry, pki_dir, peer);
indicatrix_net::messages::write_message(&mut stream, &response)
.map_err(|e| e.to_string())
}
EnrollRequest::Claim { mut secret } => {
let claimed = registry.claim(&secret);
secret.zeroize_local();
let response = if let Some(claimed) = claimed {
let allowlisted = allowlist_path.map_or(Ok(()), |path| {
indicatrix_net::tls::append_to_allowlist(
path,
&claimed.bundle.client_fingerprint,
&claimed.name,
)
.map_err(|e| e.to_string())
});
match allowlisted {
Ok(()) => EnrollResponse::Claimed {
ca_pem: claimed.bundle.ca_pem,
client_cert_pem: claimed.bundle.client_cert_pem,
client_key_pem: claimed.bundle.client_key_pem.to_string(),
},
Err(e) => {
tracing::error!(
"enrollment connection {peer:?}: claim succeeded but appending to the allowlist \
failed, so it is being reported as a failed claim instead: {e}"
);
EnrollResponse::ClaimFailed
}
}
} else {
tracing::debug!(
"enrollment connection {peer:?}: claim did not match any pending enrollment (wrong \
secret, already claimed, or expired)"
);
EnrollResponse::ClaimFailed
};
indicatrix_net::messages::write_message(&mut stream, &response)
.map_err(|e| e.to_string())
}
}
}
#[cfg(test)]
mod issue_authorisation_tests {
use super::*;
use indicatrix_net::messages::{read_message, write_message};
use std::io::Cursor;
use zeroize::Zeroizing;
struct Duplex {
input: Cursor<Vec<u8>>,
output: Vec<u8>,
}
impl Read for Duplex {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.input.read(buf)
}
}
impl Write for Duplex {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.output.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn issue_from_loopback(registry: &EnrollRegistry, secret: [u8; 32]) -> EnrollResponse {
let mut request = Vec::new();
write_message(
&mut request,
&EnrollRequest::IssueAuthorized {
name: "laptop".to_string(),
operator_secret: secret,
},
)
.unwrap();
let mut duplex = Duplex {
input: Cursor::new(request),
output: Vec::new(),
};
let peer: SocketAddr = "127.0.0.1:50000".parse().unwrap();
handle_enroll_connection(&mut duplex, registry, Path::new("."), None, Some(peer)).unwrap();
read_message(&mut Cursor::new(duplex.output)).unwrap()
}
#[test]
fn an_issue_from_loopback_without_the_operator_secret_is_refused() {
let registry = EnrollRegistry::new().with_operator_secret(Zeroizing::new([7u8; 32]));
let reply = issue_from_loopback(®istry, [0u8; 32]);
assert!(
matches!(&reply, EnrollResponse::IssueRefused { reason } if reason.contains("operator secret")),
"{reply:?}"
);
}
#[test]
fn an_issue_is_refused_when_no_operator_secret_is_configured() {
let reply = issue_from_loopback(&EnrollRegistry::new(), [0u8; 32]);
assert!(
matches!(reply, EnrollResponse::IssueRefused { .. }),
"{reply:?}"
);
}
}