779 lines
28 KiB
Rust
779 lines
28 KiB
Rust
//! Fixed, authorized Event Log subprocess. A command-line mode is not a live
|
|
//! query API: the child authenticates its real SCM parent, original signed
|
|
//! request, protected public trust, and an already committed consumption/start.
|
|
//! Request/grant bytes remain in a private, create-once job file, never argv.
|
|
use crate::{event_log, native};
|
|
use anyhow::{Context, Result, ensure};
|
|
use chrono::{DateTime, Utc};
|
|
use rmm_agent_core::auth::{Binding, Outcome, Request};
|
|
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
fs::{File, OpenOptions},
|
|
io::{Read, Write},
|
|
mem::{size_of, size_of_val, zeroed},
|
|
os::windows::{
|
|
fs::OpenOptionsExt,
|
|
io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
|
},
|
|
path::{Path, PathBuf},
|
|
ptr,
|
|
sync::atomic::AtomicBool,
|
|
time::Duration,
|
|
};
|
|
use uuid::Uuid;
|
|
use windows_sys::Win32::{
|
|
Foundation::*,
|
|
Security::{self, *},
|
|
Storage::FileSystem::*,
|
|
System::{Diagnostics::ToolHelp::*, Services::*, Threading::*},
|
|
};
|
|
|
|
pub const MODE: &str = "--eventlog-worker";
|
|
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
|
|
const TICKET_LIMIT: u64 = 128 * 1024;
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct FileId {
|
|
volume: u64,
|
|
id: [u8; 16],
|
|
}
|
|
fn file_id(handle: HANDLE) -> Result<FileId> {
|
|
let mut info: FILE_ID_INFO = unsafe { zeroed() };
|
|
ensure!(
|
|
unsafe {
|
|
GetFileInformationByHandleEx(
|
|
handle,
|
|
FileIdInfo,
|
|
(&mut info as *mut FILE_ID_INFO).cast(),
|
|
size_of::<FILE_ID_INFO>() as u32,
|
|
)
|
|
} != 0,
|
|
"EVENT_LOG_FILE_ID"
|
|
);
|
|
Ok(FileId {
|
|
volume: info.VolumeSerialNumber,
|
|
id: info.FileId.Identifier,
|
|
})
|
|
}
|
|
fn owned(handle: HANDLE) -> Result<OwnedHandle> {
|
|
ensure!(
|
|
!handle.is_null() && handle != INVALID_HANDLE_VALUE,
|
|
"EVENT_LOG_HANDLE"
|
|
);
|
|
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
|
}
|
|
fn birth(handle: HANDLE) -> Result<u64> {
|
|
let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) };
|
|
ensure!(
|
|
unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0,
|
|
"EVENT_LOG_PROCESS_TIME"
|
|
);
|
|
Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime))
|
|
}
|
|
fn text(value: *const u16) -> Result<String> {
|
|
ensure!(!value.is_null(), "EVENT_LOG_NATIVE_STRING");
|
|
let mut length = 0;
|
|
while length < 32768 && unsafe { *value.add(length) } != 0 {
|
|
length += 1;
|
|
}
|
|
ensure!(length < 32768, "EVENT_LOG_NATIVE_STRING_SIZE");
|
|
Ok(String::from_utf16(unsafe {
|
|
std::slice::from_raw_parts(value, length)
|
|
})?)
|
|
}
|
|
fn process_image(handle: HANDLE) -> Result<PathBuf> {
|
|
let mut buffer = vec![0u16; 32768];
|
|
let mut len = buffer.len() as u32;
|
|
ensure!(
|
|
unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut len) } != 0,
|
|
"EVENT_LOG_PARENT_IMAGE"
|
|
);
|
|
Ok(String::from_utf16(&buffer[..len as usize])?.into())
|
|
}
|
|
struct Service(SC_HANDLE);
|
|
impl Drop for Service {
|
|
fn drop(&mut self) {
|
|
unsafe {
|
|
CloseServiceHandle(self.0);
|
|
}
|
|
}
|
|
}
|
|
fn agent_pid(image: &Path) -> Result<u32> {
|
|
let manager = Service(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
|
ensure!(!manager.0.is_null(), "EVENT_LOG_SCM");
|
|
let service = Service(unsafe {
|
|
OpenServiceW(
|
|
manager.0,
|
|
native::wide(crate::SERVICE_NAME).as_ptr(),
|
|
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS,
|
|
)
|
|
});
|
|
ensure!(!service.0.is_null(), "EVENT_LOG_AGENT_SERVICE");
|
|
let mut bytes = 0;
|
|
unsafe {
|
|
QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut bytes);
|
|
}
|
|
ensure!((1..=32768).contains(&bytes), "EVENT_LOG_AGENT_CONFIG_SIZE");
|
|
let mut storage = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
|
ensure!(
|
|
unsafe { QueryServiceConfigW(service.0, storage.as_mut_ptr().cast(), bytes, &mut bytes) }
|
|
!= 0,
|
|
"EVENT_LOG_AGENT_CONFIG"
|
|
);
|
|
let config = unsafe { &*storage.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
|
ensure!(
|
|
config.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
|
&& text(config.lpBinaryPathName)?
|
|
== format!("\"{}\" --service --config \"{CONFIG}\"", image.display())
|
|
&& text(config.lpServiceStartName)?.eq_ignore_ascii_case(r"NT AUTHORITY\LocalService"),
|
|
"EVENT_LOG_AGENT_CONFIG_BINDING"
|
|
);
|
|
let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() };
|
|
ensure!(
|
|
unsafe {
|
|
QueryServiceStatusEx(
|
|
service.0,
|
|
SC_STATUS_PROCESS_INFO,
|
|
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
|
|
size_of::<SERVICE_STATUS_PROCESS>() as u32,
|
|
&mut bytes,
|
|
)
|
|
} != 0
|
|
&& status.dwCurrentState == SERVICE_RUNNING
|
|
&& status.dwProcessId > 0,
|
|
"EVENT_LOG_AGENT_NOT_RUNNING"
|
|
);
|
|
Ok(status.dwProcessId)
|
|
}
|
|
fn token_info(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<usize>> {
|
|
let mut bytes = 0;
|
|
unsafe {
|
|
GetTokenInformation(token, class, ptr::null_mut(), 0, &mut bytes);
|
|
}
|
|
ensure!((1..=65536).contains(&bytes), "EVENT_LOG_TOKEN_SIZE");
|
|
let mut data = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
|
ensure!(
|
|
unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), bytes, &mut bytes) }
|
|
!= 0,
|
|
"EVENT_LOG_TOKEN"
|
|
);
|
|
Ok(data)
|
|
}
|
|
fn service_token(process: HANDLE) -> Result<()> {
|
|
let mut token = ptr::null_mut();
|
|
ensure!(
|
|
unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } != 0,
|
|
"EVENT_LOG_TOKEN_OPEN"
|
|
);
|
|
let token = owned(token)?;
|
|
let user = token_info(token.as_raw_handle(), TokenUser)?;
|
|
let mut service_sid = ptr::null_mut();
|
|
ensure!(
|
|
unsafe {
|
|
Security::Authorization::ConvertStringSidToSidW(
|
|
native::wide(native::service_sid()?).as_ptr(),
|
|
&mut service_sid,
|
|
)
|
|
} != 0,
|
|
"EVENT_LOG_SERVICE_SID"
|
|
);
|
|
struct Sid(PSID);
|
|
impl Drop for Sid {
|
|
fn drop(&mut self) {
|
|
unsafe {
|
|
LocalFree(self.0);
|
|
}
|
|
}
|
|
}
|
|
let service_sid = Sid(service_sid);
|
|
let mut ls = [0usize; 16];
|
|
let mut size = size_of_val(&ls) as u32;
|
|
ensure!(
|
|
unsafe {
|
|
CreateWellKnownSid(
|
|
WinLocalServiceSid,
|
|
ptr::null_mut(),
|
|
ls.as_mut_ptr().cast(),
|
|
&mut size,
|
|
)
|
|
} != 0
|
|
&& unsafe {
|
|
EqualSid(
|
|
(*user.as_ptr().cast::<TOKEN_USER>()).User.Sid,
|
|
ls.as_ptr().cast_mut().cast(),
|
|
)
|
|
} != 0,
|
|
"EVENT_LOG_LOCAL_SERVICE_REQUIRED"
|
|
);
|
|
let groups = token_info(token.as_raw_handle(), TokenGroups)?;
|
|
let g = unsafe { &*groups.as_ptr().cast::<TOKEN_GROUPS>() };
|
|
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
|
|
ensure!(
|
|
g.GroupCount <= 1024
|
|
&& offset + g.GroupCount as usize * size_of::<SID_AND_ATTRIBUTES>()
|
|
<= groups.len() * size_of::<usize>(),
|
|
"EVENT_LOG_TOKEN_GROUPS_SIZE"
|
|
);
|
|
let entries = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), g.GroupCount as usize) };
|
|
let mut admins = [0usize; 16];
|
|
let mut admin_bytes = size_of_val(&admins) as u32;
|
|
ensure!(
|
|
unsafe {
|
|
CreateWellKnownSid(
|
|
WinBuiltinAdministratorsSid,
|
|
ptr::null_mut(),
|
|
admins.as_mut_ptr().cast(),
|
|
&mut admin_bytes,
|
|
)
|
|
} != 0,
|
|
"EVENT_LOG_ADMIN_SID"
|
|
);
|
|
ensure!(
|
|
!entries
|
|
.iter()
|
|
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
|
&& unsafe { EqualSid(entry.Sid, admins.as_ptr().cast_mut().cast()) } != 0),
|
|
"EVENT_LOG_ADMINISTRATOR_FORBIDDEN"
|
|
);
|
|
// TOKEN_GROUPS enabled/deny-only bits from winnt.h, as in the pipe peer proof.
|
|
ensure!(
|
|
entries
|
|
.iter()
|
|
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
|
&& entry.Attributes & 0x0000_0010 == 0
|
|
&& unsafe { EqualSid(entry.Sid, service_sid.0) } != 0),
|
|
"EVENT_LOG_AGENT_SID_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn parent_pid() -> Result<u32> {
|
|
let snapshot = owned(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })?;
|
|
let mut entry: PROCESSENTRY32W = unsafe { zeroed() };
|
|
entry.dwSize = size_of::<PROCESSENTRY32W>() as u32;
|
|
let mut ok = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };
|
|
while ok != 0 {
|
|
if entry.th32ProcessID == std::process::id() {
|
|
return Ok(entry.th32ParentProcessID);
|
|
}
|
|
ok = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };
|
|
}
|
|
anyhow::bail!("EVENT_LOG_PARENT_UNVERIFIED")
|
|
}
|
|
fn open_private(path: &Path, share_write: bool) -> Result<File> {
|
|
ensure!(
|
|
path.is_absolute() && !path.to_string_lossy().starts_with(r"\\"),
|
|
"EVENT_LOG_LOCAL_PATH"
|
|
);
|
|
for parent in path.ancestors().skip(1) {
|
|
use std::os::windows::fs::MetadataExt;
|
|
ensure!(
|
|
std::fs::symlink_metadata(parent)?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT
|
|
== 0,
|
|
"EVENT_LOG_REPARSE_ANCESTOR"
|
|
);
|
|
}
|
|
native::private_path(path, false)?;
|
|
let file = OpenOptions::new()
|
|
.read(true)
|
|
.share_mode(FILE_SHARE_READ | if share_write { FILE_SHARE_WRITE } else { 0 })
|
|
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
|
.open(path)?;
|
|
use std::os::windows::fs::MetadataExt;
|
|
ensure!(
|
|
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
|
|
"EVENT_LOG_REPARSE_FILE"
|
|
);
|
|
Ok(file)
|
|
}
|
|
fn read(file: &mut File, limit: u64) -> Result<Vec<u8>> {
|
|
ensure!(
|
|
file.metadata()?.len() <= limit,
|
|
"EVENT_LOG_PRIVATE_FILE_LIMIT"
|
|
);
|
|
let mut value = Vec::new();
|
|
file.take(limit + 1).read_to_end(&mut value)?;
|
|
ensure!(value.len() as u64 <= limit, "EVENT_LOG_PRIVATE_FILE_LIMIT");
|
|
Ok(value)
|
|
}
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Ticket {
|
|
request: Request,
|
|
parent_pid: u32,
|
|
parent_birth: u64,
|
|
boot: Uuid,
|
|
ledger: FileId,
|
|
}
|
|
#[derive(Deserialize)]
|
|
struct WorkerConfig {
|
|
state_directory: PathBuf,
|
|
job_binding_file: PathBuf,
|
|
enable_jobs: bool,
|
|
}
|
|
fn ticket_name(permit: &ExecutionPermitPayload) -> String {
|
|
format!("eventlog-{}.json", hash(permit.grant_id.as_bytes()))
|
|
}
|
|
/// Prepared data only. No query, worker or Evt handle exists before run.
|
|
pub struct Prepared {
|
|
path: PathBuf,
|
|
_file: File,
|
|
ticket_hash: String,
|
|
job_bytes: Vec<u8>,
|
|
}
|
|
impl Prepared {
|
|
pub fn prepare(
|
|
job: &JobPayload,
|
|
directory: &Path,
|
|
request: &Request,
|
|
grant: Uuid,
|
|
boot: Uuid,
|
|
) -> Result<Self> {
|
|
event_log::for_job(job)?;
|
|
native::require_local_service()?;
|
|
service_token(unsafe { GetCurrentProcess() })?;
|
|
let image = std::env::current_exe()?;
|
|
ensure!(
|
|
agent_pid(&image)? == std::process::id(),
|
|
"EVENT_LOG_REAL_AGENT_REQUIRED"
|
|
);
|
|
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
|
ensure!(
|
|
permit.grant_id == grant && !boot.is_nil(),
|
|
"EVENT_LOG_GRANT_BINDING"
|
|
);
|
|
native::private_path(directory, true)?;
|
|
let ledger = open_private(
|
|
&directory
|
|
.parent()
|
|
.context("EVENT_LOG_STATE_DIRECTORY")?
|
|
.join("consumption.sqlite"),
|
|
true,
|
|
)?;
|
|
let ticket = Ticket {
|
|
request: request.clone(),
|
|
parent_pid: std::process::id(),
|
|
parent_birth: birth(unsafe { GetCurrentProcess() })?,
|
|
boot,
|
|
ledger: file_id(ledger.as_raw_handle())?,
|
|
};
|
|
let bytes = serde_json::to_vec(&ticket)?;
|
|
ensure!(bytes.len() as u64 <= TICKET_LIMIT, "EVENT_LOG_TICKET_LIMIT");
|
|
let path = directory.join(ticket_name(&permit));
|
|
let mut writer = OpenOptions::new()
|
|
.create_new(true)
|
|
.write(true)
|
|
.share_mode(0)
|
|
.open(&path)?;
|
|
writer.write_all(&bytes)?;
|
|
writer.sync_all()?;
|
|
drop(writer);
|
|
let mut file = open_private(&path, false)?;
|
|
ensure!(
|
|
read(&mut file, TICKET_LIMIT)? == bytes,
|
|
"EVENT_LOG_TICKET_CHANGED"
|
|
);
|
|
Ok(Self {
|
|
path,
|
|
_file: file,
|
|
ticket_hash: hash(&bytes),
|
|
job_bytes: request.job_bytes.clone(),
|
|
})
|
|
}
|
|
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
|
event_log::for_job(job)?;
|
|
ensure!(
|
|
serde_json::from_slice::<serde_json::Value>(&self.job_bytes)?
|
|
== serde_json::to_value(job)?,
|
|
"EVENT_LOG_JOB_CHANGED"
|
|
);
|
|
let mut file = open_private(&self.path, false)?;
|
|
ensure!(
|
|
hash(&read(&mut file, TICKET_LIMIT)?) == self.ticket_hash,
|
|
"EVENT_LOG_TICKET_CHANGED"
|
|
);
|
|
let output = crate::process::run(
|
|
&std::env::current_exe()?,
|
|
&[MODE.into(), self.path.as_os_str().into()],
|
|
self.path.parent().context("EVENT_LOG_JOB_DIRECTORY")?,
|
|
job.max_runtime_seconds,
|
|
job.max_output_bytes as usize,
|
|
cancel,
|
|
)?;
|
|
if output.interrupted {
|
|
return Ok(Outcome::unknown(if output.cancelled {
|
|
"EVENT_LOG_CANCELLED_RESULT_UNKNOWN"
|
|
} else {
|
|
"EVENT_LOG_TIMEOUT_RESULT_UNKNOWN"
|
|
}));
|
|
}
|
|
ensure!(
|
|
output.exit_code == Some(0) && !output.truncated && output.stderr.is_empty(),
|
|
"EVENT_LOG_WORKER_RESULT_UNVERIFIED"
|
|
);
|
|
outcome(job, output.stdout)
|
|
}
|
|
}
|
|
|
|
fn consumed(
|
|
db: &rusqlite::Connection,
|
|
binding: &Binding,
|
|
ticket: &Ticket,
|
|
permit: &ExecutionPermitPayload,
|
|
) -> Result<()> {
|
|
let length: u64 = db.query_row("SELECT length(e.start) FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1", [permit.grant_id.to_string()], |r| r.get(0))?;
|
|
ensure!(length <= TICKET_LIMIT, "EVENT_LOG_START_SIZE");
|
|
type Row = (String, u64, String, String, bool, Vec<u8>, bool);
|
|
let row: Row = db.query_row("SELECT c.agent,c.generation,c.job,c.attempt,c.result IS NULL,e.start,e.outcome IS NULL FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
|
|
[permit.grant_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?)))?;
|
|
ensure!(
|
|
row.0 == binding.agent_id.to_string()
|
|
&& row.1 == binding.enrollment_generation
|
|
&& row.2 == permit.job_id.to_string()
|
|
&& row.3 == permit.attempt_id.to_string()
|
|
&& row.4
|
|
&& row.6,
|
|
"EVENT_LOG_CONSUMPTION_BINDING"
|
|
);
|
|
let start: serde_json::Value = serde_json::from_slice(&row.5)?;
|
|
ensure!(
|
|
start["previous_boot_id"] == ticket.boot.to_string()
|
|
&& serde_json::to_vec(&serde_json::from_value::<Request>(
|
|
start["request"].clone()
|
|
)?)? == serde_json::to_vec(&ticket.request)?,
|
|
"EVENT_LOG_ORIGINAL_START_BINDING"
|
|
);
|
|
let identity: String = db.query_row(
|
|
"SELECT identity FROM windows_binding WHERE length(identity)<=512",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
identity
|
|
== format!(
|
|
"{}:{}:{}:{}:{}",
|
|
binding.tenant_id,
|
|
binding.asset_id,
|
|
binding.agent_id,
|
|
binding.enrollment_generation,
|
|
binding.assignment_version
|
|
),
|
|
"EVENT_LOG_LEDGER_BINDING"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn validate_ticket_path(path: &Path, directory: &Path) -> Result<()> {
|
|
let name = path
|
|
.file_name()
|
|
.and_then(|s| s.to_str())
|
|
.context("EVENT_LOG_TICKET_NAME")?;
|
|
let hash_name = name
|
|
.strip_prefix("eventlog-")
|
|
.and_then(|s| s.strip_suffix(".json"))
|
|
.context("EVENT_LOG_TICKET_NAME")?;
|
|
ensure!(
|
|
path.parent() == Some(directory)
|
|
&& hash_name.len() == 64
|
|
&& hash_name
|
|
.bytes()
|
|
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
|
|
"EVENT_LOG_TICKET_PATH_BINDING"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
/// Internal mode admission. Failure emits only the main executable's fixed
|
|
/// initialization error; no request, query XML or private Win32 error is logged.
|
|
pub fn worker(path: &Path) -> Result<()> {
|
|
native::require_local_service()?;
|
|
service_token(unsafe { GetCurrentProcess() })?;
|
|
let image = std::env::current_exe()?;
|
|
let actual_parent = parent_pid()?;
|
|
ensure!(
|
|
agent_pid(&image)? == actual_parent,
|
|
"EVENT_LOG_REAL_PARENT_REQUIRED"
|
|
);
|
|
let parent = owned(unsafe {
|
|
OpenProcess(
|
|
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
|
|
0,
|
|
actual_parent,
|
|
)
|
|
})?;
|
|
let parent_birth = birth(parent.as_raw_handle())?;
|
|
ensure!(
|
|
process_image(parent.as_raw_handle())? == image
|
|
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
|
"EVENT_LOG_PARENT_INSTANCE"
|
|
);
|
|
service_token(parent.as_raw_handle())?;
|
|
crate::job_binding::check_admin_readonly(Path::new(CONFIG))?;
|
|
let mut config_file = open_private(Path::new(CONFIG), false)?;
|
|
let config: WorkerConfig = serde_json::from_slice(&read(&mut config_file, 32768)?)?;
|
|
ensure!(
|
|
config.enable_jobs && config.state_directory.is_absolute(),
|
|
"EVENT_LOG_JOBS_NOT_ENABLED"
|
|
);
|
|
let directory = config.state_directory.join("jobs");
|
|
native::private_path(&directory, true)?;
|
|
validate_ticket_path(path, &directory)?;
|
|
// Only the exact jobs leaf is read; PKI/keys and arbitrary private files
|
|
// cannot be passed to this mode, even by another LocalService process.
|
|
let mut ticket_file = open_private(path, false)?;
|
|
let ticket: Ticket = serde_json::from_slice(&read(&mut ticket_file, TICKET_LIMIT)?)?;
|
|
ensure!(
|
|
ticket.parent_pid == actual_parent && ticket.parent_birth == parent_birth,
|
|
"EVENT_LOG_PARENT_INSTANCE"
|
|
);
|
|
let binding = crate::job_binding::readonly_binding(&config.job_binding_file)?;
|
|
let clock = crate::clock::NativeClock::new();
|
|
let now = clock.now()?;
|
|
let (job, permit) = binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
|
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
|
let query = event_log::for_job(&job)?;
|
|
let expected = config
|
|
.state_directory
|
|
.join("jobs")
|
|
.join(ticket_name(&permit));
|
|
ensure!(path == expected, "EVENT_LOG_TICKET_PATH_BINDING");
|
|
let runtime = tokio::runtime::Runtime::new()?;
|
|
ensure!(
|
|
Uuid::parse_str(&runtime.block_on(native::boot_id())?)? == ticket.boot,
|
|
"EVENT_LOG_ORIGINAL_BOOT_REQUIRED"
|
|
);
|
|
let ledger_path = config.state_directory.join("consumption.sqlite");
|
|
let ledger_file = open_private(&ledger_path, true)?;
|
|
ensure!(
|
|
file_id(ledger_file.as_raw_handle())? == ticket.ledger,
|
|
"EVENT_LOG_LEDGER_FILE_CHANGED"
|
|
);
|
|
let db = rusqlite::Connection::open_with_flags(
|
|
&ledger_path,
|
|
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
|
)?;
|
|
db.busy_timeout(Duration::from_millis(100))?;
|
|
let mut sqlite_handle: HANDLE = ptr::null_mut();
|
|
ensure!(
|
|
unsafe {
|
|
rusqlite::ffi::sqlite3_file_control(
|
|
db.handle(),
|
|
c"main".as_ptr(),
|
|
rusqlite::ffi::SQLITE_FCNTL_WIN32_GET_HANDLE,
|
|
(&mut sqlite_handle as *mut HANDLE).cast(),
|
|
)
|
|
} == rusqlite::ffi::SQLITE_OK
|
|
&& file_id(sqlite_handle)? == ticket.ledger,
|
|
"EVENT_LOG_CONNECTED_LEDGER_FILE"
|
|
);
|
|
db.execute_batch("PRAGMA query_only=ON; BEGIN;")?;
|
|
consumed(&db, &binding, &ticket, &permit)?;
|
|
// Per-grant durable CAS prevents worker re-entry after a lost child reply.
|
|
let marker = path.with_extension("started");
|
|
let mut once = OpenOptions::new()
|
|
.create_new(true)
|
|
.write(true)
|
|
.share_mode(0)
|
|
.open(&marker)?;
|
|
once.write_all(b"event-log-dispatch-v1\n")?;
|
|
once.sync_all()?;
|
|
native::private_path(&marker, false)?;
|
|
// File I/O, CIM and child scheduling cannot extend the signed start window.
|
|
let now = clock.now()?;
|
|
binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
|
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
|
ensure!(
|
|
agent_pid(&image)? == actual_parent
|
|
&& birth(parent.as_raw_handle())? == ticket.parent_birth
|
|
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
|
"EVENT_LOG_PARENT_CHANGED"
|
|
);
|
|
consumed(&db, &binding, &ticket, &permit)?;
|
|
let report = event_log::query(&query, &AtomicBool::new(false))?;
|
|
let bytes = serde_json::to_vec(&report)?;
|
|
ensure!(
|
|
bytes.len() <= job.max_output_bytes as usize,
|
|
"EVENT_LOG_OUTPUT_LIMIT"
|
|
);
|
|
std::io::stdout().lock().write_all(&bytes)?;
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct WireReport {
|
|
channel: String,
|
|
provider: String,
|
|
start_utc: DateTime<Utc>,
|
|
end_utc: DateTime<Utc>,
|
|
quality: String,
|
|
completeness: String,
|
|
truncated: bool,
|
|
error_code: Option<String>,
|
|
win32_error: Option<u32>,
|
|
events: Vec<event_log::Event>,
|
|
bookmark_updated: bool,
|
|
deadline_enforcement: String,
|
|
}
|
|
fn outcome(job: &JobPayload, bytes: Vec<u8>) -> Result<Outcome> {
|
|
let q = event_log::for_job(job)?;
|
|
ensure!(
|
|
bytes.len() <= q.max_output_bytes as usize,
|
|
"EVENT_LOG_OUTPUT_LIMIT"
|
|
);
|
|
let report: WireReport = serde_json::from_slice(&bytes)?;
|
|
ensure!(
|
|
report.channel == q.channel
|
|
&& report.provider == q.provider
|
|
&& report.start_utc == q.start_utc
|
|
&& report.end_utc == q.end_utc
|
|
&& !report.bookmark_updated
|
|
&& report.events.len() <= q.max_events as usize
|
|
&& report.deadline_enforcement == "cooperative_between_win32_calls",
|
|
"EVENT_LOG_REPORT_BINDING"
|
|
);
|
|
let mut ids = std::collections::BTreeSet::new();
|
|
for event in &report.events {
|
|
ensure!(
|
|
event.channel == q.channel
|
|
&& event.provider == q.provider
|
|
&& event.record_id > 0
|
|
&& ids.insert(event.record_id)
|
|
&& event.created_utc >= q.start_utc
|
|
&& event.created_utc < q.end_utc
|
|
&& event.xml.len() <= 64 * 1024
|
|
&& !event.xml.contains('\0'),
|
|
"EVENT_LOG_EVENT_BINDING"
|
|
);
|
|
}
|
|
let complete =
|
|
report.completeness == "complete" && !report.truncated && report.error_code.is_none();
|
|
let partial = report.completeness == "partial"
|
|
&& report.truncated
|
|
&& matches!(
|
|
report.error_code.as_deref(),
|
|
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
|
|
);
|
|
let success =
|
|
report.quality == "valid" && report.win32_error.is_none() && (complete || partial);
|
|
let error =
|
|
report
|
|
.error_code
|
|
.as_deref()
|
|
.unwrap_or(if success { "" } else { "EVENT_LOG_INCOMPLETE" });
|
|
Ok(Outcome {
|
|
state: if success { "succeeded" } else { "failed" }.into(),
|
|
stdout: bytes,
|
|
stderr: vec![],
|
|
exit_code: None,
|
|
output_truncated: report.truncated,
|
|
reboot_required: false,
|
|
error_code: if success { String::new() } else { error.into() },
|
|
evidence: serde_json::json!({"postconditions_passed":success,
|
|
"source_id":rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE,
|
|
"channel":q.channel,"provider":q.provider,"start_utc":q.start_utc,"end_utc":q.end_utc,
|
|
"max_events":q.max_events,"max_output_bytes":q.max_output_bytes,
|
|
"quality":report.quality,"completeness":report.completeness,"truncated":report.truncated,
|
|
"error_code":report.error_code,"win32_error":report.win32_error,
|
|
"bookmark_updated":false,"execution_sid":"S-1-5-19","process_tree_bounded":true,
|
|
"cursor_status":"not_advanced_no_ack_contract","observed_at":Utc::now()}),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
fn job() -> JobPayload {
|
|
let id = Uuid::new_v4();
|
|
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
|
JobPayload {
|
|
schema_version: 1,
|
|
tenant_id: id,
|
|
asset_id: id,
|
|
agent_id: id,
|
|
enrollment_generation: 1,
|
|
assignment_version: 1,
|
|
job_id: id,
|
|
attempt_id: id,
|
|
action: rmm_domain::jobs::Action::QueryLogs {
|
|
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
|
since: now,
|
|
until: now + chrono::Duration::minutes(5),
|
|
max_lines: 2,
|
|
},
|
|
execution_identity: "agent_service".into(),
|
|
not_before: now,
|
|
start_before: now + chrono::Duration::seconds(60),
|
|
max_runtime_seconds: 10,
|
|
max_output_bytes: 4096,
|
|
}
|
|
}
|
|
#[test]
|
|
fn ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves() {
|
|
let directory = Path::new(r"C:\ProgramData\RustDiscovery\state\jobs");
|
|
let leaf = format!("eventlog-{}.json", "a".repeat(64));
|
|
assert!(validate_ticket_path(&directory.join(&leaf), directory).is_ok());
|
|
for path in [
|
|
PathBuf::from(r"C:\ProgramData\RustDiscovery\state\device-key.pem"),
|
|
directory.join("..\\jobs").join(&leaf),
|
|
directory.join(format!("eventlog-{}.json", "A".repeat(64))),
|
|
directory.join(format!("eventlog-{}.json", "a".repeat(63))),
|
|
directory.join(format!("eventlog-{}.json:stream", "a".repeat(64))),
|
|
directory.join("other.json"),
|
|
] {
|
|
assert!(
|
|
validate_ticket_path(&path, directory).is_err(),
|
|
"{}",
|
|
path.display()
|
|
);
|
|
}
|
|
}
|
|
#[test]
|
|
fn event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success() {
|
|
let job = job();
|
|
let q = event_log::for_job(&job).unwrap();
|
|
let mut report = serde_json::json!({"channel":q.channel,"provider":q.provider,
|
|
"start_utc":q.start_utc,"end_utc":q.end_utc,"quality":"valid",
|
|
"completeness":"complete","truncated":false,"error_code":null,"win32_error":null,
|
|
"events":[],"bookmark_updated":false,"deadline_enforcement":"cooperative_between_win32_calls"});
|
|
assert_eq!(
|
|
outcome(&job, serde_json::to_vec(&report).unwrap())
|
|
.unwrap()
|
|
.state,
|
|
"succeeded"
|
|
);
|
|
for code in [
|
|
"EVENT_LOG_TIME_LIMIT",
|
|
"EVENT_LOG_CANCELLED",
|
|
"EVENT_LOG_API_ERROR",
|
|
] {
|
|
let mut partial = report.clone();
|
|
partial["truncated"] = true.into();
|
|
partial["completeness"] = "unknown".into();
|
|
partial["error_code"] = code.into();
|
|
assert_eq!(
|
|
outcome(&job, serde_json::to_vec(&partial).unwrap())
|
|
.unwrap()
|
|
.state,
|
|
"failed"
|
|
);
|
|
}
|
|
report["truncated"] = true.into();
|
|
report["completeness"] = "partial".into();
|
|
report["error_code"] = "EVENT_LOG_BYTE_LIMIT".into();
|
|
let bounded = outcome(&job, serde_json::to_vec(&report).unwrap()).unwrap();
|
|
assert_eq!(bounded.state, "succeeded");
|
|
assert!(bounded.output_truncated);
|
|
report["quality"] = "permission_denied".into();
|
|
report["win32_error"] = 5.into();
|
|
assert_eq!(
|
|
outcome(&job, serde_json::to_vec(&report).unwrap())
|
|
.unwrap()
|
|
.state,
|
|
"failed"
|
|
);
|
|
report["provider"] = "another-provider".into();
|
|
assert!(outcome(&job, serde_json::to_vec(&report).unwrap()).is_err());
|
|
}
|
|
}
|