Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/argus-core/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ pub enum ActionError {
/// service speaks another protocol and refused it: updating the service
/// lets it act again. Only the host reports it; the service never sends it.
ServiceOutdated,
/// Denied although Argus acted with administrator rights (elevated, or
/// through the privileged service): the target guards itself, so advising
/// those rights is no help. Only the host reports it, for service
/// changes; the service never sends it.
AccessDeniedPrivileged,
/// Resuming could not be confirmed: every thread is still suspended
/// (another tool suspended the process more than once, so it needs
/// another resume), or the thread states could not be read.
Expand Down Expand Up @@ -68,6 +73,7 @@ impl ActionError {
Self::CriticalityUnknown => "process criticality could not be checked".into(),
Self::Refused => "operation refused by policy".into(),
Self::ServiceOutdated => "privileged service protocol incompatible".into(),
Self::AccessDeniedPrivileged => "access denied with administrator rights".into(),
Self::StillSuspended => "threads remain suspended or unreadable after resume".into(),
Self::Os(message) => crate::diagnostics::failure(message),
}
Expand Down Expand Up @@ -962,6 +968,10 @@ mod tests {
json(ActionError::ServiceOutdated),
r#"{"kind":"serviceOutdated"}"#
);
assert_eq!(
json(ActionError::AccessDeniedPrivileged),
r#"{"kind":"accessDeniedPrivileged"}"#
);
assert_eq!(
json(ActionError::StillSuspended),
r#"{"kind":"stillSuspended"}"#
Expand Down
160 changes: 150 additions & 10 deletions crates/argus-core/src/services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
//! Status for every service is one `EnumServicesStatusExW` call. Static
//! configuration (start type, binary path, description) costs three RPCs per
//! service, so it is cached and refreshed only occasionally.
//!
//! Services installed by an MSIX package (`SERVICE_PKG_SERVICE`) get a
//! security descriptor that grants configuration changes only to
//! `NT SERVICE\AppXSvc`: neither administrators nor SYSTEM may change their
//! start type through the SCM. Their registry key keeps the usual ACL, so
//! [`ServiceCatalog::set_start_type_in_registry`] writes `Start` there instead.
//! In testing the SCM picked the new value up at once, but nothing documents
//! that; while the two differ, the registry value is shown as a pending start
//! type, which the SCM reads at the next boot at the latest.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
Expand All @@ -13,7 +22,8 @@ use windows::Win32::Foundation::{
ERROR_SERVICE_DOES_NOT_EXIST, ERROR_SERVICE_MARKED_FOR_DELETE, ERROR_SUCCESS,
};
use windows::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_READ, RegCloseKey, RegLoadMUIStringW, RegOpenKeyExW,
HKEY, HKEY_LOCAL_MACHINE, KEY_QUERY_VALUE, KEY_READ, KEY_SET_VALUE, REG_DWORD, REG_SAM_FLAGS,
RegCloseKey, RegLoadMUIStringW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
};
use windows::Win32::System::Services::{
ChangeServiceConfig2W, ChangeServiceConfigW, CloseServiceHandle, ControlService, DeleteService,
Expand All @@ -37,6 +47,8 @@ const CONFIG_TTL: Duration = Duration::from_secs(60);
const SERVICE_ACCEPT_STOP: u32 = 0x1;
const SERVICE_WIN32_SHARE_PROCESS: u32 = 0x20;
const SERVICE_STOPPED: u32 = 1;
/// `SERVICE_PKG_SERVICE`: the service belongs to an MSIX package.
const SERVICE_PKG_SERVICE: u32 = 0x200;

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -49,6 +61,12 @@ pub struct ServiceInfo {
pub state: &'static str,
/// `boot` | `system` | `auto` | `autoDelayed` | `manual` | `disabled`
pub start_type: Option<&'static str>,
/// Start type written to the registry that the SCM picks up at the next
/// boot; None when it matches `start_type`.
pub pending_start_type: Option<&'static str>,
/// Installed by an MSIX package, so only its registry value can change
/// the start type.
pub packaged: bool,
/// Hosting process; 0 when not running.
pub pid: u32,
/// Command line of the service binary.
Expand Down Expand Up @@ -81,6 +99,8 @@ struct Config {
/// Display name in the user's UI language (the SCM resolves it in the system one).
display_name: Option<String>,
start_type: Option<&'static str>,
pending_start_type: Option<&'static str>,
packaged: bool,
path: Option<Arc<str>>,
account: Option<Arc<str>>,
description: Option<Arc<str>>,
Expand Down Expand Up @@ -200,6 +220,8 @@ impl ServiceCatalog {
description: config.description.clone(),
state: state_name(st.dwCurrentState.0),
start_type: config.start_type,
pending_start_type: config.pending_start_type,
packaged: config.packaged,
pid: st.dwProcessId,
path: config.path.clone(),
account: config.account.clone(),
Expand Down Expand Up @@ -314,6 +336,33 @@ impl ServiceCatalog {
self.invalidate(name);
Ok(())
}

/// Writes the start type of a packaged service straight to its registry
/// key, for when the SCM refuses the change (see the module docs). The SCM
/// usually applies it at once, at the next boot at the latest; an update of
/// the package may restore its own value. Refuses services that are not packaged: those go through the SCM.
pub fn set_start_type_in_registry(
&self,
name: &str,
start: StartType,
) -> Result<(), ActionError> {
let scm = open_scm()?;
let packaged = query_config(&scm, name)
.ok_or(ActionError::NotFound)?
.packaged;
if !packaged {
return Err(ActionError::Refused);
}
let key =
open_registry_key(name, KEY_QUERY_VALUE | KEY_SET_VALUE).map_err(ActionError::from)?;
let (code, delayed) = start_values(start);
set_dword(&key, "Start", code)?;
if let Some(delayed) = delayed {
set_dword(&key, "DelayedAutostart", delayed.into())?;
}
self.invalidate(name);
Ok(())
}
}

/// The standard right to delete an object, which `DeleteService` needs.
Expand All @@ -336,6 +385,62 @@ pub fn remains(name: &str) -> bool {
}
}

/// `Start` and, for automatic starts, `DelayedAutostart` registry values.
fn start_values(start: StartType) -> (u32, Option<bool>) {
match start {
StartType::Auto => (2, Some(false)),
StartType::AutoDelayed => (2, Some(true)),
StartType::Manual => (3, None),
StartType::Disabled => (4, None),
}
}

/// The start type the registry values describe, named like `start_type`.
fn registry_start_name(start: u32, delayed: bool) -> Option<&'static str> {
match (start, delayed) {
(0, _) => Some("boot"),
(1, _) => Some("system"),
(2, true) => Some("autoDelayed"),
(2, false) => Some("auto"),
(3, _) => Some("manual"),
(4, _) => Some("disabled"),
_ => None,
}
}

fn set_dword(key: &RegKey, value: &str, data: u32) -> Result<(), ActionError> {
let v = wide(value);
unsafe {
RegSetValueExW(
key.0,
PCWSTR(v.as_ptr()),
None,
REG_DWORD,
Some(&data.to_le_bytes()),
)
}
.ok()?;
Ok(())
}

fn read_dword(key: &RegKey, value: &str) -> Option<u32> {
let v = wide(value);
let mut data = [0u8; 4];
let mut len = data.len() as u32;
let mut kind = REG_DWORD;
let r = unsafe {
RegQueryValueExW(
key.0,
PCWSTR(v.as_ptr()),
None,
Some(&mut kind),
Some(data.as_mut_ptr()),
Some(&mut len),
)
};
(r == ERROR_SUCCESS && kind == REG_DWORD && len == 4).then(|| u32::from_le_bytes(data))
}

fn start(scm: &Handle, name: &str) -> Result<(), ActionError> {
let svc = open_service(scm, name, SERVICE_START)?;
unsafe { StartServiceW(svc.0, None) }?;
Expand Down Expand Up @@ -387,6 +492,7 @@ fn query_config(scm: &Handle, name: &str) -> Option<Config> {
4 => Some("disabled"),
_ => None,
};
config.packaged = c.dwServiceType.0 & SERVICE_PKG_SERVICE != 0;
config.path = unsafe { pwstr(c.lpBinaryPathName) }.map(Into::into);
config.account = unsafe { pwstr(c.lpServiceStartName) }.map(Into::into);
}
Expand All @@ -396,9 +502,10 @@ fn query_config(scm: &Handle, name: &str) -> Option<Config> {
let d = unsafe { &*(buf.as_ptr() as *const SERVICE_DESCRIPTIONW) };
config.description = unsafe { pwstr(d.lpDescription) }.map(Into::into);
}
if let Some(key) = registry_key(name) {
config.display_name = mui_string(&key, "DisplayName");
if let Some(d) = mui_string(&key, "Description") {
let key = open_registry_key(name, KEY_READ).ok();
if let Some(key) = &key {
config.display_name = mui_string(key, "DisplayName");
if let Some(d) = mui_string(key, "Description") {
config.description = Some(d.into());
}
}
Expand All @@ -410,6 +517,15 @@ fn query_config(scm: &Handle, name: &str) -> Option<Config> {
config.start_type = Some("autoDelayed");
}
}
// A registry value the SCM has not taken up (written by Argus or by hand)
// shows as pending; the SCM reads it at the next boot at the latest.
if let Some(key) = &key
&& let Some(start) = read_dword(key, "Start")
{
let delayed = read_dword(key, "DelayedAutostart").is_some_and(|d| d != 0);
config.pending_start_type = registry_start_name(start, delayed)
.filter(|registry| config.start_type.is_some_and(|scm| scm != *registry));
}
Some(config)
}

Expand All @@ -424,19 +540,20 @@ impl Drop for RegKey {
}
}

fn registry_key(name: &str) -> Option<RegKey> {
fn open_registry_key(name: &str, access: REG_SAM_FLAGS) -> windows::core::Result<RegKey> {
let path = wide(&format!(r"SYSTEM\CurrentControlSet\Services\{name}"));
let mut key = HKEY::default();
let r = unsafe {
unsafe {
RegOpenKeyExW(
HKEY_LOCAL_MACHINE,
PCWSTR(path.as_ptr()),
None,
KEY_READ,
access,
&mut key,
)
};
(r == ERROR_SUCCESS).then_some(RegKey(key))
}
.ok()?;
Ok(RegKey(key))
}

/// Reads a registry string, resolving `@file.dll,-id` references in the
Expand Down Expand Up @@ -490,7 +607,7 @@ fn state_name(state: u32) -> &'static str {

#[cfg(test)]
mod tests {
use super::{Handle, ServiceCatalog, remains};
use super::{Handle, ServiceCatalog, StartType, registry_start_name, remains, start_values};
use crate::actions::ActionError;
use crate::util::wide;
use windows::Win32::System::Services::{
Expand Down Expand Up @@ -579,4 +696,27 @@ mod tests {
assert!(!remains(&name));
assert!(matches!(catalog.delete(&name), Err(ActionError::NotFound)));
}

#[test]
fn registry_values_read_back_as_the_chosen_start_type() {
for (start, name) in [
(StartType::Auto, "auto"),
(StartType::AutoDelayed, "autoDelayed"),
(StartType::Manual, "manual"),
(StartType::Disabled, "disabled"),
] {
let (code, delayed) = start_values(start);
assert_eq!(
registry_start_name(code, delayed.unwrap_or(false)),
Some(name)
);
}
}

#[test]
fn delayed_flag_only_matters_for_automatic_starts() {
assert_eq!(registry_start_name(3, true), Some("manual"));
assert_eq!(registry_start_name(4, true), Some("disabled"));
assert_eq!(registry_start_name(7, false), None);
}
}
38 changes: 37 additions & 1 deletion crates/argus-service/src/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ pub enum Operation {
DeleteService {
name: String,
},
/// Writes `Start` in the registry key of a packaged service whose SCM
/// security descriptor refuses the change.
ServiceStartTypeRegistry {
Comment thread
digital-bombyx marked this conversation as resolved.
Resolved
name: String,
start_type: StartType,
},
CloseConnection {
local_address: String,
local_port: u16,
Expand Down Expand Up @@ -193,7 +199,8 @@ impl Operation {
}
Self::ControlService { name, .. }
| Self::ServiceStartType { name, .. }
| Self::DeleteService { name } => {
| Self::DeleteService { name }
| Self::ServiceStartTypeRegistry { name, .. } => {
if name.is_empty()
|| name.len() > 256
|| name.contains(['\0', '/', '\\'])
Expand Down Expand Up @@ -318,6 +325,9 @@ pub fn execute(operation: Operation, context: &Context, client_pid: u32) -> Repl
context.services.set_start_type(&name, start_type)
}
Operation::DeleteService { name } => context.services.delete(&name),
Operation::ServiceStartTypeRegistry { name, start_type } => context
.services
.set_start_type_in_registry(&name, start_type),
Operation::CloseConnection {
local_address,
local_port,
Expand All @@ -332,6 +342,32 @@ pub fn execute(operation: Operation, context: &Context, client_pid: u32) -> Repl
mod tests {
use super::*;

#[test]
fn registry_start_type_guards_the_name_like_the_scm_operation() {
let op = |name: &str| Operation::ServiceStartTypeRegistry {
name: name.into(),
start_type: StartType::Manual,
};
for name in [
"",
"ArgusPrivileged",
"argusprivilegeddev",
r"Foo\..\Bar",
"a/b",
"x\0",
] {
assert!(
matches!(op(name).validate(), Err(ActionError::Refused)),
"{name}"
);
}
assert!(op("CoworkVMService").validate().is_ok());
let json =
r#"{"op":"serviceStartTypeRegistry","name":"CoworkVMService","start_type":"manual"}"#;
assert!(serde_json::from_str::<Operation>(json).is_ok());
assert!(serde_json::from_str::<Operation>(&json.replace("manual", "boot")).is_err());
}

#[test]
fn disk_details_accept_only_a_bounded_disk_number() {
for input in [
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
| `system.rs` | 总 CPU 与每个逻辑处理器的 CPU(均含内核时间)、内存、提交、缓存。以标准权限查询 `SystemMemoryListInformation`,取得已修改页、各优先级的备用页、空闲与已清零页;内存组成按互不重叠的页列表显示,已缓存为备用与已修改之和。查询不可用时显示总量,组成明细留空。已压缩内存以标准权限查询 `SystemStoreInformation` 的 `MemCompressionInfoRequest`(版本 3,Windows 10 起):驻留量取进程列表中内存压缩进程的工作集(应答里的工作集字段为 32 位,超过 4 GiB 会回绕),存储的数据量按存储区的压缩比估算 |
| `cpu.rs` | 按处理器组读取独立空闲计数与周期计数,校验处理器时钟与原生计数的单位、连续性和分母;异常时重新建立基线或回退时间计数 |
| `details.rs` | 按需查询单个进程:命令行、用户、完整性级别、架构、优先级、版本 |
| `services.rs` | 通过服务控制管理器(SCM):一次 `EnumServicesStatusExW` 取得全部服务状态;启动类型、路径、描述每个服务要三次 RPC,所以缓存起来偶尔刷新;名称与描述按界面语言从 MUI 读取;启停服务、修改启动类型、删除服务(运行中的服务由 Windows 在停止后移除) |
| `services.rs` | 通过服务控制管理器(SCM):一次 `EnumServicesStatusExW` 取得全部服务状态;启动类型、路径、描述每个服务要三次 RPC,所以缓存起来偶尔刷新;名称与描述按界面语言从 MUI 读取;启停服务、修改启动类型、删除服务(运行中的服务由 Windows 在停止后移除)。MSIX 包安装的服务(`SERVICE_PKG_SERVICE`)的安全描述符只允许 `NT SERVICE\AppXSvc` 修改配置,管理员和 SYSTEM 都会被 SCM 拒绝;这类服务可改为直接写入注册表项中的 `Start`(自动启动时还有 `DelayedAutostart`),实测 SCM 通常随即采用新值,但不作保证;注册表值与 SCM 当前值不同时,作为待生效的启动类型返回,最迟在下次开机时生效 |
| `startup.rs`、`startup/packaged.rs` | 注册表 Run 键、启动文件夹(解析 .lnk)与当前账户的应用包启动任务;传统项目使用 `StartupApproved`,应用包结合 AppModel 注册状态、首次激活与用户授权标记判断是否启用,并记录禁用时间。显示程序名称和应用包本地化名称,保留原始项目标识;包清单与名称按包版本、位置和清单修改时间缓存,状态每次重新读取。删除传统项目时删去 Run 值或把启动文件夹中的文件移到回收站(不显示任何确认或错误界面),并清除其 `StartupApproved` 记录;应用包启动任务不删除 |
| `connections.rs` | TCP / UDP(IPv4 / IPv6)端点与所属进程(`netstat -ano` 显示的内容);断开 IPv4 TCP 连接 |
| `filelock.rs` | 以当前账户权限通过 Restart Manager 查找打开文件或加载 DLL 的进程。整批查询被拒时二分重试,隔离无法检查的文件 |
Expand Down
Loading