269 lines
10 KiB
Rust
269 lines
10 KiB
Rust
//! Explicit development TLS fixture only. No enrollment, service or job path.
|
|
//! The fixture private key is generated and retained on this Windows guest.
|
|
#[cfg(windows)]
|
|
#[path = "../../agent/src/https_channel.rs"]
|
|
pub mod https_channel;
|
|
|
|
#[cfg(any(windows, test))]
|
|
mod tls_errors {
|
|
use std::error::Error;
|
|
pub(super) fn classify(error: &(dyn Error + 'static)) -> &'static str {
|
|
let mut next = Some(error);
|
|
for _ in 0..16 {
|
|
let Some(current) = next else { break };
|
|
if let Some(tls) = current.downcast_ref::<rustls::Error>() {
|
|
return match tls {
|
|
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateExpired) => {
|
|
"TLS_PEER_CERTIFICATE_EXPIRED"
|
|
}
|
|
rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer) => {
|
|
"TLS_UNKNOWN_ISSUER"
|
|
}
|
|
rustls::Error::InvalidCertificate(
|
|
rustls::CertificateError::NotValidForName
|
|
| rustls::CertificateError::NotValidForNameContext { .. },
|
|
) => "TLS_SERVER_NAME_MISMATCH",
|
|
rustls::Error::InvalidCertificate(_) => "TLS_OTHER_INVALID_CERTIFICATE",
|
|
rustls::Error::AlertReceived(_) => "TLS_OTHER_PEER_ALERT",
|
|
_ => "TLS_OTHER_ERROR",
|
|
};
|
|
}
|
|
// io::Error::source skips its boxed payload itself. Inspect get_ref
|
|
// first to preserve the concrete rustls::Error inside nested TLS I/O.
|
|
next = current
|
|
.downcast_ref::<std::io::Error>()
|
|
.and_then(std::io::Error::get_ref)
|
|
.map(|inner| inner as &(dyn Error + 'static))
|
|
.or_else(|| current.source());
|
|
}
|
|
"UNCLASSIFIED_TRANSPORT_ERROR"
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[test]
|
|
fn nested_io_preserves_typed_tls_and_rejects_untyped_failures() {
|
|
use std::io::{Error as IoError, ErrorKind};
|
|
let cases = [
|
|
(
|
|
rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer),
|
|
"TLS_UNKNOWN_ISSUER",
|
|
),
|
|
(
|
|
rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName),
|
|
"TLS_SERVER_NAME_MISMATCH",
|
|
),
|
|
(
|
|
rustls::Error::AlertReceived(rustls::AlertDescription::CertificateExpired),
|
|
"TLS_PEER_CERTIFICATE_EXPIRED",
|
|
),
|
|
];
|
|
for (error, expected) in cases {
|
|
// Tokio-rustls wraps InvalidData; hyper-rustls wraps it again as Other.
|
|
let nested = IoError::other(IoError::new(ErrorKind::InvalidData, error));
|
|
assert_eq!(classify(&nested), expected);
|
|
}
|
|
for error in [
|
|
IoError::from(ErrorKind::TimedOut),
|
|
IoError::from(ErrorKind::ConnectionReset),
|
|
IoError::other("certificate has expired: UnknownIssuer"),
|
|
] {
|
|
assert_eq!(classify(&error), "UNCLASSIFIED_TRANSPORT_ERROR");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
mod probe {
|
|
use anyhow::{Result, ensure};
|
|
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyPair};
|
|
use serde_json::{Value, json};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{fs, io::Write, path::Path};
|
|
use uuid::Uuid;
|
|
|
|
const ROOT: &str = r"C:\ProgramData\RustDiscoveryBootstrap\tls-negative";
|
|
const SERVER: &str = "discovery.ease-technologies.de";
|
|
|
|
fn private_read(root: &Path, name: &str, maximum: usize) -> Result<Vec<u8>> {
|
|
let path = root.join(name);
|
|
rmm_agent_windows::native::private_path(&path, false)?;
|
|
ensure!(
|
|
fs::metadata(&path)?.len() <= maximum as u64,
|
|
"FIXTURE_FILE_LIMIT"
|
|
);
|
|
Ok(fs::read(path)?)
|
|
}
|
|
fn create(root: &Path, name: &str, bytes: &[u8]) -> Result<()> {
|
|
let mut file = fs::OpenOptions::new()
|
|
.create_new(true)
|
|
.write(true)
|
|
.open(root.join(name))?;
|
|
file.write_all(bytes)?;
|
|
file.sync_all()?;
|
|
Ok(())
|
|
}
|
|
fn prepare(root: &Path, id: Uuid) -> Result<Value> {
|
|
ensure!(
|
|
fs::read_dir(root)?.next().is_none(),
|
|
"FRESH_FIXTURE_DIRECTORY_REQUIRED"
|
|
);
|
|
let key = KeyPair::generate()?;
|
|
let mut params = CertificateParams::default();
|
|
params
|
|
.distinguished_name
|
|
.push(DnType::CommonName, id.to_string());
|
|
let csr = params.serialize_request(&key)?.pem()?;
|
|
ensure!(csr.len() < 8192, "FIXTURE_CSR_LIMIT");
|
|
// Never emit or transfer the private key. Parent directory has already
|
|
// been restricted to SYSTEM/Administrators by the bootstrap wrapper.
|
|
create(root, "fixture.key", key.serialize_pem().as_bytes())?;
|
|
create(root, "fixture.csr", csr.as_bytes())?;
|
|
let mut wrong = CertificateParams::default();
|
|
wrong.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
|
wrong
|
|
.distinguished_name
|
|
.push(DnType::CommonName, "RMM unrelated fixture CA");
|
|
let wrong_key = KeyPair::generate()?;
|
|
create(
|
|
root,
|
|
"wrong-ca.pem",
|
|
wrong.self_signed(&wrong_key)?.pem().as_bytes(),
|
|
)?;
|
|
create(
|
|
root,
|
|
"case.json",
|
|
&serde_json::to_vec(&json!({"schema_version":1,"case_id":id}))?,
|
|
)?;
|
|
Ok(
|
|
json!({"prepared":true,"case_id":id,"csr_pem":csr,"csr_sha256":format!("{:x}",Sha256::digest(csr.as_bytes())),
|
|
"private_key_exported":false,"enrollment_created":false,"jobs_created":false}),
|
|
)
|
|
}
|
|
async fn request(root: &Path, id: Uuid, kind: &str) -> Result<Value> {
|
|
let marker: Value = serde_json::from_slice(&private_read(root, "case.json", 1024)?)?;
|
|
ensure!(
|
|
marker == json!({"schema_version":1,"case_id":id}),
|
|
"FIXTURE_ID_BINDING"
|
|
);
|
|
let ca = private_read(
|
|
root,
|
|
if kind == "wrong-ca" {
|
|
"wrong-ca.pem"
|
|
} else {
|
|
"issuer-ca.pem"
|
|
},
|
|
32768,
|
|
)?;
|
|
let certificate = private_read(
|
|
root,
|
|
if kind == "expired" {
|
|
"expired.pem"
|
|
} else {
|
|
"valid.pem"
|
|
},
|
|
32768,
|
|
)?;
|
|
let key = private_read(root, "fixture.key", 16384)?;
|
|
let address = "88.99.80.202:443".parse()?;
|
|
// Exactly the production transport builder: configured CA only,
|
|
// verified DNS/SNI, mTLS, no proxy trust, redirects or invalid-cert mode.
|
|
let client = crate::https_channel::mtls_client(address, &ca, &certificate, &key)?;
|
|
let name = crate::https_channel::server_name()?;
|
|
let result = client
|
|
.post(format!("https://{name}:443/agent/v1/messages"))
|
|
.header(reqwest::header::CONTENT_TYPE, "application/x-protobuf")
|
|
.body(Vec::new())
|
|
.send()
|
|
.await;
|
|
let (status, code) = match result {
|
|
Ok(response) => (Some(response.status().as_u16()), "HTTP_RESPONSE"),
|
|
Err(error) if error.is_timeout() => (None, "TRANSPORT_TIMEOUT"),
|
|
Err(error) => (None, super::tls_errors::classify(&error)),
|
|
};
|
|
let expected = match kind {
|
|
"valid" => status == Some(401),
|
|
"expired" => status.is_none() && code == "TLS_PEER_CERTIFICATE_EXPIRED",
|
|
"wrong-ca" => status.is_none() && code == "TLS_UNKNOWN_ISSUER",
|
|
"wrong-name" => status.is_none() && code == "TLS_SERVER_NAME_MISMATCH",
|
|
_ => false,
|
|
};
|
|
Ok(
|
|
json!({"case_id":id,"kind":kind,"verified":expected,"http_status":status,"code":code,
|
|
"native_windows":true,"execution_context":"bootstrap_administrator_tls_probe",
|
|
"shared_https_client":true,"certificate_verification_disabled":false,"clock_adjusted":false,
|
|
"private_key_exported":false,"enrollment_created":false,"jobs_created":false}),
|
|
)
|
|
}
|
|
pub fn run() -> Result<Value> {
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
ensure!(
|
|
(args.len() == 2 && args[0] == "prepare") || (args.len() == 3 && args[0] == "probe"),
|
|
"FIXED_PROBE_ARGUMENTS"
|
|
);
|
|
let id = Uuid::parse_str(&args[1])?;
|
|
ensure!(
|
|
!id.is_nil() && id.to_string() == args[1],
|
|
"CANONICAL_FIXTURE_UUID"
|
|
);
|
|
let root = Path::new(ROOT).join(id.to_string());
|
|
rmm_agent_windows::native::private_path(Path::new(ROOT), true)?;
|
|
rmm_agent_windows::native::private_path(&root, true)?;
|
|
if args[0] == "prepare" {
|
|
return prepare(&root, id);
|
|
}
|
|
let kind = args[2].as_str();
|
|
ensure!(
|
|
matches!(kind, "valid" | "expired" | "wrong-ca" | "wrong-name"),
|
|
"FIXED_PROBE_KIND"
|
|
);
|
|
// SAFETY: one freshly launched process per kind, before constructing
|
|
// Tokio or any worker threads. No environment mutation during a runtime.
|
|
unsafe {
|
|
std::env::set_var(
|
|
"RMM_SERVER_NAME",
|
|
if kind == "wrong-name" {
|
|
"wrong-name.invalid"
|
|
} else {
|
|
SERVER
|
|
},
|
|
);
|
|
}
|
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
|
.enable_all()
|
|
.build()?;
|
|
runtime.block_on(request(&root, id, kind))
|
|
}
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
fn main() {
|
|
match probe::run() {
|
|
Ok(value) => {
|
|
let accepted = value
|
|
.get("prepared")
|
|
.and_then(serde_json::Value::as_bool)
|
|
.unwrap_or(false)
|
|
|| value
|
|
.get("verified")
|
|
.and_then(serde_json::Value::as_bool)
|
|
.unwrap_or(false);
|
|
println!("{value}");
|
|
if !accepted {
|
|
std::process::exit(2);
|
|
}
|
|
}
|
|
Err(_) => {
|
|
println!(
|
|
"{}",
|
|
serde_json::json!({"verified":false,"code":"WINDOWS_TLS_FIXTURE_INCOMPLETE"})
|
|
);
|
|
std::process::exit(2);
|
|
}
|
|
}
|
|
}
|
|
#[cfg(not(windows))]
|
|
fn main() {
|
|
eprintln!("Windows TLS fixture probe requires native Windows");
|
|
std::process::exit(1);
|
|
}
|