feat: verify native Windows client probe and preserve unknown APT outcome
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-13 16:04:20 +01:00
parent 42c9b9c59c
commit 12557394fa
17 changed files with 1522 additions and 15 deletions
+343
View File
@@ -0,0 +1,343 @@
use anyhow::{Result, ensure};
use chrono::Utc;
use rcgen::{CertificateParams, DnType, KeyPair};
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
use rmm_protocol::*;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
fs,
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Config {
server_name: String,
connect_address: std::net::SocketAddr,
ca_file: PathBuf,
state_directory: PathBuf,
enrollment_token_file: PathBuf,
transport: String,
}
fn create_private(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
native::private_path(path, false)
}
fn protected_read(path: &Path, max: usize) -> Result<Vec<u8>> {
native::private_path(path, false)?;
ensure!(
fs::metadata(path)?.len() <= max as u64,
"PRIVATE_FILE_LIMIT"
);
Ok(fs::read(path)?)
}
async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
let state = &config.state_directory;
let identity = state.join("identity.json");
if identity.try_exists()? {
return Ok(serde_json::from_slice(&protected_read(&identity, 32768)?)?);
}
let key_path = state.join("device.key");
let key = if key_path.try_exists()? {
KeyPair::from_pem(std::str::from_utf8(&protected_read(&key_path, 16384)?)?)?
} else {
let key = KeyPair::generate()?;
create_private(&key_path, key.serialize_pem().as_bytes())?;
key
};
let mut parameters = CertificateParams::default();
parameters
.distinguished_name
.push(DnType::CommonName, "new-windows-device");
let csr = parameters.serialize_request(&key)?.pem()?;
let token = String::from_utf8(protected_read(&config.enrollment_token_file, 128)?)?
.trim()
.to_owned();
ensure!(
token.len() == 64 && token.bytes().all(|b| b.is_ascii_hexdigit()),
"ENROLLMENT_TOKEN_FORMAT"
);
let client = reqwest::Client::builder()
.https_only(true)
.tls_built_in_root_certs(false)
.add_root_certificate(reqwest::Certificate::from_pem(ca)?)
.resolve(&config.server_name, config.connect_address)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(20))
.build()?;
let response = client
.post(format!(
"https://{}:{}/agent/v1/enroll",
config.server_name,
config.connect_address.port()
))
.json(&EnrollmentRequest {
token,
csr_pem: csr,
})
.send()
.await?;
let bytes = crate::https_channel::bounded_body(response, 32768, "application/json").await?;
let identity: EnrollmentResponse = serde_json::from_slice(&bytes)?;
Uuid::parse_str(&identity.agent_id)?;
Uuid::parse_str(&identity.asset_id)?;
// The server consumes the token once; a lost response is an explicit recovery
// gate. No automatic re-enrollment or replacement identity is attempted.
create_private(
&state.join("device.pem"),
identity.certificate_pem.as_bytes(),
)?;
create_private(
&state.join("identity.json"),
&serde_json::to_vec(&identity)?,
)?;
fs::remove_file(&config.enrollment_token_file)?;
Ok(identity)
}
struct Agent {
config: Config,
identity: EnrollmentResponse,
ca: Vec<u8>,
journal: Journal,
boot: String,
instance: String,
started: Instant,
}
impl Agent {
fn envelope(&mut self, generation: u64, payload: Payload) -> Result<Envelope> {
Ok(Envelope {
protocol_major: 1,
protocol_minor: 0,
message_id: Uuid::new_v4().to_string(),
agent_id: self.identity.agent_id.clone(),
enrollment_generation: 1,
connection_generation: generation,
boot_id: self.boot.clone(),
sequence: self.journal.next_sequence()?,
observed_at: Utc::now().timestamp_millis(),
payload: Some(payload),
})
}
fn queue_inventory(&mut self, generation: u64) -> Result<()> {
if self.journal.count()? > 0 {
return Ok(());
}
let data = serde_json::to_vec(&native::snapshot()?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
let envelope = self.envelope(
generation,
Payload::InventorySnapshot(InventorySnapshot {
snapshot_id: Uuid::new_v4().to_string(),
scope: "windows.base".into(),
schema_version: 1,
chunk_index: 0,
chunk_count: 1,
sha256: Sha256::digest(&data).to_vec(),
data,
completeness: "partial".into(),
}),
)?;
self.journal.save(&envelope)
}
async fn session(&mut self, stop: &AtomicBool) -> Result<()> {
let hello = self.envelope(
0,
Payload::ClientHello(ClientHello {
agent_version: env!("CARGO_PKG_VERSION").into(),
capabilities: CAPABILITIES.iter().map(|v| v.to_string()).collect(),
}),
)?;
let identity = crate::certificate_rotation::DeviceIdentity {
certificate_pem: protected_read(
&self.config.state_directory.join("device.pem"),
32768,
)?,
private_key_pem: protected_read(
&self.config.state_directory.join("device.key"),
16384,
)?,
};
let mode = crate::wire_channel::Mode::parse(&self.config.transport)?;
let mut channel = crate::wire_channel::connect(
mode,
self.config.connect_address,
&self.ca,
&identity,
hello,
)
.await?;
let reply = tokio::time::timeout(Duration::from_secs(20), channel.receive()).await??;
ensure!(
reply.agent_id == self.identity.agent_id
&& reply.enrollment_generation == 1
&& reply.protocol_major == 1
&& reply.protocol_minor == 0,
"SERVER_HELLO_BINDING"
);
let Some(Payload::ServerHello(server)) = reply.payload else {
anyhow::bail!("SERVER_HELLO_REQUIRED")
};
let generation = server.connection_generation;
ensure!(
generation > 0 && server.max_message_bytes == rmm_domain::MAX_MESSAGE as u32,
"SERVER_LIMITS"
);
self.queue_inventory(generation)?;
let mut replay = Instant::now() - Duration::from_secs(10);
let mut inventory = Instant::now();
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_secs(1));
while !stop.load(Ordering::SeqCst) {
tokio::select! {
_=tick.tick()=>{},
message=channel.receive()=>{
let message=message?;
ensure!(message.agent_id==self.identity.agent_id && message.enrollment_generation==1 && message.protocol_major==1 && message.protocol_minor==0 && message.connection_generation==generation,"SERVER_ENVELOPE_BINDING");
match message.payload {
Some(Payload::Ack(ack))=>self.journal.ack(&ack.message_id)?,
// There is deliberately no acceptance/start path. A stale
// or malicious offer cannot activate an unimplemented job.
Some(Payload::JobOffer(_)|Payload::ExecutionPermit(_))=>anyhow::bail!("UNSUPPORTED_EXECUTION_CAPABILITY"),
_=>anyhow::bail!("UNSUPPORTED_SERVER_MESSAGE")
}
}
}
if heartbeat.elapsed() >= heartbeat_after {
let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
});
let h = self.envelope(generation, payload)?;
channel.send(&h).await?;
if channel.uses_https() {
let poll = self.envelope(
generation,
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
}),
)?;
channel.poll(poll).await?;
}
heartbeat = Instant::now();
heartbeat_after = Duration::from_millis(rand::random_range(27000..33000));
}
if replay.elapsed() >= Duration::from_secs(5) {
for mut event in self.journal.events()? {
event.connection_generation = generation;
channel.send(&event).await?;
}
replay = Instant::now();
}
if inventory.elapsed() >= Duration::from_secs(86400) {
self.queue_inventory(generation)?;
inventory = Instant::now();
}
}
Ok(())
}
}
fn service_run(stop: &'static AtomicBool) -> Result<()> {
let arguments: Vec<String> = std::env::args().skip(1).collect();
ensure!(
arguments.len() == 3 && arguments[0] == "--service" && arguments[1] == "--config",
"SERVICE_ARGUMENTS"
);
let path = Path::new(&arguments[2]);
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
let config: Config = serde_json::from_slice(&protected_read(path, 32768)?)?;
native::private_path(&config.state_directory, true)?;
ensure!(
crate::https_channel::server_name()? == config.server_name,
"SERVER_NAME"
);
let ca = protected_read(&config.ca_file, 32768)?;
for child in fs::read_dir(&config.state_directory)? {
let child = child?;
native::private_path(&child.path(), false)?;
}
let journal = Journal::open(&config.state_directory)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()?;
runtime.block_on(async move {
let identity = enrollment(&config, &ca).await?;
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let mut agent = Agent {
config,
identity,
ca,
journal,
boot,
instance: Uuid::new_v4().to_string(),
started: Instant::now(),
};
let mut backoff = 1;
while !stop.load(Ordering::SeqCst) {
let start = Instant::now();
let _ = agent.session(stop).await;
if start.elapsed() > Duration::from_secs(60) {
backoff = 1;
}
let delay = crate::https_channel::retry_delay(backoff);
backoff = (backoff + 1).min(6);
let until = Instant::now() + delay;
while !stop.load(Ordering::SeqCst) && Instant::now() < until {
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
Ok(())
})
}
pub fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
if args == ["--help"] {
println!(
"Development Windows passive service. --service --config ABSOLUTE_PATH. No job executor or approval bypass."
);
return Ok(());
}
if args == ["--native-probe"] {
let runtime = tokio::runtime::Runtime::new()?;
let boot = runtime.block_on(native::boot_id())?;
let inventory = native::snapshot()?;
println!(
"{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
);
return Ok(());
}
ensure!(
args.first().map(String::as_str) == Some("--service"),
"UNKNOWN_ARGUMENT"
);
ensure!(
args.len() == 3 && args[1] == "--config",
"SERVICE_ARGUMENTS"
);
let config: Config = serde_json::from_slice(&protected_read(Path::new(&args[2]), 32768)?)?;
// Shared transport reads its one DNS identity. Set it before SCM dispatch
// creates its service thread and before any Tokio/collector threads exist.
unsafe {
std::env::set_var("RMM_SERVER_NAME", &config.server_name);
}
ensure!(
crate::https_channel::server_name()? == config.server_name,
"SERVER_NAME"
);
rmm_agent_windows::service::dispatch(service_run)
}