389 lines
13 KiB
Rust
389 lines
13 KiB
Rust
//! One bounded local request, authenticated BEFORE parsing/dispatch. This
|
|
//! transport cannot approve, create a grant or choose a path/command/service.
|
|
use crate::{
|
|
Budget,
|
|
files::Directory,
|
|
services::{HeldService, Service, Systemd},
|
|
};
|
|
use anyhow::{Result, ensure};
|
|
use rmm_domain::agent_update::ParticipantIdentity;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
fs,
|
|
io::{Read, Write},
|
|
os::{
|
|
fd::AsRawFd,
|
|
unix::{
|
|
fs::{MetadataExt, PermissionsExt},
|
|
net::{UnixListener, UnixStream},
|
|
},
|
|
},
|
|
path::Path,
|
|
time::{Duration, Instant},
|
|
};
|
|
use uuid::Uuid;
|
|
|
|
const MAX_FRAME: usize = 32768;
|
|
const SOCKET: &str = "/run/rmm-agent-updater/control.sock";
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(tag = "method", rename_all = "snake_case", deny_unknown_fields)]
|
|
pub enum Request {
|
|
/// Live service identity only. Not a readiness/approval/start response.
|
|
Describe {},
|
|
/// Refers to the ORIGINAL immutable handoff already committed together
|
|
/// with consumption. Engine must reject a duplicate or unknown dispatch.
|
|
Activate {
|
|
grant_id: Uuid,
|
|
owner_nonce: Uuid,
|
|
handoff_sha256: String,
|
|
},
|
|
Read {
|
|
grant_id: Uuid,
|
|
owner_nonce: Uuid,
|
|
handoff_sha256: String,
|
|
},
|
|
/// Signed evidence bytes only; Engine independently checks actual local
|
|
/// sync/inventory/service/ledger state before the original Outcome CAS.
|
|
Health {
|
|
grant_id: Uuid,
|
|
owner_nonce: Uuid,
|
|
handoff_sha256: String,
|
|
payload_base64url: String,
|
|
signature_base64url: String,
|
|
},
|
|
}
|
|
impl Request {
|
|
fn validate(&self) -> Result<()> {
|
|
match self {
|
|
Self::Describe {} => Ok(()),
|
|
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()
|
|
&& crate::valid_digest(handoff_sha256),
|
|
"UPDATE_IPC_BINDING"
|
|
);
|
|
if let Self::Health {
|
|
payload_base64url,
|
|
signature_base64url,
|
|
..
|
|
} = self
|
|
{
|
|
ensure!(
|
|
!payload_base64url.is_empty()
|
|
&& payload_base64url.len() <= 21846
|
|
&& signature_base64url.len() == 86,
|
|
"UPDATE_IPC_HEALTH_LIMIT"
|
|
);
|
|
ensure!(
|
|
payload_base64url
|
|
.bytes()
|
|
.chain(signature_base64url.bytes())
|
|
.all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)),
|
|
"UPDATE_IPC_BASE64URL"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Response {
|
|
pub schema_version: u32,
|
|
pub state: State,
|
|
/// Always false: this local protocol never publishes ordinary readiness.
|
|
pub ready: bool,
|
|
pub updater: ParticipantIdentity,
|
|
pub head_sha256: Option<String>,
|
|
}
|
|
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum State {
|
|
Described,
|
|
Inflight,
|
|
OutcomePersisted,
|
|
Unknown,
|
|
NotConfigured,
|
|
}
|
|
|
|
/// Trusted embedding runtime. MUST bind every request to the actual original
|
|
/// request/signature/handoff/delegation in the existing helper ledger, enforce
|
|
/// one dispatch and its current authenticated participant, and implement all
|
|
/// independent clock/trust/health/preservation checks. No default engine.
|
|
pub trait Engine {
|
|
fn handle(&mut self, peer: &ParticipantIdentity, request: Request) -> Result<Response>;
|
|
}
|
|
|
|
pub struct Listener {
|
|
socket: UnixListener,
|
|
directory: Directory,
|
|
inode: u64,
|
|
device: u64,
|
|
}
|
|
impl Listener {
|
|
/// Bootstrap must create the fixed private directory separately. Existing
|
|
/// sockets are never unlinked/reused, including after an ambiguous restart.
|
|
pub fn bind() -> Result<Self> {
|
|
ensure!(
|
|
unsafe { libc::geteuid() } == 0,
|
|
"UPDATE_IPC_ROOT_SERVICE_REQUIRED"
|
|
);
|
|
let directory = Directory::open(Path::new("/run/rmm-agent-updater"), 0, true)?;
|
|
directory.verify()?;
|
|
let socket = UnixListener::bind(SOCKET)?;
|
|
fs::set_permissions(SOCKET, fs::Permissions::from_mode(0o600))?;
|
|
let m = fs::symlink_metadata(SOCKET)?;
|
|
use std::os::unix::fs::FileTypeExt;
|
|
ensure!(
|
|
m.file_type().is_socket()
|
|
&& m.uid() == 0
|
|
&& m.mode() & 0o777 == 0o600
|
|
&& m.nlink() == 1,
|
|
"UPDATE_IPC_PRIVATE_SOCKET"
|
|
);
|
|
directory.verify()?;
|
|
Ok(Self {
|
|
socket,
|
|
directory,
|
|
inode: m.ino(),
|
|
device: m.dev(),
|
|
})
|
|
}
|
|
pub fn serve_one(
|
|
&self,
|
|
helpers: &Systemd,
|
|
budget: &Budget,
|
|
engine: &mut impl Engine,
|
|
) -> Result<()> {
|
|
budget.check()?;
|
|
self.directory.verify()?;
|
|
let m = fs::symlink_metadata(SOCKET)?;
|
|
ensure!(
|
|
m.dev() == self.device
|
|
&& m.ino() == self.inode
|
|
&& m.uid() == 0
|
|
&& m.mode() & 0o777 == 0o600,
|
|
"UPDATE_IPC_SOCKET_CHANGED"
|
|
);
|
|
// Poll bounds accept independently of whether any helper connects.
|
|
let mut poll = libc::pollfd {
|
|
fd: self.socket.as_raw_fd(),
|
|
events: libc::POLLIN,
|
|
revents: 0,
|
|
};
|
|
let result = unsafe { libc::poll(&mut poll, 1, 100) };
|
|
ensure!(
|
|
result > 0 && poll.revents == libc::POLLIN,
|
|
"UPDATE_IPC_NO_REQUEST"
|
|
);
|
|
let (stream, _) = self.socket.accept()?;
|
|
let peer = helpers.authenticate_helper_peer(&stream, budget)?;
|
|
let mut stream = SocketIo::new(stream, budget);
|
|
let request = read_request(&mut stream)?;
|
|
budget.check()?;
|
|
let response = engine.handle(&peer, request)?;
|
|
stream.deadline = Instant::now() + Duration::from_secs(5);
|
|
ensure!(
|
|
response.schema_version == 1
|
|
&& !response.ready
|
|
&& response.updater.validate()
|
|
&& response.updater.role == rmm_domain::agent_update::ParticipantRole::LinuxUpdater
|
|
&& response
|
|
.head_sha256
|
|
.as_ref()
|
|
.is_none_or(|h| crate::valid_digest(h)),
|
|
"UPDATE_IPC_RESPONSE"
|
|
);
|
|
let raw = serde_json::to_vec(&response)?;
|
|
ensure!(
|
|
!raw.is_empty() && raw.len() <= MAX_FRAME,
|
|
"UPDATE_IPC_RESPONSE_LIMIT"
|
|
);
|
|
stream.write_all(&(raw.len() as u32).to_be_bytes())?;
|
|
stream.write_all(&raw)?;
|
|
stream.flush()?;
|
|
Ok(())
|
|
}
|
|
}
|
|
fn read_request(stream: &mut impl Read) -> Result<Request> {
|
|
let mut header = [0; 4];
|
|
stream.read_exact(&mut header)?;
|
|
let length = u32::from_be_bytes(header) as usize;
|
|
ensure!(length > 0 && length <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT");
|
|
let mut raw = vec![0; length];
|
|
stream.read_exact(&mut raw)?;
|
|
let value: Request = serde_json::from_slice(&raw)?;
|
|
value.validate()?;
|
|
Ok(value)
|
|
}
|
|
|
|
/// Client transport does not retry a mutating Activate after any IO error.
|
|
/// Caller must independently verify updater against the fixed service pins.
|
|
pub fn exchange(
|
|
stream: UnixStream,
|
|
updater: &HeldService,
|
|
budget: &Budget,
|
|
request: &Request,
|
|
) -> Result<Response> {
|
|
budget.check()?;
|
|
ensure!(
|
|
updater.proof().service == Service::Updater,
|
|
"UPDATE_IPC_UPDATER_ROLE"
|
|
);
|
|
let authenticated = updater.authenticate_peer(&stream, budget)?;
|
|
request.validate()?;
|
|
let raw = serde_json::to_vec(request)?;
|
|
ensure!(raw.len() <= MAX_FRAME, "UPDATE_IPC_FRAME_LIMIT");
|
|
let mut stream = SocketIo::new(stream, budget);
|
|
stream.write_all(&(raw.len() as u32).to_be_bytes())?;
|
|
stream.write_all(&raw)?;
|
|
stream.flush()?;
|
|
let mut length = [0; 4];
|
|
stream.read_exact(&mut length)?;
|
|
let length = u32::from_be_bytes(length) as usize;
|
|
ensure!(
|
|
length > 0 && length <= MAX_FRAME,
|
|
"UPDATE_IPC_RESPONSE_LIMIT"
|
|
);
|
|
let mut bytes = vec![0; length];
|
|
stream.read_exact(&mut bytes)?;
|
|
let response: Response = serde_json::from_slice(&bytes)?;
|
|
ensure!(
|
|
response.schema_version == 1
|
|
&& !response.ready
|
|
&& response.updater == authenticated
|
|
&& response
|
|
.head_sha256
|
|
.as_ref()
|
|
.is_none_or(|h| crate::valid_digest(h)),
|
|
"UPDATE_IPC_NOT_READY_OR_WRONG_UPDATER"
|
|
);
|
|
updater.verify(budget)?;
|
|
Ok(response)
|
|
}
|
|
|
|
/// A kernel timeout restarts after each successful byte. Also bound the whole
|
|
/// frame, including a slow sender. The enclosing job budget is never renewed.
|
|
struct SocketIo<'a> {
|
|
stream: UnixStream,
|
|
budget: &'a Budget,
|
|
deadline: Instant,
|
|
}
|
|
impl<'a> SocketIo<'a> {
|
|
fn new(stream: UnixStream, budget: &'a Budget) -> Self {
|
|
Self {
|
|
stream,
|
|
budget,
|
|
deadline: Instant::now() + Duration::from_secs(5),
|
|
}
|
|
}
|
|
fn remaining(&self) -> std::io::Result<Duration> {
|
|
let original = self.budget.remaining().map_err(std::io::Error::other)?;
|
|
let duration = self
|
|
.deadline
|
|
.saturating_duration_since(Instant::now())
|
|
.min(original);
|
|
if duration.is_zero() {
|
|
return Err(std::io::Error::new(
|
|
std::io::ErrorKind::TimedOut,
|
|
"UPDATE_IPC_FRAME_DEADLINE",
|
|
));
|
|
}
|
|
Ok(duration)
|
|
}
|
|
}
|
|
impl Read for SocketIo<'_> {
|
|
fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
|
|
self.stream.set_read_timeout(Some(self.remaining()?))?;
|
|
self.stream.read(bytes)
|
|
}
|
|
}
|
|
impl Write for SocketIo<'_> {
|
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
|
self.stream.set_write_timeout(Some(self.remaining()?))?;
|
|
self.stream.write(bytes)
|
|
}
|
|
fn flush(&mut self) -> std::io::Result<()> {
|
|
self.remaining()?;
|
|
self.stream.flush()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn framing_denies_large_duplicate_unknown_and_unbound_requests_before_dispatch() {
|
|
let frame = |raw: &[u8]| {
|
|
let mut b = (raw.len() as u32).to_be_bytes().to_vec();
|
|
b.extend_from_slice(raw);
|
|
b
|
|
};
|
|
assert!(matches!(
|
|
read_request(&mut frame(br#"{"method":"describe"}"#).as_slice()).unwrap(),
|
|
Request::Describe {}
|
|
));
|
|
for raw in [br#"{"method":"describe","method":"describe"}"#.as_slice(),br#"{"method":"describe","approved":true}"#.as_slice(),br#"{"method":"execute","command":"anything"}"#.as_slice(),br#"{"method":"activate","grant_id":"00000000-0000-0000-0000-000000000000","owner_nonce":"00000000-0000-0000-0000-000000000000","handoff_sha256":"invalid"}"#.as_slice()]{assert!(read_request(&mut frame(raw).as_slice()).is_err());}
|
|
assert!(read_request(&mut 32769u32.to_be_bytes().as_slice()).is_err());
|
|
assert!(read_request(&mut 0u32.to_be_bytes().as_slice()).is_err());
|
|
}
|
|
#[test]
|
|
fn partial_socket_frame_does_not_extend_its_total_deadline() {
|
|
for (original, frame) in [
|
|
(Duration::from_secs(1), Duration::from_millis(5)),
|
|
(Duration::from_millis(5), Duration::from_secs(5)),
|
|
] {
|
|
assert_fragmented_request_expires(original, frame);
|
|
}
|
|
}
|
|
fn assert_fragmented_request_expires(original: Duration, frame: Duration) {
|
|
let (left, mut right) = UnixStream::pair().unwrap();
|
|
let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id")
|
|
.unwrap()
|
|
.trim()
|
|
.parse()
|
|
.unwrap();
|
|
let (written, wait_written) = std::sync::mpsc::channel();
|
|
let (proceed, wait_proceed) = std::sync::mpsc::channel();
|
|
let sender = std::thread::spawn(move || {
|
|
let raw = br#"{"method":"describe"}"#;
|
|
right.write_all(&(raw.len() as u32).to_be_bytes()).unwrap();
|
|
right.write_all(&raw[..1]).unwrap();
|
|
written.send(()).unwrap();
|
|
wait_proceed.recv().unwrap();
|
|
for byte in &raw[1..] {
|
|
std::thread::sleep(Duration::from_millis(2));
|
|
if right.write_all(&[*byte]).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
wait_written.recv().unwrap();
|
|
let budget = Budget::new(boot, original).unwrap();
|
|
let mut receiver = SocketIo::new(left, &budget);
|
|
receiver.deadline = Instant::now() + frame;
|
|
proceed.send(()).unwrap();
|
|
assert!(read_request(&mut receiver).is_err());
|
|
drop(receiver);
|
|
sender.join().unwrap();
|
|
}
|
|
}
|