311 lines
11 KiB
Rust
311 lines
11 KiB
Rust
//! mTLS-only, write-once trust bootstrap. Never replaces a pin from the helper
|
|
//! or converts a job-supplied key into authority.
|
|
use anyhow::{Result, ensure};
|
|
use rmm_privileged_helper::{Binding, SigningKey};
|
|
#[cfg(test)]
|
|
use std::fs;
|
|
use std::{net::SocketAddr, path::Path, time::Duration};
|
|
|
|
#[cfg(test)]
|
|
fn client(dir: &Path, address: SocketAddr, ca: &[u8]) -> Result<reqwest::Client> {
|
|
let mut identity = fs::read(dir.join("device.pem"))?;
|
|
identity.extend_from_slice(&fs::read(dir.join("device.key"))?);
|
|
Ok(reqwest::Client::builder()
|
|
.https_only(true)
|
|
.tls_built_in_root_certs(false)
|
|
.add_root_certificate(reqwest::Certificate::from_pem(ca)?)
|
|
.identity(reqwest::Identity::from_pem(&identity)?)
|
|
.resolve(&crate::https_channel::server_name()?, address)
|
|
.no_proxy()
|
|
.redirect(reqwest::redirect::Policy::none())
|
|
.connect_timeout(Duration::from_secs(10))
|
|
.timeout(Duration::from_secs(15))
|
|
.build()?)
|
|
}
|
|
#[cfg(test)]
|
|
pub async fn provision(
|
|
dir: &Path,
|
|
address: SocketAddr,
|
|
ca: &[u8],
|
|
binding: &mut Binding,
|
|
) -> Result<()> {
|
|
download(dir, address, binding, client(dir, address, ca)?).await
|
|
}
|
|
pub async fn provision_current(
|
|
dir: &Path,
|
|
address: SocketAddr,
|
|
ca: &[u8],
|
|
binding: &mut Binding,
|
|
identity: &crate::certificate_rotation::DeviceIdentity,
|
|
) -> Result<()> {
|
|
let client = crate::https_channel::mtls_client(
|
|
address,
|
|
ca,
|
|
&identity.certificate_pem,
|
|
&identity.private_key_pem,
|
|
)?;
|
|
download(dir, address, binding, client).await
|
|
}
|
|
async fn download(
|
|
dir: &Path,
|
|
address: SocketAddr,
|
|
binding: &mut Binding,
|
|
client: reqwest::Client,
|
|
) -> Result<()> {
|
|
let mut response = client
|
|
.get(format!(
|
|
"https://{}:{}/api/v1/job-signing-key",
|
|
crate::https_channel::server_name()?,
|
|
address.port()
|
|
))
|
|
.timeout(Duration::from_secs(15))
|
|
.send()
|
|
.await?;
|
|
ensure!(
|
|
response.status() == reqwest::StatusCode::OK,
|
|
"SIGNING_KEY_AUTHENTICATED_ENDPOINT_REJECTED"
|
|
);
|
|
ensure!(
|
|
response.content_length().is_none_or(|n| n <= 4096),
|
|
"SIGNING_KEY_SIZE"
|
|
);
|
|
let mut bytes = vec![];
|
|
while let Some(chunk) = response.chunk().await? {
|
|
ensure!(bytes.len() + chunk.len() <= 4096, "SIGNING_KEY_SIZE");
|
|
bytes.extend_from_slice(&chunk);
|
|
}
|
|
let downloaded: SigningKey = serde_json::from_slice(&bytes)?;
|
|
pin(dir, binding, &downloaded)
|
|
}
|
|
fn pin(dir: &Path, binding: &mut Binding, downloaded: &SigningKey) -> Result<()> {
|
|
downloaded.validate()?;
|
|
ensure!(
|
|
binding.public_key_hex.is_empty() || binding.public_key_hex == downloaded.public_key_hex,
|
|
"PROVISIONED_KEY_MISMATCH"
|
|
);
|
|
let path = dir.join("job-signing-key.json");
|
|
if path.try_exists()? {
|
|
let cached = SigningKey::read(&path, unsafe { libc::geteuid() })?;
|
|
ensure!(
|
|
cached == *downloaded,
|
|
"SIGNING_KEY_ROTATION_REQUIRES_CONTROLLED_PROVISIONING"
|
|
);
|
|
} else {
|
|
crate::storage::create_secret(&path, &serde_json::to_vec(downloaded)?)?;
|
|
}
|
|
binding.public_key_hex = downloaded.public_key_hex.clone();
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
fn key() -> SigningKey {
|
|
let public = openssl::pkey::PKey::generate_ed25519()
|
|
.unwrap()
|
|
.raw_public_key()
|
|
.unwrap();
|
|
SigningKey {
|
|
key_id: rmm_domain::jobs::hash(&public),
|
|
algorithm: "Ed25519".into(),
|
|
schema_version: 1,
|
|
public_key_hex: public.iter().map(|b| format!("{b:02x}")).collect(),
|
|
}
|
|
}
|
|
#[test]
|
|
fn bootstrap_never_rotates_existing_or_provisioned_trust() {
|
|
let path = std::env::temp_dir().join(format!("rmm-key-bootstrap-{}", uuid::Uuid::new_v4()));
|
|
crate::storage::prepare_dir(&path).unwrap();
|
|
let mut binding = Binding {
|
|
tenant_id: uuid::Uuid::new_v4(),
|
|
asset_id: uuid::Uuid::new_v4(),
|
|
agent_id: uuid::Uuid::new_v4(),
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
public_key_hex: String::new(),
|
|
};
|
|
let first = key();
|
|
pin(&path, &mut binding, &first).unwrap();
|
|
pin(&path, &mut binding, &first).unwrap();
|
|
assert!(pin(&path, &mut binding, &key()).is_err());
|
|
binding.public_key_hex.clear();
|
|
assert!(pin(&path, &mut binding, &key()).is_err());
|
|
assert_eq!(
|
|
SigningKey::read(&path.join("job-signing-key.json"), unsafe {
|
|
libc::geteuid()
|
|
})
|
|
.unwrap(),
|
|
first
|
|
);
|
|
let mut bad = first.clone();
|
|
bad.algorithm = "RSA".into();
|
|
assert!(bad.validate().is_err());
|
|
bad = first.clone();
|
|
bad.schema_version = 2;
|
|
assert!(bad.validate().is_err());
|
|
bad = first;
|
|
bad.key_id = "wrong".into();
|
|
assert!(bad.validate().is_err());
|
|
fs::remove_dir_all(path).unwrap();
|
|
}
|
|
|
|
fn certificate(
|
|
cn: &str,
|
|
issuer: Option<(
|
|
&openssl::x509::X509,
|
|
&openssl::pkey::PKey<openssl::pkey::Private>,
|
|
)>,
|
|
server: bool,
|
|
) -> (
|
|
openssl::x509::X509,
|
|
openssl::pkey::PKey<openssl::pkey::Private>,
|
|
) {
|
|
use openssl::{
|
|
asn1::Asn1Time,
|
|
bn::BigNum,
|
|
ec::{EcGroup, EcKey},
|
|
nid::Nid,
|
|
pkey::PKey,
|
|
x509::{
|
|
X509, X509NameBuilder,
|
|
extension::{BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName},
|
|
},
|
|
};
|
|
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
|
|
let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
|
|
let mut name = X509NameBuilder::new().unwrap();
|
|
name.append_entry_by_text("CN", cn).unwrap();
|
|
let name = name.build();
|
|
let mut builder = X509::builder().unwrap();
|
|
builder.set_version(2).unwrap();
|
|
builder
|
|
.set_serial_number(
|
|
&BigNum::from_u32(rand::random_range(1..u32::MAX))
|
|
.unwrap()
|
|
.to_asn1_integer()
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
builder.set_subject_name(&name).unwrap();
|
|
builder
|
|
.set_issuer_name(issuer.map_or(name.as_ref(), |(ca, _)| ca.subject_name()))
|
|
.unwrap();
|
|
builder.set_pubkey(&key).unwrap();
|
|
builder
|
|
.set_not_before(&Asn1Time::days_from_now(0).unwrap())
|
|
.unwrap();
|
|
builder
|
|
.set_not_after(&Asn1Time::days_from_now(1).unwrap())
|
|
.unwrap();
|
|
if issuer.is_none() {
|
|
builder
|
|
.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
|
.unwrap();
|
|
builder
|
|
.append_extension(KeyUsage::new().key_cert_sign().crl_sign().build().unwrap())
|
|
.unwrap();
|
|
} else {
|
|
builder
|
|
.append_extension(BasicConstraints::new().build().unwrap())
|
|
.unwrap();
|
|
let mut usage = ExtendedKeyUsage::new();
|
|
if server {
|
|
usage.server_auth();
|
|
} else {
|
|
usage.client_auth();
|
|
}
|
|
builder.append_extension(usage.build().unwrap()).unwrap();
|
|
if server {
|
|
let context = builder.x509v3_context(issuer.map(|(ca, _)| ca.as_ref()), None);
|
|
let san = SubjectAlternativeName::new()
|
|
.dns(cn)
|
|
.build(&context)
|
|
.unwrap();
|
|
builder.append_extension(san).unwrap();
|
|
}
|
|
}
|
|
builder
|
|
.sign(
|
|
issuer.map_or(&key, |(_, k)| k),
|
|
openssl::hash::MessageDigest::sha256(),
|
|
)
|
|
.unwrap();
|
|
(builder.build(), key)
|
|
}
|
|
async fn tls_bootstrap(server_name: &str) -> bool {
|
|
use openssl::ssl::{SslAcceptor, SslMethod, SslVerifyMode};
|
|
use std::{
|
|
io::{Read, Write},
|
|
net::TcpListener,
|
|
};
|
|
let dir = std::env::temp_dir().join(format!("rmm-mtls-key-{}", uuid::Uuid::new_v4()));
|
|
crate::storage::prepare_dir(&dir).unwrap();
|
|
let (ca, ca_key) = certificate("test CA", None, false);
|
|
let (server, server_key) = certificate(server_name, Some((&ca, &ca_key)), true);
|
|
let (device, device_key) = certificate("enrolled device", Some((&ca, &ca_key)), false);
|
|
crate::storage::create_secret(&dir.join("device.pem"), &device.to_pem().unwrap()).unwrap();
|
|
crate::storage::create_secret(
|
|
&dir.join("device.key"),
|
|
&device_key.private_key_to_pem_pkcs8().unwrap(),
|
|
)
|
|
.unwrap();
|
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
let downloaded = key();
|
|
let response = serde_json::to_vec(&downloaded).unwrap();
|
|
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls_server()).unwrap();
|
|
acceptor.set_certificate(&server).unwrap();
|
|
acceptor.set_private_key(&server_key).unwrap();
|
|
acceptor.cert_store_mut().add_cert(ca.clone()).unwrap();
|
|
acceptor.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
|
let acceptor = acceptor.build();
|
|
let worker = std::thread::spawn(move || {
|
|
let (socket, _) = listener.accept().unwrap();
|
|
socket
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.unwrap();
|
|
if let Ok(mut tls) = acceptor.accept(socket) {
|
|
assert!(tls.ssl().peer_certificate().is_some());
|
|
let mut bytes = [0; 8192];
|
|
if let Ok(n) = tls.read(&mut bytes) {
|
|
assert!(
|
|
String::from_utf8_lossy(&bytes[..n])
|
|
.starts_with("GET /api/v1/job-signing-key HTTP/1.1")
|
|
);
|
|
let header = format!(
|
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
|
response.len()
|
|
);
|
|
let _ = tls.write_all(header.as_bytes());
|
|
let _ = tls.write_all(&response);
|
|
}
|
|
}
|
|
});
|
|
let mut binding = Binding {
|
|
tenant_id: uuid::Uuid::new_v4(),
|
|
asset_id: uuid::Uuid::new_v4(),
|
|
agent_id: uuid::Uuid::new_v4(),
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
public_key_hex: String::new(),
|
|
};
|
|
let result = provision(&dir, address, &ca.to_pem().unwrap(), &mut binding).await;
|
|
worker.join().unwrap();
|
|
if result.is_ok() {
|
|
assert_eq!(binding.public_key_hex, downloaded.public_key_hex);
|
|
} else {
|
|
assert!(!dir.join("job-signing-key.json").exists());
|
|
}
|
|
fs::remove_dir_all(dir).unwrap();
|
|
result.is_ok()
|
|
}
|
|
#[tokio::test]
|
|
async fn bootstrap_uses_real_mtls_and_dns_connect_override() {
|
|
assert!(tls_bootstrap("rmm-dev.internal").await);
|
|
}
|
|
#[tokio::test]
|
|
async fn bootstrap_rejects_wrong_server_name_without_creating_trust() {
|
|
assert!(!tls_bootstrap("wrong.internal").await);
|
|
}
|
|
}
|