use std::path::Path;
use anyhow::{Context as _, Result, bail};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
pub const RECORD_FILE: &str = "agent-account.json";
pub const DIR: &str = "agent-account";
pub const PASSWORD_FILE: &str = "password.dpapi";
pub const VERSION: u32 = 1;
pub const PREFIX: &str = "openmoat-";
const MAX_NAME: usize = 20;
const FORBIDDEN: &[char] = &[
'"', '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', ' ', '%',
];
pub const INTERACTIVE_RIGHT: &str = "SeInteractiveLogonRight";
pub const DENIED_RIGHTS: [&str; 4] = [
"SeDenyNetworkLogonRight",
"SeDenyRemoteInteractiveLogonRight",
"SeDenyServiceLogonRight",
"SeDenyBatchLogonRight",
];
pub const PROFILE_MASK: u32 = 0x0012_00A9;
pub const READ_DENY_MASK: u32 = 0x001F_01FF;
pub const USER_LIST_KEY: &str =
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList";
pub const RELAY_KEY: &str = r"SOFTWARE\OpenMoat\AgentAccounts";
pub const COMMAND_LINE_MAX: usize = 1024;
pub const ELEVATE: &str = "run it from an administrator terminal (Terminal or PowerShell, \"Run \
as administrator\")";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AclEntry {
pub path: String,
pub allows: bool,
pub mask: u32,
pub inherit: bool,
}
impl AclEntry {
fn same(&self, other: &Self) -> bool {
self.path.eq_ignore_ascii_case(&other.path)
&& self.allows == other.allows
&& self.mask == other.mask
&& self.inherit == other.inherit
}
}
pub mod wfp;
pub use wfp::Wfp;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RunAs {
#[default]
Person,
Account,
Filtered,
}
impl RunAs {
pub fn account(self) -> bool {
self != Self::Person
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Record {
pub version: u32,
pub account: String,
pub sid: String,
pub person_sid: String,
pub profile: String,
pub rights: Vec<String>,
pub denied_rights: Vec<String>,
pub hidden: bool,
pub relay_registered: bool,
pub profile_entry: AclEntry,
pub wfp: Option<Wfp>,
#[serde(default)]
pub write_entries: Vec<AclEntry>,
#[serde(default)]
pub read_entries: Vec<AclEntry>,
}
impl Record {
pub fn parse(text: &str) -> Result<Self> {
let record: Self =
serde_json::from_str(text).context("reading the agent account's record")?;
if record.version != VERSION {
bail!(
"the agent account's record has version {}, this OpenMoat reads {VERSION}",
record.version
);
}
if !record.account.starts_with(PREFIX) || record.account.len() > MAX_NAME {
bail!(
"the agent account's record names `{}`, not an account setup makes",
record.account
);
}
if !record.sid.starts_with("S-1-5-21-") {
bail!(
"the agent account's record names the SID {}, not a local account's",
record.sid
);
}
if let Some(wfp) = &record.wfp {
wfp.check()
.context("in the agent account's record of its network filters")?;
}
Ok(record)
}
pub fn load(dir: &Path) -> Result<Option<Self>> {
let path = dir.join(RECORD_FILE);
match std::fs::read_to_string(&path) {
Ok(text) => Self::parse(&text)
.with_context(|| format!("in {}", path.display()))
.map(Some),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
}
}
pub fn to_json(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)? + "\n")
}
pub fn entries(&self) -> impl Iterator<Item = &AclEntry> {
std::iter::once(&self.profile_entry)
.chain(&self.write_entries)
.chain(&self.read_entries)
}
pub fn add_writes(&mut self, entries: &[AclEntry]) {
for entry in entries {
if !self.write_entries.iter().any(|e| e.same(entry)) {
self.write_entries.push(entry.clone());
}
}
}
}
pub fn stale(previous: &[AclEntry], wanted: &[AclEntry]) -> Vec<AclEntry> {
previous
.iter()
.filter(|old| !wanted.iter().any(|new| new.same(old)))
.cloned()
.collect()
}
pub fn account_name(person: &str) -> String {
let mut name = PREFIX.to_owned();
for c in person.chars().flat_map(char::to_lowercase) {
if c.is_control() || FORBIDDEN.contains(&c) {
continue;
}
if name.len() + c.len_utf8() > MAX_NAME {
break;
}
name.push(c);
}
if name.len() == PREFIX.len() {
name.push_str("agent");
}
name
}
pub fn password(hex: &str) -> Zeroizing<String> {
let mut password = Zeroizing::new(String::with_capacity(hex.len() + 3));
password.push_str(hex);
password.push_str("A7!");
password
}
pub fn command_line_fits(units: usize) -> Result<()> {
if units > COMMAND_LINE_MAX {
bail!(
"the agent's command line is {units} characters long; Windows starts a program as \
another account with at most {COMMAND_LINE_MAX} (`CreateProcessWithLogonW`), so \
it does not start: shorten its arguments"
);
}
Ok(())
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Observed {
pub sid: Option<String>,
pub groups: Option<Vec<String>>,
pub rights: Option<Vec<String>>,
pub hidden: bool,
pub relay: Option<String>,
pub profile_entry: bool,
pub password: bool,
pub wfp: wfp::Read,
}
pub fn unread(seen: &Observed) -> Vec<&'static str> {
let mut out = Vec::new();
if seen.groups.is_none() {
out.push("its local groups");
}
if seen.rights.is_none() {
out.push("its logon rights");
}
if seen.wfp == wfp::Read::Unread {
out.push("its network filters");
}
out
}
pub fn drift(record: &Record, seen: &Observed) -> Vec<String> {
let mut out = Vec::new();
let name = &record.account;
match &seen.sid {
None => out.push(format!("the account {name} is gone")),
Some(sid) if !sid.eq_ignore_ascii_case(&record.sid) => out.push(format!(
"the account {name} has the SID {sid}, not the recorded {}",
record.sid
)),
Some(_) => {}
}
if let Some(groups) = seen.groups.as_ref().filter(|g| !g.is_empty()) {
out.push(format!(
"the account {name} is in local groups ({}): it must be in none",
groups.join(", ")
));
}
if let Some(rights) = &seen.rights {
out.extend(rights_drift(rights));
}
if record.hidden && !seen.hidden {
out.push(format!("{name} is shown on the sign-in screen again"));
}
let relay_ok = seen
.relay
.as_deref()
.is_some_and(|p| p.eq_ignore_ascii_case(&record.person_sid));
if record.relay_registered && !relay_ok {
out.push(
"the hook relay's registration of the account (HKLM\\SOFTWARE\\OpenMoat) is gone or \
changed"
.to_owned(),
);
}
if !seen.profile_entry {
out.push(format!(
"the account's read entry on {} is gone",
record.profile
));
}
if !seen.password {
out.push("the account's encrypted password is gone".to_owned());
}
match (&record.wfp, &seen.wfp) {
(Some(recorded), wfp::Read::Seen(filters)) => out.extend(wfp::drift(recorded, filters)),
(Some(_), wfp::Read::NotAsked) => {
out.push("the network filters were not read back".to_owned());
}
_ => {}
}
out
}
fn rights_drift(rights: &[String]) -> Vec<String> {
let wanted: Vec<&str> = std::iter::once(INTERACTIVE_RIGHT)
.chain(DENIED_RIGHTS)
.collect();
let missing: Vec<&str> = wanted
.iter()
.filter(|r| !rights.iter().any(|s| s.eq_ignore_ascii_case(r)))
.copied()
.collect();
let extra: Vec<&str> = rights
.iter()
.filter(|s| !wanted.iter().any(|r| s.eq_ignore_ascii_case(r)))
.map(String::as_str)
.collect();
let mut out = Vec::new();
if !missing.is_empty() {
out.push(format!("logon rights missing: {}", missing.join(", ")));
}
if !extra.is_empty() {
out.push(format!(
"logon rights setup did not give: {}",
extra.join(", ")
));
}
out
}
#[cfg(test)]
mod tests;