Integrate signed agent catalog, tenant enrollment and HTTPS installers
This commit is contained in:
@@ -0,0 +1,419 @@
|
||||
//! Stable updater channel, separate from the LocalService agent channel.
|
||||
//! Mutually pinned service identity is checked before decoding a bounded call.
|
||||
//! An Activate is never retried by the transport. A response is not readiness.
|
||||
use crate::helper_ipc::{self as ipc, PeerPin, PeerProof};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_agent_core::auth::Binding;
|
||||
use rmm_domain::{
|
||||
agent_update::{ParticipantIdentity, ParticipantRole},
|
||||
jobs::hash,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
mem::size_of,
|
||||
os::windows::io::{AsRawHandle, OwnedHandle},
|
||||
path::Path,
|
||||
ptr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::*,
|
||||
Storage::FileSystem::*,
|
||||
System::{Pipes::*, Threading::*},
|
||||
};
|
||||
|
||||
pub const SERVICE: &str = "RmmDiscoveryUpdater";
|
||||
pub const BINARY: &str = r"C:\Program Files\RustDiscovery\rmm-updater-windows.exe";
|
||||
pub const PIPE: &str = r"\\.\pipe\RustDiscovery-Updater-v1";
|
||||
const LIMIT: usize = 32768;
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Pin {
|
||||
pub schema_version: u32,
|
||||
pub binding: Binding,
|
||||
pub policy_sha256: String,
|
||||
pub helper: PeerPin,
|
||||
pub updater: PeerPin,
|
||||
}
|
||||
impl Pin {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1 && ipc::digest(&self.policy_sha256),
|
||||
"UPDATE_IPC_PIN"
|
||||
);
|
||||
self.helper.validate(true)?;
|
||||
ensure!(
|
||||
self.updater.service_name == SERVICE
|
||||
&& self.updater.service_sid == ipc::service_sid(SERVICE)?
|
||||
&& self.updater.user_sid == "S-1-5-18"
|
||||
&& self.updater.binary == Path::new(BINARY)
|
||||
&& ipc::digest(&self.updater.binary_sha256),
|
||||
"UPDATE_IPC_UPDATER_PIN"
|
||||
);
|
||||
ensure!(
|
||||
!self.binding.agent_id.is_nil()
|
||||
&& !self.binding.asset_id.is_nil()
|
||||
&& !self.binding.tenant_id.is_nil()
|
||||
&& self.binding.enrollment_generation > 0
|
||||
&& self.binding.assignment_version > 0,
|
||||
"UPDATE_IPC_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Request {
|
||||
Describe {},
|
||||
Activate {
|
||||
grant_id: Uuid,
|
||||
owner_nonce: Uuid,
|
||||
handoff_sha256: String,
|
||||
},
|
||||
Read {
|
||||
grant_id: Uuid,
|
||||
owner_nonce: Uuid,
|
||||
handoff_sha256: String,
|
||||
},
|
||||
Health {
|
||||
grant_id: Uuid,
|
||||
owner_nonce: Uuid,
|
||||
handoff_sha256: String,
|
||||
payload_base64url: String,
|
||||
signature_base64url: String,
|
||||
},
|
||||
}
|
||||
impl Request {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
match self {
|
||||
Self::Describe {} => {}
|
||||
Self::Activate {
|
||||
grant_id,
|
||||
owner_nonce,
|
||||
handoff_sha256,
|
||||
}
|
||||
| Self::Read {
|
||||
grant_id,
|
||||
owner_nonce,
|
||||
handoff_sha256,
|
||||
}
|
||||
| Self::Health {
|
||||
grant_id,
|
||||
owner_nonce,
|
||||
handoff_sha256,
|
||||
..
|
||||
} => {
|
||||
ensure!(
|
||||
!grant_id.is_nil() && !owner_nonce.is_nil() && ipc::digest(handoff_sha256),
|
||||
"UPDATE_IPC_ORIGINAL_BINDING"
|
||||
);
|
||||
if let Self::Health {
|
||||
payload_base64url,
|
||||
signature_base64url,
|
||||
..
|
||||
} = self
|
||||
{
|
||||
ensure!(
|
||||
!payload_base64url.is_empty()
|
||||
&& payload_base64url.len() <= 21846
|
||||
&& signature_base64url.len() == 86
|
||||
&& payload_base64url
|
||||
.bytes()
|
||||
.chain(signature_base64url.bytes())
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)),
|
||||
"UPDATE_IPC_HEALTH_LIMIT"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum State {
|
||||
Described,
|
||||
Inflight,
|
||||
OutcomePersisted,
|
||||
Unknown,
|
||||
NotConfigured,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Response {
|
||||
pub schema_version: u32,
|
||||
pub state: State,
|
||||
pub ready: bool,
|
||||
pub updater: ParticipantIdentity,
|
||||
pub head_sha256: Option<String>,
|
||||
}
|
||||
impl Response {
|
||||
fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1
|
||||
&& !self.ready
|
||||
&& self.updater.validate()
|
||||
&& self.updater.role == ParticipantRole::WindowsUpdater
|
||||
&& self.head_sha256.as_ref().is_none_or(|v| ipc::digest(v)),
|
||||
"UPDATE_IPC_RESPONSE"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Call {
|
||||
schema_version: u32,
|
||||
challenge: Uuid,
|
||||
binding_sha256: String,
|
||||
policy_sha256: String,
|
||||
request: Request,
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Reply {
|
||||
schema_version: u32,
|
||||
challenge: Uuid,
|
||||
binding_sha256: String,
|
||||
policy_sha256: String,
|
||||
response: Response,
|
||||
}
|
||||
/// The instance digest covers the pinned SCM command and held live process,
|
||||
/// including image file identity and service SID, rather than PID alone.
|
||||
pub fn participant(peer: &PeerProof, role: ParticipantRole) -> Result<ParticipantIdentity> {
|
||||
ensure!(
|
||||
matches!(
|
||||
role,
|
||||
ParticipantRole::WindowsHelper | ParticipantRole::WindowsUpdater
|
||||
),
|
||||
"UPDATE_IPC_PARTICIPANT_ROLE"
|
||||
);
|
||||
let p = peer.identity();
|
||||
let expected = if role == ParticipantRole::WindowsHelper {
|
||||
ipc::HELPER_SERVICE
|
||||
} else {
|
||||
SERVICE
|
||||
};
|
||||
ensure!(
|
||||
p.user_sid == "S-1-5-18" && p.service_sid == ipc::service_sid(expected)?,
|
||||
"UPDATE_IPC_PARTICIPANT_SID"
|
||||
);
|
||||
let value = ParticipantIdentity {
|
||||
role,
|
||||
pid: p.pid,
|
||||
birth: p.creation_ticks,
|
||||
image_sha256: p.image_sha256.clone(),
|
||||
security_principal: p.user_sid.clone(),
|
||||
service_instance_sha256: hash(&serde_json::to_vec(p)?),
|
||||
};
|
||||
ensure!(value.validate(), "UPDATE_IPC_PARTICIPANT");
|
||||
Ok(value)
|
||||
}
|
||||
pub fn observe(pin: &PeerPin, role: ParticipantRole) -> Result<(PeerProof, ParticipantIdentity)> {
|
||||
let mut proof = PeerProof::for_service(pin, ipc::service_status(pin)?)?;
|
||||
proof.check()?;
|
||||
let value = participant(&proof, role)?;
|
||||
Ok((proof, value))
|
||||
}
|
||||
/// Caller implements all original-ledger, retained-state, clock and one-pass
|
||||
/// checks. This transport has no default handler or automatic startup replay.
|
||||
pub trait Engine {
|
||||
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response>;
|
||||
}
|
||||
pub struct Server {
|
||||
pipe: OwnedHandle,
|
||||
pin: Pin,
|
||||
}
|
||||
impl Server {
|
||||
pub fn bind(pin: Pin) -> Result<Self> {
|
||||
pin.validate()?;
|
||||
ipc::require_self(&pin.updater)?;
|
||||
let descriptor = ipc::Descriptor::from(&format!(
|
||||
"O:SYG:SYD:P(D;;GA;;;NU)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{})(A;;0x{:08x};;;{})",
|
||||
pin.updater.service_sid,
|
||||
ipc::CLIENT_PIPE_RIGHTS,
|
||||
pin.helper.service_sid
|
||||
))?;
|
||||
let sa = SECURITY_ATTRIBUTES {
|
||||
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
|
||||
lpSecurityDescriptor: descriptor.0,
|
||||
bInheritHandle: 0,
|
||||
};
|
||||
let pipe = ipc::owned(unsafe {
|
||||
CreateNamedPipeW(
|
||||
ipc::wide(PIPE).as_ptr(),
|
||||
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
|
||||
1,
|
||||
LIMIT as u32,
|
||||
LIMIT as u32,
|
||||
1000,
|
||||
&sa,
|
||||
)
|
||||
})?;
|
||||
Ok(Self { pipe, pin })
|
||||
}
|
||||
pub fn serve_one(&self, engine: &mut impl Engine) -> Result<bool> {
|
||||
let result = self.serve_connected(engine);
|
||||
unsafe {
|
||||
DisconnectNamedPipe(self.pipe.as_raw_handle());
|
||||
}
|
||||
result
|
||||
}
|
||||
fn serve_connected(&self, engine: &mut impl Engine) -> Result<bool> {
|
||||
ipc::require_self(&self.pin.updater)?;
|
||||
let pipe = self.pipe.as_raw_handle();
|
||||
let mut event = ipc::IoEvent::new()?;
|
||||
if unsafe { ConnectNamedPipe(pipe, &mut event.overlapped) } == 0 {
|
||||
let error = unsafe { GetLastError() };
|
||||
if error == ERROR_IO_PENDING {
|
||||
if let Err(e) = event.wait(pipe, Instant::now() + Duration::from_millis(250)) {
|
||||
if ipc::diagnostic(&e).code == "HELPER_PIPE_TIMEOUT" {
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
} else {
|
||||
ensure!(error == ERROR_PIPE_CONNECTED, "UPDATE_IPC_CONNECT");
|
||||
}
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let len = ipc::length(pipe, deadline)?;
|
||||
ensure!(len <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
|
||||
let mut peer = PeerProof::capture(pipe, &self.pin.helper, true)?;
|
||||
ensure!(
|
||||
unsafe { ImpersonateNamedPipeClient(pipe) } != 0,
|
||||
"UPDATE_IPC_IMPERSONATE"
|
||||
);
|
||||
let auth = (|| -> Result<()> {
|
||||
let mut token = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token) } != 0,
|
||||
"UPDATE_IPC_THREAD_TOKEN"
|
||||
);
|
||||
let token = ipc::owned(token)?;
|
||||
ipc::verify_token(
|
||||
token.as_raw_handle(),
|
||||
&self.pin.helper.user_sid,
|
||||
&self.pin.helper.service_sid,
|
||||
)
|
||||
})();
|
||||
if unsafe { RevertToSelf() } == 0 {
|
||||
std::process::abort();
|
||||
}
|
||||
auth?;
|
||||
ipc::require_self(&self.pin.updater)?;
|
||||
let call: Call = ipc::body(pipe, len, deadline)?;
|
||||
ensure!(
|
||||
call.schema_version == 1
|
||||
&& !call.challenge.is_nil()
|
||||
&& call.binding_sha256 == ipc::binding_hash(&self.pin.binding)?
|
||||
&& call.policy_sha256 == self.pin.policy_sha256,
|
||||
"UPDATE_IPC_CALL_BINDING"
|
||||
);
|
||||
call.request.validate()?;
|
||||
peer.check()?;
|
||||
let response = engine.handle(
|
||||
&participant(&peer, ParticipantRole::WindowsHelper)?,
|
||||
call.request,
|
||||
)?;
|
||||
response.validate()?;
|
||||
let (_own, own) = observe(&self.pin.updater, ParticipantRole::WindowsUpdater)?;
|
||||
ensure!(response.updater == own, "UPDATE_IPC_SELF_RESPONSE");
|
||||
let reply = Reply {
|
||||
schema_version: 1,
|
||||
challenge: call.challenge,
|
||||
binding_sha256: call.binding_sha256,
|
||||
policy_sha256: call.policy_sha256,
|
||||
response,
|
||||
};
|
||||
let mut bytes = ipc::encode(&reply)?;
|
||||
ensure!(bytes.len() <= LIMIT, "UPDATE_IPC_REPLY_LIMIT");
|
||||
peer.check()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
ipc::send_bytes(pipe, &mut bytes, deadline)?;
|
||||
let mut receipt = [0; ipc::DRAIN_RECEIPT_LEN];
|
||||
ipc::transfer(pipe, &mut receipt, false, deadline)?;
|
||||
ipc::verify_drain_receipt(&receipt, reply.challenge, &bytes)?;
|
||||
peer.check()?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
/// Bounded blocking lane only. Every failure propagates; no Activate retry.
|
||||
pub fn exchange(pin: &Pin, request: &Request, timeout: Duration) -> Result<Response> {
|
||||
pin.validate()?;
|
||||
request.validate()?;
|
||||
ipc::require_self(&pin.helper)?;
|
||||
ensure!(
|
||||
(Duration::from_secs(1)..=Duration::from_secs(30)).contains(&timeout),
|
||||
"UPDATE_IPC_TIMEOUT"
|
||||
);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let pipe = ipc::owned(unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(PIPE).as_ptr(),
|
||||
ipc::CLIENT_PIPE_RIGHTS,
|
||||
0,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
})
|
||||
.context("UPDATE_IPC_UNAVAILABLE")?;
|
||||
let mut peer = PeerProof::capture(pipe.as_raw_handle(), &pin.updater, false)?;
|
||||
let expected = participant(&peer, ParticipantRole::WindowsUpdater)?;
|
||||
let call = Call {
|
||||
schema_version: 1,
|
||||
challenge: Uuid::new_v4(),
|
||||
binding_sha256: ipc::binding_hash(&pin.binding)?,
|
||||
policy_sha256: pin.policy_sha256.clone(),
|
||||
request: request.clone(),
|
||||
};
|
||||
let raw = ipc::encode(&call)?;
|
||||
ensure!(raw.len() <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
|
||||
ipc::send(pipe.as_raw_handle(), &call, deadline)?;
|
||||
let len = ipc::length(pipe.as_raw_handle(), deadline)?;
|
||||
ensure!(len <= LIMIT, "UPDATE_IPC_FRAME_LIMIT");
|
||||
let bytes = ipc::body_bytes(pipe.as_raw_handle(), len, deadline)?;
|
||||
let reply: Reply = serde_json::from_slice(&bytes)?;
|
||||
peer.check()?;
|
||||
ensure!(
|
||||
reply.schema_version == 1
|
||||
&& reply.challenge == call.challenge
|
||||
&& reply.binding_sha256 == call.binding_sha256
|
||||
&& reply.policy_sha256 == call.policy_sha256
|
||||
&& reply.response.updater == expected,
|
||||
"UPDATE_IPC_REPLY_BINDING"
|
||||
);
|
||||
reply.response.validate()?;
|
||||
let mut receipt = ipc::drain_receipt(call.challenge, &bytes);
|
||||
ipc::transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)?;
|
||||
Ok(reply.response)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn request_cannot_select_a_path_command_service_or_weak_original_binding() {
|
||||
for raw in [
|
||||
r#"{"method":"activate","grant_id":"00000000-0000-0000-0000-000000000000","owner_nonce":"00000000-0000-0000-0000-000000000000","handoff_sha256":"00"}"#,
|
||||
r#"{"method":"describe","path":"C:\\Windows\\cmd.exe"}"#,
|
||||
r#"{"method":"prepare"}"#,
|
||||
] {
|
||||
assert!(
|
||||
serde_json::from_str::<Request>(raw)
|
||||
.and_then(|r| r.validate().map_err(serde::de::Error::custom))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
serde_json::from_str::<Request>(r#"{"method":"describe"}"#)
|
||||
.unwrap()
|
||||
.validate()
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user