feat: verify native Windows client probe and preserve unknown APT outcome
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
use anyhow::{Result, ensure};
|
||||
use fs2::FileExt;
|
||||
use prost::Message;
|
||||
use rmm_protocol::Envelope;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use std::{fs::OpenOptions, path::Path};
|
||||
|
||||
pub struct Journal {
|
||||
db: Connection,
|
||||
_lock: std::fs::File,
|
||||
}
|
||||
impl Journal {
|
||||
pub fn open(directory: &Path) -> Result<Self> {
|
||||
ensure!(directory.is_dir(), "STATE_DIRECTORY_REQUIRED");
|
||||
let lock = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(directory.join("agent.lock"))?;
|
||||
lock.try_lock_exclusive()?;
|
||||
let db = Connection::open(directory.join("telemetry.sqlite"))?;
|
||||
db.execute_batch(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL);
|
||||
INSERT OR IGNORE INTO metadata VALUES('sequence',0);
|
||||
CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);",
|
||||
)?;
|
||||
ensure!(
|
||||
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||
"JOURNAL_INTEGRITY"
|
||||
);
|
||||
Ok(Self { db, _lock: lock })
|
||||
}
|
||||
pub fn next_sequence(&mut self) -> Result<u64> {
|
||||
let tx = self.db.transaction()?;
|
||||
let sequence: i64 =
|
||||
tx.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| {
|
||||
r.get(0)
|
||||
})?;
|
||||
let next = sequence
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?;
|
||||
tx.execute("UPDATE metadata SET value=?1 WHERE key='sequence'", [next])?;
|
||||
tx.commit()?;
|
||||
Ok(u64::try_from(next)?)
|
||||
}
|
||||
pub fn save(&self, envelope: &Envelope) -> Result<()> {
|
||||
// This slice never deletes a durable event to make room for telemetry.
|
||||
// At the fixed cap it stops collecting until concrete ACKs release room.
|
||||
ensure!(self.count()? < 8, "TELEMETRY_BACKPRESSURE");
|
||||
ensure!(
|
||||
matches!(
|
||||
envelope.payload,
|
||||
Some(rmm_protocol::Payload::InventorySnapshot(_))
|
||||
),
|
||||
"PASSIVE_INVENTORY_ONLY"
|
||||
);
|
||||
let bytes = envelope.encode_to_vec();
|
||||
ensure!(bytes.len() <= 512 * 1024, "TELEMETRY_LIMIT");
|
||||
self.db.execute(
|
||||
"INSERT INTO events(id,payload) VALUES(?1,?2)",
|
||||
params![envelope.message_id, bytes],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn events(&self) -> Result<Vec<Envelope>> {
|
||||
let mut q = self
|
||||
.db
|
||||
.prepare("SELECT payload FROM events ORDER BY rowid")?;
|
||||
q.query_map([], |r| r.get::<_, Vec<u8>>(0))?
|
||||
.map(|v| Ok(Envelope::decode(v?.as_slice())?))
|
||||
.collect()
|
||||
}
|
||||
pub fn count(&self) -> Result<u64> {
|
||||
Ok(self
|
||||
.db
|
||||
.query_row("SELECT count(*) FROM events", [], |r| r.get(0))?)
|
||||
}
|
||||
pub fn ack(&self, message_id: &str) -> Result<()> {
|
||||
// Unknown IDs have no effect. An HTTP status never calls this function.
|
||||
self.db
|
||||
.execute("DELETE FROM events WHERE id=?1", [message_id])?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn pin_identity(&self, id: &str) -> Result<()> {
|
||||
self.db
|
||||
.execute_batch("CREATE TABLE IF NOT EXISTS identity(agent TEXT PRIMARY KEY)")?;
|
||||
let old: Option<String> = self
|
||||
.db
|
||||
.query_row("SELECT agent FROM identity", [], |r| r.get(0))
|
||||
.optional()?;
|
||||
if let Some(old) = old {
|
||||
ensure!(old == id, "JOURNAL_IDENTITY_MISMATCH");
|
||||
} else {
|
||||
self.db.execute("INSERT INTO identity VALUES(?1)", [id])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn durable_reopen_ack_identity_and_single_process() {
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("rmm-windows-journal-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
let mut j = Journal::open(&directory).unwrap();
|
||||
assert!(Journal::open(&directory).is_err());
|
||||
j.pin_identity("a").unwrap();
|
||||
assert!(j.pin_identity("b").is_err());
|
||||
let first = j.next_sequence().unwrap();
|
||||
let e = Envelope {
|
||||
message_id: uuid::Uuid::new_v4().to_string(),
|
||||
sequence: first,
|
||||
payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())),
|
||||
..Default::default()
|
||||
};
|
||||
j.save(&e).unwrap();
|
||||
drop(j);
|
||||
let mut j = Journal::open(&directory).unwrap();
|
||||
assert!(j.next_sequence().unwrap() > first);
|
||||
assert_eq!(j.events().unwrap()[0].message_id, e.message_id);
|
||||
j.ack("unrelated").unwrap();
|
||||
assert_eq!(j.count().unwrap(), 1);
|
||||
j.ack(&e.message_id).unwrap();
|
||||
assert_eq!(j.count().unwrap(), 0);
|
||||
let heartbeat = Envelope {
|
||||
payload: Some(rmm_protocol::Payload::Heartbeat(Default::default())),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(j.save(&heartbeat).is_err());
|
||||
drop(j);
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! First Windows slice: passive observations and durable telemetry only.
|
||||
//! No executor, startgrant consumer or privileged helper is advertised.
|
||||
pub mod journal;
|
||||
#[cfg(windows)]
|
||||
pub mod native;
|
||||
#[cfg(windows)]
|
||||
pub mod service;
|
||||
|
||||
pub const SERVICE_NAME: &str = "RmmDiscoveryWindows";
|
||||
pub const CAPABILITIES: &[&str] = &["windows.base/1", "heartbeat/1"];
|
||||
@@ -0,0 +1,32 @@
|
||||
#[cfg(windows)]
|
||||
#[path = "../../agent/src/https_channel.rs"]
|
||||
mod https_channel;
|
||||
#[cfg(windows)]
|
||||
mod runtime;
|
||||
#[cfg(windows)]
|
||||
#[path = "../../agent/src/transport.rs"]
|
||||
mod transport;
|
||||
#[cfg(windows)]
|
||||
#[path = "../../agent/src/wire_channel.rs"]
|
||||
mod wire_channel;
|
||||
#[cfg(windows)]
|
||||
mod certificate_rotation {
|
||||
// Shared transport input only. Windows certificate rotation is not yet a
|
||||
// capability: this first slice refuses expired TLS identities normally.
|
||||
pub struct DeviceIdentity {
|
||||
pub certificate_pem: Vec<u8>,
|
||||
pub private_key_pem: Vec<u8>,
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn main() {
|
||||
if runtime::main().is_err() {
|
||||
eprintln!("Windows passive agent stopped: INITIALIZATION_OR_TRANSPORT_FAILURE");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
fn main() {
|
||||
eprintln!("This binary requires native Windows.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Read-only Windows APIs. Boot identity comes from Win32_OperatingSystem's
|
||||
//! LastBootUpTime, never from the lifetime of this agent process.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::Utc;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
self, ACCESS_ALLOWED_ACE, ACL,
|
||||
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
},
|
||||
Storage::FileSystem::{FILE_ATTRIBUTE_REPARSE_POINT, GetDiskFreeSpaceExW},
|
||||
System::{Registry::*, SystemInformation::*},
|
||||
};
|
||||
pub fn wide(value: impl AsRef<std::ffi::OsStr>) -> Vec<u16> {
|
||||
value.as_ref().encode_wide().chain(Some(0)).collect()
|
||||
}
|
||||
fn sid_string(sid: *mut c_void) -> Result<String> {
|
||||
let mut text = ptr::null_mut();
|
||||
// SAFETY: SID was returned by the Windows security API; API allocates text.
|
||||
ensure!(
|
||||
unsafe { ConvertSidToStringSidW(sid, &mut text) } != 0,
|
||||
"SID_CONVERSION"
|
||||
);
|
||||
let mut len = 0;
|
||||
unsafe {
|
||||
while *text.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
}
|
||||
let result = String::from_utf16(unsafe { std::slice::from_raw_parts(text, len) })?;
|
||||
unsafe {
|
||||
LocalFree(text.cast());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
pub fn service_sid() -> Result<String> {
|
||||
let account = wide(format!("NT SERVICE\\{}", crate::SERVICE_NAME));
|
||||
let mut sid_len = 0;
|
||||
let mut domain_len = 0;
|
||||
let mut use_type = 0;
|
||||
unsafe {
|
||||
Security::LookupAccountNameW(
|
||||
ptr::null(),
|
||||
account.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
&mut sid_len,
|
||||
ptr::null_mut(),
|
||||
&mut domain_len,
|
||||
&mut use_type,
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
sid_len > 0 && sid_len <= 256 && domain_len <= 256,
|
||||
"SERVICE_SID_REQUIRED"
|
||||
);
|
||||
let mut sid = vec![0u8; sid_len as usize];
|
||||
let mut domain = vec![0u16; domain_len as usize];
|
||||
ensure!(
|
||||
unsafe {
|
||||
Security::LookupAccountNameW(
|
||||
ptr::null(),
|
||||
account.as_ptr(),
|
||||
sid.as_mut_ptr().cast(),
|
||||
&mut sid_len,
|
||||
domain.as_mut_ptr(),
|
||||
&mut domain_len,
|
||||
&mut use_type,
|
||||
)
|
||||
} != 0,
|
||||
"SERVICE_SID_LOOKUP"
|
||||
);
|
||||
sid_string(sid.as_mut_ptr().cast())
|
||||
}
|
||||
pub fn private_path(path: &Path, directory: bool) -> Result<()> {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& metadata.is_dir() == directory,
|
||||
"PRIVATE_PATH_TYPE"
|
||||
);
|
||||
let allowed = [
|
||||
"S-1-5-18".to_owned(),
|
||||
"S-1-5-32-544".to_owned(),
|
||||
service_sid()?,
|
||||
];
|
||||
let name = wide(path);
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut dacl: *mut ACL = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
// SAFETY: API writes pointers into one allocated descriptor, released below.
|
||||
let status = unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
name.as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&mut owner,
|
||||
ptr::null_mut(),
|
||||
&mut dacl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "PRIVATE_PATH_SECURITY");
|
||||
let result = (|| {
|
||||
ensure!(
|
||||
!owner.is_null() && !dacl.is_null(),
|
||||
"PRIVATE_PATH_NULL_DACL"
|
||||
);
|
||||
let owner = sid_string(owner)?;
|
||||
ensure!(
|
||||
allowed.contains(&owner) || (!directory && owner == "S-1-5-19"),
|
||||
"PRIVATE_PATH_OWNER"
|
||||
);
|
||||
ensure!(unsafe { (*dacl).AceCount } > 0, "PRIVATE_PATH_EMPTY_DACL");
|
||||
for n in 0..unsafe { (*dacl).AceCount } {
|
||||
let mut ace = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { Security::GetAce(dacl, u32::from(n), &mut ace) } != 0,
|
||||
"PRIVATE_PATH_ACE"
|
||||
);
|
||||
let ace = unsafe { &*ace.cast::<ACCESS_ALLOWED_ACE>() };
|
||||
ensure!(
|
||||
ace.Header.AceType == 0
|
||||
&& usize::from(ace.Header.AceSize) >= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||
"PRIVATE_PATH_ACE_TYPE"
|
||||
);
|
||||
let sid = ptr::addr_of!(ace.SidStart).cast_mut().cast();
|
||||
ensure!(
|
||||
allowed.contains(&sid_string(sid)?),
|
||||
"PRIVATE_PATH_BROAD_ACL"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
result
|
||||
}
|
||||
fn registry_string(name: &str) -> Result<String> {
|
||||
let key = wide("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
|
||||
let name = wide(name);
|
||||
let mut bytes = vec![0u16; 2048];
|
||||
let mut size = (bytes.len() * 2) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
RegGetValueW(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
key.as_ptr(),
|
||||
name.as_ptr(),
|
||||
RRF_RT_REG_SZ,
|
||||
ptr::null_mut(),
|
||||
bytes.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
} == 0,
|
||||
"OS_REGISTRY"
|
||||
);
|
||||
ensure!(
|
||||
size >= 2 && size as usize <= bytes.len() * 2,
|
||||
"OS_REGISTRY_SIZE"
|
||||
);
|
||||
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
|
||||
}
|
||||
pub fn snapshot() -> Result<Value> {
|
||||
let started = Utc::now();
|
||||
let mut hostname = vec![0u16; 256];
|
||||
let mut len = hostname.len() as u32;
|
||||
ensure!(
|
||||
unsafe { GetComputerNameExW(ComputerNameDnsHostname, hostname.as_mut_ptr(), &mut len) }
|
||||
!= 0,
|
||||
"HOSTNAME_QUERY"
|
||||
);
|
||||
let hostname = String::from_utf16(&hostname[..len as usize])?;
|
||||
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
|
||||
let mut available = 0;
|
||||
let mut total = 0;
|
||||
let mut free = 0;
|
||||
ensure!(
|
||||
unsafe { GetDiskFreeSpaceExW(volume.as_ptr(), &mut available, &mut total, &mut free) } != 0,
|
||||
"VOLUME_QUERY"
|
||||
);
|
||||
ensure!(total > 0 && available <= total, "VOLUME_VALUES");
|
||||
let product = registry_string("ProductName")?;
|
||||
let display = registry_string("DisplayVersion")?;
|
||||
let build = registry_string("CurrentBuildNumber")?;
|
||||
let os = format!("{product}; DisplayVersion={display}; Build={build}");
|
||||
let completed = Utc::now();
|
||||
Ok(
|
||||
json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
|
||||
"collection_started_at":started,"collection_completed_at":completed,
|
||||
"observations":[
|
||||
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
|
||||
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
|
||||
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
|
||||
]}),
|
||||
)
|
||||
}
|
||||
pub async fn boot_id() -> Result<String> {
|
||||
// Fixed passive query only. Never interpolates a job or caller-supplied code.
|
||||
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
|
||||
let executable = Path::new(&std::env::var("SystemRoot")?)
|
||||
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
|
||||
let mut command = tokio::process::Command::new(executable);
|
||||
command.args(["-NoLogo","-NoProfile","-NonInteractive","-Command","$ErrorActionPreference='Stop'; (Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture)"]);
|
||||
command.kill_on_drop(true);
|
||||
let output = tokio::time::timeout(Duration::from_secs(15), command.output()).await??;
|
||||
ensure!(
|
||||
output.status.success() && output.stdout.len() <= 128 && output.stderr.is_empty(),
|
||||
"BOOT_TIME_QUERY"
|
||||
);
|
||||
let text = std::str::from_utf8(&output.stdout)?.trim();
|
||||
ensure!(
|
||||
(17..=19).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_digit()),
|
||||
"BOOT_TIME_FORMAT"
|
||||
);
|
||||
let mut bytes: [u8; 16] = Sha256::digest(format!("rmm.windows.boot.cim.ticks.v1:{text}"))
|
||||
.as_slice()[..16]
|
||||
.try_into()?;
|
||||
bytes[6] = (bytes[6] & 15) | 0x80;
|
||||
bytes[8] = (bytes[8] & 63) | 0x80;
|
||||
Ok(uuid::Uuid::from_bytes(bytes).to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn native_inventory_has_real_windows_sources_and_no_fake_inodes() {
|
||||
let v = super::snapshot().unwrap();
|
||||
assert!(v["root_total_bytes"].as_u64().unwrap() > 0);
|
||||
assert!(v["root_available_inodes"].is_null());
|
||||
assert!(!v["hostname"].as_str().unwrap().is_empty());
|
||||
assert!(
|
||||
v["observations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|o| o["scope"].as_str().unwrap().starts_with("windows."))
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn boot_identity_survives_independent_native_queries() {
|
||||
assert_eq!(
|
||||
super::boot_id().await.unwrap(),
|
||||
super::boot_id().await.unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Native SCM lifecycle. This service has no privileged action endpoint.
|
||||
use anyhow::{Result, ensure};
|
||||
use std::{
|
||||
ptr,
|
||||
sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
use windows_sys::Win32::System::Services::*;
|
||||
static STOP: AtomicBool = AtomicBool::new(false);
|
||||
static HANDLE: AtomicUsize = AtomicUsize::new(0);
|
||||
type Runner = fn(&'static AtomicBool) -> Result<()>;
|
||||
static RUN: OnceLock<Runner> = OnceLock::new();
|
||||
fn status(state: u32, exit: u32) {
|
||||
let handle = HANDLE.load(Ordering::SeqCst) as SERVICE_STATUS_HANDLE;
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
let value = SERVICE_STATUS {
|
||||
dwServiceType: SERVICE_WIN32_OWN_PROCESS,
|
||||
dwCurrentState: state,
|
||||
dwControlsAccepted: if state == SERVICE_RUNNING {
|
||||
SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN
|
||||
} else {
|
||||
0
|
||||
},
|
||||
dwWin32ExitCode: exit,
|
||||
dwServiceSpecificExitCode: 0,
|
||||
dwCheckPoint: 0,
|
||||
dwWaitHint: if state == SERVICE_STOP_PENDING {
|
||||
15000
|
||||
} else {
|
||||
0
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
SetServiceStatus(handle, &value);
|
||||
}
|
||||
}
|
||||
unsafe extern "system" fn control(
|
||||
code: u32,
|
||||
_event: u32,
|
||||
_data: *mut std::ffi::c_void,
|
||||
_context: *mut std::ffi::c_void,
|
||||
) -> u32 {
|
||||
if code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN {
|
||||
STOP.store(true, Ordering::SeqCst);
|
||||
status(SERVICE_STOP_PENDING, 0);
|
||||
}
|
||||
0
|
||||
}
|
||||
unsafe extern "system" fn service_main(_count: u32, _args: *mut *mut u16) {
|
||||
let name = crate::native::wide(crate::SERVICE_NAME);
|
||||
let handle =
|
||||
unsafe { RegisterServiceCtrlHandlerExW(name.as_ptr(), Some(control), ptr::null_mut()) };
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
HANDLE.store(handle as usize, Ordering::SeqCst);
|
||||
status(SERVICE_RUNNING, 0);
|
||||
let result = RUN.get().expect("SCM runner initialized")(&STOP);
|
||||
// Error details never enter the Windows event log: paths may contain secrets.
|
||||
status(SERVICE_STOPPED, if result.is_ok() { 0 } else { 1066 });
|
||||
}
|
||||
pub fn dispatch(run: Runner) -> Result<()> {
|
||||
ensure!(RUN.set(run).is_ok(), "SCM_ALREADY_INITIALIZED");
|
||||
let mut name = crate::native::wide(crate::SERVICE_NAME);
|
||||
let table = [
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: name.as_mut_ptr(),
|
||||
lpServiceProc: Some(service_main),
|
||||
},
|
||||
SERVICE_TABLE_ENTRYW {
|
||||
lpServiceName: ptr::null_mut(),
|
||||
lpServiceProc: None,
|
||||
},
|
||||
];
|
||||
ensure!(
|
||||
unsafe { StartServiceCtrlDispatcherW(table.as_ptr()) } != 0,
|
||||
"SCM_DISPATCH_FAILED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user