Release Squid 0.1.6 with malware scanning and startup management
Adds the Protection half of the app: a Security page (quick / full / custom scans, findings by confidence, quarantine and restore) and a Startup items page (LaunchAgents, login items, registry Run, scheduled tasks, services), plus a Processes tab on the real-time monitor that joins a running process to the entry that launched it. XProtect and Defender stay the real-time protection — Squid only reads what they report, uploads nothing, and installs no daemon, kext or privileged helper. On the interface, the two new screens reuse the vocabulary the older screens already had instead of starting a second one: `.panel`, `.status-chip`, `.search-field`, `.icon-button`, `.text-button`, `.metric-icon` with `tone-*`, `.settings-row`. Findings, startup entries and quarantined files share one row shape, so a row is one definition for three screens. Explanatory copy was cut to one sentence per screen and per control, and a count now sits on the filter that produces it rather than also in a summary line above. Two defects fixed on the way: - `src-tauri` is excluded from the root workspace and had no `[profile.release]` of its own, so no desktop build had ever been stripped; the universal binary is 20.6 MiB smaller now. `panic` stays unwind — turning a failed request into a dead app is not a change this release should be making. - The schedule note was built in Rust as an English string, so a Chinese interface showed "squid only scans when you ask." beside everything else in Chinese. The schedule is now described once, in the frontend, in both languages.main
parent
6d9db8b700
commit
eb8f899fe0
|
|
@ -66,3 +66,5 @@ __pycache__/
|
|||
!release/0.1.4/Squid-Setup-0.1.4-win-x64.exe
|
||||
!release/0.1.5/Squid-0.1.5-macOS-universal.dmg
|
||||
!release/0.1.5/Squid-Setup-0.1.5-win-x64.exe
|
||||
!release/0.1.6/Squid-0.1.6-macOS-universal.dmg
|
||||
!release/0.1.6/Squid-Setup-0.1.6-win-x64.exe
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ default:
|
|||
|
||||
rust-lint-test:
|
||||
stage: check
|
||||
image: rust:1.85
|
||||
image: rust:1.95
|
||||
cache:
|
||||
key:
|
||||
files: [Cargo.lock]
|
||||
|
|
@ -31,7 +31,7 @@ rust-lint-test:
|
|||
|
||||
windows-cross-check:
|
||||
stage: check
|
||||
image: rust:1.85
|
||||
image: rust:1.95
|
||||
cache:
|
||||
key:
|
||||
files: [Cargo.lock]
|
||||
|
|
@ -74,7 +74,7 @@ desktop-frontend:
|
|||
|
||||
desktop-rust-check:
|
||||
stage: check
|
||||
image: rust:1.85
|
||||
image: rust:1.95
|
||||
needs:
|
||||
- job: desktop-frontend
|
||||
artifacts: true
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -4,9 +4,9 @@ members = ["crates/*"]
|
|||
exclude = ["src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
rust-version = "1.95"
|
||||
license = "GPL-3.0-only"
|
||||
authors = ["squid contributors"]
|
||||
repository = "https://github.com/nexdev/squid"
|
||||
|
|
@ -18,6 +18,7 @@ squid-platform = { path = "crates/squid-platform" }
|
|||
squid-rules = { path = "crates/squid-rules" }
|
||||
squid-engine = { path = "crates/squid-engine" }
|
||||
squid-stats = { path = "crates/squid-stats" }
|
||||
squid-guard = { path = "crates/squid-guard" }
|
||||
squid-tui = { path = "crates/squid-tui" }
|
||||
|
||||
anyhow = "1"
|
||||
|
|
@ -33,9 +34,9 @@ dirs = "6"
|
|||
libc = "0.2"
|
||||
plist = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk"] }
|
||||
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk", "user"] }
|
||||
crossterm = "0.28"
|
||||
ratatui = "0.29"
|
||||
ratatui = "0.30"
|
||||
unicode-width = "0.2"
|
||||
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
|
||||
|
||||
|
|
|
|||
35
README.en.md
35
README.en.md
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
**Give your computer a bath.**
|
||||
|
||||
Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, and shows live system health.
|
||||
Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, shows live system health, and scans for malware with reversible quarantine.
|
||||
|
||||
The desktop app, CLI, and TUI share one Rust scan-and-delete engine. Cleaning rules, safety boundaries, the deletion ledger, and settings live in one place. Squid requires no cloud service and no root access.
|
||||
|
||||
|
|
@ -27,7 +27,9 @@ The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share
|
|||
| Uninstall apps | Finds an app by name and builds one plan containing the app bundle plus preferences, caches, containers, or AppData leftovers |
|
||||
| Deep Clean | Finds rebuildable build output such as `node_modules`, disk images, installers, and stale downloads while protecting recently used projects |
|
||||
| Storage | Measures folders level by level, with the largest children and files |
|
||||
| Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds; processes can be ended after confirmation |
|
||||
| Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds. The Processes tab lists every process with its signature and startup entry, and ends them after confirmation |
|
||||
| Security | Reports XProtect or Defender status, scans for malware by hash, YARA rule and heuristic, grades findings confirmed / suspicious / advisory, and quarantines them reversibly |
|
||||
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; the ones the current user owns can be disabled and re-enabled |
|
||||
| History and undo | Every real deletion is recorded in a local ledger; items still in Trash or the Recycle Bin can be restored |
|
||||
| System updates | Checks, verifies, downloads, and installs new versions from the release channel |
|
||||
|
||||
|
|
@ -38,16 +40,22 @@ Language settings offer only Simplified Chinese and English, with the current sy
|
|||
### Sidebar
|
||||
|
||||
- **Maintenance**: Computer overview, Daily cleanup, Uninstall apps, Deep Clean
|
||||
- **Protection**: Security, Startup items
|
||||
- **Insights**: Storage, Real-time monitor
|
||||
- **Bottom**: History, Settings
|
||||
|
||||
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+8` on Windows to switch pages.
|
||||
Use `⌘1`–`⌘0` on macOS or `Ctrl+1`–`Ctrl+0` on Windows to switch pages, in the
|
||||
sidebar order above. Since 0.1.6, `7` and `8` open Security and Startup items;
|
||||
History and Settings moved to `9` and `0`.
|
||||
|
||||
### Menu bar / tray
|
||||
|
||||
Closing the main window only hides it; Squid keeps running. The tray menu offers:
|
||||
|
||||
- Open Squid
|
||||
- Protection status (a read-only status line)
|
||||
- Scan for malware
|
||||
- Manage startup items
|
||||
- Daily cleanup
|
||||
- Uninstall apps
|
||||
- Deep Clean
|
||||
|
|
@ -65,11 +73,20 @@ The tray follows the active interface language. Reopening the app, double-clicki
|
|||
|
||||
### Permissions and privacy
|
||||
|
||||
- On first launch, Squid shows an optional Full Disk Access check once. It does not force the macOS permission prompt and never blocks startup.
|
||||
- On first launch, Squid shows a security-readiness card once: system protection, scan
|
||||
access, notifications, launch at login and rule updates. Every item is optional, no
|
||||
permission is requested that you did not ask for, and closing the card changes nothing.
|
||||
- Full Disk Access stays optional. Without it, protected folders are skipped and the
|
||||
Security page reports the coverage as limited rather than clean.
|
||||
- **Settings → System permissions** provides a status check and a shortcut to **System Settings → Privacy & Security → Full Disk Access**.
|
||||
- Without Full Disk Access, TCC-protected locations are skipped and every other feature remains available.
|
||||
- Storage analysis and Deep Clean read only user-selected or configured folders; file contents are never uploaded.
|
||||
- The app makes no network requests other than update checks and installer downloads.
|
||||
- The app makes no network requests other than update checks, installer downloads and
|
||||
rule-pack downloads. **Nothing is ever uploaded**: no file name, hash, finding or
|
||||
quarantined file leaves the machine.
|
||||
- Security scanning does not install a daemon, kernel extension or privileged helper.
|
||||
XProtect and Defender stay the real-time protection; Squid reads their state, never
|
||||
turns them off, and never calls `xprotect update` on your behalf.
|
||||
|
||||
### Launch at login
|
||||
|
||||
|
|
@ -126,6 +143,11 @@ Common commands:
|
|||
| `whitelist add\|list\|remove` | Maintain protected paths that are never selected |
|
||||
| `rules` | List active rules |
|
||||
| `doctor` | Check permissions, configuration, history, and effective paths |
|
||||
| `guard status` | Report XProtect or Defender state, rule-pack version, startup counts and quarantine size |
|
||||
| `guard scan [PATHS…]` | Scan for malware. No paths uses the quick range; `--full`, `--json`, `-y` to auto-quarantine confirmed |
|
||||
| `guard startup` | List login/startup entries; `--all` includes the operating system's own, `--risky` filters |
|
||||
| `guard quarantine <ID>` / `restore <ID>` | Act on a finding id a scan printed, or put a quarantined file back |
|
||||
| `guard held` | List what the quarantine holds, and why |
|
||||
|
||||
Every delete command supports `--dry-run`; non-interactive environments require `-y/--yes`. Run `squid <command> --help` for complete options.
|
||||
|
||||
|
|
@ -137,6 +159,7 @@ crates/
|
|||
├── squid-platform macOS / Linux / Windows adapters: apps, leftovers, volumes, Trash, processes
|
||||
├── squid-rules TOML rule engine: expansion, anchors, protection, age, and risk flags
|
||||
├── squid-stats sysinfo sampling, trends, battery, network, and disk activity
|
||||
├── squid-guard malware scanning, YARA and hash rules, startup trust, reversible quarantine
|
||||
├── squid-engine clean / uninstall / purge / analyze and the single deletion path
|
||||
├── squid-tui ratatui terminal interface
|
||||
└── squid-cli clap command-line entry point
|
||||
|
|
@ -147,7 +170,7 @@ scripts/ development, verification, and dual-platform release script
|
|||
docs/ architecture, design, desktop, and release specifications
|
||||
```
|
||||
|
||||
`src-tauri` is separate from the root Cargo workspace, but depends directly on `squid-core`, `squid-platform`, `squid-stats`, and `squid-engine`. The desktop app does not maintain a second cleanup implementation.
|
||||
`src-tauri` is separate from the root Cargo workspace, but depends directly on `squid-core`, `squid-platform`, `squid-guard`, `squid-stats`, and `squid-engine`. The desktop app does not maintain a second cleanup implementation.
|
||||
|
||||
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for architecture details and [`docs/DESIGN.md`](docs/DESIGN.md) for the shared Nex color, typography, component, and language rules.
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI
|
|||
- **Uninstall apps / 应用卸载** — One plan for the app and its preferences, caches, containers, or AppData leftovers.
|
||||
- **Deep Clean / 深度清理** — Rebuildable build output, disk images, installers, and stale downloads with project-age protection.
|
||||
- **Storage & monitor / 存储与监控** — Folder-level disk analysis, live CPU, memory, network, disk, battery, and process views.
|
||||
- **Security / 安全** — XProtect and Defender status, malware scanning with confirmed / suspicious / advisory findings, and reversible quarantine. No daemon, no kernel extension, no upload.
|
||||
- **Startup items / 启动项** — LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable the ones you own.
|
||||
- **History & updates / 历史与更新** — Restorable Trash sessions and a size- and SHA256-verified update channel.
|
||||
|
||||
The interface follows the system language by default and can be switched to Simplified Chinese or English in Settings.
|
||||
|
|
|
|||
|
|
@ -27,7 +27,9 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
|
|||
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
|
||||
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
|
||||
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
|
||||
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程 |
|
||||
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 |
|
||||
| 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 |
|
||||
| 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 |
|
||||
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
|
||||
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
|
||||
|
||||
|
|
@ -38,16 +40,21 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
|
|||
### 左侧菜单
|
||||
|
||||
- **维护**:电脑概览、日常清理、应用卸载、深度清理
|
||||
- **保护**:安全、启动项
|
||||
- **洞察**:存储空间、实时监控
|
||||
- **底部**:历史记录、设置
|
||||
|
||||
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+8`(Windows)可以直接切换页面。
|
||||
`⌘1`–`⌘0`(macOS)或 `Ctrl+1`–`Ctrl+0`(Windows)按上面的侧栏顺序切换页面。
|
||||
0.1.6 起 `7`、`8` 打开安全与启动项,历史记录与设置顺延到 `9`、`0`。
|
||||
|
||||
### 常驻托盘
|
||||
|
||||
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
|
||||
|
||||
- 打开 Squid
|
||||
- 保护状态(只读状态行)
|
||||
- 扫描恶意软件
|
||||
- 管理启动项
|
||||
- 日常清理
|
||||
- 应用卸载
|
||||
- 深度清理
|
||||
|
|
@ -67,9 +74,12 @@ Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建
|
|||
|
||||
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
|
||||
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
|
||||
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用。
|
||||
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用;安全页会把覆盖范围标为「受限」,不会显示成干净。
|
||||
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
|
||||
- 除更新检查和安装包下载外,应用不发起网络请求。
|
||||
- 除更新检查、安装包下载与规则包下载外,应用不发起网络请求。**任何内容都不会上传**:
|
||||
文件名、哈希、扫描结果与被隔离的文件都不会离开这台电脑。
|
||||
- 安全扫描不安装 daemon、内核扩展或特权 helper。实时防护仍由 XProtect / Defender 承担,
|
||||
Squid 只读取它们的状态,不会替你关闭,也不会替你调用 `xprotect update`。
|
||||
|
||||
### 开机自启
|
||||
|
||||
|
|
@ -126,6 +136,11 @@ squid undo # 还原最近一次废纸篓会话
|
|||
| `whitelist add\|list\|remove` | 维护永不选中的保护路径 |
|
||||
| `rules` | 列出当前生效的规则 |
|
||||
| `doctor` | 检查权限、配置、历史文件和生效路径 |
|
||||
| `guard status` | 报告 XProtect / Defender 状态、规则包版本、启动项数量与隔离区占用 |
|
||||
| `guard scan [PATHS…]` | 扫描恶意软件。不给路径即快速范围;`--full`、`--json`、`-y` 自动隔离已确认项 |
|
||||
| `guard startup` | 列出登录/启动条目;`--all` 含系统自带,`--risky` 只看需注意的 |
|
||||
| `guard quarantine <ID>` / `restore <ID>` | 对扫描输出的发现 id 执行隔离或恢复 |
|
||||
| `guard held` | 列出隔离区里有什么、以及当初为什么进来 |
|
||||
|
||||
所有删除命令都支持 `--dry-run`;非交互环境必须使用 `-y/--yes`。完整参数请运行 `squid <command> --help`。
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ squid-engine.workspace = true
|
|||
squid-platform.workspace = true
|
||||
squid-rules.workspace = true
|
||||
squid-stats.workspace = true
|
||||
squid-guard.workspace = true
|
||||
squid-tui.workspace = true
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
|
|
|
|||
|
|
@ -0,0 +1,638 @@
|
|||
//! `squid guard` — the security half of the command line.
|
||||
//!
|
||||
//! Three verbs carry the roadmap's CLI contract: `status` says what protects
|
||||
//! this machine and what squid can see, `scan` finds things, `quarantine` acts on
|
||||
//! a finding. The rest (`startup`, `held`, `restore`, `unignore`) exists because
|
||||
//! a person reading a finding in a terminal needs the same follow-up the desktop
|
||||
//! app offers, and it is all the same code underneath.
|
||||
//!
|
||||
//! The one asymmetry worth stating: `quarantine` takes a finding id, not a path.
|
||||
//! A finding records the hash and size the scan saw, and the quarantine refuses
|
||||
//! a file that has changed since. Taking a path from the command line would throw
|
||||
//! that away, so the CLI re-runs the scan to find the id again instead.
|
||||
|
||||
use crate::{bullet, clip, heading, human_stream_is_tty, live, paint, shout, shrink};
|
||||
use anyhow::Result;
|
||||
use clap::{Args, Subcommand};
|
||||
use squid_core::progress::{CancelToken, Event, Progress};
|
||||
use squid_core::{paths, Bytes, Settings};
|
||||
use squid_guard::quarantine::Quarantine;
|
||||
use squid_guard::scan::{Guard, ScanTarget};
|
||||
use squid_guard::Confidence;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct GuardArgs {
|
||||
#[command(subcommand)]
|
||||
pub action: GuardAction,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub enum GuardAction {
|
||||
/// What protects this machine right now, and what squid can see
|
||||
Status {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Scan for malware. With no paths, the quick-scan range is used.
|
||||
Scan(ScanArgs),
|
||||
/// What starts when this machine logs in
|
||||
Startup(StartupArgs),
|
||||
/// Move one finding into the quarantine, by the id a scan printed
|
||||
Quarantine { id: String },
|
||||
/// Put a quarantined file back where it came from
|
||||
Restore { id: String },
|
||||
/// What squid is holding, and why
|
||||
Held {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// Stop ignoring a finding so future scans report it again
|
||||
Unignore { fingerprint: String },
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct ScanArgs {
|
||||
/// Paths to scan instead of the quick-scan range
|
||||
paths: Vec<String>,
|
||||
/// Also walk the folders a payload rarely lives in
|
||||
#[arg(long)]
|
||||
full: bool,
|
||||
/// Machine-readable output with every finding and its evidence
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
/// Quarantine confirmed findings without asking
|
||||
#[arg(long, short = 'y')]
|
||||
yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct StartupArgs {
|
||||
/// Include the entries the operating system owns
|
||||
#[arg(long)]
|
||||
all: bool,
|
||||
/// Only the entries that deserve a second look
|
||||
#[arg(long)]
|
||||
risky: bool,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
}
|
||||
|
||||
pub fn run(args: GuardArgs, json: bool) -> Result<i32> {
|
||||
match args.action {
|
||||
GuardAction::Status { json: as_json } => status(as_json || json),
|
||||
GuardAction::Scan(args) => scan(args, json),
|
||||
GuardAction::Startup(args) => startup(args),
|
||||
GuardAction::Quarantine { id } => quarantine(&id),
|
||||
GuardAction::Restore { id } => restore(&id),
|
||||
GuardAction::Held { json: as_json } => held(as_json || json),
|
||||
GuardAction::Unignore { fingerprint } => unignore(&fingerprint),
|
||||
}
|
||||
}
|
||||
|
||||
/// A guard with the user's exclusions applied. Built once per command so what
|
||||
/// `status` reports and what `scan` uses cannot disagree.
|
||||
fn context() -> Guard {
|
||||
let (settings, errors) = Settings::load();
|
||||
for error in errors {
|
||||
shout("33", &format!("config: {error}"));
|
||||
}
|
||||
Guard::new(settings.security.exclusion_paths())
|
||||
}
|
||||
|
||||
fn status(as_json: bool) -> Result<i32> {
|
||||
let protection = squid_platform::protection::status();
|
||||
let intel = squid_guard::intel::status();
|
||||
let startup = squid_platform::startup::inventory();
|
||||
let mut held = Quarantine::new();
|
||||
let held_items = held.entries().len();
|
||||
let held_size = held.total_size();
|
||||
|
||||
if as_json {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"protection": protection,
|
||||
"rules": intel,
|
||||
"startup": {
|
||||
"total": startup.items.len(),
|
||||
"user": startup.user_count(),
|
||||
"system": startup.system_count(),
|
||||
"disabled": startup.disabled_count(),
|
||||
"notes": startup.notes,
|
||||
},
|
||||
"quarantine": { "items": held_items, "size": held_size },
|
||||
}))?
|
||||
);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
heading("Protection");
|
||||
let state = match protection.is_healthy() {
|
||||
Some(true) => paint("32", "active"),
|
||||
Some(false) => paint("31", "needs attention"),
|
||||
None => paint("33", "unknown"),
|
||||
};
|
||||
let product = if protection.product_name.is_empty() {
|
||||
protection.provider.as_str()
|
||||
} else {
|
||||
protection.product_name.as_str()
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
crate::priced(&format!(
|
||||
" {:<12} {} ({})",
|
||||
paint("90", "system"),
|
||||
state,
|
||||
product
|
||||
))
|
||||
);
|
||||
if !protection.definitions.is_empty() {
|
||||
println!(
|
||||
"{}",
|
||||
crate::priced(&format!(
|
||||
" {:<12} {}{}",
|
||||
paint("90", "definitions"),
|
||||
protection.definitions,
|
||||
if protection.definitions_date.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · from {}", protection.definitions_date)
|
||||
}
|
||||
))
|
||||
);
|
||||
}
|
||||
let flag = |value: Option<bool>| match value {
|
||||
Some(true) => paint("32", "on"),
|
||||
Some(false) => paint("31", "off"),
|
||||
None => paint("33", "unknown"),
|
||||
};
|
||||
for (label, value) in [
|
||||
("background", protection.background_scans),
|
||||
("at launch", protection.launch_scans),
|
||||
("gatekeeper", protection.gatekeeper),
|
||||
] {
|
||||
if value.is_some() {
|
||||
println!(
|
||||
"{}",
|
||||
crate::priced(&format!(" {:<12} {}", paint("90", label), flag(value)))
|
||||
);
|
||||
}
|
||||
}
|
||||
for note in &protection.notes {
|
||||
shout("33", &format!(" ! {note}"));
|
||||
}
|
||||
|
||||
heading("Squid");
|
||||
let rules = if intel.source == "builtin" {
|
||||
format!(
|
||||
"{} built-in rules (no pack downloaded)",
|
||||
intel.builtin_rules
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"{} rules from pack r{}, {} built-in",
|
||||
intel.installed_rules, intel.revision, intel.builtin_rules
|
||||
)
|
||||
};
|
||||
for (label, value) in [
|
||||
("rules", rules),
|
||||
(
|
||||
"startup",
|
||||
format!(
|
||||
"{} user · {} system · {} disabled",
|
||||
startup.user_count(),
|
||||
startup.system_count(),
|
||||
startup.disabled_count()
|
||||
),
|
||||
),
|
||||
(
|
||||
"quarantine",
|
||||
format!("{} items · {}", held_items, Bytes(held_size).human_long()),
|
||||
),
|
||||
] {
|
||||
println!(
|
||||
"{}",
|
||||
crate::priced(&format!(" {:<12} {}", paint("90", label), value))
|
||||
);
|
||||
}
|
||||
shout(
|
||||
"90",
|
||||
" squid reads the protection above; it does not replace it",
|
||||
);
|
||||
for note in &startup.notes {
|
||||
shout("33", &format!(" ! {note}"));
|
||||
}
|
||||
println!();
|
||||
shout("90", " squid guard scan · squid guard startup");
|
||||
Ok(if protection.is_healthy() == Some(false) {
|
||||
2
|
||||
} else {
|
||||
0
|
||||
})
|
||||
}
|
||||
|
||||
fn scan(args: ScanArgs, json: bool) -> Result<i32> {
|
||||
let target = if !args.paths.is_empty() {
|
||||
ScanTarget::Paths(args.paths.clone())
|
||||
} else if args.full {
|
||||
ScanTarget::Full
|
||||
} else {
|
||||
ScanTarget::Quick
|
||||
};
|
||||
let mode = target.mode();
|
||||
shout(
|
||||
"90",
|
||||
&format!(" {} scan — {}", mode.as_str(), mode.estimate()),
|
||||
);
|
||||
|
||||
let mut guard = context();
|
||||
let started = std::time::Instant::now();
|
||||
let report = with_progress("scan", &mut guard, move |guard, progress, cancel| {
|
||||
guard.scan(&target, progress, cancel)
|
||||
})?;
|
||||
|
||||
// Recording happens before anything is printed, so an interrupted report
|
||||
// still leaves a finding id the next command can act on.
|
||||
let mut store = squid_guard::store::Store::new();
|
||||
store.set_scan(squid_guard::store::StoredScan::record(&report));
|
||||
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
return Ok(if report.confirmed() > 0 { 2 } else { 0 });
|
||||
}
|
||||
|
||||
heading(&format!("Security · {}", mode.as_str()));
|
||||
if report.cancelled {
|
||||
shout("33", " cancelled — this scan did not finish");
|
||||
}
|
||||
if report.findings.is_empty() {
|
||||
if report.clean_and_complete() {
|
||||
shout("32", " ✓ nothing found in the range this scan covers");
|
||||
} else {
|
||||
shout("33", " nothing found in what could be read");
|
||||
}
|
||||
}
|
||||
for finding in &report.findings {
|
||||
let dot = match finding.confidence {
|
||||
Confidence::Confirmed => paint("31", "●"),
|
||||
Confidence::Suspicious => paint("33", "●"),
|
||||
Confidence::Advisory => paint("90", "○"),
|
||||
};
|
||||
shout(
|
||||
"0",
|
||||
&format!(
|
||||
" {} {} {}",
|
||||
dot,
|
||||
paint("1", &shrink(&finding.name, 32)),
|
||||
paint(
|
||||
"90",
|
||||
&shrink(finding.display_path.as_deref().unwrap_or(""), 54)
|
||||
)
|
||||
),
|
||||
);
|
||||
shout(
|
||||
"0",
|
||||
&format!(" {} {}", paint("90", "→"), shrink(&finding.title, 88)),
|
||||
);
|
||||
for item in finding.evidence.iter().take(3) {
|
||||
shout("90", &format!(" {}", shrink(&item.summary(), 92)));
|
||||
}
|
||||
shout("36", &format!(" {}", finding.id));
|
||||
}
|
||||
for advisory in &report.system_advisories {
|
||||
shout("90", &format!(" ○ {}", shrink(&advisory.description, 96)));
|
||||
}
|
||||
|
||||
if !report.coverage.complete() {
|
||||
shout("33", " coverage was limited:");
|
||||
for gap in report.coverage.gaps() {
|
||||
shout(
|
||||
"33",
|
||||
&format!(
|
||||
" {} — {}",
|
||||
gap.display_path,
|
||||
gap.reason.as_deref().unwrap_or(gap.outcome.as_str())
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
shout(
|
||||
"90",
|
||||
&format!(
|
||||
" {} files checked · {} reused · {} skipped · {:.1}s",
|
||||
squid_core::bytes::format_thousands(report.examined as u64),
|
||||
squid_core::bytes::format_thousands(report.cached as u64),
|
||||
squid_core::bytes::format_thousands(report.skipped as u64),
|
||||
started.elapsed().as_secs_f64()
|
||||
),
|
||||
);
|
||||
|
||||
// 2 means "this scan has something to act on", which covers a suspicious
|
||||
// finding as well as one that never finished: a script should check the
|
||||
// report, not infer safety from an exit code.
|
||||
let incomplete = report.cancelled || !report.coverage.complete();
|
||||
let (settings, _) = Settings::load();
|
||||
let confirmed: Vec<_> = report
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.confidence == Confidence::Confirmed)
|
||||
.collect();
|
||||
if confirmed.is_empty() {
|
||||
let outstanding = report.confirmed() + report.suspicious();
|
||||
return Ok(if outstanding > 0 || incomplete { 2 } else { 0 });
|
||||
}
|
||||
if args.yes || settings.security.auto_quarantine {
|
||||
let mut held = Quarantine::new();
|
||||
for finding in confirmed {
|
||||
match held.quarantine(finding) {
|
||||
Ok(entry) => shout(
|
||||
"32",
|
||||
&format!(" quarantined {} ({})", entry.display_path, entry.id),
|
||||
),
|
||||
Err(error) => shout(
|
||||
"31",
|
||||
&format!(
|
||||
" could not quarantine {}: {error}",
|
||||
finding.display_path.clone().unwrap_or_default()
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
shout(
|
||||
"90",
|
||||
" nothing was moved — squid guard quarantine <id> acts on one finding",
|
||||
);
|
||||
}
|
||||
Ok(2)
|
||||
}
|
||||
|
||||
fn startup(args: StartupArgs) -> Result<i32> {
|
||||
let inventory = squid_platform::startup::inventory();
|
||||
if args.json {
|
||||
println!("{}", serde_json::to_string_pretty(&inventory)?);
|
||||
return Ok(0);
|
||||
}
|
||||
heading("Startup items");
|
||||
let mut shown = 0_usize;
|
||||
for item in &inventory.items {
|
||||
if !args.all && item.system_vendor {
|
||||
continue;
|
||||
}
|
||||
if args.risky && item.risks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
shown += 1;
|
||||
let scope = match item.scope {
|
||||
squid_platform::startup::StartupScope::User => paint("36", "user"),
|
||||
squid_platform::startup::StartupScope::System => paint("90", "sys "),
|
||||
};
|
||||
let state = if item.disabled {
|
||||
paint("33", "off")
|
||||
} else if item.modifiable {
|
||||
paint("32", "on ")
|
||||
} else {
|
||||
paint("90", "ro ")
|
||||
};
|
||||
shout(
|
||||
"0",
|
||||
&format!(
|
||||
" {scope} {state} {} {}",
|
||||
paint("1", &shrink(&item.name, 28)),
|
||||
paint("90", &shrink(item.source.as_str(), 15))
|
||||
),
|
||||
);
|
||||
shout("90", &format!(" {}", shrink(&item.command, 96)));
|
||||
let mut marks: Vec<String> = item
|
||||
.risks
|
||||
.iter()
|
||||
.map(|risk| format!("{risk:?}").to_lowercase().replace('_', "-"))
|
||||
.collect();
|
||||
if let Some(publisher) = &item.publisher {
|
||||
marks.push(format!("signed: {publisher}"));
|
||||
} else if !item.signed {
|
||||
marks.push("unsigned".into());
|
||||
}
|
||||
if !marks.is_empty() {
|
||||
shout("33", &format!(" {}", shrink(&marks.join(" · "), 96)));
|
||||
}
|
||||
}
|
||||
println!();
|
||||
shout(
|
||||
"90",
|
||||
&format!(
|
||||
" {shown} of {} entries · {} belong to the operating system",
|
||||
inventory.items.len(),
|
||||
inventory
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.system_vendor)
|
||||
.count()
|
||||
),
|
||||
);
|
||||
for note in &inventory.notes {
|
||||
shout("33", &format!(" ! {note}"));
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn quarantine(id: &str) -> Result<i32> {
|
||||
let store = squid_guard::store::Store::new();
|
||||
let Some(found) = store.finding(id) else {
|
||||
shout(
|
||||
"31",
|
||||
&format!(" no finding {id} — run `squid guard scan` and use an id it printed"),
|
||||
);
|
||||
return Ok(1);
|
||||
};
|
||||
let finding = found.clone();
|
||||
let mut held = Quarantine::new();
|
||||
match held.quarantine(&finding) {
|
||||
Ok(entry) => {
|
||||
shout("32", &format!(" quarantined {}", entry.display_path));
|
||||
shout("90", &format!(" squid guard restore {}", entry.id));
|
||||
let mut store = squid_guard::store::Store::new();
|
||||
store.update_scan(|scan| {
|
||||
if let Some(tracked) = scan.findings.iter_mut().find(|f| f.id == id) {
|
||||
tracked.quarantined = true;
|
||||
}
|
||||
});
|
||||
Ok(0)
|
||||
}
|
||||
Err(error) => {
|
||||
shout("31", &format!(" refused: {error}"));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore(id: &str) -> Result<i32> {
|
||||
let mut held = Quarantine::new();
|
||||
match held.restore(id) {
|
||||
Ok(path) => {
|
||||
shout("32", &format!(" restored {}", paths::pretty(&path)));
|
||||
// The finding is live again on disk, so the next scan must be able
|
||||
// to report it; clearing the flag keeps the stored scan honest.
|
||||
let mut store = squid_guard::store::Store::new();
|
||||
store.update_scan(|scan| {
|
||||
for finding in &mut scan.findings {
|
||||
if finding
|
||||
.path
|
||||
.as_ref()
|
||||
.is_some_and(|candidate| paths::same_path(candidate, &path))
|
||||
{
|
||||
finding.quarantined = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(0)
|
||||
}
|
||||
Err(error) => {
|
||||
shout("31", &format!(" refused: {error}"));
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn held(as_json: bool) -> Result<i32> {
|
||||
let mut held = Quarantine::new();
|
||||
if as_json {
|
||||
println!("{}", serde_json::to_string_pretty(held.entries())?);
|
||||
return Ok(0);
|
||||
}
|
||||
heading("Quarantine");
|
||||
if held.entries().is_empty() {
|
||||
shout("90", " empty — nothing has been moved out of the way");
|
||||
return Ok(0);
|
||||
}
|
||||
for entry in held.entries() {
|
||||
shout(
|
||||
"0",
|
||||
&format!(
|
||||
" {} {} {}",
|
||||
paint("33", "◆"),
|
||||
paint("1", &shrink(&entry.display_path, 58)),
|
||||
paint("90", &Bytes(entry.size).human_long())
|
||||
),
|
||||
);
|
||||
shout(
|
||||
"90",
|
||||
&format!(" {} · {}", shrink(&entry.title, 58), entry.id),
|
||||
);
|
||||
}
|
||||
println!();
|
||||
shout(
|
||||
"90",
|
||||
&format!(
|
||||
" {} items · {} · restore puts one back, the folder is the last copy",
|
||||
held.entries().len(),
|
||||
Bytes(held.total_size()).human_long()
|
||||
),
|
||||
);
|
||||
shout(
|
||||
"90",
|
||||
&format!(
|
||||
" {}",
|
||||
paths::pretty(&squid_guard::coverage::quarantine_root())
|
||||
),
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn unignore(fingerprint: &str) -> Result<i32> {
|
||||
let (mut settings, errors) = Settings::load();
|
||||
for error in errors {
|
||||
shout("33", &format!("config: {error}"));
|
||||
}
|
||||
if settings.security.unignore(fingerprint) {
|
||||
let path = settings.save()?;
|
||||
shout("32", &format!(" {fingerprint} will be reported again"));
|
||||
shout("90", &format!(" saved {}", paths::pretty(&path)));
|
||||
} else {
|
||||
shout("90", &format!(" {fingerprint} was not ignored"));
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// The same progress rendering the cleanup commands use, driven by a guard scan
|
||||
/// rather than an `Engine`.
|
||||
fn with_progress<T>(
|
||||
label: &str,
|
||||
guard: &mut Guard,
|
||||
work: impl FnOnce(&mut Guard, &Progress, &CancelToken) -> squid_core::Result<T>,
|
||||
) -> squid_core::Result<T> {
|
||||
let label = label.to_owned();
|
||||
let progress = Progress::new();
|
||||
let cancel = CancelToken::new();
|
||||
let printer = progress.clone();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let printer_stop = stop.clone();
|
||||
let printer_thread = std::thread::spawn(move || {
|
||||
let mut frames = label.chars();
|
||||
loop {
|
||||
let stop_now = printer_stop.load(Ordering::Relaxed);
|
||||
for event in printer.drain() {
|
||||
match event {
|
||||
Event::Phase { phase, detail } => {
|
||||
shout("36", &format!(" {} {phase} — {detail}", bullet()));
|
||||
}
|
||||
Event::Tick {
|
||||
done,
|
||||
total,
|
||||
subject,
|
||||
} => {
|
||||
if human_stream_is_tty() {
|
||||
let glyph = frames
|
||||
.next()
|
||||
.unwrap_or_else(|| label.chars().next().unwrap_or('#'));
|
||||
let text = match total {
|
||||
Some(total) if total > 0 => format!(
|
||||
" {glyph} {done}/{}",
|
||||
squid_core::bytes::format_thousands(total)
|
||||
),
|
||||
_ => format!(
|
||||
" {glyph} {}",
|
||||
squid_core::bytes::format_thousands(done)
|
||||
),
|
||||
};
|
||||
let tail = subject
|
||||
.as_ref()
|
||||
.map(|path| shrink(&paths::pretty(path), 40))
|
||||
.unwrap_or_default();
|
||||
live(Some(&format!(
|
||||
"{} {}",
|
||||
paint("36", &text),
|
||||
paint("90", &tail)
|
||||
)));
|
||||
}
|
||||
}
|
||||
Event::Warning(text) => shout("33", &format!(" ! {}", clip(&text, 100))),
|
||||
Event::Note(text) => shout("90", &format!(" · {}", clip(&text, 100))),
|
||||
Event::Deleted { path, freed } => shout(
|
||||
"90",
|
||||
&format!(
|
||||
" ✓ {} ({})",
|
||||
shrink(&paths::pretty(&path), 70),
|
||||
freed.human()
|
||||
),
|
||||
),
|
||||
Event::Bucket { .. } | Event::Done(_) => {}
|
||||
}
|
||||
}
|
||||
if stop_now {
|
||||
if human_stream_is_tty() {
|
||||
live(None);
|
||||
}
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(40));
|
||||
}
|
||||
});
|
||||
let result = work(guard, &progress, &cancel);
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = printer_thread.join();
|
||||
result
|
||||
}
|
||||
|
|
@ -6,6 +6,8 @@
|
|||
//! and the ledger. This file only parses arguments, shows progress and asks for
|
||||
//! confirmation.
|
||||
|
||||
mod guard;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use crossterm::tty::IsTty;
|
||||
|
|
@ -80,6 +82,8 @@ enum Command {
|
|||
Rules,
|
||||
/// Report permissions, settings and ledger health
|
||||
Doctor,
|
||||
/// Malware scan, login-item inventory and quarantine
|
||||
Guard(guard::GuardArgs),
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
|
|
@ -231,7 +235,7 @@ fn change() -> &'static Exchange {
|
|||
/// a console: whatever glass reads it tomorrow may well be able to afford the
|
||||
/// `█`, and an archive of `#` is a worse record for the sake of a screen that
|
||||
/// was never looking. Only a screen is offered the exchange.
|
||||
fn priced(text: &str) -> String {
|
||||
pub(crate) fn priced(text: &str) -> String {
|
||||
if !human_stream_is_tty() {
|
||||
return text.to_string();
|
||||
}
|
||||
|
|
@ -288,7 +292,7 @@ fn say(text: &str) {
|
|||
/// overwritten. Chrome may only be exchanged for ASCII when somebody is looking
|
||||
/// at the console that cannot afford it — because that is the only place the
|
||||
/// exchange is an improvement rather than a loss.
|
||||
fn human_stream_is_tty() -> bool {
|
||||
pub(crate) fn human_stream_is_tty() -> bool {
|
||||
if DIAG_STDERR.load(Ordering::Relaxed) {
|
||||
std::io::stderr().is_tty()
|
||||
} else {
|
||||
|
|
@ -297,7 +301,7 @@ fn human_stream_is_tty() -> bool {
|
|||
}
|
||||
|
||||
/// Rewrite the live progress line, or clear it when `text` is `None`.
|
||||
fn live(text: Option<&str>) {
|
||||
pub(crate) fn live(text: Option<&str>) {
|
||||
let line = match text {
|
||||
Some(text) => format!("\r\x1b[K{}", priced(text)),
|
||||
None => "\r\x1b[K".to_string(),
|
||||
|
|
@ -381,12 +385,13 @@ fn run() -> Result<i32> {
|
|||
Some(Command::Whitelist(args)) => cmd_whitelist(args),
|
||||
Some(Command::Rules) => cmd_rules(cli.json),
|
||||
Some(Command::Doctor) => cmd_doctor(),
|
||||
Some(Command::Guard(args)) => guard::run(args, cli.json),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------- output
|
||||
|
||||
fn paint(code: &str, text: &str) -> String {
|
||||
pub(crate) fn paint(code: &str, text: &str) -> String {
|
||||
if COLOR.load(Ordering::Relaxed) {
|
||||
format!("\x1b[{code}m{text}\x1b[0m")
|
||||
} else {
|
||||
|
|
@ -394,13 +399,13 @@ fn paint(code: &str, text: &str) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
fn shout(code: &str, text: &str) {
|
||||
pub(crate) fn shout(code: &str, text: &str) {
|
||||
if !QUIET.load(Ordering::Relaxed) || code == "31" {
|
||||
diag(code, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn heading(text: &str) {
|
||||
pub(crate) fn heading(text: &str) {
|
||||
if QUIET.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -409,7 +414,7 @@ fn heading(text: &str) {
|
|||
diag("90", &"─".repeat(text.chars().count().min(64)));
|
||||
}
|
||||
|
||||
fn shrink(text: &str, width: usize) -> String {
|
||||
pub(crate) fn shrink(text: &str, width: usize) -> String {
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width {
|
||||
return text.to_string();
|
||||
|
|
@ -430,7 +435,7 @@ fn shrink(text: &str, width: usize) -> String {
|
|||
format!("...{out}")
|
||||
}
|
||||
|
||||
fn clip(text: &str, width: usize) -> String {
|
||||
pub(crate) fn clip(text: &str, width: usize) -> String {
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width {
|
||||
return text.to_string();
|
||||
|
|
@ -612,7 +617,7 @@ fn with_progress<T>(
|
|||
result
|
||||
}
|
||||
|
||||
fn bullet() -> String {
|
||||
pub(crate) fn bullet() -> String {
|
||||
if COLOR.load(Ordering::Relaxed) {
|
||||
"●".to_string()
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ pub fn format_thousands(value: u64) -> String {
|
|||
let digits = value.to_string();
|
||||
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
|
||||
for (idx, ch) in digits.chars().enumerate() {
|
||||
if idx > 0 && (digits.len() - idx) % 3 == 0 {
|
||||
if idx > 0 && (digits.len() - idx).is_multiple_of(3) {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(ch);
|
||||
|
|
|
|||
|
|
@ -178,6 +178,31 @@ pub fn normalized(path: &Path) -> PathBuf {
|
|||
out
|
||||
}
|
||||
|
||||
/// A path reduced to one comparable string.
|
||||
///
|
||||
/// This is [`same_path`] made cheap enough to index a table with. `same_path` is
|
||||
/// correct but builds a `Vec` of lowercased components per call, which is fine for
|
||||
/// a dozen comparisons and quadratic when a scan asks one per cached file: a
|
||||
/// 15,000-file security scan spent most of ten minutes doing nothing but
|
||||
/// re-comparing paths.
|
||||
///
|
||||
/// The two must agree, because a key that matched where `same_path` would not let
|
||||
/// a cached verdict be reused for the wrong file. Both fold case unconditionally —
|
||||
/// the rule [`keys_match`] already applies on every platform — and a test asserts
|
||||
/// the agreement rather than trusting this wording.
|
||||
pub fn canonical_key(path: &Path) -> String {
|
||||
let parts: Vec<String> = parts(path).into_iter().map(|(key, _)| key).collect();
|
||||
// `parts` keeps the root as its own component so that an absolute path cannot
|
||||
// collide with a relative one, which would let a cached verdict be reused for
|
||||
// the wrong file. Joining them verbatim reads as `//a/b`, so the root is put
|
||||
// back as a prefix instead: same uniqueness, and the cache file on disk stays
|
||||
// legible to whoever opens it.
|
||||
match parts.first().map(String::as_str) {
|
||||
Some("/") => format!("/{}", parts[1..].join("/")),
|
||||
_ => parts.join("/"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Name that survives being shown in a one-line row: deepest meaningful label.
|
||||
pub fn label_for(path: &Path) -> String {
|
||||
path.file_name()
|
||||
|
|
@ -189,6 +214,59 @@ pub fn label_for(path: &Path) -> String {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_canonical_key_agrees_with_same_path() {
|
||||
let cases: [(&str, &str, bool); 7] = [
|
||||
("/a/b/c", "/a/b/c", true),
|
||||
("/a/b/../b/c", "/a/b/c", true),
|
||||
("/a/./b/c", "/a/b/c", true),
|
||||
("/a/b/c", "/a/b/d", false),
|
||||
("/a/b/c", "/a/b", false),
|
||||
("/a/b/c", "/a/b/c/d", false),
|
||||
("/A/b", "/a/b", true),
|
||||
];
|
||||
for (left, right, same) in cases {
|
||||
let (a, b) = (Path::new(left), Path::new(right));
|
||||
assert_eq!(
|
||||
same_path(a, b),
|
||||
canonical_key(a) == canonical_key(b),
|
||||
"same_path and canonical_key disagree about {left} and {right}"
|
||||
);
|
||||
assert_eq!(
|
||||
same,
|
||||
same_path(a, b),
|
||||
"unexpected same_path for {left} and {right}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_spelling_of_one_file_gives_one_key() {
|
||||
// A cache keyed by this must not answer "never seen it" to a file it has
|
||||
// already judged, or every scan re-reads the disk and the cache is a lie.
|
||||
for spelling in ["/a/b/c", "/a/b/c/", "/a/./b/c", "/a/b/../b/c"] {
|
||||
assert_eq!(
|
||||
canonical_key(Path::new(spelling)),
|
||||
canonical_key(Path::new("/a/b/c")),
|
||||
"{spelling} is the same file as /a/b/c"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canonical_key_is_usable_as_a_hash_key() {
|
||||
// Two spellings of one file must land on one slot, or a cache lookup
|
||||
// would answer "never seen it" and re-hash the whole disk every scan.
|
||||
assert_eq!(
|
||||
canonical_key(Path::new("/Users/Tester/Library/Caches")),
|
||||
canonical_key(Path::new("/Users/Tester/./Library/Caches"))
|
||||
);
|
||||
assert_ne!(
|
||||
canonical_key(Path::new("/a/b")),
|
||||
canonical_key(Path::new("/a/b/c"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_home() {
|
||||
let home = Path::new("/Users/tester");
|
||||
|
|
|
|||
|
|
@ -36,6 +36,131 @@ pub struct Settings {
|
|||
/// Whether the desktop app's first-run permission card has been dismissed.
|
||||
/// Older configs have no such field and therefore see the card once.
|
||||
pub desktop_setup_reviewed: bool,
|
||||
/// Malware scanning and quarantine. A whole section so an old config keeps
|
||||
/// working: `#[serde(default)]` above fills this in when the file has none.
|
||||
pub security: SecuritySettings,
|
||||
}
|
||||
|
||||
/// How often squid runs its own scan while the app is open in the tray.
|
||||
///
|
||||
/// `OnLaunch` and the intervals only fire while squid is actually running: there
|
||||
/// is no daemon, and pretending otherwise would promise a watchdog that is not
|
||||
/// there. `Manual` is the default because a scan that starts by itself is a
|
||||
/// surprise the user did not ask for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum ScanSchedule {
|
||||
Manual,
|
||||
OnLaunch,
|
||||
Daily,
|
||||
Weekly,
|
||||
}
|
||||
|
||||
impl ScanSchedule {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ScanSchedule::Manual => "manual",
|
||||
ScanSchedule::OnLaunch => "on-launch",
|
||||
ScanSchedule::Daily => "daily",
|
||||
ScanSchedule::Weekly => "weekly",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<ScanSchedule> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"manual" | "off" | "none" => Some(ScanSchedule::Manual),
|
||||
"on-launch" | "launch" => Some(ScanSchedule::OnLaunch),
|
||||
"daily" => Some(ScanSchedule::Daily),
|
||||
"weekly" => Some(ScanSchedule::Weekly),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a scan of this kind must wait before running again, or `None`
|
||||
/// when it never runs by itself.
|
||||
pub fn interval_secs(self) -> Option<i64> {
|
||||
match self {
|
||||
ScanSchedule::Manual => None,
|
||||
ScanSchedule::OnLaunch => Some(0),
|
||||
ScanSchedule::Daily => Some(24 * 60 * 60),
|
||||
ScanSchedule::Weekly => Some(7 * 24 * 60 * 60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct SecuritySettings {
|
||||
pub scan_schedule: ScanSchedule,
|
||||
/// Notify through the operating system when a scan finds something. The
|
||||
/// in-app banner and the tray state work without this.
|
||||
pub notify_on_findings: bool,
|
||||
/// Move confirmed findings into the quarantine without asking. Suspicious
|
||||
/// ones are never moved automatically, whatever this is set to.
|
||||
pub auto_quarantine: bool,
|
||||
/// Download signed rule packs. Off means squid uses only what it shipped with.
|
||||
pub update_rules: bool,
|
||||
/// Paths the scan must not read. Separate from `whitelist` on purpose: a
|
||||
/// folder a person protects from *cleaning* must not silently stop a
|
||||
/// malware finding from being reported.
|
||||
pub scan_exclusions: Vec<String>,
|
||||
/// Findings the user dismissed, as `confidence|path` fingerprints.
|
||||
pub ignored_findings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for SecuritySettings {
|
||||
fn default() -> Self {
|
||||
SecuritySettings {
|
||||
scan_schedule: ScanSchedule::Manual,
|
||||
notify_on_findings: true,
|
||||
// Off by default: a security tool that moves files on its own has to
|
||||
// earn that right first.
|
||||
auto_quarantine: false,
|
||||
update_rules: true,
|
||||
scan_exclusions: Vec::new(),
|
||||
ignored_findings: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SecuritySettings {
|
||||
pub fn exclude(&mut self, path: impl Into<String>) {
|
||||
let path = path.into();
|
||||
if !self.scan_exclusions.contains(&path) {
|
||||
self.scan_exclusions.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_exclusion(&mut self, path: &str) -> bool {
|
||||
let before = self.scan_exclusions.len();
|
||||
self.scan_exclusions.retain(|kept| kept != path);
|
||||
self.scan_exclusions.len() != before
|
||||
}
|
||||
|
||||
/// Expanded, existing paths, ready to hand a scan.
|
||||
pub fn exclusion_paths(&self) -> Vec<PathBuf> {
|
||||
self.scan_exclusions
|
||||
.iter()
|
||||
.map(|raw| paths::expand(raw))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn ignore(&mut self, fingerprint: impl Into<String>) {
|
||||
let fingerprint = fingerprint.into();
|
||||
if !self.ignored_findings.contains(&fingerprint) {
|
||||
self.ignored_findings.push(fingerprint);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_ignored(&self, fingerprint: &str) -> bool {
|
||||
self.ignored_findings.iter().any(|kept| kept == fingerprint)
|
||||
}
|
||||
|
||||
pub fn unignore(&mut self, fingerprint: &str) -> bool {
|
||||
let before = self.ignored_findings.len();
|
||||
self.ignored_findings.retain(|kept| kept != fingerprint);
|
||||
self.ignored_findings.len() != before
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
|
|
@ -67,6 +192,7 @@ impl Default for Settings {
|
|||
language: None,
|
||||
history_keep: 60,
|
||||
desktop_setup_reviewed: false,
|
||||
security: SecuritySettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -256,7 +256,7 @@ pub fn largest_files(
|
|||
return Err(squid_core::SquidError::Cancelled);
|
||||
}
|
||||
visited += 1;
|
||||
if visited % 64 == 0 {
|
||||
if visited.is_multiple_of(64) {
|
||||
progress.tick(visited as u64, None, Some(dir.clone()));
|
||||
}
|
||||
if visited > 500_000 {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "squid-guard"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
description = "Malware scanning, detection rules and reversible quarantine for squid"
|
||||
|
||||
[dependencies]
|
||||
squid-core.workspace = true
|
||||
squid-platform.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
walkdir.workspace = true
|
||||
yara-x = { version = "1.23", default-features = false, features = ["string-module","math-module","hash-module","time-module","macho-module","pe-module","constant-folding","exact-atoms","fast-regexp"] }
|
||||
chrono.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
plist.workspace = true
|
||||
|
|
@ -0,0 +1,231 @@
|
|||
//! Which parts of the machine a scan actually looked at.
|
||||
//!
|
||||
//! A cleaner can be vague about coverage because missing a cache costs nothing.
|
||||
//! A security scan cannot: "no threats found" that quietly skipped
|
||||
//! `~/Library/Mail` for lack of Full Disk Access is worse than no answer at all.
|
||||
//! So every root records what happened to it, and the report is only allowed to
|
||||
//! say "clean" for the roots that were walked.
|
||||
//!
|
||||
//! Nothing here asks the operating system for permission and nothing here
|
||||
//! retries a refusal. A denied directory is a fact about this run, reported as
|
||||
//! one, and the person using squid decides whether to grant access and rescan.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use squid_core::paths;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What happened to one root during a scan.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum RootOutcome {
|
||||
/// Every readable entry beneath it was offered to the detectors.
|
||||
Walked,
|
||||
/// The root itself could not be opened — usually a privacy permission.
|
||||
Denied,
|
||||
/// It was not there, which is not a gap in coverage.
|
||||
Absent,
|
||||
/// The user or a rule excluded it on purpose.
|
||||
Excluded,
|
||||
/// Deliberately not part of this scan mode.
|
||||
OutOfScope,
|
||||
/// Stopped early: cancelled, or the entry budget ran out.
|
||||
Partial,
|
||||
}
|
||||
|
||||
impl RootOutcome {
|
||||
pub fn counts_as_gap(self) -> bool {
|
||||
matches!(self, RootOutcome::Denied | RootOutcome::Partial)
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
RootOutcome::Walked => "walked",
|
||||
RootOutcome::Denied => "denied",
|
||||
RootOutcome::Absent => "absent",
|
||||
RootOutcome::Excluded => "excluded",
|
||||
RootOutcome::OutOfScope => "out-of-scope",
|
||||
RootOutcome::Partial => "partial",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RootRecord {
|
||||
pub path: PathBuf,
|
||||
pub display_path: String,
|
||||
pub outcome: RootOutcome,
|
||||
pub reason: Option<String>,
|
||||
pub files: usize,
|
||||
pub scanned: usize,
|
||||
pub skipped: usize,
|
||||
}
|
||||
|
||||
/// The whole coverage statement for one scan.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Coverage {
|
||||
pub roots: Vec<RootRecord>,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
pub fn push(&mut self, mut record: RootRecord) {
|
||||
if record.display_path.is_empty() {
|
||||
record.display_path = paths::pretty(&record.path);
|
||||
}
|
||||
self.roots.push(record);
|
||||
}
|
||||
|
||||
/// True when the scan saw everything it meant to see. This is the only
|
||||
/// condition under which the UI is allowed to say "nothing found" without a
|
||||
/// qualifier next to it.
|
||||
pub fn complete(&self) -> bool {
|
||||
!self.roots.iter().any(|root| root.outcome.counts_as_gap())
|
||||
}
|
||||
|
||||
pub fn gaps(&self) -> Vec<&RootRecord> {
|
||||
self.roots
|
||||
.iter()
|
||||
.filter(|root| root.outcome.counts_as_gap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn walked_files(&self) -> usize {
|
||||
self.roots.iter().map(|root| root.scanned).sum()
|
||||
}
|
||||
|
||||
pub fn skipped_files(&self) -> usize {
|
||||
self.roots.iter().map(|root| root.skipped).sum()
|
||||
}
|
||||
|
||||
/// Record the outcome of walking one root, folding in the entry count.
|
||||
pub fn record_walk(
|
||||
&mut self,
|
||||
root: &Path,
|
||||
outcome: RootOutcome,
|
||||
reason: Option<String>,
|
||||
files: usize,
|
||||
scanned: usize,
|
||||
) {
|
||||
self.push(RootRecord {
|
||||
path: root.to_path_buf(),
|
||||
display_path: String::new(),
|
||||
outcome,
|
||||
reason,
|
||||
files,
|
||||
scanned,
|
||||
skipped: files.saturating_sub(scanned),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Decide what happened to a root from the error reading it, so a missing
|
||||
/// `~/Applications` is not reported as a coverage gap while a refused
|
||||
/// `~/Library/Mail` is.
|
||||
pub fn outcome_for_error(error: &std::io::Error) -> RootOutcome {
|
||||
use std::io::ErrorKind;
|
||||
match error.kind() {
|
||||
ErrorKind::NotFound => RootOutcome::Absent,
|
||||
ErrorKind::PermissionDenied => RootOutcome::Denied,
|
||||
_ => RootOutcome::Denied,
|
||||
}
|
||||
}
|
||||
|
||||
/// A path the scan should never descend into, wherever it appears.
|
||||
pub fn is_never_scanned(path: &Path) -> bool {
|
||||
const SKIP_DIRS: [&str; 8] = [
|
||||
".git",
|
||||
"node_modules",
|
||||
".Trash",
|
||||
".Trashes",
|
||||
"$RECYCLE.BIN",
|
||||
"System Volume Information",
|
||||
".Spotlight-V100",
|
||||
".fseventsd",
|
||||
];
|
||||
// The quarantine holds files this crate moved deliberately; scanning it
|
||||
// would report the same finding forever.
|
||||
if path.starts_with(quarantine_root()) {
|
||||
return true;
|
||||
}
|
||||
path.ancestors()
|
||||
.filter_map(|ancestor| ancestor.file_name())
|
||||
.any(|name| SKIP_DIRS.iter().any(|skip| name.eq(*skip)))
|
||||
}
|
||||
|
||||
/// Where quarantined files live. One place, inside the state directory, so the
|
||||
/// user can always find and empty it.
|
||||
pub fn quarantine_root() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("quarantine")
|
||||
}
|
||||
|
||||
/// Where rule packs and the hash cache live.
|
||||
pub fn intel_root() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("intel")
|
||||
}
|
||||
|
||||
/// Where startup-item backups are kept before a change.
|
||||
pub fn startup_backup_root() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("startup-backups")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_missing_folder_is_not_a_coverage_gap() {
|
||||
let error = std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
assert_eq!(outcome_for_error(&error), RootOutcome::Absent);
|
||||
assert!(!RootOutcome::Absent.counts_as_gap());
|
||||
let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(outcome_for_error(&denied), RootOutcome::Denied);
|
||||
assert!(RootOutcome::Denied.counts_as_gap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_is_only_complete_without_denials() {
|
||||
let mut coverage = Coverage::default();
|
||||
coverage.record_walk(Path::new("/a"), RootOutcome::Walked, None, 10, 10);
|
||||
coverage.record_walk(Path::new("/b"), RootOutcome::Absent, None, 0, 0);
|
||||
assert!(coverage.complete());
|
||||
coverage.record_walk(
|
||||
Path::new("/c"),
|
||||
RootOutcome::Denied,
|
||||
Some("Full Disk Access".into()),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
assert!(!coverage.complete());
|
||||
assert_eq!(coverage.gaps().len(), 1);
|
||||
assert_eq!(coverage.walked_files(), 10);
|
||||
assert_eq!(coverage.skipped_files(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vendored_and_recycle_directories_are_never_walked() {
|
||||
assert!(is_never_scanned(Path::new(
|
||||
"/Users/x/proj/node_modules/left-pad"
|
||||
)));
|
||||
assert!(is_never_scanned(Path::new(
|
||||
"/Volumes/Data/.Trash/thing.app"
|
||||
)));
|
||||
assert!(is_never_scanned(&quarantine_root().join("payload.bin")));
|
||||
assert!(!is_never_scanned(Path::new("/Applications/Calculator.app")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quarantine_lives_in_the_state_directory() {
|
||||
assert!(
|
||||
quarantine_root().ends_with("security/quarantine")
|
||||
|| quarantine_root()
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/")
|
||||
.ends_with("security/quarantine")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
//! What a scan decided about one file, and how it knows.
|
||||
//!
|
||||
//! The three levels are not a severity dial. They answer different questions,
|
||||
//! and the difference is the contract the UI relies on:
|
||||
//!
|
||||
//! - [`Confidence::Confirmed`] means a specific published rule or hash says this
|
||||
//! exact file is bad. It may be quarantined automatically if the user opted in.
|
||||
//! - [`Confidence::Suspicious`] means the file has properties that a careful
|
||||
//! person would check, with nothing published to point at. Alert, never move.
|
||||
//! - [`Confidence::Advisory`] is not about the file at all — it is about the
|
||||
//! machine: protection switched off, definitions old, a directory that could
|
||||
//! not be read. Nothing to quarantine, something to say.
|
||||
//!
|
||||
//! Every finding carries [`Evidence`], and the UI shows that evidence rather
|
||||
//! than a score. "SHA-256 is on the known-bad list" is checkable; "risk 72" is
|
||||
//! not.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Confidence {
|
||||
Advisory,
|
||||
Suspicious,
|
||||
Confirmed,
|
||||
}
|
||||
|
||||
impl Confidence {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Confidence::Advisory => "advisory",
|
||||
Confidence::Suspicious => "suspicious",
|
||||
Confidence::Confirmed => "confirmed",
|
||||
}
|
||||
}
|
||||
|
||||
/// Only confirmed findings may be moved without asking again, and only this
|
||||
/// method decides that — the UI cannot widen it.
|
||||
pub fn auto_quarantinable(self) -> bool {
|
||||
self == Confidence::Confirmed
|
||||
}
|
||||
}
|
||||
|
||||
/// One reason a file was reported. A finding may hold several: a binary that
|
||||
/// matches a family rule *and* starts at login *and* is unsigned is three
|
||||
/// statements, and a person reading the row deserves all three.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Evidence {
|
||||
/// The SHA-256 of the file is on the known-bad list.
|
||||
DeniedHash { sha256: String, threat: String },
|
||||
/// A YARA-X rule fired.
|
||||
YaraRule {
|
||||
rule: String,
|
||||
description: String,
|
||||
family: String,
|
||||
},
|
||||
/// A published allow-list entry does not cover a file that claims to be it.
|
||||
Impersonation { claimed: String, path: PathBuf },
|
||||
/// Where this entry is started from.
|
||||
StartsAtLogin { entry: String, source: String },
|
||||
/// No usable code signature.
|
||||
Unsigned { path: PathBuf, note: Option<String> },
|
||||
/// Runs from a location every normal user of this machine can rewrite.
|
||||
WritableLocation { path: PathBuf },
|
||||
/// The file the entry points at is gone.
|
||||
MissingTarget { path: PathBuf },
|
||||
/// An advisory about the machine rather than a file.
|
||||
SystemState { key: String, detail: String },
|
||||
/// Part of the scan could not be checked.
|
||||
Coverage { path: PathBuf, reason: String },
|
||||
}
|
||||
|
||||
impl Evidence {
|
||||
/// Stable identity for de-duplication across scans, so an ignored finding
|
||||
/// stays ignored after a rescan rather than reappearing under a new row.
|
||||
pub fn key(&self) -> String {
|
||||
match self {
|
||||
Evidence::DeniedHash { sha256, threat } => format!("hash:{sha256}:{threat}"),
|
||||
Evidence::YaraRule { rule, .. } => format!("yara:{rule}"),
|
||||
Evidence::Impersonation { claimed, .. } => format!("impersonation:{claimed}"),
|
||||
Evidence::StartsAtLogin { entry, .. } => format!("startup:{entry}"),
|
||||
Evidence::Unsigned { path, .. } => format!("unsigned:{}", path.display()),
|
||||
Evidence::WritableLocation { path } => format!("writable:{}", path.display()),
|
||||
Evidence::MissingTarget { path } => format!("missing:{}", path.display()),
|
||||
Evidence::SystemState { key, .. } => format!("state:{key}"),
|
||||
Evidence::Coverage { path, reason } => {
|
||||
format!("coverage:{}:{reason}", path.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One line for a table cell. The full evidence stays available in details.
|
||||
pub fn summary(&self) -> String {
|
||||
match self {
|
||||
Evidence::DeniedHash { threat, .. } => format!("known-bad hash: {threat}"),
|
||||
Evidence::YaraRule { rule, family, .. } => {
|
||||
if family.is_empty() {
|
||||
format!("matches rule {rule}")
|
||||
} else {
|
||||
format!("matches rule {rule} ({family})")
|
||||
}
|
||||
}
|
||||
Evidence::Impersonation { claimed, .. } => {
|
||||
format!("claims to be {claimed} but is not where {claimed} lives")
|
||||
}
|
||||
Evidence::StartsAtLogin { entry, source } => {
|
||||
format!("starts at login via {source} ({entry})")
|
||||
}
|
||||
Evidence::Unsigned { note, .. } => match note {
|
||||
Some(note) => format!("not signed: {note}"),
|
||||
None => "not signed".into(),
|
||||
},
|
||||
Evidence::WritableLocation { path } => {
|
||||
format!("runs from a user-writable location: {}", path.display())
|
||||
}
|
||||
Evidence::MissingTarget { path } => {
|
||||
format!("target is gone: {}", path.display())
|
||||
}
|
||||
Evidence::SystemState { detail, .. } => detail.clone(),
|
||||
Evidence::Coverage { path, reason } => {
|
||||
format!("not checked ({}): {reason}", path.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> Option<&PathBuf> {
|
||||
match self {
|
||||
Evidence::Impersonation { path, .. }
|
||||
| Evidence::Unsigned { path, .. }
|
||||
| Evidence::WritableLocation { path }
|
||||
| Evidence::MissingTarget { path }
|
||||
| Evidence::Coverage { path, .. } => Some(path),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One reported file or machine state.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Finding {
|
||||
/// Backend-issued. The frontend sends this back to quarantine; it never
|
||||
/// sends a path.
|
||||
pub id: String,
|
||||
pub confidence: Confidence,
|
||||
/// The file the finding is about. `None` for machine-state advisories.
|
||||
pub path: Option<PathBuf>,
|
||||
pub display_path: Option<String>,
|
||||
/// What the thing is called in a list: file name, or the advisory subject.
|
||||
pub name: String,
|
||||
/// Human-readable statement of the threat or the reason.
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub evidence: Vec<Evidence>,
|
||||
pub size: u64,
|
||||
pub sha256: Option<String>,
|
||||
pub signed: bool,
|
||||
pub publisher: Option<String>,
|
||||
pub found_at_ms: u64,
|
||||
/// Set once the file has been quarantined, from the ledger.
|
||||
pub quarantined: bool,
|
||||
/// The user dismissed this finding for this scan only.
|
||||
pub ignored: bool,
|
||||
}
|
||||
|
||||
impl Finding {
|
||||
pub fn confirmed(&self) -> bool {
|
||||
self.confidence == Confidence::Confirmed
|
||||
}
|
||||
|
||||
/// De-duplication identity: the same file reported by two detectors is one
|
||||
/// row with two pieces of evidence.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let path = self
|
||||
.path
|
||||
.as_ref()
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "-".into());
|
||||
format!("{}|{}", self.confidence.as_str(), path)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,445 @@
|
|||
//! Judgement calls that no published signature makes for you.
|
||||
//!
|
||||
//! These rules describe conditions a person would want to know about, not
|
||||
//! threats. Each one produces [`Evidence`] and a ceiling, and the ceiling is the
|
||||
//! important part: heuristics stop at `suspicious`, so a machine with an
|
||||
//! unsigned updater in `~/Library/Application Support` gets a row to read, not a
|
||||
//! file moved behind its back.
|
||||
//!
|
||||
//! Two properties do most of the work. **Who can rewrite the file**: a binary
|
||||
//! that starts at login from a folder the current user owns can be replaced by
|
||||
//! anything the current user runs, which is how persistence malware survives an
|
||||
//! update. **What claims to be true**: a file named like a system component, or
|
||||
//! launched by an entry whose target has vanished, is a mismatch between the
|
||||
//! story and the facts.
|
||||
|
||||
use crate::findings::{Confidence, Evidence};
|
||||
use squid_platform::startup::{StartupItem, StartupRisk, StartupScope, StartupSource};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What the scanner knows about one candidate file when it asks for a judgement.
|
||||
pub struct Candidate<'a> {
|
||||
pub path: &'a Path,
|
||||
/// The login/startup entry that launches this file, when there is one.
|
||||
pub startup: Option<&'a StartupItem>,
|
||||
/// True when any user of this machine can replace the file.
|
||||
pub world_writable: bool,
|
||||
/// Whether the file carries a signature blob, from
|
||||
/// [`squid_platform::trust::has_signature_blob`]. The caller answers this
|
||||
/// because it decides what the question is worth: asking the operating
|
||||
/// system to *validate* a signature costs a subprocess on macOS and a
|
||||
/// certificate-chain walk on Windows, which is affordable for the few files
|
||||
/// a scan is already reporting and ruinous for the thousands it is only
|
||||
/// filtering.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
/// Judge one candidate. Returns evidence; the caller combines it with whatever
|
||||
/// the published detectors found and takes the strongest level.
|
||||
pub fn judge(candidate: &Candidate) -> Vec<Evidence> {
|
||||
let mut evidence = Vec::new();
|
||||
|
||||
if let Some(item) = candidate.startup {
|
||||
evidence.push(Evidence::StartsAtLogin {
|
||||
entry: item.name.clone(),
|
||||
source: item.source.as_str().to_string(),
|
||||
});
|
||||
if item.risks.contains(&StartupRisk::MissingTarget) {
|
||||
evidence.push(Evidence::MissingTarget {
|
||||
path: item
|
||||
.program
|
||||
.clone()
|
||||
.unwrap_or_else(|| candidate.path.to_path_buf()),
|
||||
});
|
||||
}
|
||||
if item.scope == StartupScope::System {
|
||||
// A system-scope entry pointed at a user-writable file is the
|
||||
// classic privilege hop: root runs something an unqualified user may
|
||||
// overwrite.
|
||||
if candidate.world_writable || starts_in_user_space(candidate.path) {
|
||||
evidence.push(Evidence::WritableLocation {
|
||||
path: candidate.path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !candidate.signed {
|
||||
evidence.push(Evidence::Unsigned {
|
||||
path: candidate.path.to_path_buf(),
|
||||
note: None,
|
||||
});
|
||||
}
|
||||
|
||||
if starts_in_user_space(candidate.path) && candidate.startup.is_some() {
|
||||
evidence.push(Evidence::WritableLocation {
|
||||
path: candidate.path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(claimed) =
|
||||
impersonated_component(candidate.path).or_else(|| windows_lookalike(candidate.path))
|
||||
{
|
||||
evidence.push(Evidence::Impersonation {
|
||||
claimed: claimed.to_string(),
|
||||
path: candidate.path.to_path_buf(),
|
||||
});
|
||||
}
|
||||
|
||||
dedupe(&mut evidence);
|
||||
evidence
|
||||
}
|
||||
|
||||
/// The ceiling these heuristics can support: suspicious, never confirmed.
|
||||
pub const CEILING: Confidence = Confidence::Suspicious;
|
||||
|
||||
/// Level for a set of heuristic findings alone.
|
||||
///
|
||||
/// One weak signal is a note; two that point the same way are a finding. A binary
|
||||
/// with no signature is ordinary — squid itself is one — but a binary with no
|
||||
/// signature *that starts at login* is the shape persistence malware takes, and a
|
||||
/// file that claims to be a system component while sitting somewhere else is
|
||||
/// suspicious on its own because nothing honest does that.
|
||||
///
|
||||
/// The alternative, which this used to be, was to call any single signal
|
||||
/// suspicious. On a real machine that produced nine hundred rows next to a
|
||||
/// download folder, and a list that long is read as noise and then ignored, which
|
||||
/// is worse than not reporting it.
|
||||
pub fn confidence(evidence: &[Evidence]) -> Confidence {
|
||||
let mut weight = 0_u8;
|
||||
for item in evidence {
|
||||
match item {
|
||||
// The one signal strong enough to stand alone.
|
||||
Evidence::Impersonation { .. } => return Confidence::Suspicious,
|
||||
Evidence::StartsAtLogin { .. }
|
||||
| Evidence::Unsigned { .. }
|
||||
| Evidence::WritableLocation { .. } => weight += 1,
|
||||
// "The file it points at is gone" is housekeeping. It explains a
|
||||
// finding and is worth showing beside one, but on its own it has
|
||||
// never hurt anybody.
|
||||
Evidence::MissingTarget { .. } => {}
|
||||
// Everything else is not a heuristic's verdict at all. A denied hash
|
||||
// or a YARA match is graded by the detector that produced it, and
|
||||
// counting it here would let a published hit lend false
|
||||
// corroboration to a weak heuristic sitting next to it.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if weight >= 2 {
|
||||
Confidence::Suspicious
|
||||
} else {
|
||||
Confidence::Advisory
|
||||
}
|
||||
}
|
||||
|
||||
/// Locations every user of this machine can write to, and therefore locations
|
||||
/// where a file that runs at login can be swapped without asking anybody.
|
||||
fn starts_in_user_space(path: &Path) -> bool {
|
||||
let home = squid_platform::startup::home_dir();
|
||||
let text = path.to_string_lossy().to_lowercase();
|
||||
if path.starts_with(&home) {
|
||||
return true;
|
||||
}
|
||||
const WRITABLE: [&str; 4] = ["/users/shared/", "/tmp/", "/private/tmp/", "/var/folders/"];
|
||||
WRITABLE.iter().any(|prefix| text.starts_with(prefix))
|
||||
}
|
||||
|
||||
/// Names that belong to the operating system, so a file wearing one somewhere
|
||||
/// else is worth a look. Matched on the whole stem, never a substring, because
|
||||
/// `SpotlightHelper.app` in a legit vendor's folder is not claiming to be Apple's.
|
||||
const LOOKALIKES: [(&str, &str); 8] = [
|
||||
(
|
||||
"Activity Monitor",
|
||||
"/System/Applications/Utilities/Activity Monitor.app",
|
||||
),
|
||||
("Dock", "/System/Library/CoreServices/Dock.app"),
|
||||
(
|
||||
"ControlCenter",
|
||||
"/System/Library/CoreServices/ControlCenter.app",
|
||||
),
|
||||
(
|
||||
"WindowServer",
|
||||
"/System/Library/PrivateFrameworks/SkyLight.framework",
|
||||
),
|
||||
("kernel_task", "the kernel"),
|
||||
("launchd", "/sbin/launchd"),
|
||||
(
|
||||
"loginwindow",
|
||||
"/System/Library/CoreServices/loginwindow.app",
|
||||
),
|
||||
(
|
||||
"UserNotificationCenter",
|
||||
"/System/Library/CoreServices/UserNotificationCenter.app",
|
||||
),
|
||||
];
|
||||
|
||||
fn impersonated_component(path: &Path) -> Option<&'static str> {
|
||||
let file_name = path.file_name()?.to_string_lossy().into_owned();
|
||||
let stem = file_name
|
||||
.trim_end_matches(".app")
|
||||
.trim_end_matches(".plist")
|
||||
.to_string();
|
||||
let (name, real_home) = LOOKALIKES
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
|
||||
// Apple's own copy living in its own place is not impersonating anything,
|
||||
// and neither is anything Apple ships inside /System.
|
||||
if path.starts_with("/System") || path.starts_with("/usr/libexec") {
|
||||
return None;
|
||||
}
|
||||
let _ = real_home;
|
||||
Some(*name)
|
||||
}
|
||||
|
||||
/// Windows keeps its own set of names that people recognise and malware borrows.
|
||||
#[cfg(windows)]
|
||||
const WINDOWS_LOOKALIKES: [(&str, &str); 4] = [
|
||||
("svchost", "%SystemRoot%\\System32\\svchost.exe"),
|
||||
("explorer", "%SystemRoot%\\explorer.exe"),
|
||||
("lsass", "%SystemRoot%\\System32\\lsass.exe"),
|
||||
("taskhostw", "%SystemRoot%\\System32\\taskhostw.exe"),
|
||||
];
|
||||
|
||||
#[cfg(windows)]
|
||||
fn windows_lookalike(path: &Path) -> Option<&'static str> {
|
||||
let file_name = path.file_name()?.to_string_lossy().into_owned();
|
||||
let stem = file_name.trim_end_matches(".exe").to_string();
|
||||
let system = std::env::var("SystemRoot").unwrap_or_default();
|
||||
let (name, real) = WINDOWS_LOOKALIKES
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
|
||||
if !system.is_empty() && path.starts_with(&system) {
|
||||
return None;
|
||||
}
|
||||
let _ = real;
|
||||
Some(*name)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn windows_lookalike(_path: &Path) -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn dedupe(evidence: &mut Vec<Evidence>) {
|
||||
let mut seen: Vec<String> = Vec::with_capacity(evidence.len());
|
||||
evidence.retain(|item| {
|
||||
let key = item.key();
|
||||
if seen.contains(&key) {
|
||||
return false;
|
||||
}
|
||||
seen.push(key);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Startup entries whose own risk flags deserve a row in the findings list, even
|
||||
/// though there is no file to quarantine. These are advisories about the
|
||||
/// machine's persistence, and they are how a person finds an entry whose target
|
||||
/// was deleted by hand and left behind.
|
||||
pub fn startup_advisories(
|
||||
items: &[StartupItem],
|
||||
) -> Vec<(PathBuf, String, Confidence, Vec<Evidence>)> {
|
||||
let mut out = Vec::new();
|
||||
for item in items {
|
||||
if item.system_vendor {
|
||||
continue;
|
||||
}
|
||||
let mut evidence = Vec::new();
|
||||
if item.risks.contains(&StartupRisk::MissingTarget) {
|
||||
evidence.push(Evidence::MissingTarget {
|
||||
path: item.program.clone().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
if item.risks.contains(&StartupRisk::InTempDir)
|
||||
|| item.risks.contains(&StartupRisk::HiddenHomeDirectory)
|
||||
{
|
||||
evidence.push(Evidence::WritableLocation {
|
||||
path: item.program.clone().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
if item.risks.contains(&StartupRisk::ScriptInterpreter) {
|
||||
evidence.push(Evidence::StartsAtLogin {
|
||||
entry: item.name.clone(),
|
||||
source: format!("{} via script interpreter", item.source.as_str()),
|
||||
});
|
||||
}
|
||||
if item.source == StartupSource::LoginItem {
|
||||
continue;
|
||||
}
|
||||
if evidence.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let level = if item.risks.contains(&StartupRisk::MissingTarget) {
|
||||
Confidence::Advisory
|
||||
} else {
|
||||
Confidence::Suspicious
|
||||
};
|
||||
out.push((
|
||||
item.program
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from(&item.id)),
|
||||
item.name.clone(),
|
||||
level,
|
||||
evidence,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use squid_platform::startup::{StartupScope, StartupSource};
|
||||
|
||||
fn item(path: &Path, source: StartupSource, scope: StartupScope) -> StartupItem {
|
||||
let mut item = StartupItem::new(path.to_string_lossy(), "probe", source, scope);
|
||||
item.program = Some(path.to_path_buf());
|
||||
item
|
||||
}
|
||||
|
||||
fn candidate<'a>(path: &'a Path, startup: Option<&'a StartupItem>) -> Candidate<'a> {
|
||||
Candidate {
|
||||
path,
|
||||
startup,
|
||||
world_writable: false,
|
||||
// The probes below are plain text written by the test, so this is
|
||||
// the honest answer for those files rather than a stub.
|
||||
signed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_home_folder_file_is_user_writable() {
|
||||
let home = squid_platform::startup::home_dir();
|
||||
assert!(starts_in_user_space(
|
||||
&home.join("Library/Application Support/Thing/thing")
|
||||
));
|
||||
assert!(starts_in_user_space(Path::new("/tmp/thing")));
|
||||
assert!(!starts_in_user_space(Path::new("/usr/libexec/thing")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_named_like_a_system_component_outside_its_home_is_flagged() {
|
||||
assert_eq!(
|
||||
impersonated_component(Path::new(
|
||||
"/Users/tester/Library/Application Support/Dock/Dock.app"
|
||||
)),
|
||||
Some("Dock")
|
||||
);
|
||||
// The real one is not impersonating itself.
|
||||
assert_eq!(
|
||||
impersonated_component(Path::new("/System/Library/CoreServices/Dock.app")),
|
||||
None
|
||||
);
|
||||
// A vendor app whose name merely contains the word is not a claim.
|
||||
assert_eq!(
|
||||
impersonated_component(Path::new("/Applications/DockFinder.app")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heuristics_never_claim_confirmation() {
|
||||
let path = squid_platform::startup::home_dir()
|
||||
.join("Library/Application Support/guard-probe/updater");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"#!/bin/sh\necho probe\n").unwrap();
|
||||
let entry = item(&path, StartupSource::LaunchAgent, StartupScope::User);
|
||||
let evidence = judge(&candidate(&path, Some(&entry)));
|
||||
assert!(
|
||||
!evidence.is_empty(),
|
||||
"an unsigned login agent should say something"
|
||||
);
|
||||
assert_eq!(confidence(&evidence), Confidence::Suspicious);
|
||||
assert!(confidence(&evidence) != Confidence::Confirmed);
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_missing_target_is_housekeeping_not_a_threat() {
|
||||
let evidence = vec![
|
||||
Evidence::StartsAtLogin {
|
||||
entry: "ghost".into(),
|
||||
source: "launch-agent".into(),
|
||||
},
|
||||
Evidence::MissingTarget {
|
||||
path: PathBuf::from("/Users/tester/gone"),
|
||||
},
|
||||
];
|
||||
assert_eq!(confidence(&evidence), Confidence::Advisory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_weak_signal_is_a_note_and_two_are_a_finding() {
|
||||
let unsigned = || Evidence::Unsigned {
|
||||
path: PathBuf::from("/a"),
|
||||
note: None,
|
||||
};
|
||||
let login = || Evidence::StartsAtLogin {
|
||||
entry: "thing".into(),
|
||||
source: "launch-agent".into(),
|
||||
};
|
||||
// The whole machine is unsigned. Saying so once per file is noise.
|
||||
assert_eq!(confidence(&[unsigned()]), Confidence::Advisory);
|
||||
assert_eq!(confidence(&[]), Confidence::Advisory);
|
||||
// Unsigned *and* started at login is the persistence shape.
|
||||
assert_eq!(
|
||||
confidence(&[unsigned(), login()]),
|
||||
Confidence::Suspicious,
|
||||
"corroborating signals have to outrank one lonely signal"
|
||||
);
|
||||
// Wearing a system component's name is enough on its own.
|
||||
assert_eq!(
|
||||
confidence(&[Evidence::Impersonation {
|
||||
claimed: "Dock".into(),
|
||||
path: PathBuf::from("/Users/tester/Dock"),
|
||||
}]),
|
||||
Confidence::Suspicious
|
||||
);
|
||||
// …and heuristics still cannot reach confirmed, whatever the combination.
|
||||
assert_ne!(
|
||||
confidence(&[unsigned(), login()]),
|
||||
Confidence::Confirmed,
|
||||
"no heuristic may claim certainty"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_published_hit_does_not_make_a_weak_heuristic_look_stronger() {
|
||||
// One unsigned file plus one confirmed hash hit. The hash decides the
|
||||
// level; the heuristic half must still say "one weak signal", or the
|
||||
// ceiling that keeps heuristics out of `confirmed` would be grading the
|
||||
// detector's evidence rather than its own.
|
||||
let evidence = vec![
|
||||
Evidence::DeniedHash {
|
||||
sha256: "aa".into(),
|
||||
threat: "known bad".into(),
|
||||
},
|
||||
Evidence::Unsigned {
|
||||
path: PathBuf::from("/a"),
|
||||
note: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(confidence(&evidence), Confidence::Advisory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evidence_is_not_reported_twice() {
|
||||
let mut evidence = vec![
|
||||
Evidence::Unsigned {
|
||||
path: PathBuf::from("/a"),
|
||||
note: None,
|
||||
},
|
||||
Evidence::Unsigned {
|
||||
path: PathBuf::from("/a"),
|
||||
note: None,
|
||||
},
|
||||
Evidence::Unsigned {
|
||||
path: PathBuf::from("/b"),
|
||||
note: None,
|
||||
},
|
||||
];
|
||||
dedupe(&mut evidence);
|
||||
assert_eq!(evidence.len(), 2);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,627 @@
|
|||
//! Rule packs: the on-disk format, its verification, and the fallback that keeps
|
||||
//! a bad download from leaving the machine unguarded.
|
||||
//!
|
||||
//! A pack is YARA source plus a JSON manifest, published beside the installers
|
||||
//! on the same git-backed channel the app update uses. Two keys are involved and
|
||||
//! they are deliberately different: the release key signs installers, and the
|
||||
//! intel key signs rules. Rotating one should not have to move the other, and a
|
||||
//! leaked installer key must not become a rule-injection path.
|
||||
//!
|
||||
//! Nothing is uploaded. The client fetches a manifest and, if newer, a pack; no
|
||||
//! filename, hash, or scan result ever leaves the machine. That is a property of
|
||||
//! this module, not of the caller's good intentions — there is no function here
|
||||
//! that takes a path from the local disk and sends it anywhere.
|
||||
|
||||
use crate::rules::RuleLevel;
|
||||
use crate::rules::RuleMeta;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "squid-intel.json";
|
||||
pub const SIGNATURE_FILE: &str = "squid-intel.sig";
|
||||
const SUPPORTED_SCHEMA: u32 = 1;
|
||||
/// Parsers are the first thing a hostile input breaks, so the size gate is not
|
||||
/// about disk space.
|
||||
const MAX_PACK_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IntelManifest {
|
||||
pub schema: u32,
|
||||
/// Monotonic pack revision. Compared as a number, not a date, so a re-issue
|
||||
/// on the same day still wins.
|
||||
pub revision: u64,
|
||||
pub date: String,
|
||||
pub pack: String,
|
||||
pub sha256: String,
|
||||
pub size: u64,
|
||||
pub rules: Vec<RuleMeta>,
|
||||
}
|
||||
|
||||
/// How the bytes reached us, which is a different fact from *what* they are.
|
||||
///
|
||||
/// Both variants mean the pack's SHA-256 and byte length matched its manifest and
|
||||
/// that YARA accepted the source. Only `Verified` means a key this build knows
|
||||
/// about signed the manifest.
|
||||
///
|
||||
/// The distinction exists because the release key is baked in at build time, so a
|
||||
/// build from source has none. Refusing to update then would make rule packs a
|
||||
/// feature only the release build can use; accepting silently would let the UI
|
||||
/// print "signed" about a manifest nothing checked. So an unbaked key is accepted
|
||||
/// and remembered as unverified, and the interface says so. A build that *does*
|
||||
/// have a key and fails to verify it is an error, not a fallback.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Provenance {
|
||||
/// A baked public key verified the manifest's Ed25519 signature.
|
||||
Verified,
|
||||
/// Integrity came from the manifest's SHA-256 alone: this build has no key.
|
||||
Unverified,
|
||||
}
|
||||
|
||||
/// A pack that has been read, verified, and compiled.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pack {
|
||||
pub manifest: IntelManifest,
|
||||
pub source: String,
|
||||
pub provenance: Provenance,
|
||||
}
|
||||
|
||||
impl Pack {
|
||||
pub fn rule_count(&self) -> usize {
|
||||
self.manifest.rules.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Where packs live: `current` is what the next scan uses, `previous` is what a
|
||||
/// failed update falls back to. Keeping both is what makes a bad pack survivable.
|
||||
pub fn intel_dir() -> PathBuf {
|
||||
crate::coverage::intel_root()
|
||||
}
|
||||
|
||||
fn current_pack_path() -> PathBuf {
|
||||
intel_dir().join("current.json")
|
||||
}
|
||||
|
||||
fn previous_pack_path() -> PathBuf {
|
||||
intel_dir().join("previous.json")
|
||||
}
|
||||
|
||||
/// Validate a parsed manifest before anything reads its fields.
|
||||
pub fn validate_manifest(manifest: &IntelManifest) -> Result<(), String> {
|
||||
if manifest.schema > SUPPORTED_SCHEMA {
|
||||
return Err(format!(
|
||||
"This rule pack needs intel schema {}, which Squid {} cannot read",
|
||||
manifest.schema,
|
||||
env!("CARGO_PKG_VERSION")
|
||||
));
|
||||
}
|
||||
if !is_hex(manifest.sha256.as_bytes(), 64) {
|
||||
return Err("The rule pack manifest does not carry a SHA-256.".into());
|
||||
}
|
||||
if manifest.size == 0 || manifest.size > MAX_PACK_BYTES {
|
||||
return Err(format!(
|
||||
"The rule pack size ({} bytes) is outside what Squid will read.",
|
||||
manifest.size
|
||||
));
|
||||
}
|
||||
let file = Path::new(&manifest.pack)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
if file.is_empty() || file != manifest.pack || manifest.pack.contains("..") {
|
||||
return Err("The rule pack names a file outside its own folder.".into());
|
||||
}
|
||||
if !file.ends_with(".json") {
|
||||
return Err("The rule pack file must be a .json pack.".into());
|
||||
}
|
||||
if manifest.rules.is_empty() {
|
||||
return Err("The rule pack declares no rules.".into());
|
||||
}
|
||||
for rule in &manifest.rules {
|
||||
if rule.name.is_empty()
|
||||
|| !rule
|
||||
.name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
{
|
||||
return Err(format!(
|
||||
"Rule name {:?} is not a YARA identifier.",
|
||||
rule.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_manifest(text: &str) -> Result<IntelManifest, String> {
|
||||
let manifest: IntelManifest = serde_json::from_str(text)
|
||||
.map_err(|error| format!("The rule manifest is not readable: {error}"))?;
|
||||
validate_manifest(&manifest)?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
/// Read a downloaded pack and check it against the manifest the caller verified.
|
||||
/// Signature verification happens where the public key lives (the desktop
|
||||
/// layer), so this takes the manifest as given and proves only that *these
|
||||
/// bytes* are the pack that manifest describes.
|
||||
pub fn read_pack(
|
||||
dir: &Path,
|
||||
manifest: &IntelManifest,
|
||||
provenance: Provenance,
|
||||
) -> Result<Pack, String> {
|
||||
let path = dir.join(&manifest.pack);
|
||||
let metadata = std::fs::metadata(&path)
|
||||
.map_err(|error| format!("Could not read the rule pack: {error}"))?;
|
||||
if metadata.len() != manifest.size {
|
||||
return Err(format!(
|
||||
"{} is {} bytes, the manifest says {}.",
|
||||
manifest.pack,
|
||||
metadata.len(),
|
||||
manifest.size
|
||||
));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
|
||||
let actual = digest(&bytes);
|
||||
if !actual.eq_ignore_ascii_case(&manifest.sha256) {
|
||||
return Err(format!(
|
||||
"The rule pack hash does not match the manifest ({}).",
|
||||
short(&actual)
|
||||
));
|
||||
}
|
||||
let parsed: PackFile = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| format!("The rule pack is not readable: {error}"))?;
|
||||
if parsed.revision != manifest.revision {
|
||||
return Err("The rule pack revision does not match the manifest.".into());
|
||||
}
|
||||
// Compile before accepting: a pack YARA rejects must never become
|
||||
// `current`, because the next scan would fail at the worst moment.
|
||||
crate::rules::Detector::from_source_for_pack(&parsed.source, &manifest.rules)?;
|
||||
Ok(Pack {
|
||||
manifest: manifest.clone(),
|
||||
source: parsed.source,
|
||||
provenance,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct PackFile {
|
||||
revision: u64,
|
||||
source: String,
|
||||
}
|
||||
|
||||
/// What squid keeps on disk: the pack, together with the manifest that was
|
||||
/// verified when it was installed. One file, so no later read can pair a pack
|
||||
/// with the wrong manifest.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct PackRecord {
|
||||
manifest: IntelManifest,
|
||||
revision: u64,
|
||||
source: String,
|
||||
/// Recorded at install so the UI can still say, after a restart and with no
|
||||
/// network, whether what it is running was ever signature-verified.
|
||||
/// Defaults to the honest pessimistic answer for a record written before this
|
||||
/// field existed: nothing is claimed about the signature.
|
||||
#[serde(default = "Provenance::unverified")]
|
||||
provenance: Provenance,
|
||||
}
|
||||
|
||||
impl Provenance {
|
||||
const fn unverified() -> Provenance {
|
||||
Provenance::Unverified
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the pack file that gets published, so a pack is produced by the same
|
||||
/// code that reads one.
|
||||
pub fn pack_file(revision: u64, source: &str) -> Vec<u8> {
|
||||
let file = PackFile {
|
||||
revision,
|
||||
source: source.to_string(),
|
||||
};
|
||||
serde_json::to_vec_pretty(&file).expect("a pack file always serialises")
|
||||
}
|
||||
|
||||
/// Install a verified pack, keeping the record it replaces for rollback.
|
||||
pub fn install_pack(pack: &Pack) -> Result<(), String> {
|
||||
let dir = intel_dir();
|
||||
std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
|
||||
let current = current_pack_path();
|
||||
if current.is_file() {
|
||||
let text = std::fs::read_to_string(¤t).map_err(|error| error.to_string())?;
|
||||
std::fs::write(previous_pack_path(), text).map_err(|error| error.to_string())?;
|
||||
}
|
||||
let record = PackRecord {
|
||||
manifest: pack.manifest.clone(),
|
||||
revision: pack.manifest.revision,
|
||||
source: pack.source.clone(),
|
||||
provenance: pack.provenance,
|
||||
};
|
||||
let bytes = serde_json::to_vec_pretty(&record).map_err(|error| error.to_string())?;
|
||||
std::fs::write(¤t, bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
/// The best installed pack, falling back to the previous record when `current`
|
||||
/// has been corrupted or truncated since it was written.
|
||||
pub fn installed_pack() -> Option<Pack> {
|
||||
for path in [current_pack_path(), previous_pack_path()] {
|
||||
if let Some(pack) = read_record(&path) {
|
||||
return Some(pack);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read one stored record and re-prove it: the hash against its own manifest,
|
||||
/// and the source against the rule table. A record that fails either is treated
|
||||
/// as absent, because half a rule set is how a bad pack becomes a false sense of
|
||||
/// safety.
|
||||
pub fn read_record(path: &Path) -> Option<Pack> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let record: PackRecord = serde_json::from_str(&text).ok()?;
|
||||
validate_manifest(&record.manifest).ok()?;
|
||||
let bytes = pack_file(record.revision, &record.source);
|
||||
if bytes.len() as u64 != record.manifest.size {
|
||||
return None;
|
||||
}
|
||||
if !digest(&bytes).eq_ignore_ascii_case(&record.manifest.sha256) {
|
||||
return None;
|
||||
}
|
||||
if crate::rules::Detector::from_source_for_pack(&record.source, &record.manifest.rules).is_err()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Pack {
|
||||
manifest: record.manifest,
|
||||
source: record.source,
|
||||
provenance: record.provenance,
|
||||
})
|
||||
}
|
||||
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
/// Everything the UI shows about the installed rules, without touching the
|
||||
/// network. `builtin` is the floor: a machine that never downloaded a pack is
|
||||
/// still guarded by the compiled-in rules.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IntelStatus {
|
||||
pub builtin_rules: usize,
|
||||
pub installed_rules: usize,
|
||||
pub revision: u64,
|
||||
pub published: String,
|
||||
/// Compiled-in rules are as trusted as the binary itself; a downloaded pack is
|
||||
/// `true` only when a key this build knows about signed its manifest.
|
||||
pub signed: bool,
|
||||
pub source: String,
|
||||
pub path: String,
|
||||
pub fallback_available: bool,
|
||||
}
|
||||
|
||||
pub fn status() -> IntelStatus {
|
||||
let builtin = crate::rules::builtin_meta().len();
|
||||
match installed_pack() {
|
||||
Some(pack) => IntelStatus {
|
||||
builtin_rules: builtin,
|
||||
installed_rules: pack.rule_count(),
|
||||
revision: pack.manifest.revision,
|
||||
published: pack.manifest.date.clone(),
|
||||
signed: pack.provenance == Provenance::Verified,
|
||||
source: "pack".into(),
|
||||
path: current_pack_path().to_string_lossy().into_owned(),
|
||||
fallback_available: previous_pack_path().is_file(),
|
||||
},
|
||||
None => IntelStatus {
|
||||
builtin_rules: builtin,
|
||||
installed_rules: builtin,
|
||||
revision: 0,
|
||||
published: String::new(),
|
||||
signed: true,
|
||||
source: "builtin".into(),
|
||||
path: intel_dir().to_string_lossy().into_owned(),
|
||||
fallback_available: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Roll back one step, used when a scan reports that the newest pack misbehaves.
|
||||
pub fn rollback() -> Result<(), String> {
|
||||
let previous = previous_pack_path();
|
||||
let text = std::fs::read_to_string(&previous)
|
||||
.map_err(|_| "There is no previous rule pack to fall back to.".to_string())?;
|
||||
std::fs::write(current_pack_path(), text).map_err(|error| error.to_string())?;
|
||||
let _ = std::fs::remove_file(previous);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path of the installed record, for the UI that shows where rules came from.
|
||||
pub fn current_pack_record() -> PathBuf {
|
||||
current_pack_path()
|
||||
}
|
||||
|
||||
fn is_hex(bytes: &[u8], length: usize) -> bool {
|
||||
bytes.len() == length && bytes.iter().all(|byte| byte.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn short(value: &str) -> String {
|
||||
value.chars().take(12).collect()
|
||||
}
|
||||
|
||||
/// Rule levels as the pack spells them, checked against what the scanner will
|
||||
/// accept. A pack cannot invent a level, and cannot promote itself to
|
||||
/// `signature` for a rule the client has never seen before without saying so.
|
||||
pub fn level_is_known(level: &RuleLevel) -> bool {
|
||||
matches!(level, RuleLevel::Signature | RuleLevel::Behaviour)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The manifest that honestly describes one pack source.
|
||||
fn manifest_for(revision: u64, rule: &str, source: &str) -> IntelManifest {
|
||||
let bytes = pack_file(revision, source);
|
||||
IntelManifest {
|
||||
schema: SUPPORTED_SCHEMA,
|
||||
revision,
|
||||
date: "2026-11-06".into(),
|
||||
pack: "squid-rules.json".into(),
|
||||
sha256: digest(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
rules: vec![RuleMeta {
|
||||
name: rule.into(),
|
||||
description: "only in the pack".into(),
|
||||
family: "pack".into(),
|
||||
level: RuleLevel::Signature,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn manifest(revision: u64) -> IntelManifest {
|
||||
let source = r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#;
|
||||
let bytes = pack_file(revision, source);
|
||||
IntelManifest {
|
||||
schema: SUPPORTED_SCHEMA,
|
||||
revision,
|
||||
date: "2026-11-06".into(),
|
||||
pack: "squid-rules.json".into(),
|
||||
sha256: write_and_hash(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
rules: vec![RuleMeta {
|
||||
name: "PackOnly".into(),
|
||||
description: "only in the pack".into(),
|
||||
family: "pack".into(),
|
||||
level: RuleLevel::Signature,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn write_and_hash(bytes: &[u8]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("squid-intel-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let _ = std::fs::remove_file(dir.join("squid-rules.json"));
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pack_round_trips_through_its_manifest() {
|
||||
let dir = temp_dir("round-trip");
|
||||
let manifest = manifest(7);
|
||||
std::fs::write(
|
||||
dir.join(&manifest.pack),
|
||||
pack_file(
|
||||
7,
|
||||
r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let manifest = {
|
||||
let bytes = std::fs::read(dir.join(&manifest.pack)).unwrap();
|
||||
IntelManifest {
|
||||
sha256: write_and_hash(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
..manifest
|
||||
}
|
||||
};
|
||||
let pack =
|
||||
read_pack(&dir, &manifest, Provenance::Verified).expect("the pack should read back");
|
||||
assert_eq!(pack.rule_count(), 1);
|
||||
assert_eq!(pack.manifest.revision, 7);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_pack_is_refused_before_it_is_used() {
|
||||
let dir = temp_dir("truncated");
|
||||
let manifest = manifest(8);
|
||||
std::fs::write(dir.join(&manifest.pack), b"half a file").unwrap();
|
||||
let error = read_pack(&dir, &manifest, Provenance::Verified)
|
||||
.expect_err("size must match the manifest");
|
||||
assert!(error.contains("bytes"), "{error}");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pack_that_yara_rejects_never_installs() {
|
||||
let dir = temp_dir("broken-yara");
|
||||
let bytes = pack_file(9, "rule {{{ not yara");
|
||||
std::fs::write(dir.join("squid-rules.json"), &bytes).unwrap();
|
||||
let manifest = IntelManifest {
|
||||
schema: SUPPORTED_SCHEMA,
|
||||
revision: 9,
|
||||
date: "2026-11-06".into(),
|
||||
pack: "squid-rules.json".into(),
|
||||
sha256: write_and_hash(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
rules: vec![RuleMeta {
|
||||
name: "Whatever".into(),
|
||||
description: String::new(),
|
||||
family: "pack".into(),
|
||||
level: RuleLevel::Behaviour,
|
||||
}],
|
||||
};
|
||||
assert!(
|
||||
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
|
||||
"a pack YARA rejects must not be installable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsigned_pack_survives_the_round_trip_as_unsigned() {
|
||||
// A build with no baked key can still take updates, but must not end up
|
||||
// claiming afterwards that something verified them.
|
||||
let _guard = crate::state_guard("provenance");
|
||||
let pack = Pack {
|
||||
manifest: manifest_for(7, "ProvOnly", r#"rule ProvOnly { condition: false }"#),
|
||||
source: r#"rule ProvOnly { condition: false }"#.to_string(),
|
||||
provenance: Provenance::Unverified,
|
||||
};
|
||||
install_pack(&pack).unwrap();
|
||||
let status = status();
|
||||
assert_eq!(status.source, "pack");
|
||||
assert!(
|
||||
!status.signed,
|
||||
"the UI has to be able to tell an unverified pack from a signed one"
|
||||
);
|
||||
assert_eq!(installed_pack().unwrap().provenance, Provenance::Unverified);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_from_before_provenance_existed_is_not_assumed_signed() {
|
||||
// An old `current.json` has no provenance field. Reading it as
|
||||
// `Verified` would print a green "signed" for a pack nobody checked.
|
||||
let _guard = crate::state_guard("provenance-old");
|
||||
let pack = published_pack(8, "OldOnly", r#"rule OldOnly { condition: false }"#);
|
||||
install_pack(&pack).unwrap();
|
||||
let path = current_pack_path();
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
// The field is last in the pretty-printed object, so the comma to remove
|
||||
// is the one before it.
|
||||
let stripped = text.replace(",\n \"provenance\": \"verified\"", "");
|
||||
assert_ne!(text, stripped, "the fixture must actually carry the field");
|
||||
std::fs::write(&path, stripped).unwrap();
|
||||
let read = read_record(&path).expect("a record missing one field still reads");
|
||||
assert_eq!(read.provenance, Provenance::Unverified);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_pack_is_never_installed_even_when_the_hash_matches() {
|
||||
let dir = std::env::temp_dir().join("squid-intel-yara");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = "rule Broken { condition: this is not yara ((( }";
|
||||
let manifest = manifest_for(9, "Broken", source);
|
||||
std::fs::write(dir.join(&manifest.pack), pack_file(9, source)).unwrap();
|
||||
assert!(
|
||||
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
|
||||
"a pack YARA cannot compile must be refused"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_cannot_escape_its_folder_or_lie_about_size() {
|
||||
for escape in ["../evil.json", "/etc/passwd", "sub/dir/rules.json"] {
|
||||
let base = manifest(1);
|
||||
let dodgy = IntelManifest {
|
||||
pack: escape.into(),
|
||||
..base
|
||||
};
|
||||
assert!(
|
||||
validate_manifest(&dodgy).is_err(),
|
||||
"{escape} should be refused"
|
||||
);
|
||||
}
|
||||
let huge = IntelManifest {
|
||||
size: MAX_PACK_BYTES + 1,
|
||||
..manifest(1)
|
||||
};
|
||||
assert!(validate_manifest(&huge).is_err());
|
||||
let no_hash = IntelManifest {
|
||||
sha256: "deadbeef".into(),
|
||||
..manifest(1)
|
||||
};
|
||||
assert!(validate_manifest(&no_hash).is_err());
|
||||
let empty = IntelManifest {
|
||||
rules: Vec::new(),
|
||||
..manifest(1)
|
||||
};
|
||||
assert!(validate_manifest(&empty).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_schema_is_refused_rather_than_misread() {
|
||||
let newer = IntelManifest {
|
||||
schema: SUPPORTED_SCHEMA + 1,
|
||||
..manifest(1)
|
||||
};
|
||||
let error = validate_manifest(&newer).expect_err("schema must be checked");
|
||||
assert!(error.contains("schema"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_names_must_be_yara_identifiers() {
|
||||
let dodgy = IntelManifest {
|
||||
rules: vec![RuleMeta {
|
||||
name: "not a rule name".into(),
|
||||
description: String::new(),
|
||||
family: String::new(),
|
||||
level: RuleLevel::Behaviour,
|
||||
}],
|
||||
..manifest(1)
|
||||
};
|
||||
assert!(validate_manifest(&dodgy).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_builtin_pack_reports_itself_without_any_download() {
|
||||
let _guard = crate::state_guard("builtin");
|
||||
let status = status();
|
||||
assert_eq!(status.source, "builtin");
|
||||
assert_eq!(status.revision, 0);
|
||||
assert!(status.installed_rules >= status.builtin_rules);
|
||||
assert!(
|
||||
status.signed,
|
||||
"compiled-in rules are as trusted as the binary"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installing_a_pack_keeps_the_previous_one_and_can_roll_back() {
|
||||
let _guard = crate::state_guard("rollback");
|
||||
let first = published_pack(10, "PackOnly", r#"rule PackOnly { condition: false }"#);
|
||||
let second = published_pack(
|
||||
11,
|
||||
"PackOnlyTwo",
|
||||
r#"rule PackOnlyTwo { condition: false }"#,
|
||||
);
|
||||
install_pack(&first).unwrap();
|
||||
install_pack(&second).unwrap();
|
||||
assert!(
|
||||
previous_pack_path().is_file(),
|
||||
"the record it replaced is kept"
|
||||
);
|
||||
assert_eq!(installed_pack().unwrap().manifest.revision, 11);
|
||||
|
||||
rollback().unwrap();
|
||||
let back = installed_pack().expect("rollback restores the older pack");
|
||||
assert_eq!(back.manifest.revision, 10);
|
||||
}
|
||||
|
||||
/// Build a pack the way an update does: the source first, then a manifest
|
||||
/// that honestly describes those exact bytes.
|
||||
fn published_pack(revision: u64, rule: &str, source: &str) -> Pack {
|
||||
Pack {
|
||||
manifest: manifest_for(revision, rule, source),
|
||||
source: source.to_string(),
|
||||
provenance: Provenance::Verified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
//! squid-guard — the security half of squid.
|
||||
//!
|
||||
//! Position matters more than ambition here. XProtect (macOS) and Defender
|
||||
//! (Windows) remain the real-time protection of this machine; squid does not
|
||||
//! replace them, does not copy their rules, and does not install anything that
|
||||
//! runs before execve. What this crate adds is the part those engines leave to
|
||||
//! the owner of the machine: an inventory of *what* starts at login, an
|
||||
//! evidence-grade scan of the files behind that inventory and the obvious
|
||||
//! user-writable run locations, and a reversible quarantine that never deletes.
|
||||
//!
|
||||
//! Two rules keep the crate honest:
|
||||
//!
|
||||
//! 1. A scan never removes anything. It produces [`finding::Finding`]s with
|
||||
//! evidence, and only an explicit user decision (or the opt-in automatic
|
||||
//! quarantine, confirmed-level only) moves a file.
|
||||
//! 2. Findings are addressed by backend-issued id, never by path. The caller
|
||||
//! cannot quarantine a file the scan never reported.
|
||||
//!
|
||||
//! Detection is layered so a weak layer can never masquerade as a strong one:
|
||||
//!
|
||||
//! - a SHA-256 blacklist answers "is this exact file known bad" (`confirmed`);
|
||||
//! - YARA-X rules answer "does this file match a known family" (`confirmed` for
|
||||
//! high-confidence rules, `suspicious` otherwise);
|
||||
//! - heuristics answer "would a careful person look at this twice"
|
||||
//! (`suspicious`/`advisory`) and never quarantine on their own.
|
||||
|
||||
pub mod coverage;
|
||||
pub mod findings;
|
||||
pub mod heuristics;
|
||||
pub mod intel;
|
||||
pub mod quarantine;
|
||||
pub mod rules;
|
||||
pub mod scan;
|
||||
pub mod store;
|
||||
|
||||
pub use findings::{Confidence, Evidence, Finding};
|
||||
pub use quarantine::{QuarantineEntry, QuarantineLedger};
|
||||
pub use scan::{ScanMode, ScanReport as GuardReport, ScanTarget};
|
||||
pub use store::Store;
|
||||
|
||||
/// Crate version tag written into the quarantine ledger, mirroring the
|
||||
/// cleanup ledger's habit of stamping the format it was written by.
|
||||
pub const LEDGER_TAG: &str = concat!("squid-guard/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// Tests that touch on-disk state share one lock, because the state directory is
|
||||
/// chosen by a process-wide environment variable. Without it, a quarantine test
|
||||
/// can reopen its ledger in whatever directory an intel test pointed the process
|
||||
/// at a moment earlier.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn state_guard(tag: &str) -> std::sync::MutexGuard<'static, ()> {
|
||||
static GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
let guard = GUARD
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let dir = std::env::temp_dir().join(format!("squid-guard-state-{tag}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("a test can create its own state directory");
|
||||
std::env::set_var("SQUID_STATE_DIR", &dir);
|
||||
guard
|
||||
}
|
||||
|
|
@ -0,0 +1,682 @@
|
|||
//! The quarantine: files squid moved out of the way, and the record that lets
|
||||
//! them go back.
|
||||
//!
|
||||
//! Three properties are worth stating because they are what distinguishes this
|
||||
//! from "delete" and from the system Trash:
|
||||
//!
|
||||
//! - **Reversible until told otherwise.** Each object keeps its original path,
|
||||
//! mode and timestamps, so `restore` can put it back where it came from.
|
||||
//! - **Inert.** Files land in squid's own state folder with the execute bit
|
||||
//! cleared and owner-only permissions, so a quarantined login item cannot run
|
||||
//! again while it waits there.
|
||||
//! - **Owned by squid.** The Trash is the operating system's, and sending a
|
||||
//! suspected binary there means the user has to remember to empty it. Here the
|
||||
//! ledger and the objects sit together, and the UI can say exactly what is in
|
||||
//! the way.
|
||||
//!
|
||||
//! The ledger is the authority. A file is quarantined because the ledger says
|
||||
//! so, and every operation re-reads the ledger before touching the disk, so a
|
||||
//! half-finished move on a full disk shows up as an honest error rather than a
|
||||
//! file in two places.
|
||||
|
||||
use crate::coverage::quarantine_root;
|
||||
use crate::findings::{Evidence, Finding};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use squid_core::paths;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// One quarantined object, as recorded before anything was moved.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QuarantineEntry {
|
||||
pub id: String,
|
||||
/// Where the file lived. Kept for restore, never trusted as-is.
|
||||
pub original_path: PathBuf,
|
||||
pub display_path: String,
|
||||
/// Relative name inside the quarantine folder.
|
||||
pub stored: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
/// Unix mode, or the Windows read-only flag folded into it.
|
||||
pub mode: u32,
|
||||
pub modified_ms: u64,
|
||||
pub quarantined_ms: u64,
|
||||
/// Why it was moved, kept so the list can explain itself a month later.
|
||||
pub title: String,
|
||||
pub confidence: String,
|
||||
pub evidence: Vec<Evidence>,
|
||||
}
|
||||
|
||||
/// The quarantine folder's own ledger. Written beside the objects so the whole
|
||||
/// thing can be inspected, copied or deleted by hand.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QuarantineLedger {
|
||||
pub version: u32,
|
||||
pub entries: Vec<QuarantineEntry>,
|
||||
}
|
||||
|
||||
impl QuarantineLedger {
|
||||
fn load(path: &Path) -> QuarantineLedger {
|
||||
std::fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or(QuarantineLedger {
|
||||
version: 1,
|
||||
entries: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn save(&self, path: &Path) -> Result<(), String> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
}
|
||||
let text = serde_json::to_string_pretty(self).map_err(|error| error.to_string())?;
|
||||
std::fs::write(path, text).map_err(|error| error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn ledger_path() -> PathBuf {
|
||||
quarantine_root().join("ledger.json")
|
||||
}
|
||||
|
||||
fn objects_dir() -> PathBuf {
|
||||
quarantine_root().join("objects")
|
||||
}
|
||||
|
||||
/// The quarantine, opened for one session of the app.
|
||||
#[derive(Default)]
|
||||
pub struct Quarantine {
|
||||
ledger: QuarantineLedger,
|
||||
loaded: bool,
|
||||
}
|
||||
|
||||
impl Quarantine {
|
||||
pub fn new() -> Quarantine {
|
||||
Quarantine::default()
|
||||
}
|
||||
|
||||
fn ensure_loaded(&mut self) {
|
||||
if !self.loaded {
|
||||
self.ledger = QuarantineLedger::load(&ledger_path());
|
||||
self.loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the ledger recorded. Reading the list is what loads the
|
||||
/// ledger, so a freshly opened quarantine describes what is on disk rather
|
||||
/// than an empty list that would offer "quarantine" for a file already moved.
|
||||
pub fn entries(&mut self) -> &[QuarantineEntry] {
|
||||
self.ensure_loaded();
|
||||
&self.ledger.entries
|
||||
}
|
||||
|
||||
pub fn find(&mut self, id: &str) -> Option<&QuarantineEntry> {
|
||||
self.ensure_loaded();
|
||||
self.ledger.entries.iter().find(|entry| entry.id == id)
|
||||
}
|
||||
|
||||
/// Move one finding into the quarantine.
|
||||
///
|
||||
/// The finding is what the scan reported; nothing here accepts a bare path.
|
||||
/// Before moving, the file is re-hashed and compared with the value recorded
|
||||
/// at scan time, so a file that changed between "found" and "quarantine" is
|
||||
/// reported rather than moved: the bytes the user decided about are not the
|
||||
/// bytes on disk.
|
||||
pub fn quarantine(&mut self, finding: &Finding) -> Result<QuarantineEntry, String> {
|
||||
self.ensure_loaded();
|
||||
let path = finding
|
||||
.path
|
||||
.as_ref()
|
||||
.ok_or_else(|| "This finding has no file to quarantine.".to_string())?;
|
||||
let refused = refusal(path)?;
|
||||
if let Some(reason) = refused {
|
||||
return Err(reason);
|
||||
}
|
||||
|
||||
let metadata = std::fs::symlink_metadata(path).map_err(|error| error.to_string())?;
|
||||
if !metadata.is_file() {
|
||||
return Err(
|
||||
"Only single files can be quarantined — a folder needs the uninstaller.".into(),
|
||||
);
|
||||
}
|
||||
let is_link = metadata.file_type().is_symlink();
|
||||
if is_link {
|
||||
return Err("A symbolic link is not the file that was scanned.".into());
|
||||
}
|
||||
if metadata.len() != finding.size {
|
||||
return Err(format!(
|
||||
"{} changed size since the scan. Run the scan again.",
|
||||
paths::pretty(path)
|
||||
));
|
||||
}
|
||||
let hash = hash_file(path)?;
|
||||
if let Some(expected) = finding.sha256.as_deref() {
|
||||
if !expected.eq_ignore_ascii_case(&hash) {
|
||||
return Err(format!(
|
||||
"{} changed since the scan. Run the scan again.",
|
||||
paths::pretty(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let id = new_id(path, &hash);
|
||||
if self.ledger.entries.iter().any(|entry| entry.id == id) {
|
||||
return Err("This file is already in the quarantine.".into());
|
||||
}
|
||||
// Two scans of the same bytes in different places get different ids,
|
||||
// because the original path is part of what restore needs.
|
||||
let stored = format!("{id}.bin");
|
||||
let destination = objects_dir().join(&stored);
|
||||
if destination.exists() {
|
||||
return Err("The quarantine already holds an object with this name.".into());
|
||||
}
|
||||
|
||||
// Read the mode before anything else happens to the file: the stored
|
||||
// copy is deliberately made inert below, and restore has to hand back
|
||||
// what the file was, not what the quarantine keeps it as.
|
||||
let mode = current_mode(path);
|
||||
|
||||
std::fs::create_dir_all(objects_dir()).map_err(|error| error.to_string())?;
|
||||
std::fs::rename(path, &destination).or_else(|rename_error| {
|
||||
// Renaming fails across volumes, which is normal for an external
|
||||
// disk or a DMG that is still mounted.
|
||||
std::fs::copy(path, &destination)
|
||||
.map_err(|copy_error| {
|
||||
format!(
|
||||
"Could not move the file into the quarantine: {rename_error}; copy failed: {copy_error}"
|
||||
)
|
||||
})
|
||||
.and_then(|_| std::fs::remove_file(path).map_err(|error| error.to_string()))
|
||||
})?;
|
||||
|
||||
// Make the object inert while it waits: no execute, readable only by the
|
||||
// owner who chose to quarantine it.
|
||||
restrict_permissions(&destination);
|
||||
|
||||
let entry = QuarantineEntry {
|
||||
id: id.clone(),
|
||||
original_path: path.clone(),
|
||||
display_path: paths::pretty(path),
|
||||
stored,
|
||||
size: metadata.len(),
|
||||
sha256: hash,
|
||||
mode,
|
||||
modified_ms: metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|since| since.as_millis() as u64)
|
||||
.unwrap_or_default(),
|
||||
quarantined_ms: now_ms(),
|
||||
title: finding.title.clone(),
|
||||
confidence: finding.confidence.as_str().to_string(),
|
||||
evidence: finding.evidence.clone(),
|
||||
};
|
||||
self.ledger.entries.push(entry.clone());
|
||||
if let Err(error) = self.ledger.save(&ledger_path()) {
|
||||
// The file is already in place, so undo the move rather than leave a
|
||||
// file the ledger does not know about.
|
||||
let _ = std::fs::rename(&destination, path);
|
||||
self.ledger.entries.retain(|kept| kept.id != id);
|
||||
return Err(format!("Could not record the quarantine: {error}"));
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
/// Put one object back where it came from.
|
||||
pub fn restore(&mut self, id: &str) -> Result<PathBuf, String> {
|
||||
self.ensure_loaded();
|
||||
let index = self
|
||||
.ledger
|
||||
.entries
|
||||
.iter()
|
||||
.position(|entry| entry.id == id)
|
||||
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
|
||||
let entry = self.ledger.entries[index].clone();
|
||||
let stored = objects_dir().join(&entry.stored);
|
||||
if !stored.is_file() {
|
||||
return Err(format!(
|
||||
"The quarantined copy of {} is gone from disk.",
|
||||
entry.display_path
|
||||
));
|
||||
}
|
||||
if entry.original_path.exists() {
|
||||
return Err(format!(
|
||||
"{} is there again. Squid will not overwrite it.",
|
||||
entry.display_path
|
||||
));
|
||||
}
|
||||
if let Some(parent) = entry.original_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
}
|
||||
std::fs::rename(&stored, &entry.original_path).or_else(|error| {
|
||||
std::fs::copy(&stored, &entry.original_path)
|
||||
.map_err(|copy| format!("Could not restore the file: {error}; {copy}"))
|
||||
.and_then(|_| std::fs::remove_file(&stored).map_err(|error| error.to_string()))
|
||||
})?;
|
||||
restore_permissions(&entry.original_path, entry.mode);
|
||||
|
||||
// A byte-for-byte check is the only proof that restore worked: the file
|
||||
// is back, in one place, with the content that was taken out.
|
||||
let restored_hash = hash_file(&entry.original_path)?;
|
||||
if !restored_hash.eq_ignore_ascii_case(&entry.sha256) {
|
||||
return Err(format!(
|
||||
"{} came back with different bytes; the quarantine copy was kept.",
|
||||
entry.display_path
|
||||
));
|
||||
}
|
||||
self.ledger.entries.remove(index);
|
||||
self.ledger.save(&ledger_path())?;
|
||||
Ok(entry.original_path)
|
||||
}
|
||||
|
||||
/// Throw one object away for real. This is the only place in the security
|
||||
/// half of squid that destroys user data, so it is only reachable from the
|
||||
/// quarantine list, never from a scan.
|
||||
pub fn purge(&mut self, id: &str) -> Result<(), String> {
|
||||
self.ensure_loaded();
|
||||
let index = self
|
||||
.ledger
|
||||
.entries
|
||||
.iter()
|
||||
.position(|entry| entry.id == id)
|
||||
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
|
||||
let entry = self.ledger.entries.remove(index);
|
||||
let stored = objects_dir().join(&entry.stored);
|
||||
let result = match std::fs::remove_file(&stored) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => self.ledger.save(&ledger_path()),
|
||||
Err(error) => {
|
||||
self.ledger.entries.insert(index, entry);
|
||||
Err(format!("Could not delete the quarantined copy: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconcile the ledger with the folder. Deleting objects by hand, or an
|
||||
/// interrupted release upgrade, can leave entries whose file is gone; the UI
|
||||
/// must not offer "restore" for something that is not there.
|
||||
pub fn reconcile(&mut self) -> Vec<String> {
|
||||
self.ensure_loaded();
|
||||
let mut lost = Vec::new();
|
||||
self.ledger.entries.retain(|entry| {
|
||||
let present = objects_dir().join(&entry.stored).is_file();
|
||||
if !present {
|
||||
lost.push(entry.id.clone());
|
||||
}
|
||||
present
|
||||
});
|
||||
if !lost.is_empty() {
|
||||
let _ = self.ledger.save(&ledger_path());
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
pub fn total_size(&mut self) -> u64 {
|
||||
self.ledger.entries.iter().map(|entry| entry.size).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// The paths a quarantine must never touch, whatever a scan claimed. Checked at
|
||||
/// move time rather than trusted from the scan, because the scan is a snapshot
|
||||
/// of an opinion and this is the moment data actually moves.
|
||||
fn refusal(path: &Path) -> Result<Option<String>, String> {
|
||||
const PROTECTED: [&str; 6] = [
|
||||
"/System",
|
||||
"/usr",
|
||||
"/bin",
|
||||
"/sbin",
|
||||
"/Library/Apple",
|
||||
"/Applications/Utilities",
|
||||
];
|
||||
if PROTECTED.iter().any(|prefix| path.starts_with(prefix)) {
|
||||
return Ok(Some(
|
||||
"Squid does not quarantine files inside the operating system.".into(),
|
||||
));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Ok(system) = std::env::var("SystemRoot") {
|
||||
if path.starts_with(system) {
|
||||
return Ok(Some(
|
||||
"Squid does not quarantine files inside Windows.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if path.starts_with(quarantine_root()) {
|
||||
return Ok(Some("That file is already in the quarantine.".into()));
|
||||
}
|
||||
if path.starts_with(squid_core::Settings::state_dir())
|
||||
|| path.starts_with(squid_core::Settings::config_dir())
|
||||
{
|
||||
return Ok(Some("That file belongs to Squid itself.".into()));
|
||||
}
|
||||
if is_own_binary(path) {
|
||||
return Ok(Some("That is the app you are using right now.".into()));
|
||||
}
|
||||
if !std::fs::symlink_metadata(path).is_ok() {
|
||||
return Ok(Some("The file is not there any more.".into()));
|
||||
}
|
||||
// The current user has to own it, or be able to write its folder: without
|
||||
// that, moving the file needs rights this release does not ask for.
|
||||
if !squid_platform::is_user_writable(path.parent().unwrap_or(path)) {
|
||||
return Ok(Some(
|
||||
"You do not have permission to move a file from that folder.".into(),
|
||||
));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn is_own_binary(path: &Path) -> bool {
|
||||
let Ok(current) = std::env::current_exe() else {
|
||||
return false;
|
||||
};
|
||||
paths::same_path(¤t, path)
|
||||
|| current
|
||||
.ancestors()
|
||||
.zip(path.ancestors())
|
||||
.all(|(a, b)| a == b)
|
||||
&& path.starts_with(current.parent().unwrap_or(Path::new("/")))
|
||||
}
|
||||
|
||||
fn hash_file(path: &Path) -> Result<String, String> {
|
||||
let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = vec![0_u8; 128 * 1024];
|
||||
loop {
|
||||
let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
digest.update(&buffer[..read]);
|
||||
}
|
||||
Ok(hex::encode(digest.finalize()))
|
||||
}
|
||||
|
||||
fn new_id(path: &Path, hash: &str) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(path.to_string_lossy().as_bytes());
|
||||
digest.update(hash.as_bytes());
|
||||
let full = hex::encode(digest.finalize());
|
||||
full[..20].to_string()
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|since| since.as_millis() as u64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn restrict_permissions(path: &Path) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn restrict_permissions(path: &Path) {
|
||||
if let Ok(metadata) = std::fs::metadata(path) {
|
||||
let mut permissions = metadata.permissions();
|
||||
permissions.set_readonly(true);
|
||||
let _ = std::fs::set_permissions(path, permissions);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn restrict_permissions(_path: &Path) {}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn current_mode(path: &Path) -> u32 {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::metadata(path)
|
||||
.map(|metadata| metadata.permissions().mode())
|
||||
.unwrap_or(0o644)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn current_mode(_path: &Path) -> u32 {
|
||||
0o644
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn restore_permissions(path: &Path, mode: u32) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restore_permissions(path: &Path, mode: u32) {
|
||||
if let Ok(metadata) = std::fs::metadata(path) {
|
||||
let mut permissions = metadata.permissions();
|
||||
permissions.set_readonly(mode & 0o200 == 0);
|
||||
let _ = std::fs::set_permissions(path, permissions);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::findings::Confidence;
|
||||
use std::io::Write;
|
||||
|
||||
fn finding_for(path: &Path) -> Finding {
|
||||
let hash = hash_file(path).unwrap();
|
||||
Finding {
|
||||
id: "f1".into(),
|
||||
confidence: Confidence::Confirmed,
|
||||
path: Some(path.to_path_buf()),
|
||||
display_path: Some(paths::pretty(path)),
|
||||
name: "probe".into(),
|
||||
title: "test finding".into(),
|
||||
description: String::new(),
|
||||
evidence: vec![Evidence::DeniedHash {
|
||||
sha256: hash.clone(),
|
||||
threat: "probe".into(),
|
||||
}],
|
||||
size: std::fs::metadata(path).unwrap().len(),
|
||||
sha256: Some(hash),
|
||||
signed: false,
|
||||
publisher: None,
|
||||
found_at_ms: now_ms(),
|
||||
quarantined: false,
|
||||
ignored: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn probe(name: &str, bytes: &[u8]) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("squid-quarantine-{name}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("payload.bin");
|
||||
let mut file = std::fs::File::create(&path).unwrap();
|
||||
file.write_all(bytes).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
/// Quarantine paths come from `Settings::state_dir()`, which honours
|
||||
/// `SQUID_STATE_DIR`. Every test that touches the ledger takes this lock and
|
||||
/// points the state directory at its own folder, so the suite neither sees
|
||||
/// the real quarantine nor leaves debris in it.
|
||||
/// Quarantine paths come from `Settings::state_dir()`, which honours
|
||||
/// `SQUID_STATE_DIR`, and that variable is process-wide. So each ledger test
|
||||
/// holds one lock for its whole body and gets a freshly emptied directory of
|
||||
/// its own: no test sees another's entries, and none of them touch the real
|
||||
|
||||
#[test]
|
||||
fn quarantine_and_restore_round_trip_is_byte_identical() {
|
||||
let _guard = crate::state_guard("round-trip");
|
||||
let path = probe("round-trip", b"the payload that has to come back");
|
||||
let before = std::fs::metadata(&path).unwrap();
|
||||
let mut quarantine = Quarantine::new();
|
||||
let entry = quarantine
|
||||
.quarantine(&finding_for(&path))
|
||||
.expect("quarantine should accept a file the test owns");
|
||||
assert!(!path.exists(), "the file should have moved");
|
||||
assert!(!entry.stored.is_empty());
|
||||
|
||||
let restored = quarantine.restore(&entry.id).expect("restore");
|
||||
assert_eq!(restored, path);
|
||||
assert_eq!(
|
||||
std::fs::read(&path).unwrap(),
|
||||
b"the payload that has to come back"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().len(),
|
||||
before.len(),
|
||||
"the file should be back at its original size"
|
||||
);
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restoring_restores_the_execute_bit() {
|
||||
let _guard = crate::state_guard("execute-bit");
|
||||
let path = probe("execute-bit", b"#!/bin/sh\n");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_ne!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
|
||||
0,
|
||||
"the probe should start executable"
|
||||
);
|
||||
}
|
||||
let mut quarantine = Quarantine::new();
|
||||
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let stored = objects_dir().join(&entry.stored);
|
||||
assert_eq!(
|
||||
std::fs::metadata(stored).unwrap().permissions().mode() & 0o111,
|
||||
0,
|
||||
"a quarantined file must not be executable"
|
||||
);
|
||||
}
|
||||
quarantine.restore(&entry.id).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_ne!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
|
||||
0,
|
||||
"restore should hand the execute bit back"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_changed_after_the_scan_is_not_moved() {
|
||||
let _guard = crate::state_guard("changed");
|
||||
let path = probe("changed", b"original bytes");
|
||||
let finding = finding_for(&path);
|
||||
std::fs::write(&path, b"somebody else rewrote this file").unwrap();
|
||||
let error = Quarantine::new()
|
||||
.quarantine(&finding)
|
||||
.expect_err("the file no longer matches the scan");
|
||||
assert!(
|
||||
error.contains("changed"),
|
||||
"the message should say the file changed: {error}"
|
||||
);
|
||||
assert!(path.exists(), "a refused quarantine must not move anything");
|
||||
|
||||
let finding = finding_for(&path);
|
||||
let mut quarantine = Quarantine::new();
|
||||
let entry = quarantine.quarantine(&finding).expect("a fresh scan works");
|
||||
quarantine.restore(&entry.id).unwrap();
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_and_squid_itself_are_never_quarantined() {
|
||||
let _guard = crate::state_guard("protected");
|
||||
let mut quarantine = Quarantine::new();
|
||||
for path in [
|
||||
Path::new("/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder"),
|
||||
Path::new("/usr/bin/true"),
|
||||
] {
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let error = quarantine
|
||||
.quarantine(&finding_for(path))
|
||||
.expect_err("an OS file must be refused");
|
||||
assert!(error.contains("operating system"), "{path:?}: {error}");
|
||||
assert!(path.is_file(), "{path:?} must still be where it was");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purging_deletes_only_the_quarantined_copy() {
|
||||
let _guard = crate::state_guard("purge");
|
||||
let path = probe("purge", b"this one is thrown away");
|
||||
let mut quarantine = Quarantine::new();
|
||||
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
|
||||
assert!(!path.exists());
|
||||
quarantine.purge(&entry.id).unwrap();
|
||||
assert!(!objects_dir().join(&entry.stored).exists());
|
||||
assert!(quarantine.entries().iter().all(|kept| kept.id != entry.id));
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ledger_survives_a_new_session_and_notices_lost_objects() {
|
||||
let _guard = crate::state_guard("ledger");
|
||||
let path = probe("ledger", b"survive the restart");
|
||||
let mut session = Quarantine::new();
|
||||
let entry = session.quarantine(&finding_for(&path)).unwrap();
|
||||
drop(session);
|
||||
|
||||
let mut reopened = Quarantine::new();
|
||||
assert!(
|
||||
reopened.find(&entry.id).is_some(),
|
||||
"the ledger must describe the quarantine after a restart"
|
||||
);
|
||||
|
||||
let stored = objects_dir().join(&entry.stored);
|
||||
std::fs::remove_file(&stored).unwrap();
|
||||
let mut third = Quarantine::new();
|
||||
let lost = third.reconcile();
|
||||
assert_eq!(lost, vec![entry.id.clone()]);
|
||||
assert!(third.find(&entry.id).is_none());
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_refuses_to_overwrite_a_file_that_came_back() {
|
||||
let _guard = crate::state_guard("collision");
|
||||
let path = probe("collision", b"moved away then reappeared");
|
||||
let mut quarantine = Quarantine::new();
|
||||
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
|
||||
std::fs::write(&path, b"the app re-created itself").unwrap();
|
||||
let error = quarantine
|
||||
.restore(&entry.id)
|
||||
.expect_err("restoring over a live file would lose data");
|
||||
assert!(error.contains("again"), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"the app re-created itself");
|
||||
quarantine.purge(&entry.id).unwrap();
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_id_names_the_same_file_and_bytes() {
|
||||
let a = new_id(Path::new("/tmp/x"), "aa");
|
||||
assert_eq!(a, new_id(Path::new("/tmp/x"), "aa"));
|
||||
assert_ne!(a, new_id(Path::new("/tmp/x"), "bb"));
|
||||
assert_ne!(a, new_id(Path::new("/tmp/y"), "aa"));
|
||||
assert_eq!(a.len(), 20);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,922 @@
|
|||
//! The two published detectors: a SHA-256 blacklist and a YARA-X rule set.
|
||||
//!
|
||||
//! Both are compiled once per scan and shared across workers. The YARA set is
|
||||
//! built into the binary so a scan works with the network off and before any
|
||||
//! rule pack has been downloaded, and an external pack can add to it; the pack
|
||||
//! format and its signature live in [`crate::intel`].
|
||||
//!
|
||||
//! What is *not* here matters as much as what is. Apple's XProtect signatures
|
||||
//! are not redistributed — macOS applies them itself, and squid reports that
|
||||
//! fact instead of borrowing Apple's authority. The built-in set is therefore
|
||||
//! small, explicit, and self-contained: the EICAR test file, so "the pipeline
|
||||
//! works" is testable on any machine, plus a handful of behaviour rules that
|
||||
//! describe what the scanner can actually see in a startup item or a browser
|
||||
//! extension. Every rule states the level it can support, and a behaviour rule
|
||||
//! can only ever support `suspicious`.
|
||||
|
||||
use crate::findings::{Confidence, Evidence};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
/// One compiled YARA rule plus the squid-side metadata YARA itself does not
|
||||
/// carry: how much weight a match deserves.
|
||||
pub struct Detector {
|
||||
pub rules: yara_x::Rules,
|
||||
/// Rule name → (description, family, level).
|
||||
pub meta: Vec<RuleMeta>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RuleMeta {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub family: String,
|
||||
pub level: RuleLevel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RuleLevel {
|
||||
/// A published signature for a named threat: enough to call it confirmed.
|
||||
Signature,
|
||||
/// A behaviour or structure pattern: worth a look, never a verdict.
|
||||
Behaviour,
|
||||
}
|
||||
|
||||
/// The built-in source. Rule metadata is mirrored in `meta()` because YARA's
|
||||
/// own `meta` block is typed loosely and squid wants the level to be a type.
|
||||
const BUILTIN_YARA: &str = r#"
|
||||
import "macho"
|
||||
import "pe"
|
||||
|
||||
rule Eicar_Test_File
|
||||
{
|
||||
meta:
|
||||
description = "The EICAR anti-malware test string"
|
||||
family = "EICAR-Test-File"
|
||||
strings:
|
||||
$a = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" ascii wide
|
||||
condition:
|
||||
$a
|
||||
}
|
||||
|
||||
rule ShellPayloadInUserData
|
||||
{
|
||||
meta:
|
||||
description = "Shell commands that pipe a download straight into an interpreter"
|
||||
family = "behaviour"
|
||||
strings:
|
||||
$curl = /curl[ \t]+-s[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
|
||||
$wget = /wget[ \t]+-q[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
|
||||
$osascript = "osascript -e" ascii wide
|
||||
$eval = "eval $(curl" ascii wide
|
||||
condition:
|
||||
filesize < 2MB and 2 of them
|
||||
}
|
||||
|
||||
rule LoginItemPointsAtTemp
|
||||
{
|
||||
meta:
|
||||
description = "A launch plist whose program lives in a temporary directory"
|
||||
family = "behaviour"
|
||||
strings:
|
||||
$var = "/var/folders/" ascii wide
|
||||
$tmp = "/tmp/" ascii wide
|
||||
$prog1 = "<key>Program</key>" ascii wide
|
||||
$prog2 = "<key>ProgramArguments</key>" ascii wide
|
||||
condition:
|
||||
filesize < 256KB and ($prog1 or $prog2) and ($var or $tmp)
|
||||
}
|
||||
|
||||
rule ExtensionHostsPermission
|
||||
{
|
||||
meta:
|
||||
description = "A browser extension manifest that asks to read every site it visits"
|
||||
family = "behaviour"
|
||||
strings:
|
||||
$host = "\"<all_urls>\"" ascii wide
|
||||
$tabs = "\"tabs\"" ascii wide
|
||||
$debug = "\"debugger\"" ascii wide
|
||||
$name = "\"manifest_version\"" ascii wide
|
||||
condition:
|
||||
filesize < 64KB and $name and $host and ($tabs or $debug)
|
||||
}
|
||||
|
||||
rule ScriptedOfficeMacro
|
||||
{
|
||||
meta:
|
||||
description = "A document carrying an auto-run macro that starts a program"
|
||||
family = "behaviour"
|
||||
strings:
|
||||
$a = "AutoOpen" ascii wide
|
||||
$b = "AutoExec" ascii wide
|
||||
$c = "Shell(" ascii wide
|
||||
$d = "MacScript" ascii wide
|
||||
condition:
|
||||
filesize < 32MB and 3 of them
|
||||
}
|
||||
|
||||
rule MachoDylibFromWritablePath
|
||||
{
|
||||
meta:
|
||||
description = "A binary that loads a library from a folder the user can rewrite"
|
||||
family = "behaviour"
|
||||
condition:
|
||||
macho.number_of_segments > 0
|
||||
and for any d in macho.dylibs : (
|
||||
d.name matches /^\/(Users|tmp|private\/tmp|var\/folders)\//
|
||||
)
|
||||
}
|
||||
|
||||
rule PeWithoutVersionInfo
|
||||
{
|
||||
meta:
|
||||
description = "A Windows binary that names nobody in its version resource"
|
||||
family = "behaviour"
|
||||
condition:
|
||||
pe.number_of_sections > 1 and pe.number_of_version_infos == 0
|
||||
}
|
||||
|
||||
rule PeUnnamedSection
|
||||
{
|
||||
meta:
|
||||
description = "A Windows binary with a section packers leave nameless"
|
||||
family = "behaviour"
|
||||
condition:
|
||||
pe.number_of_sections > 0
|
||||
and for any s in pe.sections : ( s.name == "" )
|
||||
}
|
||||
"#;
|
||||
|
||||
/// The metadata table for the source above. A rule that matches is only as
|
||||
/// strong as the level stated here, and behaviour rules can never reach
|
||||
/// `confirmed` no matter how many of them fire at once.
|
||||
pub fn builtin_meta() -> Vec<RuleMeta> {
|
||||
let behaviour = |name: &str, description: &str| RuleMeta {
|
||||
name: name.into(),
|
||||
description: description.into(),
|
||||
family: "behaviour".into(),
|
||||
level: RuleLevel::Behaviour,
|
||||
};
|
||||
vec![
|
||||
RuleMeta {
|
||||
name: "Eicar_Test_File".into(),
|
||||
description: "The standard anti-malware test string".into(),
|
||||
family: "EICAR-Test-File".into(),
|
||||
level: RuleLevel::Signature,
|
||||
},
|
||||
behaviour(
|
||||
"ShellPayloadInUserData",
|
||||
"Shell commands that pipe a download straight into an interpreter",
|
||||
),
|
||||
behaviour(
|
||||
"LoginItemPointsAtTemp",
|
||||
"A launch plist whose program lives in a temporary directory",
|
||||
),
|
||||
behaviour(
|
||||
"ExtensionHostsPermission",
|
||||
"A browser extension manifest that asks to read every site it visits",
|
||||
),
|
||||
behaviour(
|
||||
"ScriptedOfficeMacro",
|
||||
"A document carrying an auto-run macro that starts a program",
|
||||
),
|
||||
behaviour(
|
||||
"MachoDylibFromWritablePath",
|
||||
"A binary that loads a library from a folder the user can rewrite",
|
||||
),
|
||||
behaviour(
|
||||
"PeWithoutVersionInfo",
|
||||
"A Windows binary that names nobody in its version resource",
|
||||
),
|
||||
behaviour(
|
||||
"PeUnnamedSection",
|
||||
"A Windows binary with a section packers leave nameless",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
impl Detector {
|
||||
/// Compile the built-in rules. A failure here is a build bug, not a runtime
|
||||
/// condition, so it surfaces as an error the caller reports rather than a
|
||||
/// silently empty detector.
|
||||
pub fn builtin() -> Result<Detector, String> {
|
||||
Self::from_source(BUILTIN_YARA, builtin_meta())
|
||||
}
|
||||
|
||||
/// Built-in rules plus an external pack. If the pack fails to compile, the
|
||||
/// caller decides whether to fall back; this function does not hide that.
|
||||
pub fn with_extra(extra_sources: &[(String, Vec<RuleMeta>)]) -> Result<Detector, String> {
|
||||
let mut source = String::from(BUILTIN_YARA);
|
||||
let mut meta = builtin_meta();
|
||||
for (text, pack_meta) in extra_sources {
|
||||
source.push('\n');
|
||||
source.push_str(text);
|
||||
meta.extend(pack_meta.iter().cloned());
|
||||
}
|
||||
Self::from_source(&source, meta)
|
||||
}
|
||||
|
||||
/// Compile a downloaded pack against the metadata the pack itself declares.
|
||||
/// Used by [`crate::intel`] as the acceptance test before a pack becomes
|
||||
/// `current`.
|
||||
pub fn from_source_for_pack(source: &str, meta: &[RuleMeta]) -> Result<Detector, String> {
|
||||
Self::from_source(source, meta.to_vec())
|
||||
}
|
||||
|
||||
fn from_source(source: &str, meta: Vec<RuleMeta>) -> Result<Detector, String> {
|
||||
let rules = yara_x::compile(source).map_err(|error| format!("{error}"))?;
|
||||
Ok(Detector { rules, meta })
|
||||
}
|
||||
|
||||
pub fn rule_count(&self) -> usize {
|
||||
self.rules.iter().count()
|
||||
}
|
||||
|
||||
/// Scan one buffer. Returns evidence for every rule that fired, at the
|
||||
/// level its metadata allows.
|
||||
pub fn scan_buffer(&self, data: &[u8]) -> Vec<Evidence> {
|
||||
let mut scanner = yara_x::Scanner::new(&self.rules);
|
||||
let Ok(results) = scanner.scan(data) else {
|
||||
return Vec::new();
|
||||
};
|
||||
results
|
||||
.matching_rules()
|
||||
.filter_map(|matched| {
|
||||
let name = matched.identifier();
|
||||
let meta = self.meta.iter().find(|entry| entry.name == name)?;
|
||||
Some(Evidence::YaraRule {
|
||||
rule: name.to_string(),
|
||||
description: meta.description.clone(),
|
||||
family: meta.family.clone(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Level a matching rule can support. Rules with no metadata entry are
|
||||
/// treated as behaviour, which is the weaker answer.
|
||||
pub fn level_of(&self, rule: &str) -> RuleLevel {
|
||||
self.meta
|
||||
.iter()
|
||||
.find(|entry| entry.name == rule)
|
||||
.map(|entry| entry.level)
|
||||
.unwrap_or(RuleLevel::Behaviour)
|
||||
}
|
||||
|
||||
pub fn confidence_for(&self, evidence: &[Evidence]) -> Confidence {
|
||||
evidence
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Evidence::YaraRule { rule, .. } => Some(self.level_of(rule)),
|
||||
_ => None,
|
||||
})
|
||||
.map(|level| match level {
|
||||
RuleLevel::Signature => Confidence::Confirmed,
|
||||
RuleLevel::Behaviour => Confidence::Suspicious,
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(Confidence::Advisory)
|
||||
}
|
||||
|
||||
/// Scan one file. Large files are mapped when possible, so a 4 GB disk
|
||||
/// image in Downloads does not become a 4 GB allocation, and a read failure
|
||||
/// is an empty answer rather than an error: unreadable files are already
|
||||
/// reported through coverage.
|
||||
pub fn scan_file(&self, path: &Path) -> Vec<Evidence> {
|
||||
let Ok(metadata) = std::fs::symlink_metadata(path) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !metadata.is_file() {
|
||||
return Vec::new();
|
||||
}
|
||||
// YARA needs the bytes in memory. Above this, only the head and tail
|
||||
// are offered, and the finding says nothing about the middle.
|
||||
const FULL_LIMIT: u64 = 64 * 1024 * 1024;
|
||||
const WINDOW: usize = 4 * 1024 * 1024;
|
||||
let read = |offset: u64, length: usize| -> Vec<u8> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let mut file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut buffer = Vec::with_capacity(length.min(16 * 1024 * 1024));
|
||||
let _ = file.by_ref().take(length as u64).read_to_end(&mut buffer);
|
||||
buffer
|
||||
};
|
||||
|
||||
if metadata.len() <= FULL_LIMIT {
|
||||
return self.scan_buffer(&read(0, metadata.len() as usize));
|
||||
}
|
||||
let mut evidence = self.scan_buffer(&read(0, WINDOW));
|
||||
let tail = metadata.len().saturating_sub(WINDOW as u64);
|
||||
for item in self.scan_buffer(&read(tail, WINDOW)) {
|
||||
if !evidence.iter().any(|kept| kept.key() == item.key()) {
|
||||
evidence.push(item);
|
||||
}
|
||||
}
|
||||
evidence
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-256 blacklist. A hash match is the only detector that can call a
|
||||
/// file confirmed on its own, because it says "this exact sequence of bytes was
|
||||
/// published as bad".
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct HashIndex {
|
||||
entries: Vec<DeniedHash>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct DeniedHash {
|
||||
pub sha256: String,
|
||||
pub threat: String,
|
||||
#[serde(default)]
|
||||
pub family: String,
|
||||
}
|
||||
|
||||
impl HashIndex {
|
||||
/// Built-in list. EICAR is here as well as in the rules, because the test
|
||||
/// file is how a person verifies that scanning works at all.
|
||||
pub fn builtin() -> HashIndex {
|
||||
HashIndex {
|
||||
entries: vec![
|
||||
// The test string as published (CRLF), as a text editor would
|
||||
// save it (LF), and bare. Which terminator survives a download
|
||||
// depends on the tool that wrote the file, and a test file that
|
||||
// matches only sometimes is worse than none: it makes a working
|
||||
// scanner look broken.
|
||||
DeniedHash {
|
||||
sha256: "8b3f191819931d1f2cef7289239b5f77c00b079847b9c2636e56854d1e5eff71"
|
||||
.into(),
|
||||
threat: "EICAR test file".into(),
|
||||
family: "EICAR-Test-File".into(),
|
||||
},
|
||||
DeniedHash {
|
||||
sha256: "131f95c51cc819465fa1797f6ccacf9d494aaaff46fa3eac73ae63ffbdfd8267"
|
||||
.into(),
|
||||
threat: "EICAR test file".into(),
|
||||
family: "EICAR-Test-File".into(),
|
||||
},
|
||||
DeniedHash {
|
||||
sha256: "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"
|
||||
.into(),
|
||||
threat: "EICAR test file".into(),
|
||||
family: "EICAR-Test-File".into(),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_entries(entries: Vec<DeniedHash>) -> HashIndex {
|
||||
HashIndex { entries }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
pub fn lookup(&self, sha256: &str) -> Option<&DeniedHash> {
|
||||
let needle = sha256.to_ascii_lowercase();
|
||||
self.entries
|
||||
.iter()
|
||||
.find(|entry| entry.sha256.eq_ignore_ascii_case(&needle))
|
||||
}
|
||||
|
||||
pub fn check(&self, sha256: &str) -> Option<Evidence> {
|
||||
self.lookup(sha256).map(|entry| Evidence::DeniedHash {
|
||||
sha256: entry.sha256.clone(),
|
||||
threat: entry.threat.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// SHA-256 of a file, streamed. Returns `None` for anything that is not a
|
||||
/// regular file or cannot be opened.
|
||||
pub fn sha256_of(path: &Path) -> Option<String> {
|
||||
use sha2::{Digest, Sha256};
|
||||
let metadata = std::fs::symlink_metadata(path).ok()?;
|
||||
if !metadata.is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut file = std::fs::File::open(path).ok()?;
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = vec![0_u8; 128 * 1024];
|
||||
loop {
|
||||
let read = std::io::Read::read(&mut file, &mut buffer).ok()?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
digest.update(&buffer[..read]);
|
||||
}
|
||||
Some(hex::encode(digest.finalize()))
|
||||
}
|
||||
|
||||
/// The cheap half of the gate: can this name possibly be something that runs?
|
||||
///
|
||||
/// Used while walking, where only the path is free. It is deliberately
|
||||
/// over-inclusive — an extensionless name always passes — because the answer it
|
||||
/// avoids is expensive, and the file's `stat` data settles it a moment later in
|
||||
/// [`worth_scanning`].
|
||||
/// `assume_payload_location` widens the name gate for a scan the user pointed at
|
||||
/// a folder of their own, where nothing about the location can be assumed.
|
||||
pub fn plausible_by_name_in(path: &Path, assume_payload_location: bool) -> bool {
|
||||
let Some(name) = path.file_name() else {
|
||||
return false;
|
||||
};
|
||||
let name = name.to_string_lossy().to_ascii_lowercase();
|
||||
match name.rsplit_once('.') {
|
||||
// `thing.dylib`, `com.foo.plist`, and a dotted name whose tail is not an
|
||||
// extension at all (`v2ray-core`, `a.b.c`) all fall through to the
|
||||
// extensionless branch, which is the safe direction.
|
||||
Some((_, extension))
|
||||
if !extension.contains('.') && EXTENSION_GATED.contains(&extension) =>
|
||||
{
|
||||
true
|
||||
}
|
||||
Some(_) | None => assume_payload_location || extensionless_may_run(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extensions that are only ever worth a look where a payload is expected.
|
||||
/// Plists are the launchd configuration itself, and are the single most common
|
||||
/// place a persistence mechanism is written, so they are judged by name alone.
|
||||
const EXTENSION_GATED: [&str; 3] = ["plist", "mobileconfig", "crx"];
|
||||
|
||||
/// Extensions that mean "this runs" anywhere on the machine.
|
||||
///
|
||||
/// PowerShell, batch and HTA are on the list because they are the most common way
|
||||
/// a Windows machine is actually infected, and they are kilobytes of text each.
|
||||
/// Not on it: `.js`, `.json`, `.html`, `.lnk`. Those are everywhere — 35,000 files
|
||||
/// and 1.3 GB in the quick-scan range of an ordinary developer's Mac — and a scan
|
||||
/// that reads all of them to find the occasional malicious one is a scan nobody
|
||||
/// runs. A custom scan still sees them, because there the name is not trusted.
|
||||
const EXECUTABLE_EXTENSIONS: [&str; 23] = [
|
||||
"dylib", "so", "xpc", "bundle", "exe", "dll", "sys", "ocx", "msi", "appx", "dmg", "pkg", "jar",
|
||||
"sh", "bash", "command", "scpt", "vbs", "ps1", "psm1", "bat", "cmd", "hta",
|
||||
];
|
||||
|
||||
/// An extensionless name passes the cheap gate only where something extensionless
|
||||
/// can plausibly live: inside an app bundle's own executable folder, in a
|
||||
/// launchd directory, or in the folders a browser writes to. Everywhere else the
|
||||
/// name alone cannot tell a Mach-O from a cache file, and `~/Library` holds
|
||||
/// hundreds of thousands of the latter.
|
||||
fn extensionless_may_run(path: &Path) -> bool {
|
||||
let location = layout_of(path);
|
||||
matches!(
|
||||
location,
|
||||
Layout::AppBundle | Layout::Launchd | Layout::DropZone | Layout::Browser
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether one file is worth opening, decided from the name and the `stat` data
|
||||
/// the scan already has.
|
||||
///
|
||||
/// The gate has to be cheap *and* structural, because the folders a scan walks
|
||||
/// hold about a million files and almost none of them can run. An extension list
|
||||
/// alone fails in both directions: it misses the extensionless Mach-O a
|
||||
/// dropper leaves in `~/Downloads`, and — taken the other way, as "extensionless
|
||||
/// might be a binary" — it turns every cache, database and `*.dat` resource in
|
||||
/// `~/Library` into a candidate, which is what made a full scan read the whole
|
||||
/// disk before it found anything.
|
||||
///
|
||||
/// So the decision is made of three cheap questions, in this order: how big is it
|
||||
/// (nothing under 64 bytes is a program, and a scan will not read a disk image),
|
||||
/// can it be executed at all (the mode bits, which is what separates a real
|
||||
/// binary from a cache file wearing no extension), and does the name or the header
|
||||
/// say code. The header is read only for the few files the first two questions
|
||||
/// leave ambiguous.
|
||||
pub fn worth_scanning(path: &Path, metadata: &std::fs::Metadata) -> bool {
|
||||
worth_scanning_in(path, metadata, false)
|
||||
}
|
||||
|
||||
/// `assume_payload_location` lifts the location test. A custom scan is asked
|
||||
/// about the folder the user named, and a file they dropped there may be a
|
||||
/// Mach-O with no extension, no execute bit and an unhelpful suffix, so the
|
||||
/// header has to be consulted wherever the file happens to be.
|
||||
pub fn worth_scanning_in(
|
||||
path: &Path,
|
||||
metadata: &std::fs::Metadata,
|
||||
assume_payload_location: bool,
|
||||
) -> bool {
|
||||
if !metadata.is_file() {
|
||||
return false;
|
||||
}
|
||||
let size = metadata.len();
|
||||
if !(MIN_PROGRAM_BYTES..=SCAN_FILE_LIMIT).contains(&size) {
|
||||
return false;
|
||||
}
|
||||
let extension = path
|
||||
.extension()
|
||||
.map(|ext| ext.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
if EXECUTABLE_EXTENSIONS.contains(&extension.as_str())
|
||||
|| EXTENSION_GATED.contains(&extension.as_str())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// A folder the user named is asked about by content, not by name: what lands
|
||||
// there is theirs to ask about, a signature can sit in an ordinary text file,
|
||||
// and the suffix of a dropper's handiwork argues with itself. The size limits
|
||||
// above still apply, so the cost is bounded by the folder they chose.
|
||||
if assume_payload_location {
|
||||
return true;
|
||||
}
|
||||
// Elsewhere, a name that says what it is gets believed. `.svg`, `.class`,
|
||||
// `.zip` and `.docx` are not programs whatever the mode bits claim, and the
|
||||
// mode bits routinely *do* claim it: unpacking an archive marks everything
|
||||
// inside it executable, which is how a scan of a clean machine reported nine
|
||||
// hundred "unsigned binary" findings that were stylesheets and class files.
|
||||
if !extension.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// No extension, so the execute bit is the only thing to go on. It separates
|
||||
// the few thousand launchable extensionless files in a home folder from the
|
||||
// hundreds of thousands of extensionless cache entries, and costs nothing.
|
||||
if is_executable(metadata) {
|
||||
return true;
|
||||
}
|
||||
// A browser can hand over a Mach-O with no extension and no execute bit, and
|
||||
// a dropper may run one through `/bin/sh`. In the folders where that happens
|
||||
// the first bytes are consulted, and only there.
|
||||
matches!(layout_of(path), Layout::DropZone | Layout::Browser) && looks_executable(path)
|
||||
}
|
||||
|
||||
/// Below this a file cannot say anything about itself. `#!/bin/sh` plus one line
|
||||
/// is the shortest payload that can actually run something, and it is a little
|
||||
/// over twenty bytes; anything smaller is a stub, and the startup inventory
|
||||
/// reports what points at it anyway.
|
||||
const MIN_PROGRAM_BYTES: u64 = 24;
|
||||
|
||||
/// Where a path sits, in terms a scan cares about. Computed from the string
|
||||
/// because it is asked for every walked entry and a `metadata` call per entry
|
||||
/// would cost more than the walk itself.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Layout {
|
||||
/// Inside `Foo.app/Contents`, at any depth.
|
||||
AppBundle,
|
||||
/// A launchd directory, whose plists *are* the persistence mechanism.
|
||||
Launchd,
|
||||
/// Where a browser writes what it downloads.
|
||||
DropZone,
|
||||
/// A browser's own support folders, where an extension lives.
|
||||
Browser,
|
||||
/// Somewhere else entirely.
|
||||
Other,
|
||||
}
|
||||
|
||||
pub fn layout_of(path: &Path) -> Layout {
|
||||
let text = path.to_string_lossy().to_ascii_lowercase();
|
||||
let home = squid_platform::startup::home_dir();
|
||||
let home = home.to_string_lossy().to_ascii_lowercase();
|
||||
if text.contains("/contents/") || text.ends_with(".app") {
|
||||
return Layout::AppBundle;
|
||||
}
|
||||
if text.contains("/library/launchagents/")
|
||||
|| text.contains("/library/launchdaemons/")
|
||||
|| text.ends_with("/library/launchagents")
|
||||
|| text.ends_with("/library/launchdaemons")
|
||||
{
|
||||
return Layout::Launchd;
|
||||
}
|
||||
if text.starts_with(&format!("{home}/downloads"))
|
||||
|| text.starts_with(&format!("{home}/desktop"))
|
||||
{
|
||||
return Layout::DropZone;
|
||||
}
|
||||
const BROWSERS: [&str; 6] = [
|
||||
"/google/chrome",
|
||||
"/google/chrome canary",
|
||||
"/microsoft/edge",
|
||||
"/mozilla/firefox",
|
||||
"/webkit/",
|
||||
"/extensions/",
|
||||
];
|
||||
if BROWSERS.iter().any(|hint| text.contains(hint)) {
|
||||
return Layout::Browser;
|
||||
}
|
||||
Layout::Other
|
||||
}
|
||||
|
||||
/// The execute bit, for any owner. On Windows the notion does not exist and the
|
||||
/// read-only flag is the nearest thing, so the name and header carry the decision
|
||||
/// there instead.
|
||||
#[cfg(unix)]
|
||||
fn is_executable(metadata: &std::fs::Metadata) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
metadata.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn is_executable(_metadata: &std::fs::Metadata) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The largest file a scan will read. Above this a file is reported by its size
|
||||
/// and left alone: a disk image or a game archive is not what a startup payload
|
||||
/// looks like, and reading one can cost more than the rest of the scan together.
|
||||
pub const SCAN_FILE_LIMIT: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// Read the first bytes and decide whether anything could ever execute them.
|
||||
fn looks_executable(path: &Path) -> bool {
|
||||
use std::io::Read;
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
let mut head = [0_u8; 8];
|
||||
let Ok(read) = file.read(&mut head) else {
|
||||
return false;
|
||||
};
|
||||
if read < 4 {
|
||||
return false;
|
||||
}
|
||||
is_macho_magic(&head)
|
||||
|| head.starts_with(b"MZ")
|
||||
|| head.starts_with(b"#!")
|
||||
|| head.starts_with(b"PK")
|
||||
}
|
||||
|
||||
/// Mach-O in either byte order, 32-bit, 64-bit, or as a fat archive.
|
||||
fn is_macho_magic(head: &[u8]) -> bool {
|
||||
const MACHOS: [[u8; 4]; 6] = [
|
||||
[0xcf, 0xfa, 0xed, 0xfe],
|
||||
[0xce, 0xfa, 0xed, 0xfe],
|
||||
[0xca, 0xfe, 0xba, 0xbe],
|
||||
[0xfe, 0xed, 0xfa, 0xcf],
|
||||
[0xfe, 0xed, 0xfa, 0xce],
|
||||
[0xbe, 0xba, 0xfe, 0xca],
|
||||
];
|
||||
MACHOS.iter().any(|magic| head.starts_with(magic))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn temp_file(name: &str, bytes: &[u8]) -> std::path::PathBuf {
|
||||
let path = std::env::temp_dir().join(format!("squid-guard-{name}"));
|
||||
let mut file = std::fs::File::create(&path).expect("temp file");
|
||||
file.write_all(bytes).expect("write temp file");
|
||||
path
|
||||
}
|
||||
|
||||
const EICAR: &str = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\r\n";
|
||||
|
||||
#[test]
|
||||
fn the_builtin_ruleset_compiles() {
|
||||
let detector = Detector::builtin().expect("built-in rules must compile");
|
||||
assert_eq!(detector.rule_count(), builtin_meta().len());
|
||||
for entry in builtin_meta() {
|
||||
assert!(
|
||||
detector
|
||||
.rules
|
||||
.iter()
|
||||
.any(|rule| rule.identifier() == entry.name),
|
||||
"{} is declared in metadata but not compiled",
|
||||
entry.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eicar_is_found_by_both_detectors() {
|
||||
let detector = Detector::builtin().unwrap();
|
||||
let path = temp_file("eicar", EICAR.as_bytes());
|
||||
let evidence = detector.scan_file(&path);
|
||||
assert!(
|
||||
evidence
|
||||
.iter()
|
||||
.any(|item| item.key() == "yara:Eicar_Test_File"),
|
||||
"the YARA rule did not fire: {evidence:?}"
|
||||
);
|
||||
let hash = sha256_of(&path).expect("hash");
|
||||
let index = HashIndex::builtin();
|
||||
let denied = index
|
||||
.check(&hash)
|
||||
.expect("the hash blacklist should know EICAR");
|
||||
assert!(matches!(denied, Evidence::DeniedHash { .. }));
|
||||
std::fs::remove_file(path).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signature_rule_is_confirmed_and_a_behaviour_rule_is_not() {
|
||||
let detector = Detector::builtin().unwrap();
|
||||
assert_eq!(detector.level_of("Eicar_Test_File"), RuleLevel::Signature);
|
||||
assert_eq!(
|
||||
detector.level_of("ShellPayloadInUserData"),
|
||||
RuleLevel::Behaviour
|
||||
);
|
||||
assert_eq!(
|
||||
detector.confidence_for(&[Evidence::YaraRule {
|
||||
rule: "Eicar_Test_File".into(),
|
||||
description: String::new(),
|
||||
family: String::new(),
|
||||
}]),
|
||||
Confidence::Confirmed
|
||||
);
|
||||
assert_eq!(
|
||||
detector.confidence_for(&[Evidence::YaraRule {
|
||||
rule: "ShellPayloadInUserData".into(),
|
||||
description: String::new(),
|
||||
family: String::new(),
|
||||
}]),
|
||||
Confidence::Suspicious
|
||||
);
|
||||
// A rule nobody described is assumed to be the weak kind.
|
||||
assert_eq!(detector.level_of("Made_Up"), RuleLevel::Behaviour);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behaviour_rule_needs_evidence_not_a_single_string() {
|
||||
let detector = Detector::builtin().unwrap();
|
||||
let path = temp_file(
|
||||
"pipe-sh",
|
||||
b"#!/bin/sh\ncurl -sS https://example.test/install | sh\nwget -qO- https://example.test/x | bash\n",
|
||||
);
|
||||
let evidence = detector.scan_file(&path);
|
||||
assert!(
|
||||
evidence
|
||||
.iter()
|
||||
.any(|item| item.key() == "yara:ShellPayloadInUserData"),
|
||||
"two piped-shell lines should fire: {evidence:?}"
|
||||
);
|
||||
|
||||
// One line alone is how documentation and install instructions read.
|
||||
let quiet = temp_file(
|
||||
"pipe-sh-quiet",
|
||||
b"curl -sS https://example.test/install | sh\n",
|
||||
);
|
||||
assert!(detector.scan_file(&quiet).is_empty());
|
||||
std::fs::remove_file(path).ok();
|
||||
std::fs::remove_file(quiet).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_binary_reports_nothing() {
|
||||
let detector = Detector::builtin().unwrap();
|
||||
let path = temp_file("clean", b"\x7fELF this file is deliberately uninteresting");
|
||||
assert!(detector.scan_file(&path).is_empty());
|
||||
std::fs::remove_file(path).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashing_skips_directories_and_refusals() {
|
||||
assert!(sha256_of(std::path::Path::new("/")).is_none());
|
||||
assert!(sha256_of(std::path::Path::new("/definitely/not/here")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_executable_shaped_files_are_worth_reading() {
|
||||
// The gate is decided from real `stat` data, so the fixture has to be
|
||||
// real files: a cache file and a binary are the same name shape and
|
||||
// differ only in their mode bits.
|
||||
let dir = std::env::temp_dir().join("squid-gate");
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let made = |name: &str, executable: bool| -> std::path::PathBuf {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, [0x90_u8; 512]).expect("write");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = if executable { 0o755 } else { 0o644 };
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
|
||||
.expect("mode");
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = executable;
|
||||
path
|
||||
};
|
||||
|
||||
let keep = |name: &str, executable: bool| {
|
||||
let path = made(name, executable);
|
||||
let metadata = std::fs::metadata(&path).expect("metadata");
|
||||
let kept = worth_scanning(&path, &metadata);
|
||||
std::fs::remove_file(&path).ok();
|
||||
kept
|
||||
};
|
||||
let keep_size = |name: &str, executable: bool, bytes: usize| {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, vec![0x90_u8; bytes]).expect("write");
|
||||
let metadata = std::fs::metadata(&path).expect("metadata");
|
||||
let kept = worth_scanning(&path, &metadata);
|
||||
std::fs::remove_file(&path).ok();
|
||||
let _ = executable;
|
||||
kept
|
||||
};
|
||||
|
||||
assert!(keep("install.sh", false), "a script is a payload");
|
||||
assert!(keep("thing.dylib", false), "a library is a payload");
|
||||
assert!(
|
||||
keep("com.tester.agent.plist", false),
|
||||
"an agent is persistence"
|
||||
);
|
||||
assert!(!keep("notes.txt", false), "a text file is not a program");
|
||||
assert!(!keep("photo.jpg", false), "an image is not a program");
|
||||
assert!(
|
||||
!keep_size("stub", false, 8),
|
||||
"under the floor a file cannot say anything about itself"
|
||||
);
|
||||
// The execute bit is a POSIX notion; Windows has no equivalent, which is
|
||||
// why the name and the header carry the decision there instead.
|
||||
if cfg!(unix) {
|
||||
assert!(keep("runner", true), "an extensionless binary is a payload");
|
||||
assert!(
|
||||
!keep("runner-copy", false),
|
||||
"an extensionless file nobody can execute is data"
|
||||
);
|
||||
// Unpacking an archive marks everything inside it executable, so on a
|
||||
// machine with a few downloaded source trees the mode bit alone reports
|
||||
// hundreds of "unsigned binary" findings that are stylesheets. A name
|
||||
// that says what the file is beats a mode bit that does not.
|
||||
assert!(
|
||||
!keep("notes.txt", true),
|
||||
"an executable text file is still a text file"
|
||||
);
|
||||
assert!(
|
||||
!keep("styles.scss", true),
|
||||
"the exec bit does not turn a stylesheet into a payload"
|
||||
);
|
||||
}
|
||||
std::fs::remove_dir(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_the_user_named_is_judged_by_content_not_by_name() {
|
||||
// A signature can live in an ordinary text file, and the suffix of a
|
||||
// dropper's handiwork argues with itself, so a scan pointed at one folder
|
||||
// asks about anything large enough to hold a payload. The same file found
|
||||
// while walking `~/Library` is taken at its word.
|
||||
let path = temp_file("payload", b"eicar-shaped text that a rule can match");
|
||||
let metadata = std::fs::metadata(&path).expect("metadata");
|
||||
assert!(
|
||||
worth_scanning_in(&path, &metadata, true),
|
||||
"inside a folder the user named, the name does not decide"
|
||||
);
|
||||
assert!(
|
||||
!worth_scanning(&path, &metadata),
|
||||
"the same file elsewhere is a text file, and a scan says so"
|
||||
);
|
||||
std::fs::remove_file(path).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_layouts_a_quick_scan_trusts_are_the_ones_that_can_run() {
|
||||
assert_eq!(
|
||||
layout_of(std::path::Path::new(
|
||||
"/Applications/Thing.app/Contents/MacOS/Thing"
|
||||
)),
|
||||
Layout::AppBundle
|
||||
);
|
||||
assert_eq!(
|
||||
layout_of(std::path::Path::new("/Library/LaunchAgents/x.plist")),
|
||||
Layout::Launchd
|
||||
);
|
||||
assert_eq!(
|
||||
layout_of(std::path::Path::new("/Applications/Other.txt")),
|
||||
Layout::Other,
|
||||
"/Applications on its own is not a bundle"
|
||||
);
|
||||
assert!(plausible_by_name_in(
|
||||
std::path::Path::new("/a/b/com.tester.agent.plist"),
|
||||
false
|
||||
));
|
||||
assert!(!plausible_by_name_in(
|
||||
std::path::Path::new("/Users/tester/Documents/notes.txt"),
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extra_pack_adds_rules_without_losing_the_builtin_ones() {
|
||||
let extra = vec![(
|
||||
"rule PackProbe { strings: $a = \"pack-marker\" condition: $a }".to_string(),
|
||||
vec![RuleMeta {
|
||||
name: "PackProbe".into(),
|
||||
description: "from the pack".into(),
|
||||
family: "pack".into(),
|
||||
level: RuleLevel::Signature,
|
||||
}],
|
||||
)];
|
||||
let detector = Detector::with_extra(&extra).expect("the pack should compile");
|
||||
assert_eq!(detector.rule_count(), builtin_meta().len() + 1);
|
||||
assert_eq!(detector.level_of("PackProbe"), RuleLevel::Signature);
|
||||
assert!(detector
|
||||
.scan_buffer(b"prefix pack-marker suffix")
|
||||
.iter()
|
||||
.any(|item| item.key() == "yara:PackProbe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_pack_is_reported_not_swallowed() {
|
||||
let broken = vec![("rule {{{ not yara".to_string(), Vec::new())];
|
||||
assert!(Detector::with_extra(&broken).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,686 @@
|
|||
//! Two kinds of memory, both on disk, neither in a database.
|
||||
//!
|
||||
//! [`ScanCache`] remembers the verdict for a file identity — path, size,
|
||||
//! modification time and file id — so a second scan does not re-hash a file that
|
||||
//! has not moved. Identity rather than content sampling, because the whole point
|
||||
//! is to be able to say "this exact file, unchanged" without reading it.
|
||||
//!
|
||||
//! [`Store`] keeps the scan the user is looking at plus the recent-activity list
|
||||
//! the Security page shows. Findings live here precisely so quarantine can take
|
||||
//! an id: the frontend never gets to name a path, and a stale id is an error
|
||||
//! rather than a surprise move.
|
||||
//!
|
||||
//! Both files are bounded. A cleaner that grows its own state forever is its own
|
||||
//! kind of junk, so the cache drops its oldest half when it doubles past the
|
||||
//! limit, and the activity list keeps a fixed number of entries.
|
||||
|
||||
use crate::findings::{Confidence, Evidence, Finding};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use squid_core::paths;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// The three facts that make a file the same file: where it is, how big it is,
|
||||
/// and when it last changed. Anything else would mean reading it again.
|
||||
pub struct FileIdentity {
|
||||
pub path: PathBuf,
|
||||
pub size: u64,
|
||||
pub modified_ms: u64,
|
||||
pub file_id: u64,
|
||||
}
|
||||
|
||||
impl FileIdentity {
|
||||
pub fn of(path: &Path, metadata: &std::fs::Metadata) -> FileIdentity {
|
||||
FileIdentity {
|
||||
path: path.to_path_buf(),
|
||||
size: metadata.len(),
|
||||
modified_ms: modified_ms(metadata),
|
||||
file_id: file_id(metadata),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A reusable answer for one file identity.
|
||||
#[derive(Clone)]
|
||||
pub struct Hit {
|
||||
pub evidence: Vec<Evidence>,
|
||||
pub sha256: Option<String>,
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
/// One remembered verdict, and when a scan last asked for it.
|
||||
///
|
||||
/// `path` is stored as the canonical key rather than the original spelling, which
|
||||
/// is what lets the map below be keyed by it. Nothing displays that field: it is
|
||||
/// there so a person opening `verdicts.json` can see which file a verdict is about.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct CachedVerdict {
|
||||
path: String,
|
||||
size: u64,
|
||||
modified_ms: u64,
|
||||
#[serde(default)]
|
||||
file_id: u64,
|
||||
evidence: Vec<Evidence>,
|
||||
sha256: Option<String>,
|
||||
signed: bool,
|
||||
/// Scan counter, not a clock: only the order matters, and a clock would make a
|
||||
/// test depend on how fast the machine is.
|
||||
#[serde(default)]
|
||||
used: u64,
|
||||
}
|
||||
|
||||
/// The file on disk. A list, so the format stays readable and diffable, even
|
||||
/// though the cache is a map in memory.
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
struct CacheFile {
|
||||
version: u32,
|
||||
entries: Vec<CachedVerdict>,
|
||||
}
|
||||
|
||||
/// Verdicts keyed by file identity rather than by path alone: a file that was
|
||||
/// replaced between scans has a different mtime, and reusing the old answer would
|
||||
/// report the wrong bytes.
|
||||
///
|
||||
/// The map is the point. A scan offers thousands of files, and looking each one up
|
||||
/// in a list costs one path comparison per cached entry per file — which is
|
||||
/// quadratic, and was measured at several minutes of CPU on a quick scan whose
|
||||
/// entire budget is a few seconds. Trimming needs an ordering, so each entry keeps
|
||||
/// the scan number it was last used at and the list is only sorted when it is
|
||||
/// written.
|
||||
pub struct ScanCache {
|
||||
entries: HashMap<String, CachedVerdict>,
|
||||
/// Counts lookups and stores, to order the cache by recency without a clock.
|
||||
clock: u64,
|
||||
dirty: bool,
|
||||
loaded: bool,
|
||||
misses: usize,
|
||||
}
|
||||
|
||||
impl Default for ScanCache {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScanCache {
|
||||
pub fn new() -> ScanCache {
|
||||
ScanCache {
|
||||
entries: HashMap::new(),
|
||||
clock: 0,
|
||||
dirty: false,
|
||||
loaded: false,
|
||||
misses: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> PathBuf {
|
||||
cache_dir().join("verdicts.json")
|
||||
}
|
||||
|
||||
fn load(&mut self) {
|
||||
if self.loaded {
|
||||
return;
|
||||
}
|
||||
self.entries = std::fs::read(Self::path())
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
|
||||
.map(|file| {
|
||||
file.entries
|
||||
.into_iter()
|
||||
.map(|entry| (entry.path.clone(), entry))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.loaded = true;
|
||||
}
|
||||
|
||||
/// The remembered verdict for a file that has not changed since.
|
||||
pub fn verdict(&mut self, identity: &FileIdentity) -> Option<Hit> {
|
||||
self.load();
|
||||
self.clock += 1;
|
||||
let used = self.clock;
|
||||
let found = self
|
||||
.entries
|
||||
.get_mut(&paths::canonical_key(&identity.path))?;
|
||||
if found.size != identity.size
|
||||
|| found.modified_ms != identity.modified_ms
|
||||
|| found.file_id != identity.file_id
|
||||
{
|
||||
// The same path holding different bytes. Re-hash it: "you already
|
||||
// looked at this" is the one answer a scan may not give wrongly.
|
||||
self.misses += 1;
|
||||
return None;
|
||||
}
|
||||
found.used = used;
|
||||
Some(Hit {
|
||||
evidence: found.evidence.clone(),
|
||||
sha256: found.sha256.clone(),
|
||||
signed: found.signed,
|
||||
})
|
||||
}
|
||||
|
||||
/// Remember what this scan decided. Called for every file a scan looked at, so
|
||||
/// a re-scan of an unchanged tree is a sequence of hits rather than a re-read.
|
||||
pub fn remember(&mut self, identity: &FileIdentity, verdict: Hit) {
|
||||
self.load();
|
||||
self.clock += 1;
|
||||
let key = paths::canonical_key(&identity.path);
|
||||
// One row per path: a re-scan replaces the answer rather than leaving the
|
||||
// file with two verdicts, one of which is stale and might win.
|
||||
self.entries.insert(
|
||||
key.clone(),
|
||||
CachedVerdict {
|
||||
path: key,
|
||||
size: identity.size,
|
||||
modified_ms: identity.modified_ms,
|
||||
file_id: identity.file_id,
|
||||
evidence: verdict.evidence,
|
||||
sha256: verdict.sha256,
|
||||
signed: verdict.signed,
|
||||
used: self.clock,
|
||||
},
|
||||
);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Write the cache, trimming the least recently used half when it outgrows its
|
||||
/// budget. A cleaner that grows its own state forever is its own kind of junk.
|
||||
pub fn commit(&mut self) {
|
||||
self.load();
|
||||
if !self.dirty {
|
||||
return;
|
||||
}
|
||||
const LIMIT: usize = 40_000;
|
||||
let mut entries: Vec<CachedVerdict> = self.entries.values().cloned().collect();
|
||||
entries.sort_by_key(|entry| entry.used);
|
||||
if entries.len() > LIMIT * 2 {
|
||||
let drop = entries.len() - LIMIT;
|
||||
entries.drain(0..drop);
|
||||
}
|
||||
let file = CacheFile {
|
||||
version: 1,
|
||||
entries,
|
||||
};
|
||||
if let Some(parent) = Self::path().parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(bytes) = serde_json::to_vec(&file) {
|
||||
let _ = std::fs::write(Self::path(), bytes);
|
||||
}
|
||||
self.dirty = false;
|
||||
}
|
||||
|
||||
pub fn entries(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
pub fn misses(&self) -> usize {
|
||||
self.misses
|
||||
}
|
||||
|
||||
/// Forget everything. Offered when the rule pack changes, because a verdict
|
||||
/// recorded by the old rules is not an answer the new rules gave.
|
||||
pub fn invalidate(&mut self) {
|
||||
self.entries.clear();
|
||||
self.dirty = true;
|
||||
self.commit();
|
||||
}
|
||||
}
|
||||
|
||||
/// The scan the user is looking at, plus the activity list.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ActivityEntry {
|
||||
pub at_ms: u64,
|
||||
pub kind: String,
|
||||
pub detail: String,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StoredScan {
|
||||
pub scan_id: String,
|
||||
pub mode: String,
|
||||
pub finished_ms: u64,
|
||||
pub elapsed_ms: u64,
|
||||
pub cancelled: bool,
|
||||
pub examined: usize,
|
||||
pub cached: usize,
|
||||
pub skipped: usize,
|
||||
pub coverage_complete: bool,
|
||||
pub gaps: Vec<(String, String)>,
|
||||
pub findings: Vec<Finding>,
|
||||
}
|
||||
|
||||
impl StoredScan {
|
||||
/// How many findings at each level still need a decision: not ignored, and
|
||||
/// not already sitting in the quarantine.
|
||||
///
|
||||
/// This is the definition the badge, the tray line and the page header all
|
||||
/// count, so it is one function on the record itself. When it was written
|
||||
/// twice — once here, once in the desktop layer — the tray and the Security
|
||||
/// page could disagree after a restart while both looked correct.
|
||||
pub fn counts(&self) -> (usize, usize, usize) {
|
||||
let actionable = |level: Confidence| {
|
||||
self.findings
|
||||
.iter()
|
||||
.filter(|finding| {
|
||||
finding.confidence == level && !finding.ignored && !finding.quarantined
|
||||
})
|
||||
.count()
|
||||
};
|
||||
(
|
||||
actionable(Confidence::Confirmed),
|
||||
actionable(Confidence::Suspicious),
|
||||
actionable(Confidence::Advisory),
|
||||
)
|
||||
}
|
||||
|
||||
/// Freeze one finished scan for storage. The coverage is kept as a boolean
|
||||
/// plus the list of gaps, because that is everything the next session needs
|
||||
/// in order to refuse to say a plain "clean".
|
||||
pub fn record(report: &crate::scan::ScanReport) -> StoredScan {
|
||||
StoredScan {
|
||||
scan_id: report.scan_id.clone(),
|
||||
mode: report.mode.as_str().to_string(),
|
||||
finished_ms: report.finished_ms,
|
||||
elapsed_ms: report.elapsed_ms,
|
||||
cancelled: report.cancelled,
|
||||
examined: report.examined,
|
||||
cached: report.cached,
|
||||
skipped: report.skipped,
|
||||
coverage_complete: report.coverage.complete(),
|
||||
gaps: report
|
||||
.coverage
|
||||
.gaps()
|
||||
.into_iter()
|
||||
.map(|gap| {
|
||||
(
|
||||
gap.display_path.clone(),
|
||||
gap.reason
|
||||
.clone()
|
||||
.unwrap_or_else(|| gap.outcome.as_str().into()),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
findings: report.findings.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory state for one app session, persisted where it helps the next one.
|
||||
pub struct Store {
|
||||
last_scan: Option<StoredScan>,
|
||||
activity: Vec<ActivityEntry>,
|
||||
}
|
||||
|
||||
impl Default for Store {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new() -> Store {
|
||||
let activity = read_activity();
|
||||
Store {
|
||||
last_scan: read_last_scan(),
|
||||
activity,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_scan(&mut self, scan: StoredScan) {
|
||||
write_last_scan(&scan);
|
||||
self.last_scan = Some(scan);
|
||||
}
|
||||
|
||||
pub fn scan(&self) -> Option<&StoredScan> {
|
||||
self.last_scan.as_ref()
|
||||
}
|
||||
|
||||
/// Apply one change to the stored scan and write it back. Findings are
|
||||
/// mutable state — quarantined, restored, ignored — and the file is the
|
||||
/// record of that state, so every mutation goes through here rather than
|
||||
/// editing `self.last_scan` and hoping something saves it later.
|
||||
pub fn update_scan(&mut self, change: impl FnOnce(&mut StoredScan)) {
|
||||
let Some(scan) = self.last_scan.as_mut() else {
|
||||
return;
|
||||
};
|
||||
change(scan);
|
||||
write_last_scan(scan);
|
||||
}
|
||||
|
||||
/// The finding behind an id. This is the only way a caller reaches a path in
|
||||
/// the quarantine path, and it fails loudly when the id is unknown.
|
||||
pub fn finding(&self, id: &str) -> Option<&Finding> {
|
||||
self.last_scan
|
||||
.as_ref()
|
||||
.and_then(|scan| scan.findings.iter().find(|finding| finding.id == id))
|
||||
}
|
||||
|
||||
pub fn finding_mut(&mut self, id: &str) -> Option<&mut Finding> {
|
||||
self.last_scan
|
||||
.as_mut()
|
||||
.and_then(|scan| scan.findings.iter_mut().find(|finding| finding.id == id))
|
||||
}
|
||||
|
||||
pub fn note(&mut self, kind: &str, detail: impl Into<String>, path: Option<PathBuf>) {
|
||||
self.activity.push(ActivityEntry {
|
||||
at_ms: now_ms(),
|
||||
kind: kind.into(),
|
||||
detail: detail.into(),
|
||||
path: path.map(|path| paths::pretty(&path)),
|
||||
});
|
||||
const KEEP: usize = 200;
|
||||
if self.activity.len() > KEEP {
|
||||
let drop = self.activity.len() - KEEP;
|
||||
self.activity.drain(0..drop);
|
||||
}
|
||||
write_activity(&self.activity);
|
||||
}
|
||||
|
||||
pub fn activity(&self) -> &[ActivityEntry] {
|
||||
&self.activity
|
||||
}
|
||||
|
||||
/// Most recent first, which is how a log is read.
|
||||
pub fn recent_activity(&self, limit: usize) -> Vec<ActivityEntry> {
|
||||
self.activity.iter().rev().take(limit).cloned().collect()
|
||||
}
|
||||
|
||||
/// Fold the quarantine ledger into the displayed findings, so a file that
|
||||
/// has been dealt with stops being offered as actionable.
|
||||
pub fn mark_quarantined(&mut self, quarantined: &[(String, PathBuf)]) {
|
||||
let Some(scan) = self.last_scan.as_mut() else {
|
||||
return;
|
||||
};
|
||||
for finding in &mut scan.findings {
|
||||
if let Some(path) = finding.path.as_ref() {
|
||||
if quarantined
|
||||
.iter()
|
||||
.any(|(_, stored)| paths::same_path(stored, path))
|
||||
{
|
||||
finding.quarantined = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn counts(&self) -> (usize, usize, usize) {
|
||||
self.last_scan
|
||||
.as_ref()
|
||||
.map(StoredScan::counts)
|
||||
.unwrap_or((0, 0, 0))
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_dir() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("cache")
|
||||
}
|
||||
|
||||
fn activity_path() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("activity.json")
|
||||
}
|
||||
|
||||
/// The last finished scan, kept so a finding id outlives the process that
|
||||
/// produced it. `squid guard scan` and `squid guard quarantine` are two runs of
|
||||
/// one conversation, and the Security page reopening after a restart should say
|
||||
/// what the last scan found rather than "never scanned".
|
||||
fn last_scan_path() -> PathBuf {
|
||||
squid_core::Settings::state_dir()
|
||||
.join("security")
|
||||
.join("last-scan.json")
|
||||
}
|
||||
|
||||
fn read_last_scan() -> Option<StoredScan> {
|
||||
std::fs::read_to_string(last_scan_path())
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
}
|
||||
|
||||
fn write_last_scan(scan: &StoredScan) {
|
||||
let path = last_scan_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(text) = serde_json::to_string_pretty(scan) {
|
||||
let _ = std::fs::write(path, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_activity() -> Vec<ActivityEntry> {
|
||||
std::fs::read_to_string(activity_path())
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_activity(entries: &[ActivityEntry]) {
|
||||
let path = activity_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = std::fs::create_dir_all(parent);
|
||||
}
|
||||
if let Ok(text) = serde_json::to_string_pretty(entries) {
|
||||
let _ = std::fs::write(path, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
|
||||
metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|since| since.as_millis() as u64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// inode on unix, file index on Windows; the part of the identity that survives a
|
||||
/// rename and catches a replacement in place.
|
||||
fn file_id(metadata: &std::fs::Metadata) -> u64 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
metadata.ino()
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
metadata.creation_time()
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = metadata;
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|since| since.as_millis() as u64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn state_dir(tag: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("squid-store-{tag}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn probe(tag: &str, bytes: &[u8]) -> PathBuf {
|
||||
let dir = state_dir(tag);
|
||||
let path = dir.join("payload");
|
||||
let mut file = std::fs::File::create(&path).unwrap();
|
||||
file.write_all(bytes).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn hit(evidence: &[Evidence], sha256: Option<&str>, signed: bool) -> Hit {
|
||||
Hit {
|
||||
evidence: evidence.to_vec(),
|
||||
sha256: sha256.map(str::to_string),
|
||||
signed,
|
||||
}
|
||||
}
|
||||
|
||||
fn evidence() -> Vec<Evidence> {
|
||||
vec![Evidence::DeniedHash {
|
||||
sha256: "a".repeat(64),
|
||||
threat: "probe".into(),
|
||||
}]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_is_reused_only_while_the_file_is_unchanged() {
|
||||
let path = probe("reuse", b"the bytes that were judged");
|
||||
let metadata = std::fs::metadata(&path).unwrap();
|
||||
let identity = FileIdentity::of(&path, &metadata);
|
||||
let mut cache = ScanCache::new();
|
||||
assert!(
|
||||
cache.verdict(&identity).is_none(),
|
||||
"an empty cache cannot know this file"
|
||||
);
|
||||
cache.remember(&identity, hit(&evidence(), None, false));
|
||||
let stored = cache.verdict(&identity).expect("the file has not changed");
|
||||
assert_eq!(stored.evidence.len(), 1);
|
||||
|
||||
// Different size, different answer: the file was replaced.
|
||||
let bigger = FileIdentity {
|
||||
size: identity.size + 1,
|
||||
..identity
|
||||
};
|
||||
assert!(cache.verdict(&bigger).is_none());
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_file_loses_its_cached_verdict() {
|
||||
let path = probe("replaced", b"first content");
|
||||
let before = std::fs::metadata(&path).unwrap();
|
||||
let mut cache = ScanCache::new();
|
||||
cache.remember(
|
||||
&FileIdentity::of(&path, &before),
|
||||
hit(&evidence(), None, false),
|
||||
);
|
||||
std::fs::write(&path, b"a longer second content").unwrap();
|
||||
let after = std::fs::metadata(&path).unwrap();
|
||||
assert_ne!(before.len(), after.len());
|
||||
assert!(
|
||||
cache.verdict(&FileIdentity::of(&path, &after)).is_none(),
|
||||
"the new bytes must not inherit the old verdict"
|
||||
);
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_survives_a_restart_and_can_be_invalidated() {
|
||||
let _guard = crate::state_guard("cache-persist");
|
||||
let path = probe("persist", b"remembered across sessions");
|
||||
let metadata = std::fs::metadata(&path).unwrap();
|
||||
let identity = FileIdentity::of(&path, &metadata);
|
||||
{
|
||||
let mut cache = ScanCache::new();
|
||||
cache.remember(&identity, hit(&evidence(), Some("beef"), false));
|
||||
cache.commit();
|
||||
}
|
||||
let mut reopened = ScanCache::new();
|
||||
let stored = reopened.verdict(&identity).expect("the cache is on disk");
|
||||
assert_eq!(stored.sha256.as_deref(), Some("beef"));
|
||||
reopened.invalidate();
|
||||
assert!(
|
||||
ScanCache::new().verdict(&identity).is_none(),
|
||||
"invalidating must forget everything, because the rules changed"
|
||||
);
|
||||
std::fs::remove_dir_all(path.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_are_reachable_by_id_and_only_by_id() {
|
||||
let scan = StoredScan {
|
||||
scan_id: "s1".into(),
|
||||
findings: vec![
|
||||
finding("s1#0", Confidence::Confirmed, "/tmp/one"),
|
||||
finding("s1#1", Confidence::Suspicious, "/tmp/two"),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let mut store = Store::new();
|
||||
store.set_scan(scan);
|
||||
assert_eq!(
|
||||
store.finding("s1#1").unwrap().confidence,
|
||||
Confidence::Suspicious
|
||||
);
|
||||
assert!(store.finding("/tmp/one").is_none(), "a path is not an id");
|
||||
assert!(store.finding("s1#9").is_none());
|
||||
let (confirmed, suspicious, _) = store.counts();
|
||||
assert_eq!((confirmed, suspicious), (1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quarantining_a_file_stops_it_being_offered_again() {
|
||||
let mut scan = StoredScan {
|
||||
scan_id: "s2".into(),
|
||||
findings: vec![finding("s2#0", Confidence::Confirmed, "/tmp/x")],
|
||||
..Default::default()
|
||||
};
|
||||
scan.findings[0].path = Some(PathBuf::from("/tmp/x"));
|
||||
let mut store = Store::new();
|
||||
store.set_scan(scan);
|
||||
assert_eq!(store.counts().0, 1);
|
||||
store.mark_quarantined(&[("q1".into(), PathBuf::from("/tmp/x"))]);
|
||||
assert_eq!(
|
||||
store.counts().0,
|
||||
0,
|
||||
"a dealt-with finding is not outstanding"
|
||||
);
|
||||
assert!(store.finding("s2#0").unwrap().quarantined);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_activity_list_is_bounded_and_newest_first() {
|
||||
let _guard = crate::state_guard("activity");
|
||||
let mut store = Store::new();
|
||||
for index in 0..250 {
|
||||
store.note("scan", format!("run {index}"), None);
|
||||
}
|
||||
assert!(store.activity().len() <= 200, "the log must stop growing");
|
||||
let recent = store.recent_activity(3);
|
||||
assert_eq!(recent.len(), 3);
|
||||
assert_eq!(recent[0].detail, "run 249", "newest first");
|
||||
assert!(
|
||||
activity_path().is_file(),
|
||||
"the log is written for the next session"
|
||||
);
|
||||
}
|
||||
|
||||
fn finding(id: &str, confidence: Confidence, path: &str) -> Finding {
|
||||
Finding {
|
||||
id: id.into(),
|
||||
confidence,
|
||||
path: Some(PathBuf::from(path)),
|
||||
display_path: Some(path.into()),
|
||||
name: "probe".into(),
|
||||
title: "probe".into(),
|
||||
description: String::new(),
|
||||
evidence: evidence(),
|
||||
size: 1,
|
||||
sha256: None,
|
||||
signed: false,
|
||||
publisher: None,
|
||||
found_at_ms: 0,
|
||||
quarantined: false,
|
||||
ignored: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -15,11 +15,20 @@ walkdir.workspace = true
|
|||
plist.workspace = true
|
||||
rayon.workspace = true
|
||||
unicode-width.workspace = true
|
||||
sysinfo.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.52"
|
||||
sysinfo.workspace = true
|
||||
windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.59", features = [
|
||||
"Win32_System_Console",
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_Security",
|
||||
"Win32_Security_Cryptography",
|
||||
"Win32_Security_WinTrust",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ pub mod console;
|
|||
pub mod currency;
|
||||
pub mod leftovers;
|
||||
pub mod process;
|
||||
pub mod process_table;
|
||||
pub mod protection;
|
||||
pub mod startup;
|
||||
pub mod trust;
|
||||
#[cfg(unix)]
|
||||
pub mod volumes;
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,241 @@
|
|||
//! The full process table, as opposed to the twelve busiest rows the meters
|
||||
//! panel draws.
|
||||
//!
|
||||
//! `squid-stats` samples every couple of seconds and must stay cheap, so it
|
||||
//! reports names and percentages. Answering "what is this thing, who started it
|
||||
//! and did anybody sign it" is a different question, asked when a person opens
|
||||
//! the Processes tab, and it tolerates a slower path: one refresh of the table
|
||||
//! plus a signature lookup for the executables actually on screen.
|
||||
//!
|
||||
//! The table is deliberately read-only here. Deciding whether a pid may be
|
||||
//! stopped is the job of [`crate::process`], which refuses squid itself and the
|
||||
//! processes a boot rests on; this module only describes what is running.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System, Users};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ProcessRow {
|
||||
pub pid: u32,
|
||||
pub parent: Option<u32>,
|
||||
pub name: String,
|
||||
pub command: String,
|
||||
pub program: Option<PathBuf>,
|
||||
pub working_directory: Option<PathBuf>,
|
||||
pub user: String,
|
||||
pub cpu: f32,
|
||||
pub memory: u64,
|
||||
pub started_ms: Option<u64>,
|
||||
/// Set later by the desktop layer, which owns the startup inventory: a
|
||||
/// process started by a login item is a different kind of thing than one
|
||||
/// the person launched themselves.
|
||||
pub startup_item: Option<String>,
|
||||
pub signed: bool,
|
||||
pub publisher: Option<String>,
|
||||
/// False for processes owned by somebody else, which squid must not stop.
|
||||
pub owned: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct ProcessTable {
|
||||
pub rows: Vec<ProcessRow>,
|
||||
pub taken_at_ms: u64,
|
||||
}
|
||||
|
||||
/// Snapshot the table. `with_trust` asks the operating system about each
|
||||
/// distinct executable once, which is the expensive part and is only wanted
|
||||
/// when the signature column is actually on screen.
|
||||
pub fn snapshot(with_trust: bool) -> ProcessTable {
|
||||
let mut system =
|
||||
System::new_with_specifics(RefreshKind::nothing().with_processes(process_kind()));
|
||||
system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind());
|
||||
snapshot_from(&system, with_trust)
|
||||
}
|
||||
|
||||
fn process_kind() -> ProcessRefreshKind {
|
||||
ProcessRefreshKind::nothing()
|
||||
.with_cmd(sysinfo::UpdateKind::Always)
|
||||
.with_exe(sysinfo::UpdateKind::Always)
|
||||
.with_cwd(sysinfo::UpdateKind::Always)
|
||||
.with_memory()
|
||||
.with_cpu()
|
||||
.with_user(sysinfo::UpdateKind::Always)
|
||||
}
|
||||
|
||||
fn snapshot_from(system: &System, with_trust: bool) -> ProcessTable {
|
||||
let users = Users::new_with_refreshed_list();
|
||||
let current_user = current_user_name();
|
||||
let mut cache: std::collections::HashMap<PathBuf, crate::trust::Trust> =
|
||||
std::collections::HashMap::new();
|
||||
let mut rows: Vec<ProcessRow> = system
|
||||
.processes()
|
||||
.values()
|
||||
.map(|process| {
|
||||
let program = process.exe().map(|path| path.to_path_buf());
|
||||
let command = process
|
||||
.cmd()
|
||||
.iter()
|
||||
.map(|part| part.to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let user = process
|
||||
.user_id()
|
||||
.and_then(|id| users.get_user_by_id(id))
|
||||
.map(|user| user.name().to_string())
|
||||
.unwrap_or_default();
|
||||
let mut row = ProcessRow {
|
||||
pid: process.pid().as_u32(),
|
||||
parent: process.parent().map(|pid| pid.as_u32()),
|
||||
name: name_of(process.name()),
|
||||
command,
|
||||
started_ms: start_time_ms(process.start_time()),
|
||||
program,
|
||||
working_directory: process.cwd().map(|path| path.to_path_buf()),
|
||||
user,
|
||||
cpu: process.cpu_usage().min(4_000.0),
|
||||
memory: process.memory(),
|
||||
startup_item: None,
|
||||
signed: false,
|
||||
publisher: None,
|
||||
owned: true,
|
||||
};
|
||||
row.owned = row.user.is_empty()
|
||||
|| current_user.is_empty()
|
||||
|| row.user.eq_ignore_ascii_case(¤t_user);
|
||||
|
||||
if with_trust {
|
||||
if let Some(program) = row.program.as_deref() {
|
||||
let trust = cache.entry(program.to_path_buf()).or_insert_with(|| {
|
||||
if crate::trust::might_be_executable(program) {
|
||||
crate::trust::assess(program)
|
||||
} else {
|
||||
Default::default()
|
||||
}
|
||||
});
|
||||
row.signed = trust.signed;
|
||||
row.publisher = trust.signer.clone();
|
||||
}
|
||||
}
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
|
||||
rows.sort_by(|a, b| b.memory.cmp(&a.memory).then_with(|| a.pid.cmp(&b.pid)));
|
||||
ProcessTable {
|
||||
rows,
|
||||
taken_at_ms: now_ms(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, re-read right now. The desktop layer asks this before it stops
|
||||
/// anything, so the name the person clicked is checked against the pid that
|
||||
/// answers to that number today.
|
||||
pub fn row_of(pid: u32) -> Option<ProcessRow> {
|
||||
let mut system = System::new_with_specifics(RefreshKind::nothing());
|
||||
system.refresh_processes_specifics(
|
||||
ProcessesToUpdate::Some(&[sysinfo::Pid::from_u32(pid)]),
|
||||
true,
|
||||
process_kind(),
|
||||
);
|
||||
let process = system.process(sysinfo::Pid::from_u32(pid))?;
|
||||
Some(ProcessRow {
|
||||
pid,
|
||||
parent: process.parent().map(|pid| pid.as_u32()),
|
||||
name: name_of(process.name()),
|
||||
command: process
|
||||
.cmd()
|
||||
.iter()
|
||||
.map(|part| part.to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
program: process.exe().map(|path| path.to_path_buf()),
|
||||
working_directory: process.cwd().map(|path| path.to_path_buf()),
|
||||
user: String::new(),
|
||||
cpu: process.cpu_usage(),
|
||||
memory: process.memory(),
|
||||
started_ms: start_time_ms(process.start_time()),
|
||||
startup_item: None,
|
||||
signed: false,
|
||||
publisher: None,
|
||||
owned: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn name_of(name: &std::ffi::OsStr) -> String {
|
||||
name.to_string_lossy()
|
||||
.split(['/', '\\'])
|
||||
.next_back()
|
||||
.filter(|part| !part.is_empty())
|
||||
.unwrap_or("?")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// sysinfo reports Unix start times as seconds since boot; Windows and newer
|
||||
/// sysinfo releases report seconds since the epoch. Anything that already looks
|
||||
/// like an epoch passes through, so a wrong guess cannot turn into a date in
|
||||
/// 1970 on every row.
|
||||
fn start_time_ms(raw: u64) -> Option<u64> {
|
||||
if raw == 0 {
|
||||
return None;
|
||||
}
|
||||
let uptime = System::uptime();
|
||||
let now = now_ms() / 1_000;
|
||||
if raw > 1_000_000_000 && raw <= now {
|
||||
return Some(raw.saturating_mul(1_000));
|
||||
}
|
||||
if raw <= uptime {
|
||||
return Some(now.saturating_sub(raw).saturating_mul(1_000));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The account squid runs as. Ownership is compared by name because a process
|
||||
/// reports a uid/SID and the user table is the only thing that turns either one
|
||||
/// into the name a person recognises — the same source `HostInfo` prints.
|
||||
fn current_user_name() -> String {
|
||||
std::env::var("USER")
|
||||
.or_else(|_| std::env::var("USERNAME"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|since| since.as_millis() as u64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_describes_the_test_process() {
|
||||
let table = snapshot(false);
|
||||
assert!(
|
||||
table.rows.iter().any(|row| row.pid == std::process::id()),
|
||||
"the process running this test is missing from the table"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_can_be_re_read_by_pid() {
|
||||
let here = std::process::id();
|
||||
let row = row_of(here).expect("this process is running");
|
||||
assert_eq!(row.pid, here);
|
||||
assert!(!row.name.is_empty());
|
||||
assert!(row_of(u32::MAX).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysinfo_start_times_are_normalised_to_millis() {
|
||||
// Seconds since boot, which is what sysinfo gives on unix.
|
||||
assert!(start_time_ms(10).is_some());
|
||||
// Seconds since the epoch, which is what it gives on Windows.
|
||||
let epoch = 1_700_000_000;
|
||||
assert_eq!(start_time_ms(epoch), Some(epoch * 1_000));
|
||||
assert_eq!(start_time_ms(0), None);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,313 @@
|
|||
//! What the operating system's own protection says about itself.
|
||||
//!
|
||||
//! Squid reads this and never writes it. `xprotect status` and `xprotect
|
||||
//! version` are queried, `xprotect update` deliberately is not: that command
|
||||
//! contacts Apple's servers on the machine's behalf, and a third-party app
|
||||
//! starting downloads it did not pay for is not squid's to decide. The same
|
||||
//! restraint applies to Defender.
|
||||
//!
|
||||
//! The reason to show any of it is honesty about coverage. XProtect runs with or
|
||||
//! without squid, and a user who sees "background scanning: off" can act on that
|
||||
//! in System Settings. A user who sees nothing assumes it is on.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The state of the protection the operating system provides itself.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProtectionStatus {
|
||||
/// `xprotect`, `defender`, `third-party`, `unknown`.
|
||||
pub provider: String,
|
||||
/// Whether the state above was actually read, as opposed to assumed.
|
||||
pub known: bool,
|
||||
/// Signature/definition version, in whatever notation the platform uses.
|
||||
pub definitions: String,
|
||||
/// When those definitions were installed or last refreshed.
|
||||
pub definitions_date: String,
|
||||
pub realtime: Option<bool>,
|
||||
pub background_scans: Option<bool>,
|
||||
pub launch_scans: Option<bool>,
|
||||
/// Gatekeeper (`spctl`) or the Windows Defender engine state.
|
||||
pub gatekeeper: Option<bool>,
|
||||
pub last_scan_date: String,
|
||||
/// Anything that could not be determined, in plain words.
|
||||
pub notes: Vec<String>,
|
||||
pub product_name: String,
|
||||
}
|
||||
|
||||
impl ProtectionStatus {
|
||||
/// Unknown must never be rendered as healthy. This is the guard against a
|
||||
/// probe that fails on a clean machine and reports green.
|
||||
pub fn is_healthy(&self) -> Option<bool> {
|
||||
if !self.known {
|
||||
return None;
|
||||
}
|
||||
match self.provider.as_str() {
|
||||
"xprotect" => Some(
|
||||
self.realtime.unwrap_or(true)
|
||||
&& self.background_scans.unwrap_or(true)
|
||||
&& self.launch_scans.unwrap_or(true),
|
||||
),
|
||||
"defender" | "third-party" => Some(self.realtime.unwrap_or(false)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the operating system. Never fails; a platform with nothing to report says
|
||||
/// so through `known: false` and a note.
|
||||
pub fn status() -> ProtectionStatus {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::status()
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::status()
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
ProtectionStatus {
|
||||
provider: "unknown".into(),
|
||||
known: false,
|
||||
notes: vec!["this platform has no protection status that Squid can read".into()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use super::*;
|
||||
|
||||
fn run(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if output.status.success() {
|
||||
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status() -> ProtectionStatus {
|
||||
let mut status = ProtectionStatus {
|
||||
provider: "xprotect".into(),
|
||||
product_name: "XProtect".into(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match run("/usr/bin/xprotect", &["status", "--json"]) {
|
||||
Some(json) => match serde_json::from_str::<serde_json::Value>(&json) {
|
||||
Ok(value) => {
|
||||
status.known = true;
|
||||
status.background_scans = value
|
||||
.get("xprotect_background_scans")
|
||||
.and_then(|value| value.as_bool());
|
||||
status.launch_scans = value
|
||||
.get("xprotect_launch_scans")
|
||||
.and_then(|value| value.as_bool());
|
||||
status.realtime = status.launch_scans;
|
||||
}
|
||||
Err(error) => status
|
||||
.notes
|
||||
.push(format!("XProtect status was unreadable: {error}")),
|
||||
},
|
||||
None => status.notes.push(
|
||||
"XProtect did not report its state. macOS 13 and later answer this query.".into(),
|
||||
),
|
||||
}
|
||||
|
||||
if let Some(json) = run("/usr/bin/xprotect", &["version", "--json"]) {
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json) {
|
||||
if let Some(version) = value
|
||||
.get("xprotect_bundle_version")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
status.definitions = version.to_string();
|
||||
}
|
||||
if let Some(date) = value
|
||||
.get("xprotect_bundle_install_date")
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
status.definitions_date = date.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gatekeeper answers for whether a downloaded app can run at all.
|
||||
match run("/usr/sbin/spctl", &["--status"]) {
|
||||
Some(text) => status.gatekeeper = Some(text.contains("assessments enabled")),
|
||||
None => status
|
||||
.notes
|
||||
.push("Gatekeeper status could not be read.".into()),
|
||||
}
|
||||
|
||||
if !status.known {
|
||||
status.provider = "unknown".into();
|
||||
}
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use std::os::windows::process::CommandExt;
|
||||
use std::process::Command;
|
||||
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY};
|
||||
use winreg::RegKey;
|
||||
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
|
||||
/// Defender's own registry view answers without a WMI round trip: the
|
||||
/// product-registration key names the active antivirus, and the
|
||||
/// `CurrentReputation`/`Signature` keys carry the definition version.
|
||||
pub fn status() -> ProtectionStatus {
|
||||
let mut status = ProtectionStatus {
|
||||
provider: "unknown".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let base = match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
|
||||
r"SOFTWARE\Microsoft\Windows Defender",
|
||||
KEY_READ | KEY_WOW64_64KEY,
|
||||
) {
|
||||
Ok(base) => base,
|
||||
Err(_) => {
|
||||
status
|
||||
.notes
|
||||
.push("Windows Defender is not registered on this machine.".into());
|
||||
return status;
|
||||
}
|
||||
};
|
||||
|
||||
let disabled = base.get_value::<u32, _>("DisableAntiSpyware").unwrap_or(0) != 0;
|
||||
|
||||
if let Ok(signatures) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
|
||||
r"SOFTWARE\Microsoft\Windows Defender\Signature Updates",
|
||||
KEY_READ | KEY_WOW64_64KEY,
|
||||
) {
|
||||
if let Some(version) = signatures
|
||||
.get_value::<String, _>("SignatureDefinitionVersion")
|
||||
.ok()
|
||||
.or_else(|| signatures.get_value::<String, _>("AMRunVersion").ok())
|
||||
{
|
||||
status.definitions = version;
|
||||
}
|
||||
if let Ok(days) = signatures.get_value::<u32, _>("LastSignatureUpdateAge") {
|
||||
status.definitions_date = format!("{days} days ago");
|
||||
}
|
||||
status.known = true;
|
||||
}
|
||||
|
||||
// A third-party product that registered itself replaces Defender.
|
||||
let registered = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
|
||||
r"SOFTWARE\Microsoft\Windows Defender\FeatureManagement",
|
||||
KEY_READ | KEY_WOW64_64KEY,
|
||||
);
|
||||
let _ = registered;
|
||||
match active_antivirus() {
|
||||
Some(name) if !name.is_empty() => {
|
||||
status.product_name = name.clone();
|
||||
status.provider = if name.contains("Windows Defender") || name.contains("Defender")
|
||||
{
|
||||
"defender".into()
|
||||
} else {
|
||||
"third-party".into()
|
||||
};
|
||||
status.known = true;
|
||||
}
|
||||
_ => {
|
||||
status.provider = if disabled {
|
||||
"unknown".into()
|
||||
} else {
|
||||
"defender".into()
|
||||
};
|
||||
status.product_name = "Microsoft Defender Antivirus".into();
|
||||
status.realtime = Some(!disabled);
|
||||
}
|
||||
}
|
||||
if !status.known {
|
||||
status
|
||||
.notes
|
||||
.push("Windows Security Center did not report an antivirus product.".into());
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Security Center's registration list, via WMI. One subprocess, no service.
|
||||
fn active_antivirus() -> Option<String> {
|
||||
let script = "Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct | Select-Object -ExpandProperty displayName";
|
||||
let output = Command::new("powershell.exe")
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.args([
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
script,
|
||||
])
|
||||
.spawn()
|
||||
.ok()?
|
||||
.wait_with_output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())?
|
||||
.to_string();
|
||||
Some(text)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unknown_is_never_reported_as_healthy() {
|
||||
let unknown = ProtectionStatus {
|
||||
provider: "unknown".into(),
|
||||
known: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(unknown.is_healthy(), None);
|
||||
|
||||
let xprotect = ProtectionStatus {
|
||||
provider: "xprotect".into(),
|
||||
known: true,
|
||||
background_scans: Some(true),
|
||||
launch_scans: Some(true),
|
||||
realtime: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(xprotect.is_healthy(), Some(true));
|
||||
|
||||
let off = ProtectionStatus {
|
||||
provider: "defender".into(),
|
||||
known: true,
|
||||
realtime: Some(false),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(off.is_healthy(), Some(false));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn the_real_machine_answers_the_query() {
|
||||
let status = status();
|
||||
// Whether or not protection is on, the probe must produce something a
|
||||
// person can read rather than an empty card.
|
||||
assert!(
|
||||
status.known || !status.notes.is_empty(),
|
||||
"the probe said nothing at all: {status:?}"
|
||||
);
|
||||
assert!(!status.product_name.is_empty());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,734 @@
|
|||
//! Who signed this file, as far as the operating system will say.
|
||||
//!
|
||||
//! The answer is used in two places: the startup list colours an entry that
|
||||
//! nobody vouches for, and the scanner treats "unsigned binary in a user-writable
|
||||
//! path that runs at login" as evidence. It is deliberately not treated as a
|
||||
//! verdict. An unsigned file is ordinary for anything a person built themselves,
|
||||
//! and a signed file is ordinary for adware that bought a certificate, so the
|
||||
//! UI says *unsigned* rather than *suspicious* and leaves the reasoning to the
|
||||
//! reader.
|
||||
//!
|
||||
//! macOS asks `codesign`, which is the same tool the release scripts use, so the
|
||||
//! app and the release check cannot disagree about what "ad-hoc signed" means.
|
||||
//! Windows asks the Authenticode API directly, because the PowerShell equivalent
|
||||
//! costs a second to start and the process table asks this question per row.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
/// What the signature says about one file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Trust {
|
||||
/// A signature exists and the operating system considers it intact.
|
||||
pub signed: bool,
|
||||
/// Ad-hoc / link-time signature: bytes are sealed, but nobody is named.
|
||||
pub ad_hoc: bool,
|
||||
/// Authenticode is present but chain validation failed (expired, unknown CA).
|
||||
pub untrusted: bool,
|
||||
/// Vendor named by the leaf certificate.
|
||||
pub signer: Option<String>,
|
||||
/// Why there is no signature, when that is worth saying.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Trust {
|
||||
/// One word for a table column.
|
||||
pub fn state(&self) -> &'static str {
|
||||
if self.signed && !self.ad_hoc && !self.untrusted {
|
||||
"trusted"
|
||||
} else if self.signed {
|
||||
"adhoc"
|
||||
} else if self.untrusted {
|
||||
"untrusted"
|
||||
} else {
|
||||
"unsigned"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the operating system about one file. Never fails: no answer is a normal
|
||||
/// answer, and the caller decides whether silence is worth showing.
|
||||
///
|
||||
/// Answers are remembered for the life of the process, keyed by path plus the
|
||||
/// file's size and modification time, because both callers ask in bulk: the
|
||||
/// startup list asks once per entry and the process table once per distinct
|
||||
/// executable on screen. The question itself costs a subprocess on macOS and a
|
||||
/// certificate-chain walk on Windows, so one refresh of the process tab would be
|
||||
/// hundreds of them. A file that changes is looked up again, which is why the
|
||||
/// identity is part of the key and not the path alone.
|
||||
pub fn assess(path: &Path) -> Trust {
|
||||
let Some(key) = identity(path) else {
|
||||
// Nothing to key on. Asking anyway is what turns "the file is not there"
|
||||
// into an answer instead of a cached guess.
|
||||
return assess_uncached(path);
|
||||
};
|
||||
let mut cache = cache()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(found) = cache.get(&key) {
|
||||
return found.clone();
|
||||
}
|
||||
let trust = assess_uncached(path);
|
||||
// Bounded, because a utility that grows its own footprint to answer a
|
||||
// display question is its own kind of junk. Half is dropped rather than all,
|
||||
// so a table that is still on screen keeps the answers it is showing.
|
||||
if cache.len() > 4_000 {
|
||||
let stale: Vec<_> = cache.keys().take(cache.len() / 2).cloned().collect();
|
||||
for stale in stale {
|
||||
cache.remove(&stale);
|
||||
}
|
||||
}
|
||||
cache.insert(key, trust.clone());
|
||||
trust
|
||||
}
|
||||
|
||||
type CacheKey = (std::path::PathBuf, u64, u128);
|
||||
|
||||
fn identity(path: &Path) -> Option<CacheKey> {
|
||||
let metadata = std::fs::symlink_metadata(path).ok()?;
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|since| since.as_nanos())
|
||||
.unwrap_or(0);
|
||||
Some((path.to_path_buf(), metadata.len(), modified))
|
||||
}
|
||||
|
||||
fn cache() -> &'static std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>> {
|
||||
static CACHE: std::sync::OnceLock<
|
||||
std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>>,
|
||||
> = std::sync::OnceLock::new();
|
||||
CACHE.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
fn assess_uncached(path: &Path) -> Trust {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::assess(path)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::assess(path)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
Trust::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file carries a signature *blob*, without asking the operating
|
||||
/// system to validate it.
|
||||
///
|
||||
/// This is the cheap sibling of [`assess`]: it reads the Mach-O load commands or
|
||||
/// the PE certificate directory and stops, so it can run over every row of a
|
||||
/// process table or every candidate in a full scan. What it cannot tell you is
|
||||
/// whether that signature is trusted, which is exactly the difference a person
|
||||
/// needs when they open the row — and that is why the detail view still asks
|
||||
/// `assess` and this result is only ever shown as "signed by somebody" or "no
|
||||
/// signature at all".
|
||||
pub fn has_signature_blob(path: &Path) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macho_has_signature(path)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
pe_has_certificate(path)
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan the load commands for `LC_CODE_SIGNATURE` (0x1D), in either endianness,
|
||||
/// and into each slice of a fat binary.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macho_has_signature(path: &Path) -> bool {
|
||||
// Only the head of the image is ever consulted: a Mach-O header plus a
|
||||
// thousand load commands is a few tens of kilobytes, and a fat binary keeps
|
||||
// its first slice within the first megabyte. Reading a four-gigabyte disk
|
||||
// image whole to answer one yes/no question is the kind of cost that gets a
|
||||
// scanner switched off.
|
||||
const WINDOW: u64 = 2 * 1024 * 1024;
|
||||
let Ok(length) = std::fs::metadata(path).map(|metadata| metadata.len()) else {
|
||||
return false;
|
||||
};
|
||||
if length < 32 {
|
||||
return false;
|
||||
}
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
let mut bytes = Vec::with_capacity((WINDOW).min(length) as usize);
|
||||
{
|
||||
use std::io::Read;
|
||||
if Read::by_ref(&mut file)
|
||||
.take(WINDOW)
|
||||
.read_to_end(&mut bytes)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if bytes.len() < 32 {
|
||||
return false;
|
||||
}
|
||||
let word = |bytes: &[u8], offset: usize, big: bool| -> Option<u32> {
|
||||
let window = bytes.get(offset..offset + 4)?;
|
||||
Some(if big {
|
||||
u32::from_be_bytes(window.try_into().ok()?)
|
||||
} else {
|
||||
u32::from_le_bytes(window.try_into().ok()?)
|
||||
})
|
||||
};
|
||||
let head = [bytes[0], bytes[1], bytes[2], bytes[3]];
|
||||
const FAT_32: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE];
|
||||
const FAT_SWAPPED: [u8; 4] = [0xBE, 0xBA, 0xFE, 0xCA];
|
||||
if head == FAT_32 || head == FAT_SWAPPED {
|
||||
// The fat header is always big-endian in practice; the spelling of its
|
||||
// magic says which order it was actually written in, and that governs
|
||||
// only the table below — each slice re-declares its own endianness.
|
||||
let big = head == FAT_32;
|
||||
let count = word(&bytes, 4, big).unwrap_or(0).min(32) as usize;
|
||||
for index in 0..count {
|
||||
// fat_arch: cputype, cpusubtype, offset, size, align.
|
||||
let Some(offset) = word(&bytes, 8 + index * 20 + 8, big) else {
|
||||
continue;
|
||||
};
|
||||
// Each slice carries its own magic, and therefore its own
|
||||
// endianness: a fat header written big-endian normally contains
|
||||
// little-endian arm64 and x86_64 images.
|
||||
if macho_slice_signed(&bytes, offset as usize, &word) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
macho_slice_signed(&bytes, 0, &word)
|
||||
}
|
||||
|
||||
/// Walk one Mach-O header's load commands looking for the signature command.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macho_slice_signed(
|
||||
bytes: &[u8],
|
||||
start: usize,
|
||||
word: &impl Fn(&[u8], usize, bool) -> Option<u32>,
|
||||
) -> bool {
|
||||
const LC_CODE_SIGNATURE: u32 = 0x1D;
|
||||
// A 64-bit little-endian image begins `CF FA ED FE` — the magic 0xFEEDFACF
|
||||
// read back as little-endian — and a big-endian one begins with the same
|
||||
// four bytes in reverse. The 32-bit pair differs by one byte. Which spelling
|
||||
// appeared is the only thing that decides the endianness of every field
|
||||
// after it, so the table says it directly instead of inferring it from
|
||||
// wherever this header was reached from.
|
||||
// Which magic appeared decides two things at once: the endianness of every
|
||||
// field after it, and whether this is a 64-bit header (32 bytes) or a
|
||||
// 32-bit one (28 bytes). Getting either wrong reads the load commands from
|
||||
// the wrong address and reports a signed binary as unsigned.
|
||||
const THIN: [([u8; 4], bool, usize); 4] = [
|
||||
([0xCF, 0xFA, 0xED, 0xFE], false, 32), // MH_MAGIC_64, host order
|
||||
([0xCE, 0xFA, 0xED, 0xFE], false, 28), // MH_MAGIC, host order
|
||||
([0xFE, 0xED, 0xFA, 0xCF], true, 32), // MH_MAGIC_64, swapped
|
||||
([0xFE, 0xED, 0xFA, 0xCE], true, 28), // MH_MAGIC, swapped
|
||||
];
|
||||
let Some(head) = bytes.get(start..start + 4) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(head): Result<[u8; 4], _> = head.try_into() else {
|
||||
return false;
|
||||
};
|
||||
let Some((_, big, header)) = THIN.iter().find(|(magic, _, _)| *magic == head) else {
|
||||
return false;
|
||||
};
|
||||
let (big, header) = (*big, *header);
|
||||
// A corrupt fat header can point a slice past what was actually read.
|
||||
if start + header > bytes.len() {
|
||||
return false;
|
||||
}
|
||||
// mach_header: magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds…
|
||||
// `ncmds` is the fifth field, at offset 16 — reading 12 instead finds
|
||||
// `filetype`, which is how every signed binary looks unsigned.
|
||||
let commands = word(bytes, start + 16, big).unwrap_or(0).min(4096) as usize;
|
||||
let mut cursor = start + header;
|
||||
for _ in 0..commands {
|
||||
let Some(command) = word(bytes, cursor, big) else {
|
||||
return false;
|
||||
};
|
||||
// High bit marks a 64-bit-only command; the number underneath is the same.
|
||||
if command & 0x7FFF_FFFF == LC_CODE_SIGNATURE {
|
||||
return true;
|
||||
}
|
||||
let Some(size) = word(bytes, cursor + 4, big) else {
|
||||
return false;
|
||||
};
|
||||
if size < 8 {
|
||||
return false;
|
||||
}
|
||||
cursor += size as usize;
|
||||
if cursor + 8 > bytes.len() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A PE file's certificate table is data directory entry 4: an offset into the
|
||||
/// file, not a relative virtual address, which makes it a four-byte read once
|
||||
/// the header has been walked.
|
||||
#[cfg(windows)]
|
||||
fn pe_has_certificate(path: &Path) -> bool {
|
||||
pe_has_certificate_at(path).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The same walk written against `Option`, so an out-of-range field is a plain
|
||||
/// "no" rather than a panic. Split out because `?` in the `bool`-returning
|
||||
/// wrapper above does not compile, and this half only builds on Windows, so the
|
||||
/// mistake is invisible to a macOS `cargo check`.
|
||||
#[cfg(windows)]
|
||||
fn pe_has_certificate_at(path: &Path) -> Option<bool> {
|
||||
use std::io::Read;
|
||||
let length = std::fs::metadata(path).ok()?.len();
|
||||
let mut file = std::fs::File::open(path).ok()?;
|
||||
let mut head = [0_u8; 4096];
|
||||
let read = file.read(&mut head).ok()?;
|
||||
let u32_at = |offset: usize| -> Option<u32> {
|
||||
let window = head.get(offset..offset + 4)?;
|
||||
Some(u32::from_le_bytes(window.try_into().ok()?))
|
||||
};
|
||||
if read < 64 || &head[0..2] != b"MZ" {
|
||||
return Some(false);
|
||||
}
|
||||
let pe = u32_at(0x3C)? as usize;
|
||||
if pe + 24 > read || &head[pe..pe + 4] != b"PE\0\0" {
|
||||
return Some(false);
|
||||
}
|
||||
let optional = pe + 24;
|
||||
let magic = u32_at(optional)? & 0xFFFF;
|
||||
// Data directories start after the optional header; their offset differs
|
||||
// between PE32 and PE32+, which is what the magic byte says.
|
||||
let directories = optional + if magic == 0x20B { 112 } else { 96 };
|
||||
let entry = u32_at(directories + 4 * 8)?;
|
||||
let size = u32_at(directories + 4 * 8 + 4)?;
|
||||
Some(entry != 0 && size != 0 && (entry as u64) < length)
|
||||
}
|
||||
|
||||
/// Cheap gate for a table with hundreds of rows: only Mach-O and PE files can
|
||||
/// carry a signature, so everything else is answered without a subprocess.
|
||||
pub fn might_be_executable(path: &Path) -> bool {
|
||||
if path.is_dir() {
|
||||
return false;
|
||||
}
|
||||
if path.extension().is_some() {
|
||||
const SIGNED_KINDS: [&str; 9] = [
|
||||
"app",
|
||||
"framework",
|
||||
"bundle",
|
||||
"xpc",
|
||||
"dylib",
|
||||
"so",
|
||||
"exe",
|
||||
"dll",
|
||||
"sys",
|
||||
];
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|ext| ext.to_string_lossy().to_lowercase())
|
||||
.unwrap_or_default();
|
||||
return SIGNED_KINDS.contains(&ext.as_str()) || ext.is_empty();
|
||||
}
|
||||
// Extension-less binaries are the norm on macOS, so the header decides.
|
||||
header_is_executable(path)
|
||||
}
|
||||
|
||||
fn header_is_executable(path: &Path) -> bool {
|
||||
use std::io::Read;
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return false;
|
||||
};
|
||||
let mut head = [0_u8; 8];
|
||||
let Ok(_) = file.read(&mut head) else {
|
||||
return false;
|
||||
};
|
||||
// Mach-O 32/64, fat binary, and their byte-swapped forms.
|
||||
const MACHOS: [[u8; 4]; 6] = [
|
||||
[0xcf, 0xfa, 0xed, 0xfe],
|
||||
[0xce, 0xfa, 0xed, 0xfe],
|
||||
[0xca, 0xfe, 0xba, 0xbe],
|
||||
[0xfe, 0xed, 0xfa, 0xcf],
|
||||
[0xfe, 0xed, 0xfa, 0xce],
|
||||
[0xbe, 0xba, 0xfe, 0xca],
|
||||
];
|
||||
if MACHOS.iter().any(|magic| head.starts_with(magic)) {
|
||||
return true;
|
||||
}
|
||||
// PE: `MZ` at the front, `PE\0\0` wherever the header table points.
|
||||
head.starts_with(b"MZ")
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
const CODESIGN: &str = "/usr/bin/codesign";
|
||||
|
||||
/// Resolves an `.app` to the binary `codesign` should be asked about, since
|
||||
/// asking about the bundle is what `--verify --deep` would do anyway.
|
||||
fn executable_of(path: &Path) -> PathBuf {
|
||||
let candidate = path.join("Contents/MacOS");
|
||||
let Ok(entries) = std::fs::read_dir(&candidate) else {
|
||||
return path.to_path_buf();
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.find(|path| path.is_file())
|
||||
.unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
pub fn assess(path: &Path) -> Trust {
|
||||
if !path.exists() {
|
||||
return Trust {
|
||||
note: Some("the file is not there".into()),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
if !super::might_be_executable(path) {
|
||||
return Trust::default();
|
||||
}
|
||||
let target = if path.is_dir() {
|
||||
executable_of(path)
|
||||
} else {
|
||||
path.to_path_buf()
|
||||
};
|
||||
let Ok(output) = Command::new(CODESIGN)
|
||||
.args(["-dvv", &target.display().to_string()])
|
||||
.output()
|
||||
else {
|
||||
return Trust {
|
||||
note: Some("codesign could not run".into()),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
// `codesign -dvv` writes its report to stderr and exits non-zero for
|
||||
// unsigned files, which is an answer rather than a failure.
|
||||
let report = String::from_utf8_lossy(&output.stderr).into_owned();
|
||||
if report.contains("code object is not signed at all") || report.is_empty() {
|
||||
return Trust {
|
||||
note: (!report.is_empty()).then(|| "not signed".into()),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
let signer = report
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("Authority="))
|
||||
.map(|name| name.trim().to_string());
|
||||
let team = report
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("TeamIdentifier="))
|
||||
.map(|value| value.trim().to_string());
|
||||
let ad_hoc = team.as_deref() == Some("not set") && signer.is_none();
|
||||
let signed = signer.is_some()
|
||||
|| report.contains("CodeDirectory") && !ad_hoc
|
||||
|| report.contains("Signature size");
|
||||
|
||||
if ad_hoc {
|
||||
return Trust {
|
||||
signed: true,
|
||||
ad_hoc: true,
|
||||
note: Some("ad-hoc signed — the bytes are sealed, nobody is named".into()),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
if !signed {
|
||||
return Trust {
|
||||
note: Some("no usable signature".into()),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
Trust {
|
||||
signed: true,
|
||||
signer: signer.or(team),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
|
||||
/// Ask Authenticode through `WinVerifyTrust`. The status codes are read so
|
||||
/// an expired or unrooted certificate reports as *untrusted* rather than as
|
||||
/// unsigned: those files were signed by somebody, and a person deciding
|
||||
/// whether to quarantine them deserves to know that much.
|
||||
pub fn assess(path: &Path) -> Trust {
|
||||
if !super::might_be_executable(path) {
|
||||
return Trust::default();
|
||||
}
|
||||
if !path.exists() {
|
||||
return Trust {
|
||||
note: Some("the file is not there".into()),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
match authenticode(path) {
|
||||
Ok(()) => Trust {
|
||||
signed: true,
|
||||
signer: publisher(path),
|
||||
..Default::default()
|
||||
},
|
||||
Err(status) => {
|
||||
const NO_SIGNATURE: [u32; 2] = [0x800b0100, 0xc0000225];
|
||||
let present = !NO_SIGNATURE.contains(&status);
|
||||
Trust {
|
||||
untrusted: present,
|
||||
signer: present.then(|| publisher(path)).flatten(),
|
||||
note: Some(format!("Authenticode reported 0x{status:08x}")),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticode(path: &Path) -> Result<(), u32> {
|
||||
use windows_sys::core::GUID;
|
||||
use windows_sys::Win32::Security::WinTrust::{
|
||||
WinVerifyTrust, WINTRUST_DATA, WINTRUST_DATA_0, WINTRUST_FILE_INFO, WTD_CHOICE_FILE,
|
||||
WTD_REVOKE_NONE, WTD_STATEACTION_IGNORE, WTD_UI_NONE,
|
||||
};
|
||||
|
||||
// WINTRUST_ACTION_GENERIC_VERIFY_V2
|
||||
const ACTION: GUID = GUID::from_u128(0x00aa003c_0000_0000_c000_000000000046);
|
||||
|
||||
let wide = wide_path(path);
|
||||
let mut file_info = WINTRUST_FILE_INFO {
|
||||
cbStruct: std::mem::size_of::<WINTRUST_FILE_INFO>() as u32,
|
||||
pcwszFilePath: wide.as_ptr(),
|
||||
hFile: std::ptr::null_mut(),
|
||||
pgKnownSubject: std::ptr::null_mut(),
|
||||
};
|
||||
let mut data = WINTRUST_DATA {
|
||||
cbStruct: std::mem::size_of::<WINTRUST_DATA>() as u32,
|
||||
pPolicyCallbackData: std::ptr::null_mut(),
|
||||
pSIPClientData: std::ptr::null_mut(),
|
||||
dwUIChoice: WTD_UI_NONE,
|
||||
fdwRevocationChecks: WTD_REVOKE_NONE,
|
||||
dwUnionChoice: WTD_CHOICE_FILE,
|
||||
Anonymous: WINTRUST_DATA_0 {
|
||||
pFile: &mut file_info,
|
||||
},
|
||||
dwStateAction: WTD_STATEACTION_IGNORE,
|
||||
hWVTStateData: std::ptr::null_mut(),
|
||||
pwszURLReference: std::ptr::null_mut(),
|
||||
dwProvFlags: 0,
|
||||
dwUIContext: 0,
|
||||
pSignatureSettings: std::ptr::null_mut(),
|
||||
};
|
||||
let status = unsafe {
|
||||
WinVerifyTrust(
|
||||
std::ptr::null_mut(),
|
||||
&mut ACTION.clone() as *mut GUID,
|
||||
&mut data as *mut _ as *mut std::ffi::c_void,
|
||||
)
|
||||
};
|
||||
if status == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(status as u32)
|
||||
}
|
||||
}
|
||||
|
||||
fn wide_path(path: &Path) -> Vec<u16> {
|
||||
path.to_string_lossy()
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `CompanyName` of the version resource: what Task Manager prints as
|
||||
/// Publisher, and a magnitude cheaper than parsing the certificate chain.
|
||||
fn publisher(path: &Path) -> Option<String> {
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW,
|
||||
};
|
||||
|
||||
let wide = wide_path(path);
|
||||
let size = unsafe { GetFileVersionInfoSizeW(wide.as_ptr(), std::ptr::null_mut()) };
|
||||
if size == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut buffer = vec![0_u8; size as usize];
|
||||
let ok = unsafe { GetFileVersionInfoW(wide.as_ptr(), 0, size, buffer.as_mut_ptr().cast()) };
|
||||
if ok == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut pointer: *mut std::ffi::c_void = std::ptr::null_mut();
|
||||
let mut length = 0_u32;
|
||||
let translation = wide_str("\\VarFileInfo\\Translation");
|
||||
let found = unsafe {
|
||||
VerQueryValueW(
|
||||
buffer.as_ptr().cast(),
|
||||
translation.as_ptr(),
|
||||
&mut pointer,
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
let (language, code_page) = if found == 0 || length < 4 {
|
||||
(0x0409, 1200)
|
||||
} else {
|
||||
let pairs = unsafe {
|
||||
std::slice::from_raw_parts(pointer.cast::<(u16, u16)>(), (length / 4) as usize)
|
||||
};
|
||||
pairs.first().copied().unwrap_or((0x0409, 1200))
|
||||
};
|
||||
|
||||
let key = wide_str(&format!("\\StringInfo\\{language:04x}{code_page:04x}"));
|
||||
let found = unsafe {
|
||||
VerQueryValueW(
|
||||
buffer.as_ptr().cast(),
|
||||
key.as_ptr(),
|
||||
&mut pointer,
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
if found == 0 || length == 0 {
|
||||
return None;
|
||||
}
|
||||
let block =
|
||||
unsafe { std::slice::from_raw_parts(pointer.cast::<u16>(), (length / 2) as usize) };
|
||||
string_value(block, "CompanyName")
|
||||
}
|
||||
|
||||
fn wide_str(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
|
||||
/// The `StringFileInfo` block is `key\0value\0key\0value\0…` in UTF-16,
|
||||
/// terminated by an empty key.
|
||||
fn string_value(block: &[u16], wanted: &str) -> Option<String> {
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
let mut current: Vec<u16> = Vec::new();
|
||||
for unit in block {
|
||||
if *unit == 0 {
|
||||
if !current.is_empty() {
|
||||
let taken: Vec<u16> = std::mem::take(&mut current);
|
||||
entries.push(String::from_utf16_lossy(&taken));
|
||||
}
|
||||
} else {
|
||||
current.push(*unit);
|
||||
}
|
||||
}
|
||||
for pair in entries.as_chunks::<2>().0 {
|
||||
if pair[0].eq_ignore_ascii_case(wanted) && !pair[1].is_empty() {
|
||||
return Some(pair[1].clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
mod blob_tests {
|
||||
use super::*;
|
||||
|
||||
/// Apple's own binaries are signed, and these three are on every macOS
|
||||
/// version this runs on, so the header check has something fixed to point at.
|
||||
#[test]
|
||||
fn a_signed_system_binary_reports_its_signature_blob() {
|
||||
for path in ["/bin/ls", "/bin/cat", "/usr/lib/dyld"] {
|
||||
let file = std::path::Path::new(path);
|
||||
if !file.is_file() {
|
||||
continue;
|
||||
}
|
||||
assert!(
|
||||
has_signature_blob(file),
|
||||
"{path} is signed, and the load commands say so"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_a_macho_reports_no_signature() {
|
||||
let dir = std::env::temp_dir().join(format!("squid-trust-blob-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
let plain = dir.join("plain");
|
||||
std::fs::write(&plain, b"#!/bin/sh\necho not a binary\n").unwrap();
|
||||
assert!(!has_signature_blob(&plain));
|
||||
|
||||
// A Mach-O magic with nothing behind it: the header is too short to hold
|
||||
// any load commands, and reading past the end must not panic.
|
||||
let truncated = dir.join("truncated");
|
||||
std::fs::write(&truncated, [0xCF_u8, 0xFA, 0xED, 0xFE, 0, 0, 0, 1]).unwrap();
|
||||
assert!(!has_signature_blob(&truncated));
|
||||
|
||||
// A fat header that points its only slice past the end of the file.
|
||||
let lying = dir.join("lying-fat");
|
||||
let mut bytes = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 1];
|
||||
bytes.extend([0_u8; 8]);
|
||||
bytes.extend((1_u32 << 20).to_be_bytes());
|
||||
bytes.extend([0_u8; 8]);
|
||||
std::fs::write(&lying, &bytes).unwrap();
|
||||
assert!(!has_signature_blob(&lying));
|
||||
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// The strongest form of this test is the same file on both sides of the
|
||||
/// signature boundary. A freshly linked arm64 binary is already
|
||||
/// `adhoc, linker-signed`, so "just compiled" cannot prove anything; removing
|
||||
/// and re-adding the signature shows the answer follows the load command
|
||||
/// rather than the file's name, size, or the parser's mood.
|
||||
#[test]
|
||||
fn the_answer_follows_the_load_command() {
|
||||
let dir = std::env::temp_dir().join(format!("squid-trust-cc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = dir.join("probe.c");
|
||||
std::fs::write(&source, "int main(void){return 0;}\n").unwrap();
|
||||
let binary = dir.join("probe");
|
||||
let run = |program: &str, args: &[&str]| {
|
||||
std::process::Command::new(program)
|
||||
.args(args)
|
||||
.status()
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
};
|
||||
if !run(
|
||||
"cc",
|
||||
&["-o", &binary.to_string_lossy(), &source.to_string_lossy()],
|
||||
) {
|
||||
// No compiler here; the shape of the answer is still covered by the
|
||||
// non-Mach-O test above.
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
return;
|
||||
}
|
||||
if !run(
|
||||
"codesign",
|
||||
&["--remove-signature", &binary.to_string_lossy()],
|
||||
) {
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
!has_signature_blob(&binary),
|
||||
"with the signature command removed, nothing should be reported"
|
||||
);
|
||||
assert!(
|
||||
run("codesign", &["-s", "-", &binary.to_string_lossy()]),
|
||||
"ad-hoc signing the probe should succeed"
|
||||
);
|
||||
assert!(
|
||||
has_signature_blob(&binary),
|
||||
"adding the signature command back must flip the answer"
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
|
|
@ -551,7 +551,7 @@ impl Palette {
|
|||
if highlight {
|
||||
return Self::selected();
|
||||
}
|
||||
let band = if index % 2 == 0 {
|
||||
let band = if index.is_multiple_of(2) {
|
||||
Self::card_bg()
|
||||
} else {
|
||||
Self::card_bg_alt()
|
||||
|
|
|
|||
|
|
@ -23,25 +23,22 @@
|
|||
|
||||
## crate 依赖图
|
||||
|
||||
```
|
||||
┌──────────────┐
|
||||
│ squid-core │ 模型 / 字节 / 路径 / 安全策略 / 设置 / 账本 / 进度
|
||||
└──────┬───────┘
|
||||
┌─────────┼──────────┐
|
||||
┌──────▼─────┐ ┌─▼────────┐ │
|
||||
│ squid- │ │ squid- │ │ ← 只依赖 core
|
||||
│ platform │ │ rules │ │
|
||||
└──────┬─────┘ └─┬────────┘ │
|
||||
│ │ │
|
||||
┌────▼─────────▼───────┐ │ ┌────────────┐
|
||||
│ squid-engine │◄─┼───┤ squid-stats│ ← 依赖 core 与 platform
|
||||
└────┬────────────┬────┘ │ └─────┬──────┘
|
||||
┌───────▼──┐ ┌────▼───────▼──┐ │
|
||||
│ squid-tui│ │ squid-cli │◄─────┘
|
||||
└──────────┘ └───────────────┘
|
||||
```
|
||||
| 层 | crate | 依赖 |
|
||||
| --- | --- | --- |
|
||||
| 0 | `squid-core` | —(不知道任何其它 crate 的存在)|
|
||||
| 1 | `squid-platform` | core |
|
||||
| 1 | `squid-rules` | core, platform |
|
||||
| 1 | `squid-stats` | core, platform |
|
||||
| 1 | **`squid-guard`** | core, platform |
|
||||
| 2 | `squid-engine` | core, platform, rules, stats |
|
||||
| 3 | `squid-tui` | core, platform, rules, stats, engine |
|
||||
| 4 | `squid-cli` | 以上全部(含 guard)|
|
||||
| — | `src-tauri` | core, platform, guard, engine, stats |
|
||||
|
||||
依赖方向严格单向,`squid-core` 不知道其它任何 crate 的存在。
|
||||
`squid-guard` 与 `squid-engine` 在第 1 / 第 2 层并列,而不是叠在一起:清理引擎的一切
|
||||
前提都是「这东西可再生,删了没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,
|
||||
必须能原样放回去」。所以 guard 只依赖 `core` 与 `platform`,复用 `Progress`、
|
||||
`CancelToken` 与 `paths`,但不碰删除路径。
|
||||
|
||||
### squid-core
|
||||
|
||||
|
|
@ -142,6 +139,66 @@ ratatui + crossterm。六个面板 `Cleanup / Uninstall / Purge / Storage / Stat
|
|||
路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。
|
||||
- **一个 widget 只有一套下标**:`ListState::selected` 是 ratatui 用来定位滚动窗口的行号,高亮却由每一行自己画,两者必须数同一批行。卸载列表把「大小/名称/版本」表头(筛选时还多一行 filter chip)和条目一起塞进同一个 `List`,`selected` 就此比样式多算了一两行:第一屏看不出来,列表一超过一页,窗口按「光标上面那一行」定位,高亮行被挤出可视区,用户看到的是「下翻之后没有高亮了」——Mac 与 Windows 同因,因为它跟终端无关。清理面板从不出现这个现象,`ScanPanel::lines` 里只有条目,标题挂在 card 的 block 上。现在的写法把表头和 filter chip 当作 chrome 单独走一段 `Layout`:`Paragraph` 拿上面,`List` 只拿条目。`the_app_under_the_cursor_is_the_row_that_is_on_screen` 遍历每一个光标位置(含筛选态)断言「光标那一行就是屏幕上那一行、且带着强调色与加粗」,因为它无法靠猜某个卡片高度通过。
|
||||
|
||||
### squid-guard
|
||||
|
||||
恶意软件扫描、检测规则与可逆隔离。它是唯一一个会**移动用户文件**的新 crate,所以它的
|
||||
设计重心不是「能找到什么」,而是「在没有 Developer ID 与 Authenticode 的发布方式下,
|
||||
怎样做到不伤人」。
|
||||
|
||||
| 模块 | 职责 |
|
||||
| --- | --- |
|
||||
| `scan` | 扫描编排:`ScanTarget::{Quick,Full,Paths}` → 采集 → 判定 → `ScanReport`。`Guard` 装配规则、哈希表、缓存与排除项 |
|
||||
| `rules` | YARA-X `Detector`、`HashIndex`,以及决定「这个文件值不值得打开」的门(`plausible_by_name_in` / `worth_scanning_in` / `layout_of`)|
|
||||
| `heuristics` | 无签名 / 世界可写 / 登录项 / 伪装名称,产 `Evidence`;`CEILING = Suspicious`,永远到不了 Confirmed |
|
||||
| `findings` | `Confidence::{Advisory,Suspicious,Confirmed}`、`Evidence`(带 `key()` 与 `summary()`)、`Finding` |
|
||||
| `coverage` | 每个 root 的结果:walked / denied / absent。**读不到不等于干净**,二者在报告里是不同的值 |
|
||||
| `quarantine` | 账本 + 惰性对象 + 字节一致恢复 |
|
||||
| `intel` | 规则包格式、验签、安装与回退 |
|
||||
| `store` | 判定缓存(按文件身份)+ 上一次扫描 + 最近活动,落 `<state>/security/` |
|
||||
|
||||
`squid-guard` 刻意不依赖 `squid-engine`:清理引擎的一切前提都是「这东西可再生,删了
|
||||
没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,必须能原样放回去」。它复用
|
||||
`Progress`、`CancelToken` 与 `paths`,但不复用删除路径。
|
||||
|
||||
三条不变量,都有测试钉住:
|
||||
|
||||
1. **扫描不删除任何东西。** 唯一会移动文件的是隔离,而隔离只接受后端发出的 finding id。
|
||||
界面永远不能提交一个路径来要求隔离:`security_quarantine(finding_id)` 查的是后端自己
|
||||
存下的那份扫描,再核对哈希、大小与文件身份;扫描之后被换过的文件会被拒绝,而不是按
|
||||
一行过期记录搬走。
|
||||
2. **只有 `confirmed` 可能被自动隔离**,且默认关闭(`security.auto_quarantine = false`)。
|
||||
`suspicious` 只报告。级别由两处分别决定后取最大值:已发布探测器(哈希 / YARA)按自己的
|
||||
等级说话,启发式则要求**两个信号互相印证**——单个「无签名」是提示,「无签名 + 开机启动」
|
||||
才是可疑。这一条是实测逼出来的:一台干净的 Mac 按旧规则会报出 975 条可疑,其中 951 条
|
||||
只是「带执行位的文本文件」,而这么长的列表最终的下场是被人整个忽略掉。
|
||||
3. **不上传。** 这个 crate 里没有任何函数接收本地路径再发出网络请求。规则包只下载。
|
||||
|
||||
`xprotect update` 永不被调用:这台机器要不要向 Apple 的服务器取定义,不是第三方 App 能
|
||||
替用户决定的事。`squid-platform::protection` 只读 `status` / `version` / `spctl`,读不到
|
||||
就报 `known = false`,界面据此显示「无法确认」而不是绿色。
|
||||
|
||||
**门(gate)比规则更决定可用性。** 一次快速扫描会路过约 105 万个文件,其中 34 万个是没有
|
||||
扩展名的数据文件。判定顺序按代价排列:名字(免费,遍历时已经在手)→ `stat`(大小、执行位)
|
||||
→ 目录形状(bundle 内部只看主可执行文件与 `Info.plist`,否则光是 `/Applications` 就吃掉
|
||||
十 GB)→ 只有浏览器下载目录才去读头八个字节。用户自己指名的目录是例外:那里按内容判定,
|
||||
因为 `eicar.com` 的后缀和它的身份本来就互相矛盾。最终约 1,900 个文件 / 6.2 GB,冷启动
|
||||
26 秒、命中缓存 9 秒。
|
||||
|
||||
一处性能教训值得留在这里:判定缓存与候选去重原本都是 `Vec` 加 `paths::same_path` 线性
|
||||
查找,而 `same_path` 每次比较都要重建一条路径的组件向量。15,000 个文件下这就是几十亿次
|
||||
字符串分配——快速扫描跑十分钟、CPU 满核,看着像磁盘慢,其实是纯 CPU。现在两处都按
|
||||
`paths::canonical_key` 建索引,并且有测试断言 `canonical_key` 与 `same_path` 判定一致:
|
||||
键和判定不一致,就等于把一份缓存结论用到了另一个文件身上。
|
||||
|
||||
隔离区不是废纸篓。对象被放进 Squid 自己的状态目录、清掉执行位、权限收紧到仅属主,账本与
|
||||
对象放在一起,所以「隔离了一个登录项」意味着它下次开机真的不会起来。恢复按原始路径、模式
|
||||
与时间戳放回,且恢复前要确认。
|
||||
|
||||
规则包与安装包用**不同的密钥**签名:轮换发布密钥不应该顺手改变谁能推规则,泄漏了安装包
|
||||
密钥也不应该变成一条规则注入路径。包格式把 manifest 与 source 存在同一个文件里,读到什么
|
||||
就一起验什么,避免「新包配旧 manifest」这种两半漂移。任何一次更新失败都保留上一版可用
|
||||
规则,并且会清空判定缓存——旧规则给出的结论不是新规则给的结论。
|
||||
|
||||
### squid-cli
|
||||
|
||||
clap derive。约定:
|
||||
|
|
|
|||
|
|
@ -45,21 +45,71 @@ cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
|||
|
||||
| Screen | What it does |
|
||||
| --- | --- |
|
||||
| Computer overview | Smart scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries |
|
||||
| Computer overview | Security status strip, cleanup scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries |
|
||||
| Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History |
|
||||
| Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items |
|
||||
| Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections |
|
||||
| Security | XProtect / Defender status, scan coverage, findings by confidence, quarantine and restore, recent security activity |
|
||||
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable and re-enable the ones the current user owns |
|
||||
| Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files |
|
||||
| Real-time monitor | Live CPU, memory, network, disk, battery, volume and process data; process termination asks for confirmation |
|
||||
| Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
|
||||
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
|
||||
| Settings | Chinese/English language selection that defaults to the system language, launch at login, deletion mode, history retention, protected paths, local file locations, and software updates |
|
||||
| Settings | Chinese/English language selection that defaults to the system language, launch at login, the security section (scan schedule, notifications, auto-quarantine, rule-pack updates, scan exclusions), deletion mode, history retention, protected paths, local file locations, and software updates |
|
||||
|
||||
`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+8` on Windows switch screens.
|
||||
`⌘1`–`⌘0` on macOS and `Ctrl+1`–`Ctrl+0` on Windows switch screens, in sidebar
|
||||
order: `1` overview, `2` daily cleanup, `3` uninstall apps, `4` deep clean,
|
||||
`5` storage, `6` real-time monitor, `7` security, `8` startup items,
|
||||
`9` history, `0` settings.
|
||||
|
||||
In 0.1.6 `⌘7`/`⌘8` moved from History/Settings to Security/Startup items;
|
||||
History and Settings are now `⌘9` and `⌘0`.
|
||||
|
||||
The sidebar groups these into **Maintenance** (overview, daily cleanup,
|
||||
uninstall apps, deep clean), **Protection** (security, startup items) and
|
||||
**Insights** (storage, real-time monitor), with History and Settings pinned at
|
||||
the bottom.
|
||||
|
||||
The two new screens reuse the interface vocabulary the older screens already
|
||||
had rather than introducing a second one: `.panel` for a card, `.status-chip` for
|
||||
a status, `.search-field`, `.icon-button`, `.text-button`, `.metric-icon` with a
|
||||
`tone-*` class, `.settings-row` for a switch, `.empty-inline` for an empty list.
|
||||
Findings, startup entries and quarantined files share one row shape
|
||||
(`.item-row` / `.item-main` / `.item-copy` / `.item-actions`), so a change to how
|
||||
a row looks is one edit that reaches all three. Copy stays to one sentence per
|
||||
screen and per control: a count sits on the filter that produces it, not also in
|
||||
a summary line above it.
|
||||
|
||||
## Security page
|
||||
|
||||
Squid scans when asked. There is no daemon, no kernel extension and no
|
||||
privileged helper, so XProtect and Defender remain the real-time protection and
|
||||
this page only reads what they report.
|
||||
|
||||
- **Scan modes.** Quick covers application bundles, login-item targets, browser
|
||||
extensions and the folders a browser writes to. Full adds the user's Library
|
||||
and document folders and must be started deliberately. Custom scans the paths
|
||||
chosen. All three are cancellable.
|
||||
- **Confidence.** `confirmed` means a published hash or signature rule matched
|
||||
and is the only level that may ever be moved automatically. `suspicious` needs
|
||||
two corroborating signals and is report-only. `advisory` is a single weak
|
||||
signal, such as an unsigned file that does not start at login.
|
||||
- **Coverage.** A scan that could not read a folder says so. The page never
|
||||
renders "clean" for a range it did not look at, and unreadable folders are
|
||||
listed rather than omitted.
|
||||
- **Nothing is uploaded.** No file name, hash, finding or quarantined file
|
||||
leaves the machine. Rule packs are downloaded; nothing is sent back.
|
||||
- **Quarantine is reversible.** Findings are moved by backend-issued id, never
|
||||
by a path the interface supplies. The file is re-verified against the hash the
|
||||
scan recorded, stored without the execute bit, and restoring returns the
|
||||
original bytes, mode and timestamps.
|
||||
|
||||
## Tray
|
||||
|
||||
Squid keeps running after its main window is closed. The tray menu can reopen
|
||||
the window and jump directly to Daily cleanup, Uninstall apps or Deep Clean.
|
||||
the window, start a malware scan, and jump directly to Security, Startup items,
|
||||
Daily cleanup, Uninstall apps or Deep Clean. One disabled row states the current
|
||||
protection status — the count of unhandled confirmed findings, "not scanned yet"
|
||||
before the first scan, and "scanning…" while one is running.
|
||||
The tray follows the active interface language. Use **Quit Squid** in the same
|
||||
menu to stop the background process.
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,827 @@
|
|||
# Squid 安全与管理功能路线图
|
||||
|
||||
状态:P0–P3 已实现(0.1.6);P4 未开始
|
||||
更新时间:2026-11-07
|
||||
适用平台:macOS 12+、Windows 10/11(x64;ARM64 通过兼容层运行)
|
||||
|
||||
本文是新版菜单、页面职责、授权流程和交付阶段的唯一规划来源。代码实现与本文冲突时,
|
||||
先改本文并说明原因,再改代码。
|
||||
|
||||
## 1. 已确定的决策
|
||||
|
||||
1. 发布方式与 Shift 保持一致:macOS 使用 ad-hoc 签名 DMG,不公证;Windows 使用未签名、
|
||||
按用户安装的 NSIS。首次安装由用户通过 Gatekeeper / SmartScreen 自行授权。
|
||||
2. 不使用本地自签证书。自签证书会让 macOS 直接显示“应用已损坏”,且没有可用的放行入口。
|
||||
3. 不新增 daemon、系统服务、内核扩展或常驻特权 helper。需要管理员权限的动作,
|
||||
每次由系统弹窗授权。
|
||||
4. 保留现有 8 个页面,新增「安全」和「启动项」两个页面。侧栏总入口变为 10 个。
|
||||
5. 「安全」页负责扫描、发现、告警和隔离;隔离不单独开页面。
|
||||
6. 「启动项」页负责持久化入口;进程管理不单独开页面,放入「实时监控」页签。
|
||||
7. 首版不做 Cleanup + Security 的合并“智能扫描”。两个扫描入口使用不同措辞,
|
||||
避免用户以为一次扫描已经检查了所有内容。
|
||||
8. 首版不做安全评分,只展示可验证的系统状态、扫描覆盖范围和发现数量。
|
||||
9. 历史页首版仍只承载清理/卸载账本;安全扫描与隔离记录先放在安全页的“最近活动”。
|
||||
10. 清理白名单与安全排除项是两份独立配置。清理白名单不能静默抑制恶意软件发现。
|
||||
|
||||
## 2. 发布与授权基线
|
||||
|
||||
### 2.1 安装与更新
|
||||
|
||||
| 场景 | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| 首次安装 | 下载 DMG,拖入“应用程序”;首次启动由用户在 Gatekeeper 中放行一次 | 运行未签名 NSIS;SmartScreen 中选择“更多信息 → 仍要运行” |
|
||||
| 应用内更新 | 校验文件大小、SHA256 和可选 Ed25519 清单签名;挂载 DMG、替换 App、清理 quarantine,不再弹 Gatekeeper | 校验后静默运行同一个 NSIS;失败时回退为手动打开安装包 |
|
||||
| 安装权限 | 普通用户权限 | 普通用户权限,安装到 `%LOCALAPPDATA%\Programs\Squid` |
|
||||
| 代码签名 | `signingIdentity: "-"`,保持 ad-hoc;发布检查必须显示 `Signature=adhoc` | 无 Authenticode;发布说明必须写明 SmartScreen 步骤 |
|
||||
| 信任说明 | macOS 首次放行是系统信任提示,不是病毒扫描结果 | Windows SmartScreen 是系统信任提示,不是 Squid 的检测结果 |
|
||||
|
||||
应用内更新和规则包更新都不以“操作系统信任发布者”为前提,但必须继续做内容完整性校验。
|
||||
清单签名解决“更新内容是否来自 Squid 发布者”,不能替代 Gatekeeper / SmartScreen。
|
||||
|
||||
### 2.2 首次授权卡
|
||||
|
||||
扩展现有 `SetupPanel`,从单一 Full Disk Access 检查变为非阻塞的“安全准备”卡片。
|
||||
每项都显示状态、影响和修复入口,关闭卡片不改变任何设置。
|
||||
|
||||
| 检查项 | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| 系统防护 | XProtect 版本、定义日期、后台/启动扫描是否开启、Gatekeeper 状态 | Defender / 第三方杀毒软件状态、实时保护、定义版本 |
|
||||
| 扫描访问 | Full Disk Access 可选;未授权时跳过受保护目录并标注覆盖受限 | 通常无需额外隐私权限;安全中心不可读时标注状态未知 |
|
||||
| 通知 | 请求通知权限;拒绝时保留应用内告警 | 请求通知权限;拒绝时保留应用内告警 |
|
||||
| 登录启动 | 可选;用于托盘定时扫描和告警 | 可选;用于托盘定时扫描和告警 |
|
||||
| 规则更新 | 可选;只下载签名规则包,不上传扫描结果 | 同 macOS |
|
||||
|
||||
首次扫描前再显示一次扫描范围确认:
|
||||
|
||||
- 快速扫描会覆盖哪些目录。
|
||||
- 哪些目录可能触发 macOS 文件夹授权。
|
||||
- 被拒绝或不可读的目录会在结果中明确标注“未检查”。
|
||||
|
||||
更新后重新检查权限。ad-hoc 身份会随构建变化,Full Disk Access、通知等授权可能被系统重置。
|
||||
安全页顶部用一条“权限需要处理”提示承载,不再次强制弹窗。
|
||||
|
||||
### 2.3 用户授权边界
|
||||
|
||||
- 扫描本身不需要管理员权限。
|
||||
- 当前用户拥有的启动项可以直接停用/恢复。
|
||||
- 系统级启动项需要一次系统授权;不安装常驻 helper。
|
||||
- 结束进程只处理当前用户拥有的进程;系统进程和他人进程只显示原因。
|
||||
- 隔离、恢复、停用启动项默认每次确认。
|
||||
- 自动隔离默认关闭;开启后也只处理“已确认”级别,不处理“可疑”级别。
|
||||
- Windows 服务首版只读。
|
||||
- macOS 登录项首版只读,修改入口跳转系统设置。
|
||||
|
||||
### 2.4 无 Developer ID / Authenticode 时的能力边界
|
||||
|
||||
无代码签名不会阻止 Squid 做本地扫描和用户授权范围内的处置,但会限制系统对发布者的信任,
|
||||
以及后台接管能力。实现时不能把“用户放行”描述成“系统已认证安全”。
|
||||
|
||||
| 能力 | 无签名 / ad-hoc 时 | 边界 |
|
||||
| --- | --- | --- |
|
||||
| 首次安装与启动 | 可做 | 仍需要用户手动通过 Gatekeeper / SmartScreen;不承诺免提示 |
|
||||
| 应用内更新 | 可做内容完整性校验 | SHA256 + 可选 Ed25519 清单签名;不能替代系统发布者信任 |
|
||||
| 扫描用户文件 | 可做 | 受当前用户权限和 macOS Full Disk Access 限制 |
|
||||
| 隔离与恢复 | 可做 | 只处理 Squid 自己记录、且重新校验通过的发现项 |
|
||||
| XProtect / Defender 状态 | 只读查看 | 不调用系统扫描、不复制规则、不接管系统实时防护 |
|
||||
| 用户级启动项 | 可做启停 | 仅限当前用户的 LaunchAgents / HKCU Run 等 |
|
||||
| 系统级启动项 | 有限支持 | 每次依赖系统授权;不安装常驻特权 helper |
|
||||
| 进程管理 | 可做当前用户进程 | 系统进程、他人进程只显示原因,不强制结束 |
|
||||
| 常驻实时拦截 | 不做 | 没有内核扩展或系统服务;只在应用/托盘运行时做定时或手动扫描 |
|
||||
| 通知 | 可做 | 依赖系统通知权限;拒绝后保留应用内告警和托盘状态 |
|
||||
|
||||
因此首版的安全定位是“本地按需扫描 + 可逆隔离 + 启动项/进程可见性”,而不是
|
||||
CleanMyMac 式的常驻实时防病毒产品,也不是 XProtect / Defender 的替代品。
|
||||
|
||||
## 3. 菜单结构
|
||||
|
||||
### 3.1 侧栏
|
||||
|
||||
```text
|
||||
维护 Maintenance
|
||||
电脑概览 Computer overview
|
||||
日常清理 Daily cleanup
|
||||
应用卸载 Uninstall apps
|
||||
深度清理 Deep Clean
|
||||
|
||||
保护 Protection
|
||||
安全 Security
|
||||
启动项 Startup items
|
||||
|
||||
洞察 Insights
|
||||
存储空间 Storage
|
||||
实时监控 Real-time monitor
|
||||
|
||||
(侧栏底部)
|
||||
历史记录 History
|
||||
设置 Settings
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- 「安全」和「启动项」是新入口,放在「保护」组,不塞进「洞察」。
|
||||
- 「实时监控」保持原名称,但页面内部增加「性能」和「进程」两个页签。
|
||||
- 「历史记录」和「设置」继续固定在侧栏底部。
|
||||
- 不新增「隔离区」「进程」「病毒扫描」等第三个入口,避免菜单膨胀。
|
||||
|
||||
### 3.2 页面 ID 与快捷键
|
||||
|
||||
| 序号 | Page ID | 中文 | English | 快捷键 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 1 | `overview` | 电脑概览 | Computer overview | `Cmd/Ctrl+1` |
|
||||
| 2 | `cleanup` | 日常清理 | Daily cleanup | `Cmd/Ctrl+2` |
|
||||
| 3 | `applications` | 应用卸载 | Uninstall apps | `Cmd/Ctrl+3` |
|
||||
| 4 | `purge` | 深度清理 | Deep Clean | `Cmd/Ctrl+4` |
|
||||
| 5 | `storage` | 存储空间 | Storage | `Cmd/Ctrl+5` |
|
||||
| 6 | `system` | 实时监控 | Real-time monitor | `Cmd/Ctrl+6` |
|
||||
| 7 | `security` | 安全 | Security | `Cmd/Ctrl+7` |
|
||||
| 8 | `startup` | 启动项 | Startup items | `Cmd/Ctrl+8` |
|
||||
| 9 | `history` | 历史记录 | History | `Cmd/Ctrl+9` |
|
||||
| 10 | `settings` | 设置 | Settings | `Cmd/Ctrl+0` |
|
||||
|
||||
`Cmd/Ctrl+7/8` 从原来的历史/设置改为安全/启动项;历史/设置顺延到 `9/0`。
|
||||
升级说明中要写清楚这一变化。
|
||||
|
||||
### 3.3 托盘菜单
|
||||
|
||||
```text
|
||||
打开 Squid
|
||||
保护状态:正常 / 发现 2 个问题 (只读状态行)
|
||||
扫描恶意软件
|
||||
管理启动项
|
||||
---
|
||||
日常清理
|
||||
应用卸载
|
||||
深度清理
|
||||
---
|
||||
退出 Squid
|
||||
```
|
||||
|
||||
行为:
|
||||
|
||||
- 托盘菜单跟随界面语言。
|
||||
- “保护状态”是禁用状态行;有已确认发现时显示数量,点击系统通知直接打开安全页。
|
||||
- 正在扫描时,“扫描恶意软件”变为“正在扫描…”并禁用。
|
||||
- 托盘图标/提示文字显示保护状态;有高危发现时优先于“有更新”提示。
|
||||
- 点击托盘通知默认打开安全页的发现列表。
|
||||
|
||||
### 3.4 导航徽标
|
||||
|
||||
- 「安全」:存在未处理的已确认发现时显示数量徽标;只有可疑项时显示普通圆点。
|
||||
- 「启动项」:首版不加数字徽标,避免把正常的系统启动项也变成噪声。
|
||||
- 「日常清理」:保留现有圆点。
|
||||
- 「设置」:保留现有更新圆点。
|
||||
|
||||
## 4. 页面职责
|
||||
|
||||
### 4.1 页面总表
|
||||
|
||||
| 页面 | 主要职责 | 主要动作 | 不承载 |
|
||||
| --- | --- | --- | --- |
|
||||
| 电脑概览 | 汇总电脑状态、清理结果和安全状态 | 开始清理扫描、开始安全扫描、跳转 | 复杂发现处置、启动项编辑 |
|
||||
| 日常清理 | 按规则扫描并删除可重建缓存和垃圾 | 选择、删除、撤销入口 | 安全发现和隔离 |
|
||||
| 应用卸载 | 读取应用、生成卸载计划 | 卸载 App 与残留 | 安全扫描、启动项管理 |
|
||||
| 深度清理 | 查找项目构建产物和旧安装包 | 选择、删除 | 安全扫描 |
|
||||
| 存储空间 | 磁盘占用树和大文件 | 浏览、定位、打开 | 安全处置 |
|
||||
| 实时监控 | 性能监控 + 全量进程管理 | 结束进程、查看进程详情 | 启动项启停 |
|
||||
| 安全 | 系统防护、恶意软件扫描、发现、隔离 | 扫描、隔离、恢复、排除 | 编辑启动项、结束进程 |
|
||||
| 启动项 | 管理登录/启动时运行的持久化入口 | 停用、恢复、查看关联进程 | 全量进程列表 |
|
||||
| 历史记录 | 清理/卸载账本与恢复 | 查看会话、撤销 | 安全事件审计 |
|
||||
| 设置 | 全局偏好、权限、排除项、更新 | 修改设置、打开系统设置 | 扫描结果和处置 |
|
||||
|
||||
### 4.2 电脑概览
|
||||
|
||||
职责:给用户一个“现在该做什么”的入口,不在这里完成复杂处置。
|
||||
|
||||
页面区块:
|
||||
|
||||
1. 顶部问候与设备信息(保留)。
|
||||
2. 安全状态条:
|
||||
- 系统防护:XProtect / Defender 是否正常。
|
||||
- Squid 扫描:从未扫描 / 上次扫描 / 发现数量。
|
||||
- 覆盖范围:完整 / 受限。
|
||||
- 有未处理发现时替换为红色提示卡,按钮“查看发现”。
|
||||
3. 清理扫描卡(保留现有磁盘仪表和清理结果)。
|
||||
4. 两个明确分开的扫描按钮:
|
||||
- “清理扫描” / “Cleanup scan”
|
||||
- “安全快速扫描” / “Quick security scan”
|
||||
5. 快捷入口:安全、日常清理、应用卸载、存储空间。
|
||||
6. 性能概览(保留 CPU、内存、存储)。
|
||||
|
||||
首版不把两个扫描合并。用户必须能分清“释放空间”和“检查威胁”。
|
||||
|
||||
### 4.3 安全
|
||||
|
||||
职责:承载系统防护状态、恶意软件扫描、发现列表、告警和隔离区。
|
||||
|
||||
页面区块:
|
||||
|
||||
1. 页头:
|
||||
- “安全”标题。
|
||||
- 扫描按钮和扫描类型菜单:快速扫描 / 全盘扫描 / 自定义路径。
|
||||
- 扫描中显示进度、当前文件、取消按钮。
|
||||
2. 系统防护卡:
|
||||
- macOS:XProtect 版本、定义日期、启动/后台扫描、Gatekeeper。
|
||||
- Windows:当前杀毒产品、实时保护、定义版本、最近扫描。
|
||||
- 状态不可读时显示“无法确认”,不使用绿色。
|
||||
3. 覆盖范围卡:
|
||||
- 已授权目录、未授权目录、被跳过数量。
|
||||
- Full Disk Access 缺失时提供“打开系统设置”。
|
||||
- 规则包版本、上次更新、离线使用提示。
|
||||
4. 发现列表:
|
||||
- 过滤:全部 / 已确认 / 可疑 / 已隔离。
|
||||
- 行内容:级别、名称、路径、证据、发现时间、建议动作。
|
||||
- 操作:隔离、在 Finder/资源管理器中显示、忽略一次、加入排除项。
|
||||
- 只有“已确认”项可批量隔离;可疑项只能逐条处理。
|
||||
5. 隔离区:
|
||||
- 列表:原始路径、大小、发现原因、隔离时间。
|
||||
- 操作:恢复、永久删除、查看详情。
|
||||
- 空状态说明隔离区只保存 Squid 隔离的对象。
|
||||
6. 最近活动:
|
||||
- 最近 20 次扫描、隔离、恢复;首版不写入历史页。
|
||||
7. 空状态与错误:
|
||||
- 未扫描:“尚未扫描这台电脑”。
|
||||
- 扫描干净:“在已检查范围内未发现威胁”。
|
||||
- 覆盖受限:必须同时显示未检查范围,不能只显示“安全”。
|
||||
- 扫描失败:保留上次结果,不清空发现。
|
||||
|
||||
页面动作:
|
||||
|
||||
- 开始扫描、取消扫描。
|
||||
- 更新规则包。
|
||||
- 隔离/恢复/永久删除。
|
||||
- 忽略一次/加入排除项。
|
||||
- 打开系统设置、打开规则日志、打开隔离目录。
|
||||
|
||||
页面不负责:
|
||||
|
||||
- 启停启动项:跳转启动项页。
|
||||
- 结束进程:跳转实时监控 → 进程,并带上 PID/路径过滤。
|
||||
- 卸载 App:跳转应用卸载;安全页只提供入口,不自动生成卸载计划。
|
||||
|
||||
### 4.4 启动项
|
||||
|
||||
职责:展示并管理登录/启动时自动运行的持久化入口,解释每个条目的来源和风险。
|
||||
|
||||
页面区块:
|
||||
|
||||
1. 页头摘要:
|
||||
- 用户级数量、系统级数量、已停用数量、需要管理员授权的数量。
|
||||
- 不显示“优化分数”。
|
||||
2. 过滤与搜索:
|
||||
- 范围:全部 / 当前用户 / 系统。
|
||||
- 来源:LaunchAgent、LaunchDaemon、登录项、Run/RunOnce、启动文件夹、计划任务、服务。
|
||||
- 状态:已启用 / 已停用。
|
||||
- 风险:全部 / 需要注意 / 仅系统项。
|
||||
- 默认隐藏 Apple / Microsoft 系统项,可开启“显示系统项”。
|
||||
3. 列表:
|
||||
- 名称、来源、范围、发布者/签名、目标路径、状态、风险标签。
|
||||
- 风险标签:目标不存在、路径在临时目录、未签名、命令包含脚本解释器、近期创建、隐藏任务。
|
||||
- 风险标签只表示“需要检查”,不等于恶意。
|
||||
4. 详情抽屉:
|
||||
- 完整命令、参数、工作目录、父 App、签名状态、文件哈希、修改时间。
|
||||
- 关联进程:显示 PID、CPU、内存,跳转实时监控 → 进程。
|
||||
- 操作:停用/启用、在 Finder/资源管理器中显示、扫描该文件、打开系统设置。
|
||||
5. 修改确认:
|
||||
- 展示将被移动/修改的具体 plist、注册表值或任务。
|
||||
- 说明影响和恢复方式。
|
||||
- 系统级项目要求一次系统授权。
|
||||
- 操作后刷新真实状态,不只更新前端缓存。
|
||||
|
||||
首版操作范围:
|
||||
|
||||
| 平台 | 可直接操作 | 首版只读 |
|
||||
| --- | --- | --- |
|
||||
| macOS | 用户 `~/Library/LaunchAgents` | 全局 LaunchAgents/Daemons、登录项、Apple 系统项 |
|
||||
| Windows | HKCU Run/RunOnce、用户启动文件夹 | HKLM、系统计划任务、Windows 服务 |
|
||||
|
||||
后续阶段:
|
||||
|
||||
- macOS 全局 LaunchAgents/Daemons:一次性管理员授权,备份后停用/恢复。
|
||||
- Windows HKLM Run、系统计划任务:一次性 UAC 授权。
|
||||
- Windows 服务:保持只读,不提供启停。
|
||||
- macOS 登录项:保持只读,跳转系统设置。
|
||||
|
||||
### 4.5 实时监控
|
||||
|
||||
职责:性能监控与进程管理。不新增第三个进程页面。
|
||||
|
||||
页面页签:
|
||||
|
||||
1. **性能 / Performance**
|
||||
- 保留现有 CPU、内存、网络、磁盘、电池、卷、高占用进程。
|
||||
- 高占用进程标题右侧增加“查看全部进程”。
|
||||
2. **进程 / Processes**
|
||||
- 全量进程表格,按需加载,不跟随 1Hz 刷新。
|
||||
- 列:进程、PID、父进程、用户、路径、CPU、内存、启动时间、签名、关联启动项。
|
||||
- 搜索、排序、按应用聚合、只看当前用户、只看未签名、只看有启动项。
|
||||
- 行详情抽屉:命令行、可执行文件、哈希、签名、工作目录、启动项、父进程。
|
||||
- 操作:结束进程、停止并隔离(仅已确认恶意)、打开文件位置、复制路径、跳转启动项。
|
||||
|
||||
安全约束:
|
||||
|
||||
- 保留现有 PID/名称复核和关键进程保护。
|
||||
- 结束进程仍然只处理当前用户拥有的进程。
|
||||
- “停止并隔离”必须来自安全发现项或用户显式选中的已确认项,不能对任意进程直接开放。
|
||||
- 不自动结束“可疑”进程。
|
||||
|
||||
### 4.6 设置
|
||||
|
||||
保留现有设置,并增加安全相关区段:
|
||||
|
||||
1. 语言与外观(不变)。
|
||||
2. 系统权限:
|
||||
- Full Disk Access。
|
||||
- 通知权限。
|
||||
- 登录启动(用于托盘定时扫描)。
|
||||
- Windows 安全中心状态。
|
||||
3. 安全:
|
||||
- 扫描计划:关闭 / 登录后 / 每天 / 每周。
|
||||
- 发现高危时通知。
|
||||
- 自动隔离已确认项(默认关闭)。
|
||||
- 规则包自动更新(默认开启,可关闭)。
|
||||
- 扫描范围和默认排除项。
|
||||
- 安全排除项列表,独立于清理白名单;新增排除项需要二次确认并显示风险提示。
|
||||
4. 启动:
|
||||
- 现有“开机自启”重命名为“登录时启动 Squid”,与“启动项”页面区分。
|
||||
5. 删除安全(不变)。
|
||||
6. 受保护位置(清理白名单,不变;说明它不影响安全扫描)。
|
||||
7. 文件与信息:
|
||||
- 配置、历史、规则包、隔离区路径。
|
||||
- 构建信任状态:ad-hoc / 未签名,附发布说明链接。
|
||||
8. 软件更新:
|
||||
- 应用更新和规则包更新分开显示版本与信任状态。
|
||||
|
||||
### 4.7 历史记录
|
||||
|
||||
首版保持不变:只显示清理/卸载会话和撤销。
|
||||
|
||||
安全扫描、隔离、恢复和启动项修改先放在安全页的“最近活动”。
|
||||
后续如果增加“保护事件”页签,再迁移,不在首版混入清理账本。
|
||||
|
||||
### 4.8 日常清理、应用卸载、深度清理、存储空间
|
||||
|
||||
这四个页面保持现有职责,首版不做安全功能混入:
|
||||
|
||||
- 日常清理:不显示恶意软件发现。
|
||||
- 应用卸载:不自动把可疑 App 加入卸载计划。
|
||||
- 深度清理:不自动扫描或删除安全发现。
|
||||
- 存储空间:只负责体积分析和定位。
|
||||
|
||||
跨页面跳转只提供入口,不把不同引擎的状态混在同一张表里。
|
||||
|
||||
## 5. 关键流程
|
||||
|
||||
### 5.1 首次启动
|
||||
|
||||
1. 用户完成 Gatekeeper / SmartScreen 首次授权。
|
||||
2. 打开 Squid,显示“安全准备”卡片。
|
||||
3. 卡片列出系统防护、访问权限、通知、登录启动和规则更新。
|
||||
4. 用户可逐项处理,也可直接关闭。
|
||||
5. 进入概览页;没有安全扫描时显示“尚未扫描”,而不是“安全”。
|
||||
|
||||
### 5.2 发现 → 隔离
|
||||
|
||||
1. 安全页展示发现项和证据。
|
||||
2. 用户点击“隔离”。
|
||||
3. 后端重新校验发现 ID、路径、哈希、文件身份和权限。
|
||||
4. 移入 Squid 隔离区,写隔离清单。
|
||||
5. 刷新发现列表和托盘状态。
|
||||
6. 失败时明确说明原因:文件已变化、权限不足、正在运行、需要管理员授权。
|
||||
|
||||
### 5.3 进程 → 启动项
|
||||
|
||||
1. 用户在进程页打开某个进程详情。
|
||||
2. 若进程关联启动项,显示“由启动项启动”。
|
||||
3. 点击后跳转启动项页并定位该条目。
|
||||
4. 启动项页不自动停用,用户再次确认。
|
||||
|
||||
### 5.4 通知
|
||||
|
||||
1. 高置信度发现产生系统通知。
|
||||
2. 点击通知打开安全页并定位发现。
|
||||
3. 通知权限被拒绝时,应用内红色提示和托盘状态仍然有效。
|
||||
4. Squid 未运行时没有实时通知;用户可通过“登录时启动”让托盘常驻。
|
||||
|
||||
### 5.5 更新后权限检查
|
||||
|
||||
1. 应用内更新完成并重启。
|
||||
2. 重新读取 Full Disk Access、通知和登录启动状态。
|
||||
3. 权限丢失时在安全页顶部显示“扫描覆盖受限”,提供修复入口。
|
||||
4. 不阻塞启动,不自动重新弹系统权限对话框。
|
||||
|
||||
## 6. 功能契约
|
||||
|
||||
### 6.1 扫描模式
|
||||
|
||||
| 模式 | 范围 | 默认 |
|
||||
| --- | --- | --- |
|
||||
| 快速扫描 | 应用目录、用户/全局启动项、浏览器扩展、Downloads/Desktop 中的可执行候选 | 是 |
|
||||
| 全盘扫描 | 用户主目录、Applications、启动项目录;显式发起 | 否 |
|
||||
| 自定义扫描 | 用户选择的文件或目录 | 否 |
|
||||
|
||||
默认不挂载 DMG、不递归解压归档、不扫描网络卷和未授权目录。
|
||||
|
||||
### 6.2 检测层
|
||||
|
||||
1. 系统防护状态:XProtect / Defender,只读。
|
||||
2. 精确 SHA-256 哈希黑名单。
|
||||
3. YARA-X 规则,覆盖 Mach-O、PE、脚本、App Bundle、浏览器扩展和启动项 plist。
|
||||
4. 启发式风险:签名、路径、启动方式、伪装名称、异常参数。
|
||||
|
||||
级别:
|
||||
|
||||
- 已确认:哈希或高置信规则命中。
|
||||
- 可疑:只有启发式证据,不自动隔离。
|
||||
- 提示:签名/路径/启动项风险,仅展示。
|
||||
|
||||
### 6.3 隔离不变量
|
||||
|
||||
- 扫描不删除文件。
|
||||
- 隔离只接受后端缓存的发现项 ID,前端不能提交任意路径。
|
||||
- 移动前重新读取并核对哈希、大小、文件身份和权限。
|
||||
- 不跟随符号链接。
|
||||
- 不隔离系统目录、XProtect、Squid 自身和隔离区自身。
|
||||
- 隔离区文件不可执行、权限受限。
|
||||
- 恢复需要确认;永久删除只从隔离区发起。
|
||||
- 隔离清单与清理账本分开。
|
||||
|
||||
### 6.4 启动项不变量
|
||||
|
||||
- 修改前备份原 plist、注册表值或启动文件夹条目。
|
||||
- 每次只改一个条目,不做“一键全部禁用”。
|
||||
- 系统级修改必须经过一次系统授权。
|
||||
- 操作后重新读取真实状态,不信任前端缓存。
|
||||
- 目标消失、权限变化、条目被 App 重建时,报告实际状态而不是假装成功。
|
||||
|
||||
### 6.5 规则包
|
||||
|
||||
- 内置基础规则,离线可用。
|
||||
- 外部规则包使用独立 Ed25519 公钥验签,并校验 SHA256/大小。
|
||||
- 只下载规则,不上传文件名、哈希或扫描结果。
|
||||
- 验签失败、损坏或回滚时继续使用最后可用版本。
|
||||
- 更新 `docs/SECURITY.md` 的网络说明。
|
||||
|
||||
### 6.6 性能预算
|
||||
|
||||
- 不新增常驻扫描线程。
|
||||
- 空闲 0% CPU;安全页未打开时额外内存目标低于 20 MB。
|
||||
- 扫描最多 4 个 worker,低优先级,可取消。
|
||||
- 快速扫描目标 60 秒级;全盘扫描必须显式发起。
|
||||
- 安装包增加目标不超过 10 MB;规则包压缩后目标不超过 5 MB。
|
||||
- 哈希缓存按路径、大小、mtime、文件 ID 失效。
|
||||
|
||||
## 7. 实现落点
|
||||
|
||||
### 7.1 新 crate 与模块
|
||||
|
||||
```text
|
||||
crates/squid-guard/
|
||||
scan.rs 扫描编排、范围、进度、取消
|
||||
signatures.rs 哈希索引、规则包加载
|
||||
heuristics.rs 应用/启动项/进程风险判断
|
||||
quarantine.rs 隔离、恢复、清单
|
||||
intel.rs 规则包格式、验签、版本回退
|
||||
|
||||
crates/squid-platform/src/startup.rs
|
||||
crates/squid-platform/src/process_table.rs
|
||||
crates/squid-platform/src/trust.rs
|
||||
```
|
||||
|
||||
`squid-guard` 依赖 `squid-core` 和 `squid-platform`,不依赖 `squid-engine`。
|
||||
隔离执行不复用清理删除引擎,但复用进度、取消、路径规范化和权限判断。
|
||||
|
||||
### 7.2 Tauri 层
|
||||
|
||||
新增:
|
||||
|
||||
```text
|
||||
src-tauri/src/security.rs 安全状态、扫描、发现、隔离
|
||||
src-tauri/src/startup.rs 启动项清单、启停、备份恢复
|
||||
```
|
||||
|
||||
命令建议:
|
||||
|
||||
```text
|
||||
security_status
|
||||
security_scan
|
||||
security_cancel
|
||||
security_quarantine
|
||||
security_restore
|
||||
security_delete_quarantine
|
||||
security_exclusions
|
||||
security_update_rules
|
||||
startup_items
|
||||
startup_set_enabled
|
||||
process_inventory
|
||||
process_detail
|
||||
```
|
||||
|
||||
扫描结果、启动项清单和隔离项都由后端保存并分配 ID;前端只提交 ID。
|
||||
运行中的扫描复用 `Progress`、`CancelToken` 和现有 `ProgressReporter` 模式。
|
||||
|
||||
### 7.3 前端
|
||||
|
||||
```text
|
||||
src/pages/SecurityPage.tsx
|
||||
src/pages/StartupPage.tsx
|
||||
src/hooks/useSecurityWorkspace.ts
|
||||
src/hooks/useStartupWorkspace.ts
|
||||
```
|
||||
|
||||
修改:
|
||||
|
||||
```text
|
||||
src/App.tsx 新增 PageId、Protection 导航组、快捷键
|
||||
src/pages/SystemPage.tsx 增加“性能 / 进程”页签
|
||||
src/pages/OverviewPage.tsx 增加安全状态条和两个独立扫描入口
|
||||
src/pages/SettingsPage.tsx 增加安全设置与权限项
|
||||
src/components/SetupPanel.tsx 扩展为安全准备卡片
|
||||
src/types.ts / src/lib/api.ts / src/i18n.tsx
|
||||
src/styles.css
|
||||
```
|
||||
|
||||
### 7.4 CLI / TUI
|
||||
|
||||
CLI 首版增加:
|
||||
|
||||
```text
|
||||
squid guard status
|
||||
squid guard scan [paths…] --json
|
||||
squid guard quarantine --scan <id>
|
||||
```
|
||||
|
||||
CLI 只读取规则包和隔离清单,不依赖桌面端状态。
|
||||
TUI 的 Guard 面板放到后续版本,不阻塞桌面端 MVP。
|
||||
|
||||
### 7.5 本地状态
|
||||
|
||||
```text
|
||||
<state>/security/intel/ 当前与上一版规则包
|
||||
<state>/security/cache/ 哈希缓存
|
||||
<state>/security/quarantine/ 隔离对象和清单
|
||||
<state>/security/startup-backups/ 启动项备份
|
||||
```
|
||||
|
||||
`config.toml` 新增安全设置:扫描计划、通知、自动隔离、规则更新、
|
||||
安全排除项。现有清理白名单不变。
|
||||
|
||||
## 8. 阶段计划
|
||||
|
||||
### P0:发布与授权基线(2–3 天)
|
||||
|
||||
- [x] 确认 macOS ad-hoc / Windows 未签名发布流程与 Shift 一致。
|
||||
- [x] 扩展现有首次授权卡,加入安全准备检查。
|
||||
- [x] 定义扫描覆盖范围和“权限受限”状态。
|
||||
- [x] 验证 YARA-X 在 macOS universal / Windows x64 的体积、内存和 MSRV。
|
||||
- [x] 验证 XProtect `status/version`、Defender 状态读取。
|
||||
|
||||
出口:首次安装、应用内更新、权限降级三条路径都有可演示 UI,不开始写扫描器。
|
||||
|
||||
实现说明:YARA-X 1.23 关掉默认 feature,只开 string / math / hash / time / macho / pe
|
||||
等必要项。它把 workspace 的 MSRV 抬到 1.95,`ratatui` 也因此从 0.29 升到 0.30(0.29 用
|
||||
`=0.2.0` 钉死 `unicode-width`,与 yara-x 的依赖链冲突)。`pe` 与 `macho` 两个模块大约贵
|
||||
11 MB,但去掉 `pe` 就无法交叉编译到 Windows,所以留着。
|
||||
|
||||
### P1:可见性(1–1.5 周)
|
||||
|
||||
- [x] 新增 PageId、侧栏 Protection 组、快捷键、托盘菜单项。
|
||||
- [x] 安全页只读骨架:系统防护、覆盖范围、空状态。
|
||||
- [x] 启动项页只读列表和详情抽屉。
|
||||
- [x] 实时监控页增加“进程”页签,全量进程只读。
|
||||
- [x] CLI `squid guard status`。
|
||||
|
||||
出口:两平台能读到真实启动项/进程;系统项不会被误操作;权限缺失有明确说明。
|
||||
|
||||
### P2:扫描、告警与隔离(2–3 周)
|
||||
|
||||
- [x] 哈希/YARA/启发式扫描引擎。
|
||||
- [x] 快速/全盘/自定义扫描和取消。
|
||||
- [x] 发现列表、筛选、证据展示。
|
||||
- [x] 托盘状态、应用内告警、通知。
|
||||
- [x] 隔离/恢复/永久删除。
|
||||
- [x] 签名规则包与离线回退。
|
||||
|
||||
出口:EICAR、哈希样本、YARA 样本命中;隔离字节一致;正常应用不误报;
|
||||
扫描取消和权限不足路径稳定。
|
||||
|
||||
### P3:管理与修复(1–2 周)
|
||||
|
||||
- [x] 用户级启动项停用/恢复。
|
||||
- [x] 进程结束、停止并隔离、跳转启动项。
|
||||
- [x] 登录后/每日/每周扫描。
|
||||
- [x] 自动隔离已确认项(默认关闭)。
|
||||
- [x] 安全排除项。
|
||||
- [x] 安全页最近活动。
|
||||
|
||||
出口:用户级启动项可逆;关键进程保护不回归;定时扫描只在托盘进程存在时运行。
|
||||
|
||||
### P4:系统级与增强(2–3 周,可选)
|
||||
|
||||
- [ ] macOS 全局 LaunchAgents/Daemons 一次性管理员授权。
|
||||
- [ ] Windows HKLM Run / 系统计划任务一次性 UAC 授权。
|
||||
- [ ] Downloads/Desktop/启动项目录的可选监听。
|
||||
- [ ] 历史页增加“保护事件”页签。
|
||||
- [ ] TUI Guard 面板。
|
||||
- [ ] 误报反馈与本地诊断包。
|
||||
|
||||
出口:系统级修改有备份和恢复路径;不引入常驻特权 helper。
|
||||
|
||||
## 9. 验收标准
|
||||
|
||||
### 9.1 菜单与页面
|
||||
|
||||
- 侧栏 10 个入口顺序、分组、快捷键与本文一致。
|
||||
- 新页面可被托盘、通知、概览、进程详情正确跳转并定位。
|
||||
- 语言切换后菜单、托盘、页面文案同步。
|
||||
- 安全页发现数量与托盘状态一致。
|
||||
|
||||
### 9.2 扫描与隔离
|
||||
|
||||
- 扫描绝不删除文件。
|
||||
- 隔离只接受后端发现项 ID。
|
||||
- 隔离 → 恢复后字节、权限一致。
|
||||
- 已确认/可疑/提示三级不会互相冒充。
|
||||
- 覆盖受限时不显示“完全安全”。
|
||||
- 规则包篡改、断网、回滚都能安全降级。
|
||||
|
||||
### 9.3 启动项与进程
|
||||
|
||||
- 用户级启动项停用/恢复可往返。
|
||||
- 系统级项目在未授权时不会变化。
|
||||
- Apple/Microsoft 系统项默认隐藏且只读。
|
||||
- 关键进程结束被拒绝并说明原因。
|
||||
- 进程详情能正确关联启动项。
|
||||
|
||||
### 9.4 发布
|
||||
|
||||
- macOS `codesign -dv` 显示 `Signature=adhoc`,不能出现本地证书名。
|
||||
- 新 Mac 首次安装需要一次手动放行;应用内更新不再提示。
|
||||
- Windows 安装器为 per-user,无管理员权限;SmartScreen 步骤写入发布说明。
|
||||
- 两个平台的更新都完成大小、SHA256 和可选 Ed25519 校验。
|
||||
|
||||
### 9.5 性能
|
||||
|
||||
- 空闲无新增常驻线程和可测 CPU 占用。
|
||||
- 安全页未打开时额外内存低于预算。
|
||||
- 扫描可取消,取消后不继续消耗 I/O。
|
||||
- 快速扫描达到目标时间,全盘扫描必须显式确认。
|
||||
|
||||
## 10. 明确不做
|
||||
|
||||
- 不复制或再分发 Apple XProtect 规则。
|
||||
- 不伪装成 XProtect / Defender 的替代品。
|
||||
- 不做内核扩展、EndpointSecurity、驱动或实时执行前拦截。
|
||||
- 不安装常驻管理员 helper 或系统服务。
|
||||
- 不自动删除低置信度发现。
|
||||
- 不自动停用全部启动项。
|
||||
- 不把清理白名单当作安全排除项。
|
||||
- 不上传文件名、哈希、扫描结果或隔离文件。
|
||||
- 首版不做安全评分。
|
||||
- 首版不合并清理扫描和安全扫描。
|
||||
|
||||
## 11. 代码开工顺序
|
||||
|
||||
1. 先做 P0 的授权卡、发布检查和规则包/扫描引擎 spike。
|
||||
2. 再做 P1 的导航、安全只读页、启动项只读页和进程页签。
|
||||
3. P1 验收通过后接 P2 扫描与隔离。
|
||||
4. P3 只加用户级操作和定时扫描。
|
||||
5. P4 的系统级操作必须在 P3 稳定后再开始。
|
||||
|
||||
## 12. 实现后修订(0.1.6)
|
||||
|
||||
下面几条是写完、并在真机上量过之后必须回写给本文的差异。按本文开头的规矩:先改本文,
|
||||
再改代码。
|
||||
|
||||
### 12.1 6.6 性能预算的实测结果
|
||||
|
||||
在 macOS 15.7.1 / 16 GB / NVMe 的开发机上,对真实主目录测量:
|
||||
|
||||
| 指标 | 目标 | 实测 |
|
||||
| --- | --- | --- |
|
||||
| 快速扫描耗时 | 60 秒级 | 冷启动 26 秒;命中判定缓存 9 秒 |
|
||||
| 快速扫描读取量 | — | 约 1,900 个文件 / 6.2 GB |
|
||||
| 全盘扫描耗时 | 显式发起即可 | 162 秒 / 50,070 个文件 |
|
||||
| 遍历遇到的条目 | — | 约 105 万条,其中 34 万是无扩展名文件 |
|
||||
| 空闲额外线程 | 0 个常驻扫描线程 | 1 个阻塞在 channel 上的定时线程,可被设置变更唤醒 |
|
||||
|
||||
「不新增常驻扫描线程」按原意保留:只有那个定时线程,它不轮询、不占 CPU,且只在应用运行
|
||||
时存在(2.4 已写明没有 daemon)。
|
||||
|
||||
判定缓存与候选去重最初写成 `Vec` + `same_path` 线性查找,快速扫描因此跑到十分钟且 CPU
|
||||
满核——看着像磁盘慢,实际是每文件上万次路径比较的纯 CPU 开销。改成按
|
||||
`paths::canonical_key` 建索引后达到上表数字,并有测试断言 `canonical_key` 与 `same_path`
|
||||
判定一致:键和判定不一致,就等于把一份缓存结论用到了另一个文件身上。
|
||||
|
||||
### 12.2 判定门槛(6.2 的必要补充)
|
||||
|
||||
6.2 说了有哪几层检测,没说**什么文件值得打开**。这是本项目里对可用性影响最大的一个决策,
|
||||
写清楚:
|
||||
|
||||
1. 名字(遍历时免费);
|
||||
2. `stat`:大小上下限 + 执行位;
|
||||
3. 目录形状:`.app` 内部只取主可执行文件与 `Info.plist`,否则光是 `/Applications` 就要
|
||||
多读十 GB;
|
||||
4. 只有浏览器下载目录才去读文件头。
|
||||
|
||||
一条实测逼出来的修正:**扩展名要压过执行位**。解压压缩包会把里面所有文件都标成可执行,
|
||||
于是「有执行位就算程序」在一台干净的 Mac 上报出 951 条假发现(`.class`、`.svg`、`.zip`、
|
||||
`.DS_Store`)。现在的规则是:有名可查的按名字判断,无名可查的才看执行位。用户自己指名的
|
||||
目录不受这条限制——那里按内容判定,因为 `eicar.com` 的后缀和它的身份本来就互相矛盾。
|
||||
|
||||
`.js` / `.json` / `.html` / `.lnk` 故意**不在**可执行扩展名里:它们在快速范围里有 35,288
|
||||
个、1.31 GB;而恶意脚本真正的载体 `.ps1` / `.bat` / `.cmd` / `.hta` 只有 69 个文件、体积
|
||||
几乎为零。全盘扫描与自定义扫描仍然看得到前者。
|
||||
|
||||
### 12.3 6.2 级别定义的收紧
|
||||
|
||||
「可疑」原先等于「有任何一条启发式证据」。在一台干净的 Mac 上这是 975 条。现在要求**两条
|
||||
信号互相印证**——单个「无签名」只是「提示」,「无签名 + 开机启动」才是「可疑」。实测同一台
|
||||
机器降到 8 条可疑 / 296 条提示,而这 8 条确实都值得看。伪装成系统组件仍然单独就能定为可疑,
|
||||
因为没有正经程序会那么命名自己。
|
||||
|
||||
已发布探测器(哈希 / YARA)不受这条影响:它按自己的等级说话,也不替启发式充当第二条证据。
|
||||
|
||||
### 12.4 6.5 规则包的验签策略
|
||||
|
||||
6.5 要求「独立 Ed25519 公钥验签」,但没说构建里没有公钥时怎么办。按字面实现会让规则包在
|
||||
除正式发布以外的每一个构建里永远更新失败。现在的做法与应用更新一致:
|
||||
|
||||
- 构建内有公钥 → 必须验签通过,否则拒绝(这是密钥的全部意义);
|
||||
- 构建内没有公钥 → 接受,但把 `provenance` 记成 `unverified` 并落盘,安全页与设置都写明
|
||||
「仅校验哈希,未验签」。
|
||||
|
||||
清单与包体仍然照 6.5 校验大小与 SHA-256;YARA 编译不过的包照样不允许成为 `current`。
|
||||
|
||||
### 12.5 与本文的两处措辞差异
|
||||
|
||||
- 4.3 的「扫描按钮和扫描类型菜单」实现为三个并列按钮(快速 / 全盘 / 自定义),不是下拉
|
||||
菜单:全盘与自定义的代价不同,摊开比收进菜单更不容易误点。
|
||||
- 4.4 的风险标签在列表中只显示图标与短语,完整解释在详情抽屉里。一行六个橙色标签读起来
|
||||
和没有标签一样。
|
||||
|
||||
### 12.6 7.1 的模块划分与落点清单
|
||||
|
||||
7.1 写的是 `signatures.rs` 一个文件,实际需要三份互不相干的状态,硬挤在一起会分不清哪份
|
||||
磁盘缓存对应哪个结论,所以拆成:
|
||||
|
||||
- `rules.rs`:哈希黑名单与 YARA 规则的编译与加载;
|
||||
- `intel.rs`:规则包格式、验签、版本回退(与本文一致);
|
||||
- `store.rs`:扫描结果、发现、忽略项与最近活动的落盘。7.1 没提这个文件,但 6.3
|
||||
「前端只提交 ID」和 4.3「最近活动」都要求后端保存一份带 ID 的历史,它必须有归宿。
|
||||
|
||||
另外两处与清单的差集:
|
||||
|
||||
- 7.2 的命令表列了 12 条,实现为 18 条,多出 `security_open`(4.3 的「在 Finder 中显示」)、
|
||||
`security_ignore`(4.3 的「忽略一次」)、`security_settings_save`、
|
||||
`security_rollback_rules`(6.5 的回滚)、`open_quarantine_folder` 和 `process_stop`
|
||||
(4.5 的结束进程,清单把它漏在 `process_detail` 之后)。清单里的 `security_cancel` 实现了。
|
||||
- 7.1 说 `squid-guard` 不依赖 `squid-engine`:成立;它只依赖 `squid-core` 与
|
||||
`squid-platform`。
|
||||
|
||||
### 12.7 界面不新增规范,并删掉重复解释
|
||||
|
||||
两个新页面第一版写完,界面自己变成了第二套设计系统:108 个新 class、两套 chip、两套
|
||||
标签页、两个搜索框、两种图标按钮,外加 25 条超过 88 字符的解释文案。这一节把结论写死,
|
||||
以后再加页面照此执行:
|
||||
|
||||
**复用,不新造。** 新页面一律用既有原语:卡片壳 `.panel`(和 `.apps-list-panel` 同一组
|
||||
声明)、`.status-chip`(补 `is-success/warning/danger/info` 四个色调,而不是再造一个
|
||||
`.state-pill`)、`.search-field`、`.icon-button`、`.text-button`、`.metric-icon` + `tone-*`、
|
||||
`.quick-copy`、`.settings-row`、`.settings-select`、`.empty-inline`、`.host-card`、
|
||||
`.confirm-extra`。`.startup-source` 曾经同时挂在一个 `<select>` 和一个 `<span>` 上,
|
||||
`<select>` 改用 `.settings-select`。
|
||||
|
||||
**同一件事只有一种写法。** 发现行、启动项行、隔离行共用 `.item-row/.item-main/.item-copy/
|
||||
.item-actions`;抽屉正文共用 `.item-detail`;统计块共用 `.stat`。`security-toggle` 组件本身
|
||||
就是 `.settings-row` 的复制品,已删除。
|
||||
|
||||
**文案一条一句话。** 页面副标题 60–120 字符,和旧页面一致。同一个事实只在离它最近的
|
||||
控件上出现一次:发现数以前在 `SectionTitle` 副标题和筛选 chip 各写一遍,现在只有 chip
|
||||
带数字,而且 chip 上的数字就是点下去会看到的条数。
|
||||
|
||||
**不新增的规范也要说清楚。** 隔离行、启动项行原来各自定义了边框/圆角/背景,现在都来自
|
||||
`.item-row` 一处;改一处两个页面同时生效,这正是不开第二套规范的目的。
|
||||
|
||||
### 12.8 6.6 的体积预算超了,并且部分是我自己造成的
|
||||
|
||||
6.6 写「安装包增加目标不超过 10 MB」。0.1.6 实测:
|
||||
|
||||
| 安装包 | 0.1.5 | 0.1.6 | 增加 |
|
||||
| --- | --- | --- | --- |
|
||||
| macOS universal DMG | 10,702,261 | 21,831,698 | **+10.6 MiB** |
|
||||
| Windows x64 NSIS | 3,354,754 | 7,816,721 | +4.3 MiB |
|
||||
|
||||
两点都要写清楚,不要含糊过去:
|
||||
|
||||
1. **Windows 在预算内**(+4.3 MiB),macOS 略微超出。超出部分主要是 yara-x 把 wasmtime
|
||||
与 cranelift 拖了进来——`wasmtime` 在 yara-x 1.23 里是**必需依赖**,不是可选 feature,
|
||||
即便只开 `macho`/`pe` 这些模块也一样链接。想靠关 feature 省下来省不掉。
|
||||
2. **第一次构建时报 `stripping debug info with rust-objcopy failed`**:`src-tauri` 被根
|
||||
workspace `exclude`,自己又没写 `[profile.release]`,所以桌面端从来没被 strip 过。
|
||||
补上 `strip = "symbols"` 后 universal 二进制从 85,043,456 降到 63,457,920 字节
|
||||
(−20.6 MiB),DMG 从 23.6 MiB 降到 20.8 MiB。也就是说:如果没有这次发现,超预算会
|
||||
严重得多;而 `panic` 仍然保持 unwind,因为「命令线程 panic 只失败一次请求」变成
|
||||
「整个应用退出」不属于这个版本该有的行为变化。
|
||||
|
||||
预算本身不改成 11 MB:超了就是超了,写在这里比改数字更有用。下一版如果要还这笔账,
|
||||
方向是二进制本身(例如等 yara-x 提供关掉 wasm 后端的选项),不是砍功能。
|
||||
|
|
@ -7,7 +7,9 @@ squid 是一个「以删除为职责、以不删错为底线」的工具。它
|
|||
- squid 以当前用户身份运行,**不需要** root,也不安装任何 launch agent / 服务 / 内核扩展。
|
||||
- 非 root 时 `SafetyPolicy::user_only()` 生效,家目录之外的路径一律不删除;只有显式用管理员权限运行时才切换到 `SafetyPolicy::system()`。
|
||||
- 需要管理员权限的规则(`needs_admin`)在普通权限下只报告、不执行;`squid clean --user-only` 可以彻底跳过它们。
|
||||
- 不联网:`Cargo.toml` 的依赖树里没有 HTTP 客户端,squid 不上传任何遥测、路径或文件名。
|
||||
- 默认不联网。清理、卸载、深度清理与实时监控全都在本地完成,代码里没有 HTTP 客户端
|
||||
(下载规则包与应用更新走 `curl` / `Invoke-WebRequest` 子进程,见下)。**squid 从不上传
|
||||
任何遥测、路径、哈希、扫描结果或被隔离的文件。**
|
||||
|
||||
## Full Disk Access(macOS)
|
||||
|
||||
|
|
@ -41,9 +43,58 @@ squid 是一个「以删除为职责、以不删错为底线」的工具。它
|
|||
| `brew uninstall --cask --force` | App 由 Homebrew 安装时优先交给 brew 处理 | 是,仅 `squid uninstall` 确认之后,且只在检测到对应 cask 时 |
|
||||
| `flatpak` / `snap` | Linux 应用清单与卸载建议 | 清单只读;卸载建议以提示形式给出 |
|
||||
|
||||
安全功能新增的外部命令,同一套规则(不经过 shell、参数不来自不可信输入):
|
||||
|
||||
| 命令 | 用途 | 是否修改系统 |
|
||||
| --- | --- | --- |
|
||||
| `/usr/bin/xprotect status/version`、`spctl --status` | 读取 XProtect 与 Gatekeeper 状态 | 否,只读。**`xprotect update` 永不调用**:那台机器要不要向 Apple 取定义,不是第三方 App 能替用户决定的 |
|
||||
| `powershell.exe`(Defender / SecurityCenter2 查询)、注册表 `Microsoft\Windows Defender` 的 `Signature Updates` | 读取 Defender / 第三方杀软与定义版本 | 否,只读;不会开启、关闭或更新任何防护 |
|
||||
| `codesign -dvvv --display` | 读取发布者的签名信息 | 否,只读 |
|
||||
| `launchctl bootstrap/kickout` | 启用或停用**当前用户**的 LaunchAgent | 是,仅在启动项页确认之后;系统级条目在首版只读 |
|
||||
| `schtasks /query /v /fo csv` | 列举计划任务 | 否,只读(首版不提供启停)|
|
||||
| `curl` / `Invoke-WebRequest` | 下载规则包与更新清单 | 否,只下载;见「规则包的下载与验签」|
|
||||
|
||||
## 安全功能(guard)的边界
|
||||
|
||||
恶意软件扫描是 0.1.6 加入的能力,它的风险模型和「删错东西」不同:**它会移动文件**。
|
||||
因此下面几条是被测试钉住的硬边界,而不是承诺。
|
||||
|
||||
- **扫描本身绝不删除或移动任何东西。** 唯一的移动来自隔离,而隔离必须由用户点下确认,
|
||||
或由一个默认关闭的开关(`security.auto_quarantine`)触发。
|
||||
- **隔离只接受后端发出的 finding id。** 前端提交路径的能力被拿掉了:`security_quarantine`
|
||||
拿 id 去查后端自己存下的那次扫描,再核对哈希、大小与文件身份;扫描之后文件被换过就
|
||||
拒绝移动。界面伪造一个路径出来,伪造不了一个 id。
|
||||
- **只有 `confirmed` 可能自动隔离。** 这一级只能由精确 SHA-256 命中或签名级 YARA 规则到达;
|
||||
启发式(无签名、路径可疑、开机自启)的上限是 `suspicious`,永远自动隔离不到它。
|
||||
- **隔离是可逆的。** 对象进入 `<state>/security/quarantine/`,去掉执行位、权限收到仅属主,
|
||||
账本记录原路径、模式、时间戳与哈希;恢复要求原字节、原权限一致,恢复前要确认。
|
||||
永久删除只能从隔离区发起。
|
||||
- **不跟随符号链接,不隔离系统目录、XProtect、squid 自身和隔离区自身。**
|
||||
- **读不到不等于干净。** 每个扫描根的结果都记录在覆盖范围里(walked / denied / absent),
|
||||
有缺口时界面必须同时列出未检查的范围,不能只显示「安全」。系统防护读不到时显示
|
||||
「无法确认」,不显示绿色。
|
||||
- **清理白名单与安全排除项是两份独立配置。** 把一个目录从清理里保护起来,不会让它
|
||||
从此不被扫描;反过来,`config.toml` 的 `[security] scan_exclusions` 会让里面的威胁
|
||||
不再被报告,所以新增排除项要二次确认。
|
||||
|
||||
## 规则包的下载与验签
|
||||
|
||||
- 内置规则离线可用;更新只是**下载**,没有请求携带任何本地信息——没有文件名、没有哈希、
|
||||
没有扫描结果、没有被隔离的文件。
|
||||
- 规则包用**独立于安装包的 Ed25519 密钥**签名(`SQUID_INTEL_PUBKEY`)。轮换发布密钥不应该
|
||||
顺手改变谁能推规则,泄漏了安装包密钥也不应该变成一条规则注入路径。
|
||||
- 清单必须验签,包必须核对大小与 SHA-256,而且必须在**装进去之前**先编译一遍:一份
|
||||
YARA 拒绝的规则包永远不能成为 `current`,否则下一次扫描会在最不该失败的时候失败。
|
||||
- manifest 与规则源码存在同一个文件里,读到什么就一起验什么,避免「新包配旧 manifest」。
|
||||
- 验签失败、损坏或主动回滚时继续使用上一版可用规则,并且清空判定缓存——旧规则给出的
|
||||
结论不是新规则给的结论。
|
||||
- 未配置 feed 的构建(比如从源码直接 `cargo build`)不会联网,只用内置规则。
|
||||
|
||||
## 什么不属于安全问题
|
||||
|
||||
- 规则没有覆盖到某个 App 的缓存 → 功能缺口,开 issue 即可。
|
||||
- 某个恶意样本没被扫出来 → squid 不是 XProtect / Defender 的替代品,也不做实时拦截;
|
||||
它是本地按需扫描 + 可逆隔离 + 启动项与进程的可见性。系统防护仍在做实时那部分。
|
||||
- 磁盘空间没有你预期释放得多 → 可能是 APFS 快照或 purge 的年龄过滤,先用 `squid analyze` 对照。
|
||||
- 需要 Full Disk Access 才能读到的目录 → macOS 的限制,见上。
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "squid-desktop",
|
||||
"private": true,
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --port 1420 --strictPort",
|
||||
|
|
@ -17,6 +17,7 @@
|
|||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.3",
|
||||
"@tauri-apps/plugin-notification": "2",
|
||||
"@tauri-apps/plugin-opener": "^2.7.2",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^19.1.0",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,9 @@ dependencies:
|
|||
'@tauri-apps/plugin-dialog':
|
||||
specifier: ^2.8.3
|
||||
version: 2.8.3
|
||||
'@tauri-apps/plugin-notification':
|
||||
specifier: '2'
|
||||
version: 2.8.0
|
||||
'@tauri-apps/plugin-opener':
|
||||
specifier: ^2.7.2
|
||||
version: 2.7.2
|
||||
|
|
@ -849,6 +852,12 @@ packages:
|
|||
'@tauri-apps/api': 2.12.4
|
||||
dev: false
|
||||
|
||||
/@tauri-apps/plugin-notification@2.8.0:
|
||||
resolution: {integrity: sha512-BB9Kk2emiNHyMjIQr3k/ye8RKD2RJeOPCjM5OZLF+4/pO6Kfjl9RtkX4hVCe1vqgbAx5HjHXjf0O8rtdW2F2dw==}
|
||||
dependencies:
|
||||
'@tauri-apps/api': 2.12.4
|
||||
dev: false
|
||||
|
||||
/@tauri-apps/plugin-opener@2.7.2:
|
||||
resolution: {integrity: sha512-LyybP1VSzTMQiaFYcsbAse47KpivlyXdLZMQzGLEnkgQacGESnpjAfFoQ6h5sqWgAdZDH9szYjPzHMpv0Sz+TQ==}
|
||||
dependencies:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,27 @@
|
|||
Squid 0.1.6 - Windows x64
|
||||
|
||||
系统要求
|
||||
--------
|
||||
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
|
||||
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
|
||||
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
|
||||
https://developer.microsoft.com/microsoft-edge/webview2/
|
||||
- 安装与运行都不需要管理员权限。安装位置为
|
||||
%LOCALAPPDATA%\Programs\Squid。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.6-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.6-win-x64.exe -Algorithm SHA256
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
Squid 0.1.6
|
||||
|
||||
- 新增「安全」页:恶意软件扫描(快速 / 全盘 / 自定义,都可取消)、按「已确认 / 可疑 / 提示」分级的发现列表、隔离区与恢复。
|
||||
- 新增「启动项」页:LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以直接停用与恢复,且可逆。
|
||||
- 实时监控增加「进程」页签:全量进程表,含签名状态与所属启动项,可结束当前用户的进程,或对已确认恶意的文件「结束并隔离」。
|
||||
- 系统防护状态只读展示:macOS 读取 XProtect 版本与定义日期、启动/后台扫描与 Gatekeeper;Windows 读取当前杀毒产品、实时保护与定义版本。Squid 不替代 XProtect / Defender 的实时防护。
|
||||
- 侧栏新增「保护」分组,入口共 10 个。快捷键调整:`⌘7`/`⌘8` 现为安全与启动项,历史记录与设置顺延到 `⌘9`/`⌘0`。
|
||||
- 托盘与系统通知会显示保护状态与待处理发现数量;点击通知直接进入发现列表。
|
||||
- 可选的定时扫描(登录后 / 每天 / 每周)、「自动隔离已确认项」(默认关闭)与独立于清理白名单的安全排除项。
|
||||
- 规则包:内置规则离线可用;可下载更新,校验大小与 SHA-256,并在构建内无公钥时明确标注「仅校验哈希 · 未验签」,不把未验签说成已验证。
|
||||
- 不上传任何文件名、哈希、发现或隔离文件;不安装后台服务、内核扩展与常驻特权 helper。
|
||||
- 两个新页面沿用既有界面规范与配色,不新增第二套组件样式。
|
||||
- 修复:桌面端二进制此前从未被 strip(`src-tauri` 独立于根 workspace,没有继承 release 配置),现已补上,universal 二进制减少约 20 MiB。
|
||||
- macOS 与 Windows 同步发布 0.1.6。
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
859c1f4fcab14fbe1a343a9b5ee190bba6b324a627a7337653dd4b5c62db9761 Squid-0.1.6-macOS-universal.dmg
|
||||
73f4df78c7aae8f975aa67335bfca7148698a4988d6b7d2e20665ec9908ef128 Squid-Setup-0.1.6-win-x64.exe
|
||||
38da48607f55c64bcbbf6592927fe75a773ac12778701d4e7ce17e122af426d8 README-Windows-x64.txt
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.6",
|
||||
"date": "2026-11-07",
|
||||
"notes": "Squid 0.1.6\n\n- 新增「安全」页:恶意软件扫描(快速 / 全盘 / 自定义,都可取消)、按「已确认 / 可疑 / 提示」分级的发现列表、隔离区与恢复。\n- 新增「启动项」页:LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以直接停用与恢复,且可逆。\n- 实时监控增加「进程」页签:全量进程表,含签名状态与所属启动项,可结束当前用户的进程,或对已确认恶意的文件「结束并隔离」。\n- 系统防护状态只读展示:macOS 读取 XProtect 版本与定义日期、启动/后台扫描与 Gatekeeper;Windows 读取当前杀毒产品、实时保护与定义版本。Squid 不替代 XProtect / Defender 的实时防护。\n- 侧栏新增「保护」分组,入口共 10 个。快捷键调整:`⌘7`/`⌘8` 现为安全与启动项,历史记录与设置顺延到 `⌘9`/`⌘0`。\n- 托盘与系统通知会显示保护状态与待处理发现数量;点击通知直接进入发现列表。\n- 可选的定时扫描(登录后 / 每天 / 每周)、「自动隔离已确认项」(默认关闭)与独立于清理白名单的安全排除项。\n- 规则包:内置规则离线可用;可下载更新,校验大小与 SHA-256,并在构建内无公钥时明确标注「仅校验哈希 · 未验签」,不把未验签说成已验证。\n- 不上传任何文件名、哈希、发现或隔离文件;不安装后台服务、内核扩展与常驻特权 helper。\n- 两个新页面沿用既有界面规范与配色,不新增第二套组件样式。\n- 修复:桌面端二进制此前从未被 strip(`src-tauri` 独立于根 workspace,没有继承 release 配置),现已补上,universal 二进制减少约 20 MiB。\n- macOS 与 Windows 同步发布 0.1.6。",
|
||||
"artifacts": {
|
||||
"macos": {
|
||||
"file": "Squid-0.1.6-macOS-universal.dmg",
|
||||
"sha256": "859c1f4fcab14fbe1a343a9b5ee190bba6b324a627a7337653dd4b5c62db9761",
|
||||
"size": 21831698
|
||||
},
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.1.6-win-x64.exe",
|
||||
"sha256": "73f4df78c7aae8f975aa67335bfca7148698a4988d6b7d2e20665ec9908ef128",
|
||||
"size": 7816721
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -95,7 +95,10 @@ asset_text = "".join(
|
|||
for p in assets.iterdir()
|
||||
if p.suffix in {".js", ".css", ".html"}
|
||||
)
|
||||
for marker in ("智能扫描", "扫描完成", "自动检查更新"):
|
||||
# Markers are the Chinese copy that has to survive into the bundle: the two scan
|
||||
# words are what the overview offers, and 0.1.6 split them apart, so a bundle built
|
||||
# from an older or newer `dist` than the one on disk fails here rather than shipping.
|
||||
for marker in ("清理扫描", "安全快速扫描", "扫描完成", "自动检查更新"):
|
||||
if marker not in asset_text:
|
||||
missing.append(marker)
|
||||
if missing:
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,10 +1,10 @@
|
|||
[package]
|
||||
name = "squid-desktop"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor."
|
||||
authors = ["squid contributors"]
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
rust-version = "1.95"
|
||||
license = "GPL-3.0-only"
|
||||
default-run = "squid-desktop"
|
||||
|
||||
|
|
@ -23,10 +23,12 @@ tauri-build = { version = "2", features = [] }
|
|||
squid-core = { path = "../crates/squid-core" }
|
||||
squid-engine = { path = "../crates/squid-engine" }
|
||||
squid-platform = { path = "../crates/squid-platform" }
|
||||
squid-guard = { path = "../crates/squid-guard" }
|
||||
squid-stats = { path = "../crates/squid-stats" }
|
||||
tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private-api"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
dirs = "6"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
@ -44,3 +46,16 @@ debug = 1
|
|||
|
||||
[profile.dev.package."*"]
|
||||
debug = false
|
||||
|
||||
# The workspace root declares these for `crates/*`, but `src-tauri` is excluded
|
||||
# from that workspace, so this package had no release profile of its own and every
|
||||
# desktop build shipped its whole symbol table. `strip = true` would only have
|
||||
# dropped debug info, which this binary does not carry; the 23 MB that came out of
|
||||
# it was the symbol table, so it is the symbol table that has to go.
|
||||
# `panic` is deliberately left to unwind: a panic on a command thread currently
|
||||
# costs one request, and aborting the whole app instead would be a behaviour change
|
||||
# this release has no business making.
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
strip = "symbols"
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
"core:default",
|
||||
"core:window:allow-start-dragging",
|
||||
"dialog:default",
|
||||
"opener:default"
|
||||
"opener:default",
|
||||
"notification:default"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ impl AppState {
|
|||
.map_err(|_| "The application state is unavailable; restart Squid.".to_string())
|
||||
}
|
||||
|
||||
fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
|
||||
pub(crate) fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
|
||||
if job_id.trim().is_empty() {
|
||||
return Err("A job identifier is required.".into());
|
||||
}
|
||||
|
|
@ -51,7 +51,7 @@ impl AppState {
|
|||
Ok(token)
|
||||
}
|
||||
|
||||
fn finish(&self, job_id: &str) {
|
||||
pub(crate) fn finish(&self, job_id: &str) {
|
||||
if let Ok(mut jobs) = self.jobs.lock() {
|
||||
jobs.remove(job_id);
|
||||
}
|
||||
|
|
@ -72,13 +72,18 @@ struct ProgressView {
|
|||
freed: Option<u64>,
|
||||
}
|
||||
|
||||
struct ProgressReporter {
|
||||
pub(crate) struct ProgressReporter {
|
||||
stop: Arc<AtomicBool>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl ProgressReporter {
|
||||
fn start(app: AppHandle, job_id: String, kind: &'static str, progress: Progress) -> Self {
|
||||
pub(crate) fn start(
|
||||
app: AppHandle,
|
||||
job_id: String,
|
||||
kind: &'static str,
|
||||
progress: Progress,
|
||||
) -> Self {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stopped = stop.clone();
|
||||
let handle = thread::spawn(move || {
|
||||
|
|
@ -97,7 +102,7 @@ impl ProgressReporter {
|
|||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) {
|
||||
pub(crate) fn finish(mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
mod app;
|
||||
mod autostart;
|
||||
pub mod notifications;
|
||||
mod permissions;
|
||||
mod process;
|
||||
pub mod security;
|
||||
mod startup;
|
||||
mod update;
|
||||
|
||||
use security::ScanTarget;
|
||||
use squid_core::{Locale, Settings};
|
||||
use tauri::{
|
||||
menu::{Menu, MenuItem, PredefinedMenuItem},
|
||||
|
|
@ -14,7 +18,7 @@ use tauri::{
|
|||
#[cfg(target_os = "macos")]
|
||||
use tauri::RunEvent;
|
||||
|
||||
fn show_main_window(app: &AppHandle) {
|
||||
pub(crate) fn show_main_window(app: &AppHandle) {
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
|
|
@ -22,7 +26,7 @@ fn show_main_window(app: &AppHandle) {
|
|||
}
|
||||
}
|
||||
|
||||
fn navigate_to(app: &AppHandle, page: &'static str) {
|
||||
pub(crate) fn navigate_to(app: &AppHandle, page: &str) {
|
||||
show_main_window(app);
|
||||
let _ = app.emit("squid://navigate", page);
|
||||
}
|
||||
|
|
@ -43,6 +47,33 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
|
|||
true,
|
||||
None::<&str>,
|
||||
)?;
|
||||
// A status line, not a button: it is disabled because reading it is the only
|
||||
// thing it is for, and the actions that follow are where the acting happens.
|
||||
let protection = MenuItem::with_id(
|
||||
app,
|
||||
"protection",
|
||||
protection_line(app, locale),
|
||||
false,
|
||||
None::<&str>,
|
||||
)?;
|
||||
let scan = MenuItem::with_id(
|
||||
app,
|
||||
"scan",
|
||||
if security::scanning(app) {
|
||||
tray_text(locale, "Scanning…", "正在扫描…")
|
||||
} else {
|
||||
tray_text(locale, "Scan for malware", "扫描恶意软件")
|
||||
},
|
||||
!security::scanning(app),
|
||||
None::<&str>,
|
||||
)?;
|
||||
let startup = MenuItem::with_id(
|
||||
app,
|
||||
"startup",
|
||||
tray_text(locale, "Manage startup items", "管理启动项"),
|
||||
true,
|
||||
None::<&str>,
|
||||
)?;
|
||||
let cleanup = MenuItem::with_id(
|
||||
app,
|
||||
"cleanup",
|
||||
|
|
@ -77,6 +108,9 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
|
|||
app,
|
||||
&[
|
||||
&open,
|
||||
&protection,
|
||||
&scan,
|
||||
&startup,
|
||||
&first_separator,
|
||||
&cleanup,
|
||||
&apps,
|
||||
|
|
@ -87,8 +121,49 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
|
|||
)
|
||||
}
|
||||
|
||||
/// The one line that tells a person whether to open the app. It reports findings
|
||||
/// squid has actually confirmed, and says "not scanned" rather than "normal" when
|
||||
/// nothing has been looked at — a security tool that defaults to green is a
|
||||
/// security tool that lies.
|
||||
fn protection_line(app: &AppHandle, locale: Locale) -> String {
|
||||
if security::scanning(app) {
|
||||
return tray_text(locale, "Protection: scanning…", "保护状态:正在扫描").to_string();
|
||||
}
|
||||
let (confirmed, suspicious, scanned) = security::outstanding();
|
||||
if confirmed > 0 {
|
||||
return format!(
|
||||
"{} {}",
|
||||
tray_text(locale, "Protection: issues found", "保护状态:发现问题"),
|
||||
confirmed
|
||||
);
|
||||
}
|
||||
if !scanned {
|
||||
return tray_text(locale, "Protection: not scanned yet", "保护状态:尚未扫描").to_string();
|
||||
}
|
||||
if suspicious > 0 {
|
||||
return format!(
|
||||
"{} {}",
|
||||
tray_text(locale, "Protection: needs a look", "保护状态:有待检查项"),
|
||||
suspicious
|
||||
);
|
||||
}
|
||||
tray_text(
|
||||
locale,
|
||||
"Protection: nothing outstanding",
|
||||
"保护状态:没有待处理项",
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// The hover text. macOS hides the disabled menu row behind a click, so the
|
||||
/// status has to be readable without opening anything.
|
||||
fn tray_tooltip(app: &AppHandle, locale: Locale) -> String {
|
||||
format!("Squid — {}", protection_line(app, locale))
|
||||
}
|
||||
|
||||
fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
|
||||
let menu = tray_menu(app, locale)?;
|
||||
let tooltip = tray_tooltip(app, locale);
|
||||
let icon = app
|
||||
.default_window_icon()
|
||||
.cloned()
|
||||
|
|
@ -96,11 +171,13 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
|
|||
|
||||
TrayIconBuilder::with_id("squid-tray")
|
||||
.icon(icon)
|
||||
.tooltip("Squid")
|
||||
.tooltip(tooltip)
|
||||
.menu(&menu)
|
||||
.show_menu_on_left_click(true)
|
||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||
"open" => show_main_window(app),
|
||||
"scan" => security::scan_in_background(app.clone(), ScanTarget::Quick),
|
||||
"startup" => navigate_to(app, "startup"),
|
||||
"cleanup" => navigate_to(app, "cleanup"),
|
||||
"applications" => navigate_to(app, "applications"),
|
||||
"purge" => navigate_to(app, "purge"),
|
||||
|
|
@ -118,6 +195,7 @@ pub(crate) fn sync_tray(app: &AppHandle, locale: Locale) {
|
|||
if let Ok(menu) = tray_menu(app, locale) {
|
||||
let _ = tray.set_menu(Some(menu));
|
||||
}
|
||||
let _ = tray.set_tooltip(Some(tray_tooltip(app, locale)));
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
|
|
@ -128,6 +206,7 @@ pub fn run() {
|
|||
}))
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
api.prevent_close();
|
||||
|
|
@ -136,6 +215,7 @@ pub fn run() {
|
|||
})
|
||||
.manage(app::AppState::default())
|
||||
.manage(update::UpdateState::default())
|
||||
.manage(security::SecurityState::default())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
app::bootstrap,
|
||||
app::cancel_job,
|
||||
|
|
@ -167,11 +247,30 @@ pub fn run() {
|
|||
update::update_install,
|
||||
update::update_clear,
|
||||
update::set_update_check_enabled,
|
||||
security::security_status,
|
||||
security::security_scan,
|
||||
security::security_cancel,
|
||||
security::security_open,
|
||||
security::security_quarantine,
|
||||
security::security_restore,
|
||||
security::security_delete_quarantine,
|
||||
security::security_ignore,
|
||||
security::security_exclusions,
|
||||
security::security_settings_save,
|
||||
security::security_update_rules,
|
||||
security::security_rollback_rules,
|
||||
security::open_quarantine_folder,
|
||||
startup::startup_items,
|
||||
startup::startup_set_enabled,
|
||||
startup::process_inventory,
|
||||
startup::process_detail,
|
||||
startup::process_stop,
|
||||
])
|
||||
.setup(|app| {
|
||||
let (settings, _) = Settings::load();
|
||||
create_tray(app.handle(), Locale::detect(&settings))?;
|
||||
update::spawn_startup_check(app.handle());
|
||||
security::spawn_scheduler(app.handle(), &settings);
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
//! System notifications, and the one thing they must never be relied on for.
|
||||
//!
|
||||
//! A notification is a convenience: it tells a person that something is waiting.
|
||||
//! Every state it describes is also visible in the app and in the tray, because
|
||||
//! macOS and Windows both let the user switch notifications off, and a security
|
||||
//! tool that goes quiet when that happens has stopped reporting rather than
|
||||
//! stopped finding.
|
||||
//!
|
||||
//! Clicking a notification navigates rather than acting: nothing is quarantined
|
||||
//! on the strength of a click. The frontend registers the plugin's `onAction` and
|
||||
//! calls back into [`open_target`], because closing the window only hides it and
|
||||
//! a webview that is not there cannot bring itself back.
|
||||
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_notification::NotificationExt;
|
||||
|
||||
pub fn notify(app: &AppHandle, title: &str, body: &str) {
|
||||
let result = app
|
||||
.notification()
|
||||
.builder()
|
||||
.title(title)
|
||||
.body(body)
|
||||
.auto_cancel()
|
||||
.show();
|
||||
if let Err(error) = result {
|
||||
// Losing a notification is not worth a dialog, but it is worth a line in
|
||||
// the log a person sends us when "squid never told me".
|
||||
eprintln!("notification could not be shown: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a notification click leads: the findings, and nothing else. Findings are
|
||||
/// the only thing squid ever notifies about, so the tap needs no destination in its
|
||||
/// payload, and the same path the tray menu uses brings the window forward.
|
||||
pub fn open_target(app: &AppHandle) {
|
||||
crate::navigate_to(app, "security");
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,228 @@
|
|||
//! `startup_*` and `process_*`: what runs by itself, and what is running now.
|
||||
//!
|
||||
//! Two lists that look alike and answer different questions. The startup list is
|
||||
//! a claim about the next login, read from launchd plists, registry Run keys, the
|
||||
//! startup folders, scheduled tasks and services; the process list is a fact
|
||||
//! about this second. A row can appear in one and not the other for entirely
|
||||
//! ordinary reasons, so the two are joined only by a label — "this process came
|
||||
//! from that entry" — and never merged into one table.
|
||||
//!
|
||||
//! Reading is free. Writing is not: only entries the current user owns are
|
||||
//! offered as modifiable, and the platform layer re-reads reality after a change
|
||||
//! instead of trusting the caller to remember what it asked for.
|
||||
|
||||
use serde::Serialize;
|
||||
use squid_platform::process_table::ProcessRow;
|
||||
use squid_platform::startup::{StartupInventory, StartupItem};
|
||||
use squid_platform::trust;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StartupView {
|
||||
items: Vec<StartupItem>,
|
||||
notes: Vec<String>,
|
||||
user_count: usize,
|
||||
system_count: usize,
|
||||
disabled_count: usize,
|
||||
/// Entries the user owns that are not vendor-owned: what this page may act on.
|
||||
actionable_count: usize,
|
||||
risky_count: usize,
|
||||
/// Which of the two platforms' surfaces were readable at all, so a page that
|
||||
/// shows nothing can say whether that means "none" or "could not look".
|
||||
sources: Vec<String>,
|
||||
}
|
||||
|
||||
impl StartupView {
|
||||
fn of(inventory: StartupInventory) -> StartupView {
|
||||
let mut sources: Vec<String> = inventory
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.source.as_str().to_string())
|
||||
.collect();
|
||||
sources.sort();
|
||||
sources.dedup();
|
||||
StartupView {
|
||||
actionable_count: inventory
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| item.modifiable && !item.system_vendor)
|
||||
.count(),
|
||||
risky_count: inventory
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| !item.risks.is_empty())
|
||||
.count(),
|
||||
user_count: inventory.user_count(),
|
||||
system_count: inventory.system_count(),
|
||||
disabled_count: inventory.disabled_count(),
|
||||
sources,
|
||||
items: inventory.items,
|
||||
notes: inventory.notes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn startup_items() -> Result<StartupView, String> {
|
||||
tauri::async_runtime::spawn_blocking(|| StartupView::of(squid_platform::startup::inventory()))
|
||||
.await
|
||||
.map_err(|error| format!("Could not read the startup items: {error}"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StartupChange {
|
||||
item: StartupItem,
|
||||
message: String,
|
||||
view: StartupView,
|
||||
}
|
||||
|
||||
/// Disable or enable one entry. The refreshed inventory comes back with it,
|
||||
/// because the truth after a launchd reload or a registry write is whatever the
|
||||
/// system now says, not what this function intended.
|
||||
#[tauri::command]
|
||||
pub async fn startup_set_enabled(id: String, enabled: bool) -> Result<StartupChange, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let item = squid_platform::startup::set_enabled(&id, enabled)?;
|
||||
let mut store = squid_guard::store::Store::new();
|
||||
store.note(
|
||||
if enabled { "startup-on" } else { "startup-off" },
|
||||
item.name.clone(),
|
||||
item.program.clone(),
|
||||
);
|
||||
let message = if item.disabled == !enabled {
|
||||
format!(
|
||||
"{} is now {}.",
|
||||
item.name,
|
||||
if item.disabled { "off" } else { "on" }
|
||||
)
|
||||
} else {
|
||||
// The system disagrees with what was asked. Say so, because the
|
||||
// common causes — a re-armed login item, a managed profile — are
|
||||
// things the user needs to know rather than to retry.
|
||||
format!(
|
||||
"{} did not change: the system reports it as {}.",
|
||||
item.name,
|
||||
if item.disabled { "off" } else { "on" }
|
||||
)
|
||||
};
|
||||
Ok(StartupChange {
|
||||
view: StartupView::of(squid_platform::startup::inventory()),
|
||||
item,
|
||||
message,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProcessDetailView {
|
||||
row: ProcessRow,
|
||||
sha256: Option<String>,
|
||||
trust: trust::Trust,
|
||||
startup: Option<StartupItem>,
|
||||
parent: Option<ProcessRow>,
|
||||
/// Why squid would refuse to stop this one, in the user's terms.
|
||||
stop_note: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn process_inventory(with_trust: Option<bool>) -> Result<Vec<ProcessRow>, String> {
|
||||
let with_trust = with_trust.unwrap_or(true);
|
||||
tauri::async_runtime::spawn_blocking(move || -> Result<Vec<ProcessRow>, String> {
|
||||
Ok(squid_platform::process_table::snapshot(with_trust).rows)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Could not read the process table: {error}"))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn process_detail(pid: u32) -> Result<ProcessDetailView, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || -> Result<ProcessDetailView, String> {
|
||||
let row = squid_platform::process_table::row_of(pid)
|
||||
.ok_or_else(|| format!("Process {pid} has already exited."))?;
|
||||
let executable: Option<PathBuf> = row.program.clone();
|
||||
let trust = match &executable {
|
||||
Some(path) => trust::assess(path),
|
||||
None => trust::Trust::default(),
|
||||
};
|
||||
let sha256 = executable
|
||||
.as_ref()
|
||||
.and_then(|path| squid_guard::rules::sha256_of(path));
|
||||
let startup = row
|
||||
.program
|
||||
.as_ref()
|
||||
.and_then(|program| squid_platform::startup::entry_for(program));
|
||||
let parent = row.parent.and_then(squid_platform::process_table::row_of);
|
||||
let stop_note = refusal_note(&row);
|
||||
Ok(ProcessDetailView {
|
||||
trust,
|
||||
sha256,
|
||||
startup,
|
||||
parent,
|
||||
stop_note,
|
||||
row,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Could not read that process: {error}"))?
|
||||
}
|
||||
|
||||
/// Why squid will not stop a process, or `None` when it will. Mirrors the checks
|
||||
/// in `squid-stats`' sampler so the UI can explain before the user clicks, and
|
||||
/// not promise something the stop path will refuse.
|
||||
fn refusal_note(row: &ProcessRow) -> Option<String> {
|
||||
if let Some(rule) = squid_platform::process::pid_refusal(row.pid) {
|
||||
return Some(format!("Squid never stops {rule}.", rule = describe(rule)));
|
||||
}
|
||||
if let Some(rule) = squid_platform::process::refusal(row.pid, &row.name) {
|
||||
return Some(format!("Squid never stops {rule}.", rule = describe(rule)));
|
||||
}
|
||||
if !row.owned {
|
||||
return Some("This process belongs to another user or to the system.".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The rule's own wording, so a refusal shown before a click and the refusal the
|
||||
/// stop path returns cannot drift into two different sentences.
|
||||
fn describe(rule: squid_platform::process::OffLimits) -> &'static str {
|
||||
rule.reason()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProcessStopResult {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Stop one process by pid, re-checked against the live table. The name that
|
||||
/// comes back with the confirmation is the point: a pid that has been recycled
|
||||
/// between the click and the kill belongs to something else, and the row read
|
||||
/// here is the row whose name is compared.
|
||||
#[tauri::command]
|
||||
pub async fn process_stop(pid: u32, name: String) -> Result<ProcessStopResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let row = squid_platform::process_table::row_of(pid)
|
||||
.ok_or_else(|| format!("Process {pid} has already exited."))?;
|
||||
if row.name != name {
|
||||
return Err(format!(
|
||||
"Process {pid} is now {}, not {name}. Nothing was stopped.",
|
||||
row.name
|
||||
));
|
||||
}
|
||||
if let Some(refusal) = refusal_note(&row) {
|
||||
return Err(refusal);
|
||||
}
|
||||
squid_platform::process::force_stop(pid)
|
||||
.map_err(|error| format!("Could not stop {name}: {error}"))?;
|
||||
Ok(ProcessStopResult {
|
||||
message: format!("Stopped {name} ({pid})."),
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
}
|
||||
|
|
@ -27,7 +27,7 @@ const BAKED_MANIFEST_URL: &str = match option_env!("SQUID_UPDATE_URL") {
|
|||
Some(url) => url,
|
||||
None => "",
|
||||
};
|
||||
const SIGNATURE_FILE: &str = "squid-update.sig";
|
||||
pub(crate) const SIGNATURE_FILE: &str = "squid-update.sig";
|
||||
const ENV_MANIFEST_URL: &str = "SQUID_UPDATE_URL";
|
||||
const BAKED_PUBLIC_KEY: &str = match option_env!("SQUID_UPDATE_PUBKEY") {
|
||||
Some(key) => key,
|
||||
|
|
@ -254,7 +254,7 @@ fn public_key() -> Result<Option<VerifyingKey>, String> {
|
|||
key_from_hex(BAKED_PUBLIC_KEY)
|
||||
}
|
||||
|
||||
fn key_from_hex(value: &str) -> Result<Option<VerifyingKey>, String> {
|
||||
pub(crate) fn key_from_hex(value: &str) -> Result<Option<VerifyingKey>, String> {
|
||||
let key = value.trim();
|
||||
if key.is_empty() {
|
||||
return Ok(None);
|
||||
|
|
@ -267,7 +267,7 @@ fn key_from_hex(value: &str) -> Result<Option<VerifyingKey>, String> {
|
|||
.map(Some)
|
||||
}
|
||||
|
||||
fn signature_url() -> Option<String> {
|
||||
pub(crate) fn signature_url() -> Option<String> {
|
||||
let url = manifest_url();
|
||||
(!url.is_empty()).then(|| {
|
||||
let base = match url.rsplit_once('/') {
|
||||
|
|
@ -278,11 +278,46 @@ fn signature_url() -> Option<String> {
|
|||
})
|
||||
}
|
||||
|
||||
/// The rule-pack channel lives beside the installer manifest but is a different
|
||||
/// document with a different key. Rotating the release key must not silently
|
||||
/// rotate who can push rules, and a leaked installer key must not become a
|
||||
/// rule-injection path, so the two are never read from the same variable.
|
||||
pub(crate) const INTEL_MANIFEST_FILE: &str = "squid-intel.json";
|
||||
pub(crate) const INTEL_SIGNATURE_FILE: &str = "squid-intel.sig";
|
||||
const BAKED_INTEL_PUBLIC_KEY: &str = match option_env!("SQUID_INTEL_PUBKEY") {
|
||||
Some(key) => key,
|
||||
None => "",
|
||||
};
|
||||
|
||||
/// `…/squid-intel.json` on the same channel as the installers, or `None` when
|
||||
/// this build has no feed at all.
|
||||
pub(crate) fn intel_manifest_url() -> Option<String> {
|
||||
raw_asset_url(INTEL_MANIFEST_FILE).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn intel_manifest_signature() -> Result<Option<String>, String> {
|
||||
let url = match intel_manifest_url() {
|
||||
Some(_) => raw_asset_url(INTEL_SIGNATURE_FILE)?,
|
||||
None => return Ok(None),
|
||||
};
|
||||
// An absent signature file is an answer, not a failure: it means the channel
|
||||
// publishes unsigned rules, which `verify_against` then reports honestly.
|
||||
match fetch_text(&url) {
|
||||
Ok(text) => Ok(Some(text)),
|
||||
Err(error) if error.contains("404") || error.contains("not found") => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn intel_public_key() -> Result<Option<VerifyingKey>, String> {
|
||||
key_from_hex(BAKED_INTEL_PUBLIC_KEY)
|
||||
}
|
||||
|
||||
fn verify_manifest(text: &str, signature: Option<&str>) -> Result<bool, String> {
|
||||
verify_against(public_key()?.as_ref(), text, signature)
|
||||
}
|
||||
|
||||
fn verify_against(
|
||||
pub(crate) fn verify_against(
|
||||
key: Option<&VerifyingKey>,
|
||||
text: &str,
|
||||
signature: Option<&str>,
|
||||
|
|
@ -344,7 +379,7 @@ fn is_sha256_hex(value: &str) -> bool {
|
|||
value.len() == 64 && value.chars().all(|character| character.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn raw_asset_url(file: &str) -> Result<String, String> {
|
||||
pub(crate) fn raw_asset_url(file: &str) -> Result<String, String> {
|
||||
let base = manifest_url();
|
||||
if base.is_empty() {
|
||||
return Err("No update feed is configured.".into());
|
||||
|
|
@ -353,7 +388,7 @@ fn raw_asset_url(file: &str) -> Result<String, String> {
|
|||
Ok(format!("{directory}/{}", file.trim_start_matches('/')))
|
||||
}
|
||||
|
||||
fn download(
|
||||
pub(crate) fn download(
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
timeout: Duration,
|
||||
|
|
@ -452,7 +487,7 @@ fn download(
|
|||
}
|
||||
}
|
||||
|
||||
fn fetch_text(url: &str) -> Result<String, String> {
|
||||
pub(crate) fn fetch_text(url: &str) -> Result<String, String> {
|
||||
let target = std::env::temp_dir().join(format!(
|
||||
"squid-manifest-{}-{}.json",
|
||||
std::process::id(),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Squid",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"identifier": "app.nex.squid",
|
||||
"mainBinaryName": "squid-desktop",
|
||||
"build": {
|
||||
|
|
|
|||
125
src/App.tsx
125
src/App.tsx
|
|
@ -6,6 +6,7 @@ import {
|
|||
Eraser,
|
||||
History,
|
||||
LayoutDashboard,
|
||||
Power,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
ShieldCheck,
|
||||
|
|
@ -15,6 +16,8 @@ import {
|
|||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
import { useAppsWorkspace } from "./hooks/useAppsWorkspace";
|
||||
import { useScanWorkspace } from "./hooks/useScanWorkspace";
|
||||
import { useSecurityWorkspace } from "./hooks/useSecurityWorkspace";
|
||||
import { useStartupWorkspace } from "./hooks/useStartupWorkspace";
|
||||
import { useSystemSnapshot } from "./hooks/useSystemSnapshot";
|
||||
import { useUpdateFlow } from "./hooks/useUpdateFlow";
|
||||
import { detectLanguage, I18nProvider, useI18n } from "./i18n";
|
||||
|
|
@ -25,6 +28,7 @@ import type {
|
|||
DeleteMode,
|
||||
Language,
|
||||
PageId,
|
||||
SecurityStatus,
|
||||
SettingsView,
|
||||
} from "./types";
|
||||
import { useToast } from "./components/ui";
|
||||
|
|
@ -35,7 +39,9 @@ import { CleanupPage } from "./pages/CleanupPage";
|
|||
import { HistoryPage } from "./pages/HistoryPage";
|
||||
import { OverviewPage } from "./pages/OverviewPage";
|
||||
import { PurgePage } from "./pages/PurgePage";
|
||||
import { SecurityPage } from "./pages/SecurityPage";
|
||||
import { SettingsPage } from "./pages/SettingsPage";
|
||||
import { StartupPage } from "./pages/StartupPage";
|
||||
import { StoragePage } from "./pages/StoragePage";
|
||||
import { SystemPage } from "./pages/SystemPage";
|
||||
|
||||
|
|
@ -79,6 +85,14 @@ const NAV_GROUPS: {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
labelEn: "Protection",
|
||||
labelZh: "保护",
|
||||
items: [
|
||||
{ id: "security", labelEn: "Security", labelZh: "安全", icon: ShieldCheck },
|
||||
{ id: "startup", labelEn: "Startup items", labelZh: "启动项", icon: Power },
|
||||
],
|
||||
},
|
||||
{
|
||||
labelEn: "Insights",
|
||||
labelZh: "洞察",
|
||||
|
|
@ -106,6 +120,8 @@ const PAGE_TITLES: Record<PageId, [string, string]> = {
|
|||
purge: ["Deep Clean", "深度清理"],
|
||||
storage: ["Storage", "存储空间"],
|
||||
system: ["Real-time monitor", "实时监控"],
|
||||
security: ["Security", "安全"],
|
||||
startup: ["Startup items", "启动项"],
|
||||
history: ["History", "历史记录"],
|
||||
settings: ["Settings", "设置"],
|
||||
};
|
||||
|
|
@ -167,6 +183,17 @@ export default function App() {
|
|||
const systemActive = page === "overview" || page === "system";
|
||||
const system = useSystemSnapshot(systemActive);
|
||||
const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck);
|
||||
// One security state for the whole window: the overview strip, the sidebar
|
||||
// badge and the security page all read this, so they cannot disagree.
|
||||
const security = useSecurityWorkspace(true);
|
||||
const startup = useStartupWorkspace(page === "startup");
|
||||
// A process row can ask "where did this come from", and a startup entry can ask
|
||||
// "is it running". Both hand the other page a path rather than duplicating data.
|
||||
const [processFilter, setProcessFilter] = useState<string | null>(null);
|
||||
// A path handed from the process table to the startup page, where it becomes a
|
||||
// search rather than a second data load.
|
||||
const [startupQuery, setStartupQuery] = useState<string | null>(null);
|
||||
const [autostart, setAutostart] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
|
@ -179,6 +206,12 @@ export default function App() {
|
|||
setLang(next.language);
|
||||
setAutoCheck(next.updateCheckEnabled);
|
||||
setSetupOpen(!next.settings.setupReviewed);
|
||||
// The readiness card reports whether Squid starts at login, and that is a
|
||||
// fact about the system rather than about settings, so it is asked for.
|
||||
void api
|
||||
.autostartStatus()
|
||||
.then(setAutostart)
|
||||
.catch(() => setAutostart(false));
|
||||
document.documentElement.lang = next.language === "zh" ? "zh-CN" : "en";
|
||||
})
|
||||
.catch((reason) => {
|
||||
|
|
@ -189,12 +222,56 @@ export default function App() {
|
|||
};
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* A notification click goes to the findings, and brings the window back.
|
||||
*
|
||||
* Findings are the only thing squid notifies about, so the tap needs no
|
||||
* destination in its payload. The backend is asked as well because closing the
|
||||
* window only hides it: the webview is gone, so nothing on this side can undo
|
||||
* the hide, and a click that appeared to do nothing would look like a bug in the
|
||||
* security feature rather than in window management.
|
||||
*/
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let stop: { unregister: () => void } | null = null;
|
||||
void import("@tauri-apps/plugin-notification")
|
||||
.then(({ onAction }) =>
|
||||
onAction(() => {
|
||||
if (cancelled) return;
|
||||
// The backend's reply arrives as the same navigate event the tray menu
|
||||
// uses, which also shows the hidden window. Asking first and navigating
|
||||
// here as well would race the two against each other.
|
||||
void api.securityOpen().catch(() => undefined);
|
||||
void security.refresh();
|
||||
}),
|
||||
)
|
||||
.then((listener) => {
|
||||
if (cancelled) void listener.unregister();
|
||||
else stop = listener;
|
||||
})
|
||||
// No plugin, or notifications switched off: the tray line and the in-app
|
||||
// banner still report the same finding, so this is silence, not failure.
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
void stop?.unregister();
|
||||
};
|
||||
}, [security]);
|
||||
|
||||
const inspectProcess = useCallback((path: string) => {
|
||||
setProcessFilter(path);
|
||||
setPage("system");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
void api
|
||||
.onNavigate((next) => {
|
||||
if (!cancelled) setPage(next);
|
||||
// A tray or notification jump into Security must show current numbers,
|
||||
// not the ones from whenever the window last asked.
|
||||
if (next === "security") void security.refresh();
|
||||
})
|
||||
.then((stop) => {
|
||||
if (cancelled) stop();
|
||||
|
|
@ -204,7 +281,7 @@ export default function App() {
|
|||
cancelled = true;
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
}, [security]);
|
||||
|
||||
useEffect(() => {
|
||||
const order: PageId[] = [
|
||||
|
|
@ -214,6 +291,8 @@ export default function App() {
|
|||
"purge",
|
||||
"storage",
|
||||
"system",
|
||||
"security",
|
||||
"startup",
|
||||
"history",
|
||||
"settings",
|
||||
];
|
||||
|
|
@ -281,12 +360,14 @@ export default function App() {
|
|||
page={page}
|
||||
setPage={setPage}
|
||||
updateVersion={activeUpdate?.availableVersion ?? null}
|
||||
security={security.status}
|
||||
>
|
||||
{page === "overview" ? (
|
||||
<OverviewPage
|
||||
bootstrap={bootstrap}
|
||||
snapshot={system.snapshot}
|
||||
cleanup={cleanup}
|
||||
security={security}
|
||||
onNavigate={setPage}
|
||||
/>
|
||||
) : null}
|
||||
|
|
@ -309,12 +390,30 @@ export default function App() {
|
|||
/>
|
||||
) : null}
|
||||
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
|
||||
{page === "security" ? (
|
||||
<SecurityPage security={security} onOpenStartup={() => setPage("startup")} />
|
||||
) : null}
|
||||
{page === "startup" ? (
|
||||
<StartupPage
|
||||
startup={startup}
|
||||
security={security}
|
||||
initialQuery={startupQuery}
|
||||
onInspectProcess={inspectProcess}
|
||||
onShowSecurity={() => setPage("security")}
|
||||
/>
|
||||
) : null}
|
||||
{page === "system" ? (
|
||||
<SystemPage
|
||||
snapshot={system.snapshot}
|
||||
error={system.error}
|
||||
loading={system.loading}
|
||||
refresh={system.refresh}
|
||||
initialProcessFilter={processFilter}
|
||||
security={security}
|
||||
onOpenStartup={(query) => {
|
||||
setStartupQuery(query);
|
||||
setPage("startup");
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{page === "history" ? <HistoryPage /> : null}
|
||||
|
|
@ -324,28 +423,49 @@ export default function App() {
|
|||
settings={settings}
|
||||
flow={update}
|
||||
autoCheck={autoCheck}
|
||||
security={security}
|
||||
onSettingsChange={setSettings}
|
||||
onLanguageChange={changeLanguage}
|
||||
onAutoCheckChange={changeAutoCheck}
|
||||
/>
|
||||
) : null}
|
||||
</AppChrome>
|
||||
{setupOpen ? <SetupPanel onDone={() => void finishSetup()} /> : null}
|
||||
{setupOpen ? (
|
||||
<SetupPanel
|
||||
security={security}
|
||||
autostart={autostart}
|
||||
onDone={() => void finishSetup()}
|
||||
/>
|
||||
) : null}
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/// A number means "confirmed and unhandled", which is the only state that
|
||||
/// justifies interrupting. A dot alone means there is something suspicious, worth
|
||||
/// a look but not worth a badge that looks like an alarm.
|
||||
function securityBadge(security: SecurityStatus, page: PageId) {
|
||||
if (page === "security") return null;
|
||||
if (security.confirmed > 0) {
|
||||
return <i className="nav-badge">{security.confirmed > 9 ? "9+" : security.confirmed}</i>;
|
||||
}
|
||||
if (security.suspicious > 0) return <i className="nav-dot" />;
|
||||
return null;
|
||||
}
|
||||
|
||||
function AppChrome({
|
||||
bootstrap,
|
||||
page,
|
||||
setPage,
|
||||
updateVersion,
|
||||
security,
|
||||
children,
|
||||
}: {
|
||||
bootstrap: Bootstrap;
|
||||
page: PageId;
|
||||
setPage: (page: PageId) => void;
|
||||
updateVersion: string | null;
|
||||
security: SecurityStatus | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
|
|
@ -384,6 +504,7 @@ function AppChrome({
|
|||
>
|
||||
<Icon size={18} />
|
||||
<span>{lang === "zh" ? item.labelZh : item.labelEn}</span>
|
||||
{item.id === "security" && security ? securityBadge(security, page) : null}
|
||||
{item.id === "cleanup" && page !== "cleanup" ? (
|
||||
<i className="nav-dot" />
|
||||
) : null}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,560 @@
|
|||
import {
|
||||
Ban,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
FileSearch,
|
||||
Power,
|
||||
RefreshCw,
|
||||
Search,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { formatBytes, formatCount, messageFrom, shortPath } from "../lib/format";
|
||||
import type { Finding, ProcessDetail, ProcessRow } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import {
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
EmptyState,
|
||||
InlineError,
|
||||
Modal,
|
||||
useToast,
|
||||
} from "./ui";
|
||||
|
||||
type SortKey = "name" | "pid" | "cpu" | "memory" | "startedMs";
|
||||
|
||||
const PAGE = 120;
|
||||
|
||||
/**
|
||||
* The whole process table, as opposed to the twelve busiest rows the meters show.
|
||||
*
|
||||
* It is loaded when the tab is opened and refreshed by hand, never on the 1 Hz
|
||||
* sample: a signature lookup per distinct executable is the expensive part, and
|
||||
* doing it twice a second for four hundred processes is how a monitor panel
|
||||
* becomes the thing it is monitoring.
|
||||
*/
|
||||
export function ProcessTable({
|
||||
active,
|
||||
initialFilter,
|
||||
security,
|
||||
onOpenStartup,
|
||||
}: {
|
||||
active: boolean;
|
||||
initialFilter: string | null;
|
||||
security: SecurityWorkspace;
|
||||
onOpenStartup: (query: string) => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [rows, setRows] = useState<ProcessRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [query, setQuery] = useState(initialFilter ?? "");
|
||||
const [sort, setSort] = useState<SortKey>("cpu");
|
||||
const [mineOnly, setMineOnly] = useState(false);
|
||||
const [unsignedOnly, setUnsignedOnly] = useState(false);
|
||||
const [startupOnly, setStartupOnly] = useState(false);
|
||||
const [grouped, setGrouped] = useState(false);
|
||||
const [limit, setLimit] = useState(PAGE);
|
||||
const [detail, setDetail] = useState<ProcessDetail | null>(null);
|
||||
const [opening, setOpening] = useState(false);
|
||||
const [victim, setVictim] = useState<ProcessRow | null>(null);
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const [trust, setTrust] = useState(true);
|
||||
|
||||
const load = useCallback(
|
||||
async (withTrust: boolean) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setRows(await api.processInventory(withTrust));
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(messageFrom(reason));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (active && rows === null) void load(true);
|
||||
}, [active, load, rows]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialFilter) setQuery(initialFilter);
|
||||
}, [initialFilter]);
|
||||
|
||||
/**
|
||||
* The confirmed finding whose file this process is running, if any.
|
||||
*
|
||||
* This is what gates "stop and quarantine": the roadmap says quarantine may not
|
||||
* be offered for an arbitrary process, so the offer appears only when the
|
||||
* backend has actually confirmed something about this exact path. Suspicious is
|
||||
* not enough, and neither is a guess made from the process name.
|
||||
*/
|
||||
const findingFor = useCallback(
|
||||
(row: ProcessRow): Finding | null => {
|
||||
const scan = security.status?.scan ?? null;
|
||||
if (!row.program || !scan) return null;
|
||||
const needle = row.program.toLowerCase();
|
||||
return (
|
||||
scan.findings.find(
|
||||
(finding) =>
|
||||
finding.confidence === "confirmed" &&
|
||||
!finding.quarantined &&
|
||||
finding.path?.toLowerCase() === needle,
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
[security.status],
|
||||
);
|
||||
|
||||
const visible = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase();
|
||||
let list = (rows ?? []).filter((row) => {
|
||||
if (mineOnly && !row.owned) return false;
|
||||
if (unsignedOnly && row.signed) return false;
|
||||
if (startupOnly && !row.startupItem) return false;
|
||||
if (!needle) return true;
|
||||
return (
|
||||
row.name.toLowerCase().includes(needle) ||
|
||||
row.command.toLowerCase().includes(needle) ||
|
||||
(row.program ?? "").toLowerCase().includes(needle) ||
|
||||
String(row.pid) === needle
|
||||
);
|
||||
});
|
||||
list = [...list].sort((a, b) => {
|
||||
if (sort === "name") return a.name.localeCompare(b.name);
|
||||
if (sort === "pid") return a.pid - b.pid;
|
||||
if (sort === "startedMs") return (b.startedMs ?? 0) - (a.startedMs ?? 0);
|
||||
if (sort === "memory") return b.memory - a.memory;
|
||||
return b.cpu - a.cpu;
|
||||
});
|
||||
return list;
|
||||
}, [mineOnly, query, rows, sort, startupOnly, unsignedOnly]);
|
||||
|
||||
const grouped_rows = useMemo(() => {
|
||||
if (!grouped) return null;
|
||||
const merged = new Map<
|
||||
string,
|
||||
{ name: string; cpu: number; memory: number; instances: number; rows: ProcessRow[] }
|
||||
>();
|
||||
for (const row of visible) {
|
||||
const entry = merged.get(row.name) ?? {
|
||||
name: row.name,
|
||||
cpu: 0,
|
||||
memory: 0,
|
||||
instances: 0,
|
||||
rows: [],
|
||||
};
|
||||
entry.cpu += row.cpu;
|
||||
entry.memory += row.memory;
|
||||
entry.instances += 1;
|
||||
entry.rows.push(row);
|
||||
merged.set(row.name, entry);
|
||||
}
|
||||
return [...merged.values()].sort((a, b) => b.cpu - a.cpu);
|
||||
}, [grouped, visible]);
|
||||
|
||||
const openDetail = async (row: ProcessRow) => {
|
||||
setOpening(true);
|
||||
try {
|
||||
setDetail(await api.processDetail(row.pid));
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setOpening(false);
|
||||
}
|
||||
};
|
||||
|
||||
const stop = async (row: ProcessRow) => {
|
||||
setStopping(true);
|
||||
try {
|
||||
const result = await api.processStop(row.pid, row.name);
|
||||
push(result.message, "success");
|
||||
setVictim(null);
|
||||
setDetail(null);
|
||||
await load(trust);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setStopping(false);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Stop the process, then move the file it was running out of the way.
|
||||
*
|
||||
* The order is not interchangeable: a running executable cannot be quarantined
|
||||
* reliably, and quarantining something that is still in memory would leave the
|
||||
* threat running with its file gone. Only reachable when the backend has a
|
||||
* confirmed finding for this exact path, which is what `findingFor` guarantees.
|
||||
*/
|
||||
const stopAndQuarantine = async (row: ProcessRow) => {
|
||||
const finding = findingFor(row);
|
||||
if (!finding) return;
|
||||
setStopping(true);
|
||||
try {
|
||||
await api.processStop(row.pid, row.name);
|
||||
const message = await security.quarantine(finding.id);
|
||||
push(message, "success");
|
||||
setVictim(null);
|
||||
setDetail(null);
|
||||
await load(trust);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setStopping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copy = async (value: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
push(t("Copied", "已复制"), "success");
|
||||
} catch {
|
||||
push(t("Could not copy", "无法复制"), "danger");
|
||||
}
|
||||
};
|
||||
|
||||
if (error && !rows) return <InlineError message={error} />;
|
||||
|
||||
return (
|
||||
<section className="panel">
|
||||
<div className="process-controls">
|
||||
<label className="search-field">
|
||||
<Search size={14} />
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("Search name, path or PID", "搜索名称、路径或 PID")}
|
||||
/>
|
||||
</label>
|
||||
<div className="chip-row">
|
||||
<button
|
||||
className={`filter-chip ${mineOnly ? "is-active" : ""}`}
|
||||
onClick={() => setMineOnly((current) => !current)}
|
||||
>
|
||||
{t("My processes", "我的进程")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${unsignedOnly ? "is-active" : ""}`}
|
||||
onClick={() => setUnsignedOnly((current) => !current)}
|
||||
>
|
||||
{t("Unsigned only", "仅未签名")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${startupOnly ? "is-active" : ""}`}
|
||||
onClick={() => setStartupOnly((current) => !current)}
|
||||
>
|
||||
{t("Started at login", "由登录项启动")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${grouped ? "is-active" : ""}`}
|
||||
onClick={() => setGrouped((current) => !current)}
|
||||
>
|
||||
{t("Group by app", "按应用聚合")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${trust ? "is-active" : ""}`}
|
||||
onClick={() => {
|
||||
const next = !trust;
|
||||
setTrust(next);
|
||||
void load(next);
|
||||
}}
|
||||
title={t(
|
||||
"Signature lookups make each refresh slower",
|
||||
"读取签名会让每次刷新变慢",
|
||||
)}
|
||||
>
|
||||
{t("Check signatures", "检查签名")}
|
||||
</button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<RefreshCw size={14} className={loading ? "spin" : ""} />}
|
||||
onClick={() => void load(trust)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t("Refresh", "刷新")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{visible.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<Search size={24} />}
|
||||
title={t("No process matches", "没有匹配的进程")}
|
||||
description={t(
|
||||
"Clear the filters, or search by part of a path.",
|
||||
"请清除筛选条件,或按路径片段搜索。",
|
||||
)}
|
||||
/>
|
||||
) : grouped && grouped_rows ? (
|
||||
<ul className="process-grouped">
|
||||
{grouped_rows.slice(0, limit).map((group) => (
|
||||
<li key={group.name}>
|
||||
<button className="process-group-head" onClick={() => void openDetail(group.rows[0])}>
|
||||
<strong>{group.name}</strong>
|
||||
<small>
|
||||
{t(`${group.instances} instances`, `${group.instances} 个实例`)}
|
||||
</small>
|
||||
<span className="pg-cpu">{group.cpu.toFixed(1)}%</span>
|
||||
<span className="pg-memory">{formatBytes(group.memory)}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<>
|
||||
<div className="ptable pt-head">
|
||||
<button onClick={() => setSort("name")}>{t("Process", "进程")}</button>
|
||||
<button onClick={() => setSort("pid")}>PID</button>
|
||||
<span>{t("User", "用户")}</span>
|
||||
<button onClick={() => setSort("cpu")}>CPU</button>
|
||||
<button onClick={() => setSort("memory")}>{t("Memory", "内存")}</button>
|
||||
<button onClick={() => setSort("startedMs")}>{t("Started", "启动时间")}</button>
|
||||
<span>{t("Signature", "签名")}</span>
|
||||
<span />
|
||||
</div>
|
||||
<ul className="ptable pt-rows">
|
||||
{visible.slice(0, limit).map((row) => {
|
||||
const finding = findingFor(row);
|
||||
return (
|
||||
<li key={row.pid} className={finding ? "is-flagged" : ""}>
|
||||
<button className="pt-name" onClick={() => void openDetail(row)}>
|
||||
<strong title={row.program ?? row.name}>{row.name}</strong>
|
||||
<small title={row.program ?? undefined}>
|
||||
{row.program ? shortPath(row.program, 62) : t("path unavailable", "路径不可用")}
|
||||
</small>
|
||||
</button>
|
||||
<span className="pt-pid">{row.pid}</span>
|
||||
<span className="pt-user" title={row.user}>
|
||||
{row.user}
|
||||
</span>
|
||||
<span className="pt-cpu">{row.cpu.toFixed(1)}%</span>
|
||||
<span className="pt-memory">{formatBytes(row.memory)}</span>
|
||||
<span className="pt-start">
|
||||
{row.startedMs ? new Date(row.startedMs).toLocaleTimeString() : "—"}
|
||||
</span>
|
||||
<span className={`pt-sign ${row.signed ? "is-signed" : ""}`}>
|
||||
{row.signed ? (
|
||||
<>
|
||||
<ShieldCheck size={12} />
|
||||
{row.publisher ?? t("signed", "已签名")}
|
||||
</>
|
||||
) : (
|
||||
t("unsigned", "未签名")
|
||||
)}
|
||||
</span>
|
||||
<span className="pt-actions">
|
||||
{row.startupItem ? (
|
||||
<button
|
||||
className="icon-button"
|
||||
title={t("Started by a startup item", "由启动项启动")}
|
||||
onClick={() => onOpenStartup(row.program ?? row.name)}
|
||||
>
|
||||
<ShieldAlert size={14} />
|
||||
</button>
|
||||
) : null}
|
||||
{finding ? <span className="pt-flag">{t("confirmed finding", "已确认发现")}</span> : null}
|
||||
<button
|
||||
className="icon-button"
|
||||
title={
|
||||
row.owned
|
||||
? t("Stop process", "结束进程")
|
||||
: t("Not yours to stop", "无权结束")
|
||||
}
|
||||
disabled={!row.owned}
|
||||
onClick={() => setVictim(row)}
|
||||
>
|
||||
<Power size={14} />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{visible.length > limit ? (
|
||||
<button className="text-button is-center" onClick={() => setLimit((c) => c + PAGE * 3)}>
|
||||
{t(
|
||||
`Show ${Math.min(PAGE * 3, visible.length - limit)} more of ${formatCount(
|
||||
visible.length,
|
||||
)}`,
|
||||
`再显示 ${Math.min(PAGE * 3, visible.length - limit)} 项(共 ${formatCount(
|
||||
visible.length,
|
||||
)})`,
|
||||
)}
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={Boolean(detail)}
|
||||
onClose={() => setDetail(null)}
|
||||
size="drawer"
|
||||
title={detail ? `${detail.row.name} · PID ${detail.row.pid}` : ""}
|
||||
subtitle={detail?.row.program ?? undefined}
|
||||
footer={
|
||||
detail ? (
|
||||
<>
|
||||
{detail.row.program ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<ExternalLink size={15} />}
|
||||
onClick={() =>
|
||||
void api
|
||||
.revealPath(detail.row.program as string)
|
||||
.catch((reason) => push(messageFrom(reason), "danger"))
|
||||
}
|
||||
>
|
||||
{t("Open file location", "打开文件位置")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<FileSearch size={15} />}
|
||||
onClick={() => onOpenStartup(detail.row.program as string)}
|
||||
>
|
||||
{t("Startup entry", "查看启动项")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{detail.row.owned ? (
|
||||
<Button variant="danger" icon={<Power size={15} />} onClick={() => setVictim(detail.row)}>
|
||||
{t("Stop process", "结束进程")}
|
||||
</Button>
|
||||
) : null}
|
||||
{detail.row.owned && findingFor(detail.row) ? (
|
||||
<Button
|
||||
variant="danger"
|
||||
icon={<Ban size={15} />}
|
||||
disabled={stopping}
|
||||
onClick={() => void stopAndQuarantine(detail.row)}
|
||||
>
|
||||
{t("Stop and quarantine", "结束并隔离")}
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detail ? (
|
||||
<ProcessDetailBody
|
||||
detail={detail}
|
||||
lang={lang}
|
||||
onCopy={copy}
|
||||
stopNote={
|
||||
detail.stopNote ??
|
||||
(detail.row.owned
|
||||
? null
|
||||
: t("This process belongs to another user.", "该进程属于其他用户。"))
|
||||
}
|
||||
onOpenStartup={onOpenStartup}
|
||||
/>
|
||||
) : opening ? (
|
||||
<p>{t("Reading that process…", "正在读取该进程…")}</p>
|
||||
) : null}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(victim)}
|
||||
title={t("Stop this process?", "结束此进程?")}
|
||||
message={victim ? `${victim.name} · PID ${victim.pid}` : ""}
|
||||
note={t(
|
||||
"Unsaved work here may be lost. Only your own processes can be stopped.",
|
||||
"进程中未保存的内容可能丢失。只会结束当前用户的进程。",
|
||||
)}
|
||||
confirmLabel={t("Stop process", "结束进程")}
|
||||
cancelLabel={t("Cancel", "取消")}
|
||||
busy={stopping}
|
||||
icon={<Power size={22} />}
|
||||
onConfirm={() => victim && void stop(victim)}
|
||||
onClose={() => setVictim(null)}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ProcessDetailBody({
|
||||
detail,
|
||||
lang,
|
||||
onCopy,
|
||||
stopNote,
|
||||
onOpenStartup,
|
||||
}: {
|
||||
detail: ProcessDetail;
|
||||
lang: "zh" | "en";
|
||||
onCopy: (value: string) => Promise<void>;
|
||||
stopNote: string | null;
|
||||
onOpenStartup: (query: string) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const { row, trust } = detail;
|
||||
const state = trust.signed
|
||||
? trust.adHoc
|
||||
? t("Ad-hoc signature", "临时签名")
|
||||
: t("Trusted signature", "受信任签名")
|
||||
: trust.untrusted
|
||||
? t("Signature present but not trusted", "有签名但不受信任")
|
||||
: t("Unsigned", "未签名");
|
||||
const rows: [string, string][] = [
|
||||
[t("Parent", "父进程"), row.parent ? `${row.parent}` : t("none", "无")],
|
||||
[t("User", "用户"), row.user],
|
||||
[t("Working directory", "工作目录"), row.workingDirectory ?? t("unknown", "未知")],
|
||||
[t("Signature", "签名"), trust.signer ? `${state} · ${trust.signer}` : state],
|
||||
];
|
||||
if (detail.sha256) rows.push(["SHA-256", detail.sha256]);
|
||||
if (row.startedMs)
|
||||
rows.push([t("Started", "启动时间"), new Date(row.startedMs).toLocaleString(lang)]);
|
||||
return (
|
||||
<div className="item-detail">
|
||||
<div className="detail-command">
|
||||
<span>{t("Command line", "命令行")}</span>
|
||||
<code>{row.command || t("(nothing recorded)", "(未记录)")}</code>
|
||||
{row.command ? (
|
||||
<button className="icon-button" title={t("Copy", "复制")} onClick={() => void onCopy(row.command)}>
|
||||
<Copy size={13} />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
{detail.startup ? (
|
||||
<div className="detail-startup">
|
||||
<ShieldAlert size={14} />
|
||||
<div>
|
||||
<strong>{t("Started by a startup item", "由启动项启动")}</strong>
|
||||
<small>{detail.startup.name}</small>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={() => onOpenStartup(detail.startup?.name ?? "")}>
|
||||
{t("Open startup items", "打开启动项页面")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<dl className="detail-grid">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={`${label}-${value}`}>
|
||||
<dt>{label}</dt>
|
||||
<dd title={value}>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{stopNote ? (
|
||||
<p className="detail-note">
|
||||
<Power size={13} />
|
||||
{stopNote}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="detail-note">
|
||||
{t(
|
||||
"Stopping a process never touches its file. Quarantine needs a confirmed finding.",
|
||||
"结束进程不会处理其文件;只有已确认发现才会隔离。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,387 @@
|
|||
import {
|
||||
AlertTriangle,
|
||||
Download,
|
||||
FolderOpen,
|
||||
RotateCcw,
|
||||
ShieldCheck,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { messageFrom, shortPath } from "../lib/format";
|
||||
import type { ScanSchedule, SecurityStatus } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import { Button, ConfirmDialog, Toggle, useToast } from "./ui";
|
||||
|
||||
const SCHEDULES: [ScanSchedule, string, string][] = [
|
||||
["manual", "Only when I ask", "仅在我要求时"],
|
||||
["on-launch", "Once each time Squid starts", "每次启动 Squid 后一次"],
|
||||
["daily", "Daily while Squid is in the tray", "驻留托盘时每天一次"],
|
||||
["weekly", "Weekly while Squid is in the tray", "驻留托盘时每周一次"],
|
||||
];
|
||||
|
||||
/**
|
||||
* The security half of Settings.
|
||||
*
|
||||
* The schedule wording is deliberate. There is no daemon, so "daily" means daily
|
||||
* while Squid is running in the tray and not at all otherwise — a promise about a
|
||||
* timer that exists, rather than about a watchdog that does not.
|
||||
*
|
||||
* Exclusions live here and not next to the cleanup whitelist, because they mean
|
||||
* different things: one says "do not delete in here", the other says "do not look
|
||||
* in here", and a user protecting a folder from cleaning must not accidentally
|
||||
* hide a threat from being reported.
|
||||
*/
|
||||
export function SecuritySettingsCard({
|
||||
security,
|
||||
status,
|
||||
}: {
|
||||
security: SecurityWorkspace;
|
||||
status: SecurityStatus;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmAuto, setConfirmAuto] = useState(false);
|
||||
const [pendingRemove, setPendingRemove] = useState<string | null>(null);
|
||||
const [rulesNote, setRulesNote] = useState<string | null>(null);
|
||||
const settings = status.settings;
|
||||
const intel = status.intel;
|
||||
|
||||
const save = async (patch: Parameters<SecurityWorkspace["saveSettings"]>[0]) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await security.saveSettings(patch);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const add = async (path: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await security.exclude("add", path);
|
||||
setDraft("");
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const choose = async () => {
|
||||
const picked = await open({ directory: true, title: t("Exclude folder", "排除文件夹") });
|
||||
if (typeof picked === "string") void add(picked);
|
||||
};
|
||||
|
||||
const runRules = async (action: () => Promise<string>) => {
|
||||
setBusy(true);
|
||||
setRulesNote(null);
|
||||
try {
|
||||
setRulesNote(await action());
|
||||
} catch (reason) {
|
||||
setRulesNote(messageFrom(reason));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-head">
|
||||
<div>
|
||||
<h2>
|
||||
<ShieldCheck size={18} />
|
||||
{t("Security", "安全")}
|
||||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
"When scans run, what may move without asking, and what a scan must not read.",
|
||||
"扫描何时运行、什么可以不经确认就移动,以及扫描不能读取哪些位置。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="settings-row is-first">
|
||||
<div>
|
||||
<strong>{t("Scan schedule", "扫描计划")}</strong>
|
||||
<span>
|
||||
{settings.scanSchedule === "manual"
|
||||
? t(
|
||||
"Nothing is scanned unless you start it.",
|
||||
"不主动扫描,只在你点开始时才扫描。",
|
||||
)
|
||||
: t(
|
||||
"No background service, so a scheduled scan runs only while Squid is in the tray.",
|
||||
"Squid 无后台服务,定时扫描只在驻留托盘时才会运行。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<select
|
||||
className="settings-select"
|
||||
value={settings.scanSchedule}
|
||||
disabled={busy}
|
||||
onChange={(event) => void save({ scanSchedule: event.target.value })}
|
||||
>
|
||||
{SCHEDULES.map(([value, en, zh]) => (
|
||||
<option key={value} value={value}>
|
||||
{t(en, zh)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="settings-row">
|
||||
<div>
|
||||
<strong>{t("Notify on confirmed findings", "发现高危时通知")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
"The banner and the tray report the same thing without it.",
|
||||
"关闭后,应用内提示与托盘仍会显示相同状态。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Toggle
|
||||
checked={settings.notifyOnFindings}
|
||||
disabled={busy}
|
||||
label={t("Notify on confirmed findings", "发现高危时通知")}
|
||||
onChange={(next) => void save({ notifyOnFindings: next })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="settings-row">
|
||||
<div>
|
||||
<strong>{t("Auto-quarantine confirmed findings", "自动隔离已确认项")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
"Confirmed findings only. A suspicious file is never moved on its own.",
|
||||
"仅针对已确认发现,可疑项不会被自动移动。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Toggle
|
||||
checked={settings.autoQuarantine}
|
||||
disabled={busy}
|
||||
label={t("Auto-quarantine confirmed findings", "自动隔离已确认项")}
|
||||
onChange={(next) => (next ? setConfirmAuto(true) : void save({ autoQuarantine: false }))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="settings-row">
|
||||
<div>
|
||||
<strong>{t("Update rules automatically", "自动更新规则")}</strong>
|
||||
<span>
|
||||
{intel.source === "pack"
|
||||
? t(
|
||||
`Rule pack r${intel.revision} · ${intel.installedRules} rules · published ${intel.published} · ${
|
||||
intel.signed
|
||||
? "signature verified"
|
||||
: "hash only — this build has no rule-pack key"
|
||||
}.`,
|
||||
`规则包 r${intel.revision} · ${intel.installedRules} 条规则 · 发布于 ${intel.published} · ${
|
||||
intel.signed ? "已校验签名" : "仅校验哈希,本构建未内置规则包公钥"
|
||||
}。`,
|
||||
)
|
||||
: t(
|
||||
`${intel.builtinRules} built-in rules in this build; nothing downloaded yet.`,
|
||||
`当前构建内置 ${intel.builtinRules} 条规则,尚未下载规则包。`,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Toggle
|
||||
checked={settings.updateRules}
|
||||
disabled={busy}
|
||||
label={t("Update rules automatically", "自动更新规则")}
|
||||
onChange={(next) => void save({ updateRules: next })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="settings-row is-actions">
|
||||
<div>
|
||||
<strong>{t("Rule pack", "规则包")}</strong>
|
||||
<span>
|
||||
{rulesNote ??
|
||||
t(
|
||||
"Rules are downloaded to this machine. No file name, hash or result is ever sent out.",
|
||||
"规则只会下载到本机;文件名、哈希与扫描结果都不会上传。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="settings-row-buttons">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<Download size={14} />}
|
||||
disabled={busy || !settings.updateRules}
|
||||
onClick={() => void runRules(security.updateRules)}
|
||||
>
|
||||
{t("Check for rules", "检查规则更新")}
|
||||
</Button>
|
||||
{intel.fallbackAvailable ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<RotateCcw size={14} />}
|
||||
disabled={busy}
|
||||
onClick={() => void runRules(security.rollbackRules)}
|
||||
>
|
||||
{t("Roll back one pack", "回滚上一版规则")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="settings-subsection">
|
||||
<div className="settings-subsection-head">
|
||||
<strong>{t("Scan exclusions", "安全扫描排除项")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
"Separate from the cleanup whitelist. Nothing inside is reported.",
|
||||
"与清理白名单彼此独立。被排除目录内的威胁不会上报。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="whitelist-add">
|
||||
<input
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
placeholder={t("Folder a scan must not read", "扫描不读取的文件夹")}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" && draft.trim()) void add(draft.trim());
|
||||
}}
|
||||
/>
|
||||
<Button variant="secondary" icon={<FolderOpen size={15} />} onClick={() => void choose()}>
|
||||
{t("Choose", "选择")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!draft.trim() || busy}
|
||||
onClick={() => void add(draft.trim())}
|
||||
>
|
||||
{t("Add", "添加")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="whitelist-list">
|
||||
{settings.scanExclusions.length === 0 ? (
|
||||
<p className="settings-empty">
|
||||
{t("No folders are excluded from scanning.", "没有排除扫描的文件夹。")}
|
||||
</p>
|
||||
) : (
|
||||
settings.scanExclusions.map((pattern) => (
|
||||
<div className="whitelist-row" key={pattern}>
|
||||
<span className="whitelist-icon is-warning">
|
||||
<AlertTriangle size={15} />
|
||||
</span>
|
||||
<code title={pattern}>{shortPath(pattern, 88)}</code>
|
||||
<button
|
||||
className="row-reveal"
|
||||
aria-label={t("Stop excluding", "取消排除")}
|
||||
onClick={() => setPendingRemove(pattern)}
|
||||
disabled={busy}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{settings.ignoredFindings.length ? (
|
||||
<div className="settings-subsection">
|
||||
<div className="settings-subsection-head">
|
||||
<strong>{t("Ignored findings", "已忽略的发现")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
`${settings.ignoredFindings.length} dismissed. Future scans hide them until you restore them here.`,
|
||||
`已忽略 ${settings.ignoredFindings.length} 项。在恢复之前,后续扫描不会再次报告。`,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="whitelist-list">
|
||||
{settings.ignoredFindings.map((fingerprint) => (
|
||||
<div className="whitelist-row" key={fingerprint}>
|
||||
<code title={fingerprint}>{shortPath(fingerprint, 88)}</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
const match = status.scan?.findings.find(
|
||||
(finding) =>
|
||||
`${finding.confidence}|${finding.path}` === fingerprint,
|
||||
);
|
||||
if (match) {
|
||||
void security.dismiss(match.id, false).then((message) => push(message, "success"));
|
||||
} else {
|
||||
push(
|
||||
t(
|
||||
"This finding is not in the last scan — run a scan to restore it.",
|
||||
"该发现不在上次扫描结果中,请先扫描再恢复。",
|
||||
),
|
||||
"danger",
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t("Report again", "重新报告")}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmAuto}
|
||||
title={t("Let Squid move files on its own?", "允许 Squid 自动移动文件吗?")}
|
||||
tone="danger"
|
||||
busy={busy}
|
||||
icon={<ShieldCheck size={22} />}
|
||||
confirmLabel={t("Turn on", "开启")}
|
||||
cancelLabel={t("Cancel", "取消")}
|
||||
message={t(
|
||||
"Confirmed findings move to the quarantine without asking. Everything stays restorable.",
|
||||
"已确认发现将未经确认直接移入隔离区,仍可恢复。",
|
||||
)}
|
||||
onConfirm={() => {
|
||||
setConfirmAuto(false);
|
||||
void save({ autoQuarantine: true });
|
||||
}}
|
||||
onClose={() => setConfirmAuto(false)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(pendingRemove)}
|
||||
title={t("Scan this folder again?", "要恢复扫描这个文件夹吗?")}
|
||||
tone="default"
|
||||
busy={busy}
|
||||
icon={<AlertTriangle size={22} />}
|
||||
confirmLabel={t("Remove exclusion", "取消排除")}
|
||||
cancelLabel={t("Keep excluded", "保持排除")}
|
||||
message={pendingRemove ?? ""}
|
||||
note={t(
|
||||
"The next scan will read it again and may report findings inside it.",
|
||||
"下次扫描会重新读取该目录,并可能报告其中的发现。",
|
||||
)}
|
||||
onConfirm={() => {
|
||||
const path = pendingRemove;
|
||||
setPendingRemove(null);
|
||||
if (path) {
|
||||
void security
|
||||
.exclude("remove", path)
|
||||
.then((message) => push(message, "success"))
|
||||
.catch((reason) => push(messageFrom(reason), "danger"));
|
||||
}
|
||||
}}
|
||||
onClose={() => setPendingRemove(null)}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,10 @@
|
|||
import {
|
||||
BellRing,
|
||||
Check,
|
||||
Download,
|
||||
LoaderCircle,
|
||||
LockKeyhole,
|
||||
Power,
|
||||
RefreshCw,
|
||||
ShieldCheck,
|
||||
X,
|
||||
|
|
@ -9,7 +12,9 @@ import {
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import type { PermissionStatus } from "../types";
|
||||
import { messageFrom } from "../lib/format";
|
||||
import type { PermissionStatus, SecurityStatus } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import { Button } from "./ui";
|
||||
|
||||
type State = "checking" | "granted" | "denied" | "unknown" | "not-required" | "error";
|
||||
|
|
@ -19,18 +24,48 @@ const SYSTEM_SETTINGS_COPY = {
|
|||
zh: "系统设置 › 隐私与安全性 › 完全磁盘访问权限",
|
||||
};
|
||||
|
||||
export function SetupPanel({ onDone }: { onDone: () => void }) {
|
||||
/**
|
||||
* The security-readiness card, shown once before the first scan.
|
||||
*
|
||||
* A list rather than one gate, because these five things have different weights:
|
||||
* Full Disk Access only widens coverage, notifications are a convenience, and the
|
||||
* system's own protection is something squid can neither change nor claim credit
|
||||
* for. Each row says whether it is optional; closing the card changes nothing, and
|
||||
* no permission is requested here that the user did not ask for.
|
||||
*
|
||||
* The copy matters more than the layout. An unsigned build is trusted by the user
|
||||
* releasing it in Gatekeeper, not by the system vouching for a publisher, so
|
||||
* nothing here is allowed to read as "the system has certified this".
|
||||
*/
|
||||
export function SetupPanel({
|
||||
security,
|
||||
autostart,
|
||||
onDone,
|
||||
}: {
|
||||
security: SecurityWorkspace;
|
||||
autostart: boolean;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const [state, setState] = useState<State>("checking");
|
||||
const [status, setStatus] = useState<SecurityStatus | null>(security.status);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [launching, setLaunching] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setState("checking");
|
||||
try {
|
||||
const status: PermissionStatus = await api.permissionStatus();
|
||||
setState(status.fullDiskAccess);
|
||||
const permissions: PermissionStatus = await api.permissionStatus();
|
||||
setState(permissions.fullDiskAccess);
|
||||
} catch {
|
||||
setState("error");
|
||||
}
|
||||
try {
|
||||
setStatus(await api.securityStatus());
|
||||
setNote(null);
|
||||
} catch (reason) {
|
||||
setNote(messageFrom(reason));
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -79,6 +114,34 @@ export function SetupPanel({ onDone }: { onDone: () => void }) {
|
|||
"请到系统设置中确认权限,然后返回重新检查。",
|
||||
);
|
||||
|
||||
const protection = status?.protection ?? null;
|
||||
const intel = status?.intel ?? null;
|
||||
|
||||
/** One switch on the security half of settings, then re-read: this card reports
|
||||
* what the backend believes, not what was last clicked. */
|
||||
const toggle = async (key: "notifyOnFindings" | "updateRules") => {
|
||||
const next = !status?.settings[key];
|
||||
try {
|
||||
await security.saveSettings({ [key]: next });
|
||||
setStatus((current) =>
|
||||
current ? { ...current, settings: { ...current.settings, [key]: next } } : current,
|
||||
);
|
||||
} catch (reason) {
|
||||
setNote(messageFrom(reason));
|
||||
}
|
||||
};
|
||||
|
||||
const flipAutostart = async () => {
|
||||
setLaunching(true);
|
||||
try {
|
||||
await api.setAutostart(!autostart);
|
||||
} catch (reason) {
|
||||
setNote(messageFrom(reason));
|
||||
} finally {
|
||||
setLaunching(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="setup-scrim"
|
||||
|
|
@ -93,39 +156,169 @@ export function SetupPanel({ onDone }: { onDone: () => void }) {
|
|||
</span>
|
||||
<div>
|
||||
<div className="setup-eyebrow">NEX · SQUID</div>
|
||||
<h2 id="setup-title">{t("Before you start", "开始之前")}</h2>
|
||||
<h2 id="setup-title">{t("Security readiness", "安全准备")}</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Squid runs entirely on this computer. One optional macOS permission improves scan coverage.",
|
||||
"Squid 完全在这台电脑上运行。macOS 上有一项可选权限可以提升扫描覆盖范围。",
|
||||
"Nothing here is switched on for you. Nothing leaves this computer.",
|
||||
"这里不会替你打开任何开关,也不会上传任何内容。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className={`setup-check is-${checking ? "checking" : ready ? "ok" : "problem"}`}>
|
||||
<span className="setup-check-icon">
|
||||
<LockKeyhole size={18} />
|
||||
</span>
|
||||
<div className="setup-check-copy">
|
||||
<strong>
|
||||
{t("Full Disk Access", "完全磁盘访问权限")}
|
||||
<span className="setup-check-state">
|
||||
{ready ? <Check size={13} /> : needsAttention ? <X size={13} /> : null}
|
||||
{stateLabel}
|
||||
</span>
|
||||
</strong>
|
||||
<small>{detail}</small>
|
||||
{state === "denied" || state === "unknown" || state === "error" ? (
|
||||
<code>{SYSTEM_SETTINGS_COPY[lang]}</code>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<SetupRow
|
||||
icon={<ShieldCheck size={18} />}
|
||||
title={t("System protection", "系统防护")}
|
||||
state={
|
||||
!protection
|
||||
? { tone: "checking", label: t("Reading…", "读取中…") }
|
||||
: protection.known
|
||||
? { tone: "ok", label: t("Read from the system", "已读取") }
|
||||
: { tone: "problem", label: t("Cannot be confirmed", "无法确认") }
|
||||
}
|
||||
note={
|
||||
protection?.known
|
||||
? t(
|
||||
`${
|
||||
protection.productName ||
|
||||
(protection.provider === "xprotect" ? "XProtect" : protection.provider)
|
||||
}${protection.definitions ? ` · ${protection.definitions}` : ""}. Squid reads this and never turns it on, off or updates it.`,
|
||||
`${
|
||||
protection.productName ||
|
||||
(protection.provider === "xprotect" ? "XProtect" : protection.provider)
|
||||
}${protection.definitions ? ` · ${protection.definitions}` : ""}。Squid 只读取该状态,不会开启、关闭或更新它。`,
|
||||
)
|
||||
: protection?.notes[0] ??
|
||||
t(
|
||||
"When this cannot be read Squid says so, rather than showing it as healthy.",
|
||||
"读不到时 Squid 会直接说明,不会把它显示为正常。",
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<SetupRow
|
||||
icon={<LockKeyhole size={18} />}
|
||||
title={t("Scan access", "扫描访问")}
|
||||
optional
|
||||
state={{
|
||||
tone: checking ? "checking" : ready ? "ok" : "problem",
|
||||
label: stateLabel,
|
||||
}}
|
||||
note={detail}
|
||||
code={needsAttention ? SYSTEM_SETTINGS_COPY[lang] : undefined}
|
||||
action={
|
||||
needsAttention ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
void api.openFullDiskAccessSettings().catch(() => undefined)
|
||||
}
|
||||
>
|
||||
{t("Open Settings", "打开系统设置")}
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
<SetupRow
|
||||
icon={<BellRing size={18} />}
|
||||
title={t("Notifications", "通知")}
|
||||
optional
|
||||
state={{
|
||||
tone: status?.settings.notifyOnFindings ? "ok" : "problem",
|
||||
label: status?.settings.notifyOnFindings
|
||||
? t("On", "已开启")
|
||||
: t("Off", "已关闭"),
|
||||
}}
|
||||
note={t(
|
||||
"Confirmed findings only. The banner and tray still report without it.",
|
||||
"仅针对已确认发现。关闭后应用内提示与托盘仍会显示。",
|
||||
)}
|
||||
action={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!status}
|
||||
onClick={() => void toggle("notifyOnFindings")}
|
||||
>
|
||||
{status?.settings.notifyOnFindings
|
||||
? t("Turn off", "关闭")
|
||||
: t("Turn on", "开启")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<SetupRow
|
||||
icon={<Power size={18} />}
|
||||
title={t("Start at login", "登录时启动")}
|
||||
optional
|
||||
state={{
|
||||
tone: autostart ? "ok" : "problem",
|
||||
label: autostart ? t("On", "已开启") : t("Off", "已关闭"),
|
||||
}}
|
||||
note={t(
|
||||
"No background service, so a scheduled scan only runs from the tray.",
|
||||
"不安装后台服务,定时扫描只在驻留托盘时运行。",
|
||||
)}
|
||||
action={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={launching}
|
||||
onClick={() => void flipAutostart()}
|
||||
>
|
||||
{autostart ? t("Turn off", "关闭") : t("Turn on", "开启")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<SetupRow
|
||||
icon={<Download size={18} />}
|
||||
title={t("Rule updates", "规则更新")}
|
||||
optional
|
||||
state={{
|
||||
tone: status?.settings.updateRules ? "ok" : "problem",
|
||||
label: status?.settings.updateRules
|
||||
? t("On", "已开启")
|
||||
: t("Built-in only", "仅使用内置"),
|
||||
}}
|
||||
note={
|
||||
intel
|
||||
? t(
|
||||
`${
|
||||
intel.source === "pack"
|
||||
? `Rule pack r${intel.revision} · ${intel.installedRules} rules`
|
||||
: `${intel.builtinRules} built-in rules, no pack downloaded`
|
||||
}. Only rules are downloaded; no file name, hash or result leaves this machine.`,
|
||||
`${
|
||||
intel.source === "pack"
|
||||
? `规则包 r${intel.revision} · ${intel.installedRules} 条规则`
|
||||
: `内置 ${intel.builtinRules} 条规则,未下载规则包`
|
||||
}。只下载规则,文件名、哈希与扫描结果都不会离开本机。`,
|
||||
)
|
||||
: t("Reading the installed rules…", "正在读取已安装规则…")
|
||||
}
|
||||
action={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={!status}
|
||||
onClick={() => void toggle("updateRules")}
|
||||
>
|
||||
{status?.settings.updateRules
|
||||
? t("Turn off", "关闭")
|
||||
: t("Turn on", "开启")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{note ? <p className="setup-error">{note}</p> : null}
|
||||
|
||||
<p className="setup-note">
|
||||
{t(
|
||||
"You can skip this now. Permissions and the same check remain available in Settings at any time.",
|
||||
"现在可以跳过;之后随时都能在设置中检查权限或重新授权。",
|
||||
"Closing this changes nothing. The same checks stay in Settings, and an update may reset what macOS granted.",
|
||||
"关闭本卡片不会改变任何设置,这些检查在设置中依然保留。更新后 macOS 可能重置已授予的权限。",
|
||||
)}
|
||||
</p>
|
||||
|
||||
|
|
@ -140,15 +333,6 @@ export function SetupPanel({ onDone }: { onDone: () => void }) {
|
|||
>
|
||||
{t("Recheck", "重新检查")}
|
||||
</Button>
|
||||
{needsAttention ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => void api.openFullDiskAccessSettings()}
|
||||
>
|
||||
{t("Open Settings", "打开系统设置")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="setup-actions-primary">
|
||||
<Button variant="ghost" onClick={onDone}>
|
||||
|
|
@ -167,3 +351,42 @@ export function SetupPanel({ onDone }: { onDone: () => void }) {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupRow({
|
||||
icon,
|
||||
title,
|
||||
state,
|
||||
note,
|
||||
code,
|
||||
action,
|
||||
optional,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
state: { tone: "checking" | "ok" | "problem"; label: string };
|
||||
note: string;
|
||||
code?: string;
|
||||
action?: React.ReactNode;
|
||||
optional?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<div className={`setup-check is-${state.tone}`}>
|
||||
<span className="setup-check-icon">{icon}</span>
|
||||
<div className="setup-check-copy">
|
||||
<strong>
|
||||
{title}
|
||||
{optional ? <span className="setup-check-optional">{t("optional", "可选")}</span> : null}
|
||||
<span className="setup-check-state">
|
||||
{state.tone === "ok" ? <Check size={13} /> : null}
|
||||
{state.tone === "problem" ? <X size={13} /> : null}
|
||||
{state.label}
|
||||
</span>
|
||||
</strong>
|
||||
<small>{note}</small>
|
||||
{code ? <code>{code}</code> : null}
|
||||
</div>
|
||||
{action ? <div className="setup-check-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,211 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api, type SecurityPatch } from "../lib/api";
|
||||
import { isCancelled, messageFrom } from "../lib/format";
|
||||
import type { JobProgress, ScanMode, SecurityStatus } from "../types";
|
||||
|
||||
function jobId(): string {
|
||||
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
export interface SecurityWorkspace {
|
||||
status: SecurityStatus | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** A scan started from this window is running. */
|
||||
scanning: boolean;
|
||||
progress: JobProgress | null;
|
||||
refresh: () => Promise<void>;
|
||||
start: (mode: ScanMode, paths?: string[]) => Promise<void>;
|
||||
cancel: () => Promise<void>;
|
||||
quarantine: (findingId: string) => Promise<string>;
|
||||
restore: (id: string) => Promise<string>;
|
||||
purge: (id: string) => Promise<string>;
|
||||
dismiss: (findingId: string, ignored: boolean) => Promise<string>;
|
||||
exclude: (action: "add" | "remove", path: string) => Promise<string>;
|
||||
updateRules: () => Promise<string>;
|
||||
rollbackRules: () => Promise<string>;
|
||||
saveSettings: (patch: SecurityPatch) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The security state for the whole window, owned here rather than per page.
|
||||
*
|
||||
* Three surfaces show it — the overview strip, the sidebar badge, and the
|
||||
* security page — and they must not disagree, because a badge that says 2 next to
|
||||
* a page that says 1 is worse than no badge. One fetch, one refresh, passed down.
|
||||
*
|
||||
* It is fetched lazily in practice: `App` loads it once at startup for the badge
|
||||
* and the overview, and refreshes when the security page opens.
|
||||
*/
|
||||
export function useSecurityWorkspace(active: boolean): SecurityWorkspace {
|
||||
const [status, setStatus] = useState<SecurityStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [scanning, setScanning] = useState(false);
|
||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||
const activeJob = useRef<string | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
try {
|
||||
setStatus(await api.securityStatus());
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(messageFrom(reason));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (active && !status) void refresh();
|
||||
}, [active, refresh, status]);
|
||||
|
||||
/**
|
||||
* Progress comes from the shared job channel, filtered by kind, rather than from
|
||||
* a subscription to the id this window happened to start with.
|
||||
*
|
||||
* That distinction is the whole point: a scan can also be started by the tray
|
||||
* menu or by the schedule, and a security page that showed nothing while a scan
|
||||
* it did not start was running would look broken. The same channel reports every
|
||||
* security job, so the page draws whichever one is live.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
let stop: (() => void) | null = null;
|
||||
let cancelled = false;
|
||||
void api
|
||||
.onProgress((event) => {
|
||||
if (event.kind !== "security") return;
|
||||
activeJob.current = event.jobId;
|
||||
setScanning(true);
|
||||
setProgress(event);
|
||||
})
|
||||
.then((unlisten) => {
|
||||
if (cancelled) unlisten();
|
||||
else stop = unlisten;
|
||||
});
|
||||
// The backend broadcasts every finished scan. That is both the refresh and the
|
||||
// only reliable "it is over" for a scan this window did not start — from the
|
||||
// tray, or from the schedule — where there is no local promise to settle on.
|
||||
void api
|
||||
.onSecurityScan(() => {
|
||||
setScanning(false);
|
||||
setProgress(null);
|
||||
activeJob.current = null;
|
||||
void refresh();
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
stop?.();
|
||||
};
|
||||
}, [active, refresh]);
|
||||
|
||||
const start = useCallback(
|
||||
async (mode: ScanMode, paths: string[] = []) => {
|
||||
if (scanning) return;
|
||||
const id = jobId();
|
||||
activeJob.current = id;
|
||||
setScanning(true);
|
||||
setProgress(null);
|
||||
setError(null);
|
||||
try {
|
||||
await api.securityScan(id, mode, paths);
|
||||
} catch (reason) {
|
||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||
} finally {
|
||||
// The finished scan arrives on the broadcast channel; this is the fallback
|
||||
// for the window between the reply and the event, and for a scan whose
|
||||
// progress never reached this window at all.
|
||||
setScanning(false);
|
||||
setProgress(null);
|
||||
activeJob.current = null;
|
||||
await refresh();
|
||||
}
|
||||
},
|
||||
[refresh, scanning],
|
||||
);
|
||||
|
||||
const cancel = useCallback(async () => {
|
||||
if (!activeJob.current) return;
|
||||
await api.securityCancel(activeJob.current).catch(() => false);
|
||||
}, []);
|
||||
|
||||
const apply = useCallback(
|
||||
async (run: () => Promise<{ message: string; status: SecurityStatus }>) => {
|
||||
const result = await run();
|
||||
setStatus(result.status);
|
||||
return result.message;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const quarantine = useCallback(
|
||||
(findingId: string) => apply(() => api.securityQuarantine(findingId)),
|
||||
[apply],
|
||||
);
|
||||
const restore = useCallback((id: string) => apply(() => api.securityRestore(id)), [apply]);
|
||||
const purge = useCallback(
|
||||
(id: string) => apply(() => api.securityDeleteQuarantine(id)),
|
||||
[apply],
|
||||
);
|
||||
const dismiss = useCallback(
|
||||
(findingId: string, ignored: boolean) => apply(() => api.securityIgnore(findingId, ignored)),
|
||||
[apply],
|
||||
);
|
||||
|
||||
const exclude = useCallback(
|
||||
async (action: "add" | "remove", path: string) => {
|
||||
const settings = await api.securityExclusions(action, path);
|
||||
setStatus((current) => (current ? { ...current, settings } : current));
|
||||
return action === "add" ? `Excluded ${path}` : `No longer excluding ${path}`;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const updateRules = useCallback(async () => {
|
||||
const intel = await api.securityUpdateRules();
|
||||
await refresh();
|
||||
return intel.source === "pack"
|
||||
? `Rule pack r${intel.revision} installed — ${intel.installedRules} rules.`
|
||||
: `Already on the newest rules this build ships with (${intel.builtinRules}).`;
|
||||
}, [refresh]);
|
||||
|
||||
const rollbackRules = useCallback(async () => {
|
||||
const intel = await api.securityRollbackRules();
|
||||
await refresh();
|
||||
return `Rolled back to rule pack r${intel.revision}.`;
|
||||
}, [refresh]);
|
||||
|
||||
const saveSettings = useCallback(
|
||||
async (patch: SecurityPatch) => {
|
||||
const settings = await api.securitySettingsSave(patch);
|
||||
setStatus((current) => (current ? { ...current, settings } : current));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
status,
|
||||
loading,
|
||||
error,
|
||||
scanning,
|
||||
progress,
|
||||
refresh,
|
||||
start,
|
||||
cancel,
|
||||
quarantine,
|
||||
restore,
|
||||
purge,
|
||||
dismiss,
|
||||
exclude,
|
||||
updateRules,
|
||||
rollbackRules,
|
||||
saveSettings,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api } from "../lib/api";
|
||||
import { messageFrom } from "../lib/format";
|
||||
import type { StartupItem, StartupView } from "../types";
|
||||
|
||||
export interface StartupWorkspace {
|
||||
view: StartupView | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** One change at a time: a startup edit is a filesystem or registry write. */
|
||||
busy: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
setEnabled: (item: StartupItem, enabled: boolean) => Promise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The startup inventory.
|
||||
*
|
||||
* Nothing is cached between visits on purpose. A login item can be re-created by
|
||||
* its own app at any moment, and a list that remembers would show an entry as
|
||||
* enabled after the app re-armed it. Every visit re-reads the real thing, and a
|
||||
* change returns the whole refreshed inventory rather than the one edited row.
|
||||
*/
|
||||
export function useStartupWorkspace(active: boolean): StartupWorkspace {
|
||||
const [view, setView] = useState<StartupView | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading(true);
|
||||
try {
|
||||
setView(await api.startupItems());
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(messageFrom(reason));
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (active && !view) void refresh();
|
||||
}, [active, refresh, view]);
|
||||
|
||||
const setEnabled = useCallback(
|
||||
async (item: StartupItem, enabled: boolean) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await api.startupSetEnabled(item.id, enabled);
|
||||
setView(result.view);
|
||||
return result.message;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { view, loading, error, busy, refresh, setEnabled };
|
||||
}
|
||||
|
|
@ -8,13 +8,22 @@ import type {
|
|||
HistorySession,
|
||||
JobProgress,
|
||||
LargestFile,
|
||||
IntelStatus,
|
||||
PageId,
|
||||
PermissionStatus,
|
||||
PlanResult,
|
||||
ScanResult,
|
||||
SettingsView,
|
||||
SecurityAction,
|
||||
SecurityScan,
|
||||
SecuritySettings,
|
||||
SecurityStatus,
|
||||
StartupChange,
|
||||
StartupView,
|
||||
StorageNode,
|
||||
SystemSnapshot,
|
||||
ProcessDetail,
|
||||
ProcessRow,
|
||||
UndoResult,
|
||||
UpdateCheckResult,
|
||||
UpdateProgress,
|
||||
|
|
@ -30,6 +39,13 @@ export interface SettingsPatch {
|
|||
setupReviewed?: boolean;
|
||||
}
|
||||
|
||||
export interface SecurityPatch {
|
||||
scanSchedule?: string;
|
||||
notifyOnFindings?: boolean;
|
||||
autoQuarantine?: boolean;
|
||||
updateRules?: boolean;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
bootstrap: () => invoke<Bootstrap>("bootstrap"),
|
||||
cancelJob: (jobId: string) => invoke<boolean>("cancel_job", { jobId }),
|
||||
|
|
@ -80,6 +96,33 @@ export const api = {
|
|||
updateClear: () => invoke<void>("update_clear"),
|
||||
setUpdateCheckEnabled: (enabled: boolean) =>
|
||||
invoke<boolean>("set_update_check_enabled", { enabled }),
|
||||
securityStatus: () => invoke<SecurityStatus>("security_status"),
|
||||
securityScan: (jobId: string, mode: string, paths: string[] = []) =>
|
||||
invoke<SecurityScan>("security_scan", { jobId, request: { mode, paths } }),
|
||||
securityCancel: (jobId: string) => invoke<boolean>("security_cancel", { jobId }),
|
||||
securityOpen: () => invoke<void>("security_open"),
|
||||
securityQuarantine: (findingId: string) =>
|
||||
invoke<SecurityAction>("security_quarantine", { findingId }),
|
||||
securityRestore: (id: string) => invoke<SecurityAction>("security_restore", { id }),
|
||||
securityDeleteQuarantine: (id: string) =>
|
||||
invoke<SecurityAction>("security_delete_quarantine", { id }),
|
||||
securityIgnore: (findingId: string, ignored: boolean) =>
|
||||
invoke<SecurityAction>("security_ignore", { findingId, ignored }),
|
||||
securityExclusions: (action: "add" | "remove", path: string) =>
|
||||
invoke<SecuritySettings>("security_exclusions", { action, path }),
|
||||
securitySettingsSave: (patch: SecurityPatch) =>
|
||||
invoke<SecuritySettings>("security_settings_save", { patch }),
|
||||
securityUpdateRules: () => invoke<IntelStatus>("security_update_rules"),
|
||||
securityRollbackRules: () => invoke<IntelStatus>("security_rollback_rules"),
|
||||
openQuarantineFolder: () => invoke<void>("open_quarantine_folder"),
|
||||
startupItems: () => invoke<StartupView>("startup_items"),
|
||||
startupSetEnabled: (id: string, enabled: boolean) =>
|
||||
invoke<StartupChange>("startup_set_enabled", { id, enabled }),
|
||||
processInventory: (withTrust = true) =>
|
||||
invoke<ProcessRow[]>("process_inventory", { withTrust }),
|
||||
processDetail: (pid: number) => invoke<ProcessDetail>("process_detail", { pid }),
|
||||
processStop: (pid: number, name: string) =>
|
||||
invoke<{ message: string }>("process_stop", { pid, name }),
|
||||
onProgress: (handler: (progress: JobProgress) => void) =>
|
||||
listen<JobProgress>("squid://progress", (event) => handler(event.payload)),
|
||||
onUpdateProgress: (handler: (progress: UpdateProgress) => void) =>
|
||||
|
|
@ -88,8 +131,12 @@ export const api = {
|
|||
listen<UpdateStatus | null>("update://status", (event) => handler(event.payload)),
|
||||
onNavigate: (handler: (page: PageId) => void) =>
|
||||
listen<PageId>("squid://navigate", (event) => handler(event.payload)),
|
||||
onSecurityScan: (handler: (scan: SecurityScan) => void) =>
|
||||
listen<SecurityScan>("squid://security", (event) => handler(event.payload)),
|
||||
};
|
||||
|
||||
/// Progress events for one job, whatever kind of job it is. Security scans share
|
||||
/// the channel with cleanup so a page subscribes the same way.
|
||||
export async function subscribeJobProgress(
|
||||
jobId: string,
|
||||
handler: (progress: JobProgress) => void,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
import {
|
||||
AlertTriangle,
|
||||
AppWindow,
|
||||
ArrowRight,
|
||||
Boxes,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
CircleGauge,
|
||||
HardDrive,
|
||||
ScanSearch,
|
||||
ShieldCheck,
|
||||
ShieldQuestion,
|
||||
Sparkles,
|
||||
WandSparkles,
|
||||
} from "lucide-react";
|
||||
|
|
@ -13,6 +17,7 @@ import { useI18n } from "../i18n";
|
|||
import { formatBytes, formatCount, percent } from "../lib/format";
|
||||
import type { Bootstrap, SystemSnapshot } from "../types";
|
||||
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import type { PageId } from "../types";
|
||||
import { CategorySummary } from "../components/CleanupView";
|
||||
import {
|
||||
|
|
@ -24,6 +29,89 @@ import {
|
|||
UsageBar,
|
||||
} from "../components/ui";
|
||||
|
||||
/**
|
||||
* The security strip: what protects the machine, and whether anything is waiting.
|
||||
*
|
||||
* It says "not scanned yet" rather than showing a green tick. The whole point of
|
||||
* the roadmap's rule — never render an unknown as healthy — is that a strip which
|
||||
* defaults to calm teaches people to trust a colour that has not earned it.
|
||||
*/
|
||||
function SecurityStrip({
|
||||
security,
|
||||
onNavigate,
|
||||
}: {
|
||||
security: SecurityWorkspace;
|
||||
onNavigate: (page: PageId) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const status = security.status;
|
||||
if (!status) {
|
||||
return (
|
||||
<section className="security-strip tone-neutral">
|
||||
<span className="metric-icon">
|
||||
<ShieldQuestion size={18} />
|
||||
</span>
|
||||
<span className="quick-copy">
|
||||
<strong>{t("Reading this machine's protection…", "正在读取本机防护状态…")}</strong>
|
||||
</span>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
const scan = status.scan;
|
||||
const alarmed = status.confirmed > 0;
|
||||
const tone = alarmed ? "danger" : scan ? (scan.coverageComplete ? "success" : "warning") : "neutral";
|
||||
const headline = alarmed
|
||||
? t(
|
||||
`${status.confirmed} confirmed finding${status.confirmed === 1 ? "" : "s"} need a decision`,
|
||||
`有 ${status.confirmed} 项已确认发现需要处理`,
|
||||
)
|
||||
: !scan
|
||||
? t("No scan of this machine yet", "尚未进行过扫描")
|
||||
: !scan.coverageComplete
|
||||
? t("Nothing found — but coverage was limited", "未发现威胁,但覆盖范围受限")
|
||||
: t("Nothing outstanding from the last scan", "上次扫描没有待处理项");
|
||||
// One line, in the order someone asks about it: what guards the machine now,
|
||||
// what squid last looked at, and whether it could look at everything.
|
||||
const provider = !status.protection.known
|
||||
? t("protection unknown", "防护状态未知")
|
||||
: status.protection.provider === "xprotect"
|
||||
? "XProtect"
|
||||
: status.protection.productName || "Antivirus";
|
||||
const detail = scan
|
||||
? t(
|
||||
`${provider} · ${formatCount(scan.examined)} files checked · ${
|
||||
scan.coverageComplete ? "full coverage" : "coverage limited"
|
||||
}`,
|
||||
`${provider} · 已检查 ${formatCount(scan.examined)} 个文件 · ${
|
||||
scan.coverageComplete ? "覆盖完整" : "覆盖受限"
|
||||
}`,
|
||||
)
|
||||
: t(
|
||||
`${provider} · quick scan covers login items, apps and downloads`,
|
||||
`${provider} · 快速扫描覆盖登录项、应用与下载目录`,
|
||||
);
|
||||
|
||||
return (
|
||||
<section className={`security-strip tone-${tone}`}>
|
||||
<span className="metric-icon">
|
||||
{alarmed ? <AlertTriangle size={18} /> : scan ? <CheckCircle2 size={18} /> : <ShieldQuestion size={18} />}
|
||||
</span>
|
||||
<div className="quick-copy">
|
||||
<strong>{headline}</strong>
|
||||
<small>{detail}</small>
|
||||
</div>
|
||||
<Button
|
||||
variant={alarmed ? "danger" : "ghost"}
|
||||
size="sm"
|
||||
icon={<ArrowRight size={14} />}
|
||||
onClick={() => onNavigate("security")}
|
||||
>
|
||||
{alarmed ? t("Review findings", "查看发现") : t("Open security", "打开安全")}
|
||||
</Button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function greeting(lang: "zh" | "en"): string {
|
||||
const hour = new Date().getHours();
|
||||
if (lang === "zh") {
|
||||
|
|
@ -41,11 +129,13 @@ export function OverviewPage({
|
|||
bootstrap,
|
||||
snapshot,
|
||||
cleanup,
|
||||
security,
|
||||
onNavigate,
|
||||
}: {
|
||||
bootstrap: Bootstrap;
|
||||
snapshot: SystemSnapshot | null;
|
||||
cleanup: ScanWorkspace;
|
||||
security: SecurityWorkspace;
|
||||
onNavigate: (page: PageId) => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
|
|
@ -68,8 +158,8 @@ export function OverviewPage({
|
|||
eyebrow={`${greeting(lang)} · ${bootstrap.osName}`}
|
||||
title={t("Your computer, at its best.", "让电脑始终保持在最佳状态。")}
|
||||
description={t(
|
||||
"One safe scan for clutter, storage and everyday performance.",
|
||||
"一次安全扫描,整理垃圾、空间与日常性能。",
|
||||
"Cleaning and security are two different scans here — one frees space, the other checks for threats.",
|
||||
"清理与安全是两种不同的扫描:一个释放空间,另一个检查威胁。",
|
||||
)}
|
||||
actions={
|
||||
<Button
|
||||
|
|
@ -83,12 +173,23 @@ export function OverviewPage({
|
|||
disabled={cleanup.scanning}
|
||||
>
|
||||
{cleanup.result
|
||||
? t("Review scan", "查看扫描结果")
|
||||
: t("Smart scan", "智能扫描")}
|
||||
? t("Review cleanup scan", "查看清理结果")
|
||||
: t("Cleanup scan", "清理扫描")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{security.scanning ? (
|
||||
<ProgressCard
|
||||
progress={security.progress}
|
||||
title={t("Scanning for malware", "正在扫描恶意软件")}
|
||||
compact
|
||||
onCancel={() => void security.cancel()}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<SecurityStrip security={security} onNavigate={onNavigate} />
|
||||
|
||||
<section className="overview-hero">
|
||||
<div className="overview-hero-copy">
|
||||
<div className="hero-kicker">
|
||||
|
|
@ -126,7 +227,20 @@ export function OverviewPage({
|
|||
>
|
||||
{cleanup.result
|
||||
? t("Choose what to clean", "选择清理项目")
|
||||
: t("Start a smart scan", "开始智能扫描")}
|
||||
: t("Start a cleanup scan", "开始清理扫描")}
|
||||
</Button>
|
||||
{/* Two scans, two names, one screen. Merging them would let a user
|
||||
believe the clutter sweep also looked for threats, and it does
|
||||
not; this is the line the roadmap drew on purpose. */}
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<ShieldCheck size={16} />}
|
||||
onClick={() => void security.start("quick")}
|
||||
disabled={security.scanning}
|
||||
>
|
||||
{security.scanning
|
||||
? t("Security scan…", "安全扫描中…")
|
||||
: t("Quick security scan", "安全快速扫描")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
|
@ -202,6 +316,16 @@ export function OverviewPage({
|
|||
subtitle={t("The right tool for the next five minutes.", "用几分钟完成最常用的事。")}
|
||||
/>
|
||||
<div className="quick-grid">
|
||||
<button className="quick-card tone-primary" onClick={() => onNavigate("security")}>
|
||||
<span className="quick-icon">
|
||||
<ShieldCheck size={22} />
|
||||
</span>
|
||||
<span className="quick-copy">
|
||||
<strong>{t("Security", "安全")}</strong>
|
||||
<small>{t("Scan, review findings, quarantine", "扫描、查看发现、隔离")}</small>
|
||||
</span>
|
||||
<ChevronRight size={17} />
|
||||
</button>
|
||||
<button className="quick-card tone-primary" onClick={() => onNavigate("applications")}>
|
||||
<span className="quick-icon">
|
||||
<AppWindow size={22} />
|
||||
|
|
|
|||
|
|
@ -0,0 +1,946 @@
|
|||
import {
|
||||
AlertTriangle,
|
||||
Ban,
|
||||
CheckCircle2,
|
||||
Download,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FolderOpen,
|
||||
FolderSearch,
|
||||
FolderX,
|
||||
HardDriveDownload,
|
||||
RefreshCw,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
ShieldQuestion,
|
||||
Trash2,
|
||||
Undo2,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { formatBytes, formatCount, messageFrom, shortPath } from "../lib/format";
|
||||
import type { Confidence, Finding, SecurityScan, SecurityStatus } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import {
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
EmptyState,
|
||||
InlineError,
|
||||
Modal,
|
||||
PageHeader,
|
||||
ProgressCard,
|
||||
SectionTitle,
|
||||
useToast,
|
||||
} from "../components/ui";
|
||||
|
||||
type Filter = "all" | Confidence | "quarantined";
|
||||
|
||||
const CONFIDENCE_META: Record<Confidence, { tone: string; en: string; zh: string }> = {
|
||||
confirmed: { tone: "danger", en: "Confirmed", zh: "已确认" },
|
||||
suspicious: { tone: "warning", en: "Suspicious", zh: "可疑" },
|
||||
advisory: { tone: "neutral", en: "Advisory", zh: "提示" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Security: what protects this machine, what squid found, and what it is holding.
|
||||
*
|
||||
* The page never says "safe" on the strength of an empty list. `clean` is only
|
||||
* true when nothing was found *and* nothing was skipped, so a machine where
|
||||
* Full Disk Access was refused shows the gap beside the result rather than
|
||||
* underneath it.
|
||||
*/
|
||||
export function SecurityPage({
|
||||
security,
|
||||
onOpenStartup,
|
||||
}: {
|
||||
security: SecurityWorkspace;
|
||||
onOpenStartup: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [filter, setFilter] = useState<Filter>("all");
|
||||
const [detail, setDetail] = useState<Finding | null>(null);
|
||||
const [quarantining, setQuarantining] = useState<Finding | null>(null);
|
||||
const [deleting, setDeleting] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [showScope, setShowScope] = useState(false);
|
||||
const status = security.status;
|
||||
const scan = status?.scan ?? null;
|
||||
|
||||
const findings = useMemo(() => {
|
||||
const all = scan?.findings ?? [];
|
||||
if (filter === "all") return all.filter((finding) => !finding.ignored);
|
||||
if (filter === "quarantined") return all.filter((finding) => finding.quarantined);
|
||||
return all.filter((finding) => finding.confidence === filter && !finding.ignored);
|
||||
}, [filter, scan]);
|
||||
|
||||
/**
|
||||
* Per-filter counts, counted the same way the list itself is filtered so a
|
||||
* chip's number is exactly what clicking it shows. The header used to spell out
|
||||
* "3 confirmed · 2 suspicious" beside chips that said the same words; one of the
|
||||
* two had to go, and the number belongs where the click is.
|
||||
*/
|
||||
const counts = useMemo(() => {
|
||||
const all = scan?.findings ?? [];
|
||||
const open = all.filter((finding) => !finding.ignored);
|
||||
return {
|
||||
all: open.length,
|
||||
confirmed: open.filter((f) => f.confidence === "confirmed").length,
|
||||
suspicious: open.filter((f) => f.confidence === "suspicious").length,
|
||||
advisory: open.filter((f) => f.confidence === "advisory").length,
|
||||
quarantined: all.filter((f) => f.quarantined).length,
|
||||
};
|
||||
}, [scan]);
|
||||
|
||||
const run = async (mode: "quick" | "full") => {
|
||||
try {
|
||||
await security.start(mode);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
}
|
||||
};
|
||||
|
||||
const chooseCustom = async () => {
|
||||
try {
|
||||
const picked = await open({
|
||||
multiple: true,
|
||||
directory: true,
|
||||
title: t("Choose what to scan", "选择要扫描的内容"),
|
||||
});
|
||||
if (!picked) return;
|
||||
const paths = (Array.isArray(picked) ? picked : [picked]).filter(Boolean) as string[];
|
||||
if (paths.length) await security.start("custom", paths);
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
}
|
||||
};
|
||||
|
||||
const act = async (action: () => Promise<string>) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
push(await action(), "success");
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setQuarantining(null);
|
||||
setDeleting(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<div className="page is-stacked">
|
||||
<PageHeader
|
||||
eyebrow={t("Security", "安全")}
|
||||
title={t("Checking this machine…", "正在检查这台电脑…")}
|
||||
description={t(
|
||||
"Reading what protects the machine and what ran at the last login.",
|
||||
"正在读取系统防护状态与上次的启动项。",
|
||||
)}
|
||||
/>
|
||||
{security.error ? <InlineError message={security.error} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page is-stacked">
|
||||
<PageHeader
|
||||
eyebrow={t("Security", "安全")}
|
||||
title={
|
||||
scan
|
||||
? t("The last scan, and what to do about it.", "上次扫描的结果,以及下一步。")
|
||||
: t("Nothing has been scanned yet.", "还没有扫描过这台电脑。")
|
||||
}
|
||||
description={t(
|
||||
"Scans run when you ask. Real-time protection stays with the system.",
|
||||
"扫描只在你要求时运行,实时防护仍由系统负责。",
|
||||
)}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<FolderSearch size={15} />}
|
||||
onClick={() => void chooseCustom()}
|
||||
disabled={security.scanning}
|
||||
>
|
||||
{t("Custom…", "自定义…")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<ShieldAlert size={15} />}
|
||||
onClick={() => void run("full")}
|
||||
disabled={security.scanning}
|
||||
>
|
||||
{t("Full scan", "全盘扫描")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
icon={<ShieldCheck size={16} />}
|
||||
onClick={() => void run("quick")}
|
||||
disabled={security.scanning}
|
||||
>
|
||||
{security.scanning
|
||||
? t("Scanning…", "正在扫描…")
|
||||
: t("Quick scan", "快速扫描")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{security.scanning ? (
|
||||
<ProgressCard
|
||||
progress={security.progress}
|
||||
title={t("Scanning for malware", "正在扫描恶意软件")}
|
||||
onCancel={() => void security.cancel()}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{security.error ? <InlineError message={security.error} /> : null}
|
||||
|
||||
<ProtectionCard status={status} onRefresh={() => void security.refresh()} />
|
||||
|
||||
<CoverageCard
|
||||
status={status}
|
||||
scan={scan}
|
||||
security={security}
|
||||
showScope={showScope}
|
||||
onToggleScope={() => setShowScope((current) => !current)}
|
||||
/>
|
||||
|
||||
<section className="panel">
|
||||
<SectionTitle
|
||||
title={t("Findings", "发现")}
|
||||
subtitle={
|
||||
scan
|
||||
? undefined
|
||||
: t("Nothing has been scanned on this machine yet.", "这台电脑还没有扫描记录。")
|
||||
}
|
||||
action={
|
||||
scan ? (
|
||||
<div className="chip-row" role="tablist">
|
||||
{(
|
||||
[
|
||||
["all", t("All", "全部"), counts.all],
|
||||
["confirmed", t("Confirmed", "已确认"), counts.confirmed],
|
||||
["suspicious", t("Suspicious", "可疑"), counts.suspicious],
|
||||
["advisory", t("Advisory", "提示"), counts.advisory],
|
||||
["quarantined", t("Quarantined", "已隔离"), counts.quarantined],
|
||||
] as [Filter, string, number][]
|
||||
).map(([key, label, count]) => (
|
||||
<button
|
||||
key={key}
|
||||
role="tab"
|
||||
aria-selected={filter === key}
|
||||
className={`filter-chip ${filter === key ? "is-active" : ""}`}
|
||||
onClick={() => setFilter(key)}
|
||||
>
|
||||
{label}
|
||||
<b>{count}</b>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
{!scan ? (
|
||||
<EmptyState
|
||||
icon={<ShieldQuestion size={26} />}
|
||||
title={t("No scan yet", "尚未扫描")}
|
||||
description={t(
|
||||
"A quick scan covers login items, applications, browser extensions and downloads.",
|
||||
"快速扫描会检查登录项、应用程序、浏览器扩展与下载目录。",
|
||||
)}
|
||||
/>
|
||||
) : findings.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<CheckCircle2 size={26} />}
|
||||
title={
|
||||
scan.coverageComplete
|
||||
? t("Nothing found in the range this scan covers", "在已检查范围内未发现威胁")
|
||||
: t("Nothing found in what could be read", "在可读取范围内未发现威胁")
|
||||
}
|
||||
description={
|
||||
scan.coverageComplete
|
||||
? t(
|
||||
"This is not a promise about files a scan never opened — the coverage card lists those.",
|
||||
"这不代表未打开的文件也是安全的——未检查范围见上方覆盖说明。",
|
||||
)
|
||||
: t(
|
||||
"Part of this scan could not be read. See the coverage card above.",
|
||||
"本次扫描有部分目录无法读取,请查看上方覆盖范围。",
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ul className="item-list">
|
||||
{findings.map((finding) => (
|
||||
<FindingRow
|
||||
key={finding.id}
|
||||
finding={finding}
|
||||
busy={busy}
|
||||
onOpen={() => setDetail(finding)}
|
||||
onQuarantine={() => setQuarantining(finding)}
|
||||
onDismiss={(ignored) => void act(() => security.dismiss(finding.id, ignored))}
|
||||
onExclude={() =>
|
||||
finding.path &&
|
||||
void act(() => security.exclude("add", parentFolder(finding.path as string)))
|
||||
}
|
||||
onReveal={() =>
|
||||
finding.path &&
|
||||
api
|
||||
.revealPath(finding.path)
|
||||
.catch((reason) => push(messageFrom(reason), "danger"))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<QuarantineCard
|
||||
status={status}
|
||||
busy={busy}
|
||||
onRestore={(id) => void act(() => security.restore(id))}
|
||||
onDelete={(id) => setDeleting(id)}
|
||||
/>
|
||||
|
||||
<ActivityCard status={status} onOpenStartup={onOpenStartup} />
|
||||
|
||||
<Modal
|
||||
open={Boolean(detail)}
|
||||
onClose={() => setDetail(null)}
|
||||
size="drawer"
|
||||
title={detail?.name ?? ""}
|
||||
subtitle={detail?.displayPath ?? undefined}
|
||||
footer={
|
||||
detail && !detail.quarantined && detail.confidence === "confirmed" ? (
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
setDetail(null);
|
||||
setQuarantining(detail);
|
||||
}}
|
||||
>
|
||||
{t("Move to quarantine", "移入隔离区")}
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detail ? <FindingDetail finding={detail} /> : null}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(quarantining)}
|
||||
title={t("Quarantine this file?", "要隔离这个文件吗?")}
|
||||
tone="danger"
|
||||
busy={busy}
|
||||
icon={<Ban size={24} />}
|
||||
confirmLabel={t("Quarantine", "隔离")}
|
||||
cancelLabel={t("Cancel", "取消")}
|
||||
message={quarantining?.title ?? ""}
|
||||
note={t(
|
||||
"The copy cannot run, and the original path is kept so it can be restored.",
|
||||
"隔离后的副本不可执行,并保留原路径以便恢复。",
|
||||
)}
|
||||
onConfirm={() =>
|
||||
quarantining && void act(() => security.quarantine(quarantining.id))
|
||||
}
|
||||
onClose={() => setQuarantining(null)}
|
||||
>
|
||||
<div className="confirm-path">{quarantining?.displayPath}</div>
|
||||
</ConfirmDialog>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(deleting)}
|
||||
title={t("Delete permanently?", "要永久删除吗?")}
|
||||
tone="danger"
|
||||
busy={busy}
|
||||
icon={<Trash2 size={24} />}
|
||||
confirmLabel={t("Delete for good", "永久删除")}
|
||||
cancelLabel={t("Cancel", "取消")}
|
||||
message={t(
|
||||
"This removes the only copy squid is holding. It does not go to the Trash.",
|
||||
"这会删除 Squid 保存的唯一副本,且不会进入废纸篓。",
|
||||
)}
|
||||
onConfirm={() => deleting && void act(() => security.purge(deleting))}
|
||||
onClose={() => setDeleting(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function flagLabel(
|
||||
value: boolean | null,
|
||||
t: (en: string, zh: string) => string,
|
||||
): { text: string; tone: string } {
|
||||
if (value === true) return { text: t("On", "已开启"), tone: "success" };
|
||||
if (value === false) return { text: t("Off", "已关闭"), tone: "danger" };
|
||||
return { text: t("Unknown", "无法确认"), tone: "neutral" };
|
||||
}
|
||||
|
||||
function ProtectionCard({
|
||||
status,
|
||||
onRefresh,
|
||||
}: {
|
||||
status: SecurityStatus;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const protection = status.protection;
|
||||
const unknown = !protection.known;
|
||||
const providerName =
|
||||
protection.provider === "xprotect"
|
||||
? "macOS XProtect"
|
||||
: protection.provider === "defender"
|
||||
? protection.productName || "Windows Defender"
|
||||
: protection.productName || t("No product reported", "未读到防护产品");
|
||||
|
||||
return (
|
||||
<section className={`panel is-protection ${unknown ? "is-unknown" : ""}`}>
|
||||
<span className={`metric-icon ${unknown ? "tone-warning" : "tone-primary"}`}>
|
||||
{unknown ? <ShieldQuestion size={22} /> : <ShieldCheck size={22} />}
|
||||
</span>
|
||||
<div className="protection-copy">
|
||||
<div className="protection-head">
|
||||
<strong>{providerName}</strong>
|
||||
<span className={`status-chip is-${unknown ? "neutral" : "info"}`}>
|
||||
{unknown
|
||||
? t("Could not be confirmed", "无法确认")
|
||||
: t("Read from the system", "来自系统")}
|
||||
</span>
|
||||
</div>
|
||||
<p>
|
||||
{t(
|
||||
"Read only. Squid never starts, stops or updates it.",
|
||||
"只读。Squid 不会开启、关闭或更新它。",
|
||||
)}
|
||||
</p>
|
||||
{protection.notes.length ? (
|
||||
<ul className="protection-notes">
|
||||
{protection.notes.map((note) => (
|
||||
<li key={note}>{note}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="protection-facts">
|
||||
{protection.definitions ? (
|
||||
<div className="fact">
|
||||
<span>{t("Definitions", "定义版本")}</span>
|
||||
<strong>
|
||||
{protection.definitions}
|
||||
{protection.definitionsDate ? ` · ${protection.definitionsDate}` : ""}
|
||||
</strong>
|
||||
</div>
|
||||
) : null}
|
||||
{protection.realtime !== null ? (
|
||||
<Fact
|
||||
label={t("Real-time protection", "实时防护")}
|
||||
value={flagLabel(protection.realtime, t)}
|
||||
/>
|
||||
) : null}
|
||||
{protection.backgroundScans !== null ? (
|
||||
<Fact
|
||||
label={t("Background scanning", "后台扫描")}
|
||||
value={flagLabel(protection.backgroundScans, t)}
|
||||
/>
|
||||
) : null}
|
||||
{protection.launchScans !== null ? (
|
||||
<Fact
|
||||
label={t("Scan at launch", "启动时扫描")}
|
||||
value={flagLabel(protection.launchScans, t)}
|
||||
/>
|
||||
) : null}
|
||||
{protection.gatekeeper !== null ? (
|
||||
<Fact label="Gatekeeper" value={flagLabel(protection.gatekeeper, t)} />
|
||||
) : null}
|
||||
{protection.lastScanDate ? (
|
||||
<div className="fact">
|
||||
<span>{t("Last system scan", "上次系统扫描")}</span>
|
||||
<strong>{protection.lastScanDate}</strong>
|
||||
</div>
|
||||
) : null}
|
||||
<button className="text-button" onClick={onRefresh}>
|
||||
<RefreshCw size={13} />
|
||||
{t("Read again", "重新读取")}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Fact({ label, value }: { label: string; value: { text: string; tone: string } }) {
|
||||
return (
|
||||
<div className="fact">
|
||||
<span>{label}</span>
|
||||
<strong className={`is-${value.tone}`}>{value.text}</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CoverageCard({
|
||||
status,
|
||||
scan,
|
||||
showScope,
|
||||
security,
|
||||
onToggleScope,
|
||||
}: {
|
||||
status: SecurityStatus;
|
||||
scan: SecurityScan | null;
|
||||
showScope: boolean;
|
||||
security: SecurityWorkspace;
|
||||
onToggleScope: () => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [updating, setUpdating] = useState(false);
|
||||
const intel = status.intel;
|
||||
const access = status.permissions.fullDiskAccess;
|
||||
const restricted = scan ? !scan.coverageComplete : false;
|
||||
const tone = !scan ? "neutral" : restricted ? "warning" : "success";
|
||||
const title = !scan
|
||||
? t("This machine has not been scanned", "这台电脑尚未扫描")
|
||||
: restricted
|
||||
? t("Coverage was limited", "覆盖范围受限")
|
||||
: t("Coverage was complete", "覆盖范围完整");
|
||||
|
||||
return (
|
||||
<section className={`panel is-coverage is-${tone}`}>
|
||||
<div className="coverage-head">
|
||||
<div>
|
||||
<strong>{title}</strong>
|
||||
<p>
|
||||
{scan
|
||||
? t(
|
||||
`${formatCount(scan.examined)} files checked · ${formatCount(
|
||||
scan.cached,
|
||||
)} reused from last time · ${formatCount(scan.skipped)} skipped${
|
||||
scan.cancelled ? " · this scan was cancelled before it finished" : ""
|
||||
}.`,
|
||||
`已检查 ${formatCount(scan.examined)} 个文件 · 复用上次结果 ${formatCount(
|
||||
scan.cached,
|
||||
)} 个 · 跳过 ${formatCount(scan.skipped)} 个${
|
||||
scan.cancelled ? " · 本次扫描在完成前被取消" : ""
|
||||
}。`,
|
||||
)
|
||||
: t(
|
||||
"Squid has read nothing yet, so there is no result that could be called clean.",
|
||||
"Squid 还没有读取过任何内容,因此不能称其为安全。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`status-chip is-${tone}`}>
|
||||
{lang === "zh"
|
||||
? !scan
|
||||
? "未扫描"
|
||||
: restricted
|
||||
? "受限"
|
||||
: "完整"
|
||||
: !scan
|
||||
? "not scanned"
|
||||
: restricted
|
||||
? "limited"
|
||||
: "complete"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{access === "denied" || access === "unknown" ? (
|
||||
<div className="notice">
|
||||
<span>
|
||||
<AlertTriangle size={14} />
|
||||
{t(
|
||||
"Without Full Disk Access, protected folders are skipped and reported as unchecked.",
|
||||
"没有完全磁盘访问权限时,受保护目录会被跳过并标注为未检查。",
|
||||
)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => void api.openFullDiskAccessSettings().catch(() => undefined)}
|
||||
>
|
||||
{t("Open System Settings", "打开系统设置")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{scan?.gaps.length ? (
|
||||
<ul className="coverage-gaps">
|
||||
{scan.gaps.slice(0, 8).map((gap) => (
|
||||
<li key={`${gap.path}-${gap.reason}`}>
|
||||
<FolderX size={13} />
|
||||
<span title={gap.path}>{shortPath(gap.path, 56)}</span>
|
||||
<small>{gap.reason}</small>
|
||||
</li>
|
||||
))}
|
||||
{scan.gaps.length > 8 ? (
|
||||
<li className="is-more">
|
||||
{t(`${scan.gaps.length - 8} more`, `另有 ${scan.gaps.length - 8} 项`)}
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
{/* The rule actions live here as well as in Settings: someone reading a
|
||||
stale coverage card is exactly the person who wants to refresh the
|
||||
rules, and sending them off to find a setting first loses the thread. */}
|
||||
<div className="coverage-foot">
|
||||
<div className="coverage-rules">
|
||||
<span>
|
||||
{intel.source === "pack"
|
||||
? t(
|
||||
`Rule pack r${intel.revision} · ${formatCount(intel.installedRules)} rules · ${intel.published}`,
|
||||
`规则包 r${intel.revision} · ${formatCount(intel.installedRules)} 条规则 · ${intel.published}`,
|
||||
)
|
||||
: t(
|
||||
`${formatCount(intel.builtinRules)} built-in rules · no pack downloaded`,
|
||||
`内置 ${formatCount(intel.builtinRules)} 条规则 · 未下载规则包`,
|
||||
)}
|
||||
</span>
|
||||
{/* A pack is only ever described by how it was actually checked. Saying
|
||||
"signed" because a signature would have been accepted if one had been
|
||||
configured is the kind of green that costs trust later. */}
|
||||
{intel.source === "pack" ? (
|
||||
<span
|
||||
className={`status-chip is-${intel.signed ? "success" : "warning"}`}
|
||||
title={
|
||||
intel.signed
|
||||
? t(
|
||||
"This build verified the manifest against its rule-pack key.",
|
||||
"本构建已用规则包密钥校验清单签名。",
|
||||
)
|
||||
: t(
|
||||
"SHA-256 checked against the manifest. This build has no rule-pack key, so no signature was verified.",
|
||||
"已按清单核对 SHA-256;本构建未内置规则包公钥,未校验签名。",
|
||||
)
|
||||
}
|
||||
>
|
||||
{intel.signed
|
||||
? t("signature verified", "已校验签名")
|
||||
: t("hash only · not signed", "仅校验哈希 · 未验签")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="coverage-actions">
|
||||
<button className="text-button" onClick={onToggleScope}>
|
||||
<Eye size={13} />
|
||||
{showScope ? t("Hide scope", "收起范围") : t("What is scanned", "扫描范围")}
|
||||
</button>
|
||||
<button
|
||||
className="text-button"
|
||||
disabled={updating}
|
||||
onClick={() => {
|
||||
setUpdating(true);
|
||||
void security
|
||||
.updateRules()
|
||||
.then((message) => push(message, "success"))
|
||||
.catch((reason) => push(messageFrom(reason), "danger"))
|
||||
.finally(() => setUpdating(false));
|
||||
}}
|
||||
>
|
||||
<Download size={13} />
|
||||
{updating ? t("Checking rules…", "正在检查规则…") : t("Update rules", "更新规则包")}
|
||||
</button>
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={() =>
|
||||
void api
|
||||
.revealPath(intel.path)
|
||||
.catch(() => push(t("The rules folder does not exist yet.", "规则目录尚未创建。"), "danger"))
|
||||
}
|
||||
>
|
||||
<FolderOpen size={13} />
|
||||
{t("Open rules folder", "打开规则目录")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showScope ? (
|
||||
<div className="coverage-scope">
|
||||
<div>
|
||||
<h4>{t("Quick scan covers", "快速扫描覆盖")}</h4>
|
||||
<ul>
|
||||
{status.settings.quickRoots.map((root) => (
|
||||
<li key={root}>{root}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4>{t("Full scan adds", "全盘扫描额外包含")}</h4>
|
||||
<ul>
|
||||
{status.settings.fullRoots
|
||||
.filter((root) => !status.settings.quickRoots.includes(root))
|
||||
.map((root) => (
|
||||
<li key={root}>{root}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
{status.settings.scanExclusions.length ? (
|
||||
<div>
|
||||
<h4>{t("Excluded by you", "你已排除")}</h4>
|
||||
<ul>
|
||||
{status.settings.scanExclusions.map((root) => (
|
||||
<li key={root}>{root}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/// The folder a finding lives in. Excluding a whole tree is a bigger promise than
|
||||
/// ignoring one finding, so it is offered as its own action rather than folded in.
|
||||
function parentFolder(path: string): string {
|
||||
const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
||||
return cut > 0 ? path.slice(0, cut) : path;
|
||||
}
|
||||
|
||||
function FindingRow({
|
||||
finding,
|
||||
busy,
|
||||
onOpen,
|
||||
onQuarantine,
|
||||
onDismiss,
|
||||
onExclude,
|
||||
onReveal,
|
||||
}: {
|
||||
finding: Finding;
|
||||
busy: boolean;
|
||||
onOpen: () => void;
|
||||
onQuarantine: () => void;
|
||||
onDismiss: (ignored: boolean) => void;
|
||||
onExclude: () => void;
|
||||
onReveal: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const meta = CONFIDENCE_META[finding.confidence];
|
||||
return (
|
||||
<li className={`item-row is-${meta.tone} ${finding.quarantined ? "is-handled" : ""}`}>
|
||||
<button className="item-main" onClick={onOpen}>
|
||||
<span className={`level-dot is-${meta.tone}`} />
|
||||
<span className="item-copy">
|
||||
<strong>{finding.name}</strong>
|
||||
<small title={finding.displayPath ?? undefined}>
|
||||
{finding.displayPath ?? t("Machine state", "系统状态")}
|
||||
</small>
|
||||
<em>{finding.title}</em>
|
||||
</span>
|
||||
</button>
|
||||
<span className={`status-chip is-${meta.tone}`}>
|
||||
{t(meta.en, meta.zh)}
|
||||
{finding.quarantined ? ` · ${t("held", "已隔离")}` : ""}
|
||||
</span>
|
||||
<div className="item-actions">
|
||||
{finding.path ? (
|
||||
<button
|
||||
className="icon-button"
|
||||
title={t("Show in folder", "在文件夹中显示")}
|
||||
onClick={onReveal}
|
||||
>
|
||||
<FolderOpen size={15} />
|
||||
</button>
|
||||
) : null}
|
||||
{finding.quarantined ? null : (
|
||||
<>
|
||||
<button
|
||||
className="icon-button"
|
||||
title={t("Ignore this finding", "忽略此发现")}
|
||||
onClick={() => onDismiss(true)}
|
||||
>
|
||||
<EyeOff size={15} />
|
||||
</button>
|
||||
{finding.path ? (
|
||||
<button
|
||||
className="icon-button"
|
||||
title={t("Exclude this folder from future scans", "今后扫描时排除该文件夹")}
|
||||
onClick={onExclude}
|
||||
>
|
||||
<FolderX size={15} />
|
||||
</button>
|
||||
) : null}
|
||||
{finding.confidence === "confirmed" ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
disabled={busy}
|
||||
icon={<Ban size={14} />}
|
||||
onClick={onQuarantine}
|
||||
>
|
||||
{t("Quarantine", "隔离")}
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function FindingDetail({ finding }: { finding: Finding }) {
|
||||
const { t } = useI18n();
|
||||
const meta = CONFIDENCE_META[finding.confidence];
|
||||
const rows: [string, string][] = [
|
||||
[t("Confidence", "级别"), t(meta.en, meta.zh)],
|
||||
[t("Size", "大小"), formatBytes(finding.size)],
|
||||
[
|
||||
t("Signed", "签名"),
|
||||
finding.signed ? finding.publisher || t("Yes", "是") : t("No", "否"),
|
||||
],
|
||||
];
|
||||
if (finding.sha256) rows.push(["SHA-256", finding.sha256]);
|
||||
return (
|
||||
<div className="item-detail">
|
||||
<p className="item-detail-lead">{finding.description || finding.title}</p>
|
||||
<dl className="detail-grid">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd title={value}>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<h4>{t("Why this was reported", "报告原因")}</h4>
|
||||
<ul className="evidence-list">
|
||||
{finding.evidence.map((item) => (
|
||||
<li key={item.key}>
|
||||
<span className="evidence-key">{item.key.split(":")[0]}</span>
|
||||
{item.summary}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="detail-note">
|
||||
{t(
|
||||
"Restoring puts the bytes and the permissions back exactly as they were.",
|
||||
"恢复时文件内容与权限会原样返回。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuarantineCard({
|
||||
status,
|
||||
busy,
|
||||
onRestore,
|
||||
onDelete,
|
||||
}: {
|
||||
status: SecurityStatus;
|
||||
busy: boolean;
|
||||
onRestore: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const items = status.quarantine;
|
||||
return (
|
||||
<section className="panel">
|
||||
<SectionTitle
|
||||
title={t("Quarantine", "隔离区")}
|
||||
subtitle={
|
||||
items.length
|
||||
? t(
|
||||
`${formatCount(items.length)} items · ${formatBytes(
|
||||
status.quarantineSize,
|
||||
)} · held where they cannot run`,
|
||||
`${formatCount(items.length)} 项 · ${formatBytes(
|
||||
status.quarantineSize,
|
||||
)} · 存放位置无法执行`,
|
||||
)
|
||||
: t("Empty — nothing has been moved out of the way.", "空的——没有文件被移走。")
|
||||
}
|
||||
action={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<FolderOpen size={14} />}
|
||||
onClick={() => void api.openQuarantineFolder().catch(() => undefined)}
|
||||
>
|
||||
{t("Open folder", "打开目录")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{items.length === 0 ? (
|
||||
<p className="empty-inline">
|
||||
{t(
|
||||
"Only files squid moved are held here. This is not the Trash.",
|
||||
"这里只保存 Squid 移动的文件,不是废纸篓。",
|
||||
)}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="item-list">
|
||||
{items.map((item) => (
|
||||
<li key={item.id} className="item-row">
|
||||
<div className="item-copy">
|
||||
<strong title={item.originalPath}>{item.displayPath}</strong>
|
||||
<small>
|
||||
{item.title} · {formatBytes(item.size)} ·{" "}
|
||||
{new Date(item.quarantinedMs).toLocaleString()}
|
||||
</small>
|
||||
</div>
|
||||
<div className="item-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
icon={<Undo2 size={14} />}
|
||||
onClick={() => onRestore(item.id)}
|
||||
>
|
||||
{t("Restore", "恢复")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy}
|
||||
icon={<Trash2 size={14} />}
|
||||
onClick={() => onDelete(item.id)}
|
||||
>
|
||||
{t("Delete", "删除")}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ActivityCard({
|
||||
status,
|
||||
onOpenStartup,
|
||||
}: {
|
||||
status: SecurityStatus;
|
||||
onOpenStartup: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const activity = status.activity;
|
||||
if (!activity.length) return null;
|
||||
return (
|
||||
<section className="panel">
|
||||
<SectionTitle
|
||||
title={t("Recent security activity", "最近的安全活动")}
|
||||
subtitle={t("Scans, quarantines and startup changes.", "本机的扫描、隔离与启动项修改。")}
|
||||
/>
|
||||
<ul className="activity-list">
|
||||
{activity.slice(0, 10).map((entry, index) => (
|
||||
<li key={`${entry.atMs}-${index}`}>
|
||||
<span className="activity-kind">{entry.kind}</span>
|
||||
<span className="activity-detail">{entry.detail}</span>
|
||||
<time>{new Date(entry.atMs).toLocaleString()}</time>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button className="text-button" onClick={onOpenStartup}>
|
||||
<HardDriveDownload size={13} />
|
||||
{t("Manage startup items", "管理启动项")}
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -27,6 +27,8 @@ import type {
|
|||
SettingsView,
|
||||
} from "../types";
|
||||
import type { UpdateFlow } from "../hooks/useUpdateFlow";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import { SecuritySettingsCard } from "../components/SecuritySettingsCard";
|
||||
import { UpdatePanel } from "../components/UpdatePanel";
|
||||
import {
|
||||
Button,
|
||||
|
|
@ -41,6 +43,7 @@ export function SettingsPage({
|
|||
settings,
|
||||
flow,
|
||||
autoCheck,
|
||||
security,
|
||||
onSettingsChange,
|
||||
onLanguageChange,
|
||||
onAutoCheckChange,
|
||||
|
|
@ -49,6 +52,7 @@ export function SettingsPage({
|
|||
settings: SettingsView;
|
||||
flow: UpdateFlow;
|
||||
autoCheck: boolean;
|
||||
security: SecurityWorkspace;
|
||||
onSettingsChange: (settings: SettingsView) => void;
|
||||
onLanguageChange: (language: Language) => Promise<void>;
|
||||
onAutoCheckChange: (enabled: boolean) => void;
|
||||
|
|
@ -310,11 +314,11 @@ export function SettingsPage({
|
|||
</div>
|
||||
<div className="settings-row is-first">
|
||||
<div>
|
||||
<strong>{t("Launch at login", "开机自启")}</strong>
|
||||
<strong>{t("Launch Squid at login", "登录时启动 Squid")}</strong>
|
||||
<span>
|
||||
{t(
|
||||
"The app starts automatically and keeps the tray available.",
|
||||
"登录后自动启动,并保留托盘入口。",
|
||||
"Only Squid itself. To manage what else starts at login, use the Startup items page.",
|
||||
"只针对 Squid 本身。要管理其他登录时启动的程序,请前往启动项页面。",
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
|
@ -327,6 +331,10 @@ export function SettingsPage({
|
|||
</div>
|
||||
</section>
|
||||
|
||||
{security.status ? (
|
||||
<SecuritySettingsCard security={security} status={security.status} />
|
||||
) : null}
|
||||
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-head">
|
||||
<div>
|
||||
|
|
@ -433,8 +441,8 @@ export function SettingsPage({
|
|||
</h2>
|
||||
<p>
|
||||
{t(
|
||||
"Squid never deletes anything inside these folders, even if a cleanup rule matches.",
|
||||
"即使清理规则匹配,Squid 也绝不会删除这些文件夹中的内容。",
|
||||
"Squid never deletes anything inside these folders, even if a cleanup rule matches. This list does not stop the malware scan from reporting a finding inside them.",
|
||||
"即使清理规则匹配,Squid 也绝不会删除这些文件夹中的内容。该列表不会阻止恶意软件扫描在其中报告发现。",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,673 @@
|
|||
import {
|
||||
AlertTriangle,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
FileSearch,
|
||||
KeyRound,
|
||||
Lock,
|
||||
RefreshCw,
|
||||
Search,
|
||||
Settings2,
|
||||
ShieldAlert,
|
||||
ToggleLeft,
|
||||
ToggleRight,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useI18n } from "../i18n";
|
||||
import { api } from "../lib/api";
|
||||
import { formatDate, messageFrom, shortPath } from "../lib/format";
|
||||
import type { StartupItem, StartupRisk, StartupSource } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import type { StartupWorkspace } from "../hooks/useStartupWorkspace";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
ConfirmDialog,
|
||||
EmptyState,
|
||||
InlineError,
|
||||
Modal,
|
||||
PageHeader,
|
||||
SectionTitle,
|
||||
Toggle,
|
||||
useToast,
|
||||
} from "../components/ui";
|
||||
|
||||
const SOURCE_LABEL: Record<StartupSource, [string, string]> = {
|
||||
"launch-agent": ["LaunchAgent", "LaunchAgent"],
|
||||
"launch-daemon": ["LaunchDaemon", "LaunchDaemon"],
|
||||
"login-item": ["Login item", "登录项"],
|
||||
"registry-run": ["Registry Run", "注册表 Run"],
|
||||
"startup-folder": ["Startup folder", "启动文件夹"],
|
||||
"scheduled-task": ["Scheduled task", "计划任务"],
|
||||
service: ["Service", "服务"],
|
||||
};
|
||||
|
||||
const RISK_LABEL: Record<StartupRisk, [string, string]> = {
|
||||
"missing-target": ["Target is gone", "目标已不存在"],
|
||||
"in-temp-dir": ["Runs from a temp folder", "位于临时目录"],
|
||||
unsigned: ["No usable signature", "无可用签名"],
|
||||
"script-interpreter": ["Started through a script", "经由脚本启动"],
|
||||
"recently-created": ["Created recently", "最近创建"],
|
||||
"hidden-entry": ["Hidden entry", "隐藏条目"],
|
||||
"hidden-home-directory": ["Runs from a dot-folder", "位于隐藏目录"],
|
||||
};
|
||||
|
||||
type ScopeFilter = "all" | "user" | "system";
|
||||
|
||||
/// Where to reveal an entry: the program it runs if that exists, otherwise the
|
||||
/// plist, key or task file that declares it. A login item whose target is gone can
|
||||
/// still be shown by its declaration.
|
||||
function revealTarget(item: StartupItem): string | null {
|
||||
return item.program ?? (item.id.includes("/") || item.id.includes("\\") ? item.id : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Startup items: what the machine has been told to run by itself.
|
||||
*
|
||||
* A risk label here means "look at this", never "this is malware" — the page says
|
||||
* so because the alternative is a wall of orange next to entries the operating
|
||||
* system owns. System items are hidden by default and read-only wherever squid
|
||||
* has no business writing without an authorisation it does not have.
|
||||
*/
|
||||
export function StartupPage({
|
||||
startup,
|
||||
security,
|
||||
initialQuery,
|
||||
onInspectProcess,
|
||||
onShowSecurity,
|
||||
}: {
|
||||
startup: StartupWorkspace;
|
||||
security: SecurityWorkspace;
|
||||
initialQuery: string | null;
|
||||
onInspectProcess: (filter: string) => void;
|
||||
onShowSecurity: () => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [scope, setScope] = useState<ScopeFilter>("user");
|
||||
const [source, setSource] = useState<StartupSource | "all">("all");
|
||||
const [disabledOnly, setDisabledOnly] = useState(false);
|
||||
const [riskyOnly, setRiskyOnly] = useState(false);
|
||||
const [showVendor, setShowVendor] = useState(false);
|
||||
const [query, setQuery] = useState(initialQuery ?? "");
|
||||
const [detail, setDetail] = useState<StartupItem | null>(null);
|
||||
const [pending, setPending] = useState<{ item: StartupItem; enabled: boolean } | null>(null);
|
||||
const [selectMode, setSelectMode] = useState(false);
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [batch, setBatch] = useState(false);
|
||||
|
||||
/**
|
||||
* One file, scanned now, and the user is taken to the page that shows the
|
||||
* result. Scanning in place would hide the answer behind whichever page they
|
||||
* happen to be standing on.
|
||||
*/
|
||||
const scanFile = async (path: string) => {
|
||||
try {
|
||||
await security.start("custom", [path]);
|
||||
onShowSecurity();
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
}
|
||||
};
|
||||
|
||||
const items = useMemo(() => {
|
||||
const all = startup.view?.items ?? [];
|
||||
const needle = query.trim().toLowerCase();
|
||||
return all.filter((item) => {
|
||||
if (!showVendor && item.systemVendor) return false;
|
||||
if (scope !== "all" && item.scope !== scope) return false;
|
||||
if (source !== "all" && item.source !== source) return false;
|
||||
if (disabledOnly && !item.disabled) return false;
|
||||
if (riskyOnly && item.risks.length === 0) return false;
|
||||
if (!needle) return true;
|
||||
return (
|
||||
item.name.toLowerCase().includes(needle) ||
|
||||
item.command.toLowerCase().includes(needle) ||
|
||||
(item.program ?? "").toLowerCase().includes(needle)
|
||||
);
|
||||
});
|
||||
}, [disabledOnly, query, scope, showVendor, source, startup.view]);
|
||||
|
||||
const change = async (item: StartupItem, enabled: boolean) => {
|
||||
try {
|
||||
push(await startup.setEnabled(item, enabled), "success");
|
||||
} catch (reason) {
|
||||
push(messageFrom(reason), "danger");
|
||||
} finally {
|
||||
setPending(null);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* One entry at a time is the rule, and it exists for a reason: a plist that
|
||||
* fails to reload, a task the vendor re-arms on next launch, and a login item
|
||||
* that belongs to an update helper all need to be visible as themselves. "All
|
||||
* user items" is offered rather than "everything", so the worst case a batch
|
||||
* can do is bounded by what the current user owns.
|
||||
*/
|
||||
const toggleSelection = (item: StartupItem) => {
|
||||
setSelected((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(item.id)) next.delete(item.id);
|
||||
else next.add(item.id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const actionable = useMemo(
|
||||
() => new Set(items.filter((item) => item.modifiable && !item.systemVendor).map((item) => item.id)),
|
||||
[items],
|
||||
);
|
||||
const allSelected = actionable.size > 0 && [...actionable].every((id) => selected.has(id));
|
||||
|
||||
const runBatch = async (enabled: boolean) => {
|
||||
const ids = [...selected].filter((id) => actionable.has(id));
|
||||
setBatch(true);
|
||||
let done = 0;
|
||||
const failures: string[] = [];
|
||||
for (const id of ids) {
|
||||
const item = startup.view?.items.find((candidate) => candidate.id === id);
|
||||
if (!item || item.disabled === !enabled) continue;
|
||||
try {
|
||||
await startup.setEnabled(item, enabled);
|
||||
done += 1;
|
||||
} catch (reason) {
|
||||
failures.push(`${item.name}: ${messageFrom(reason)}`);
|
||||
}
|
||||
}
|
||||
setBatch(false);
|
||||
setSelected(new Set());
|
||||
setSelectMode(false);
|
||||
push(
|
||||
failures.length
|
||||
? t(
|
||||
`${done} changed · ${failures.length} refused: ${failures[0]}`,
|
||||
`已修改 ${done} 项 · ${failures.length} 项被拒绝:${failures[0]}`,
|
||||
)
|
||||
: t(
|
||||
`${done} startup items are now ${enabled ? "on" : "off"}.`,
|
||||
`${done} 个启动项已${enabled ? "启用" : "停用"}。`,
|
||||
),
|
||||
failures.length ? "danger" : "success",
|
||||
);
|
||||
};
|
||||
|
||||
// Coming from a process row means coming with a question: "is this one of
|
||||
// mine, and where is it declared?" So the handed-over path becomes the search,
|
||||
// and the vendor items the process might belong to stop being hidden.
|
||||
useEffect(() => {
|
||||
if (!initialQuery) return;
|
||||
setQuery(initialQuery);
|
||||
setShowVendor(true);
|
||||
setScope("all");
|
||||
setSource("all");
|
||||
}, [initialQuery]);
|
||||
|
||||
const view = startup.view;
|
||||
return (
|
||||
<div className="page is-stacked">
|
||||
<PageHeader
|
||||
eyebrow={t("Startup items", "启动项")}
|
||||
title={t("What your machine starts by itself.", "你的电脑自己会启动什么。")}
|
||||
description={t(
|
||||
"A risk label means worth a look, never malicious.",
|
||||
"风险标记只代表值得检查,不代表恶意。",
|
||||
)}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<Settings2 size={15} />}
|
||||
onClick={() => setSelectMode((current) => !current)}
|
||||
>
|
||||
{selectMode
|
||||
? t("Done selecting", "完成选择")
|
||||
: t("Select user items", "选择用户项目")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<RefreshCw size={15} />}
|
||||
onClick={() => void startup.refresh()}
|
||||
disabled={startup.loading}
|
||||
>
|
||||
{t("Read again", "重新读取")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{startup.error ? <InlineError message={startup.error} /> : null}
|
||||
|
||||
{view ? (
|
||||
<div className="stat-grid">
|
||||
<div className="stat">
|
||||
<strong>{view.userCount}</strong>
|
||||
<span>{t("for your user", "属于当前用户")}</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<strong>{view.systemCount}</strong>
|
||||
<span>{t("system-wide", "系统级")}</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<strong>{view.disabledCount}</strong>
|
||||
<span>{t("turned off", "已停用")}</span>
|
||||
</div>
|
||||
<div className="stat">
|
||||
<strong>{view.actionableCount}</strong>
|
||||
<span>{t("squid may change", "Squid 可修改")}</span>
|
||||
</div>
|
||||
<div className="stat is-warning">
|
||||
<strong>{view.riskyCount}</strong>
|
||||
<span>{t("worth a look", "值得检查")}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{view?.notes.length ? (
|
||||
<div className="notice">
|
||||
{view.notes.map((note) => (
|
||||
<span key={note}>
|
||||
<AlertTriangle size={13} />
|
||||
{note}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<section className="panel">
|
||||
<label className="search-field">
|
||||
<Search size={14} />
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t("Search name, command or path", "搜索名称、命令或路径")}
|
||||
/>
|
||||
</label>
|
||||
<div className="chip-row">
|
||||
{(
|
||||
[
|
||||
["user", t("My user", "当前用户")],
|
||||
["system", t("System", "系统")],
|
||||
["all", t("All scopes", "全部范围")],
|
||||
] as [ScopeFilter, string][]
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
className={`filter-chip ${scope === key ? "is-active" : ""}`}
|
||||
onClick={() => setScope(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
<select
|
||||
className="settings-select"
|
||||
value={source}
|
||||
onChange={(event) => setSource(event.target.value as StartupSource | "all")}
|
||||
>
|
||||
<option value="all">{t("Every kind", "所有类型")}</option>
|
||||
{(Object.keys(SOURCE_LABEL) as StartupSource[]).map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{lang === "zh" ? SOURCE_LABEL[key][1] : SOURCE_LABEL[key][0]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
className={`filter-chip ${disabledOnly ? "is-active" : ""}`}
|
||||
onClick={() => setDisabledOnly((current) => !current)}
|
||||
>
|
||||
{t("Turned off", "已停用")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${riskyOnly ? "is-active" : ""}`}
|
||||
onClick={() => setRiskyOnly((current) => !current)}
|
||||
>
|
||||
{t("Risky only", "仅看需注意")}
|
||||
</button>
|
||||
<button
|
||||
className={`filter-chip ${showVendor ? "is-active" : ""}`}
|
||||
onClick={() => setShowVendor((current) => !current)}
|
||||
>
|
||||
{t("Show Apple / Microsoft items", "显示系统条目")}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{selectMode ? (
|
||||
<div className="startup-batch">
|
||||
<label className="startup-batch-all">
|
||||
<Checkbox
|
||||
checked={allSelected}
|
||||
indeterminate={selected.size > 0 && !allSelected}
|
||||
onChange={() =>
|
||||
setSelected(allSelected ? new Set() : new Set(actionable))
|
||||
}
|
||||
label={t("Select all shown user items", "全选当前显示的用户项目")}
|
||||
/>
|
||||
<span>
|
||||
{t(
|
||||
`${selected.size} of ${actionable.size} changeable items shown`,
|
||||
`已选 ${selected.size} / 可修改 ${actionable.size} 项`,
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
<div className="startup-batch-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={batch || selected.size === 0}
|
||||
onClick={() => void runBatch(true)}
|
||||
>
|
||||
{t("Enable selected", "启用所选")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
disabled={batch || selected.size === 0}
|
||||
onClick={() => void runBatch(false)}
|
||||
>
|
||||
{t("Disable selected", "停用所选")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<SectionTitle
|
||||
title={t("Startup entries", "启动条目")}
|
||||
subtitle={t(
|
||||
`${items.length} shown${
|
||||
view ? ` of ${view.items.length} read from this machine` : ""
|
||||
}. Disabling keeps the original file or value so it can be put back.`,
|
||||
`当前显示 ${items.length} 项${
|
||||
view ? `,本机共读取 ${view.items.length} 项` : ""
|
||||
}。停用会保留原始文件或注册表值,可随时恢复。`,
|
||||
)}
|
||||
/>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<ToggleLeft size={26} />}
|
||||
title={t("Nothing matches these filters", "没有符合筛选条件的条目")}
|
||||
description={t(
|
||||
"System-wide entries stay hidden until you show them above.",
|
||||
"系统级条目需要在上方手动显示。",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<ul className="item-list">
|
||||
{items.map((item) => (
|
||||
<StartupRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
lang={lang}
|
||||
busy={startup.busy || batch}
|
||||
selectMode={selectMode}
|
||||
selected={selected.has(item.id)}
|
||||
selectable={actionable.has(item.id)}
|
||||
onToggleSelected={() => toggleSelection(item)}
|
||||
onOpen={() => setDetail(item)}
|
||||
onAsk={(enabled) => setPending({ item, enabled })}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={Boolean(detail)}
|
||||
onClose={() => setDetail(null)}
|
||||
size="drawer"
|
||||
title={detail?.name ?? ""}
|
||||
subtitle={
|
||||
detail
|
||||
? `${lang === "zh" ? SOURCE_LABEL[detail.source][1] : SOURCE_LABEL[detail.source][0]} · ${
|
||||
detail.scope === "user"
|
||||
? t("your user", "当前用户")
|
||||
: t("system", "系统")
|
||||
}`
|
||||
: undefined
|
||||
}
|
||||
footer={
|
||||
detail ? (
|
||||
<>
|
||||
{revealTarget(detail) ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon={<ExternalLink size={15} />}
|
||||
onClick={() =>
|
||||
void api
|
||||
.revealPath(revealTarget(detail) as string)
|
||||
.catch((reason) => push(messageFrom(reason), "danger"))
|
||||
}
|
||||
>
|
||||
{t("Show in folder", "在文件夹中显示")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
variant={detail.disabled ? "primary" : "danger"}
|
||||
disabled={!detail.modifiable || startup.busy}
|
||||
icon={detail.disabled ? <ToggleRight size={15} /> : <ToggleLeft size={15} />}
|
||||
onClick={() => {
|
||||
const next = !detail.disabled;
|
||||
setDetail(null);
|
||||
setPending({ item: detail, enabled: next });
|
||||
}}
|
||||
>
|
||||
{detail.disabled ? t("Enable", "启用") : t("Disable", "停用")}
|
||||
</Button>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{detail ? (
|
||||
<StartupDetail
|
||||
item={detail}
|
||||
lang={lang}
|
||||
onInspectProcess={onInspectProcess}
|
||||
onScan={async (path) => {
|
||||
setDetail(null);
|
||||
await scanFile(path);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(pending)}
|
||||
title={
|
||||
pending?.enabled
|
||||
? t("Enable this startup item?", "要启用这个启动项吗?")
|
||||
: t("Disable this startup item?", "要停用这个启动项吗?")
|
||||
}
|
||||
tone={pending?.enabled ? "default" : "danger"}
|
||||
busy={startup.busy}
|
||||
icon={<KeyRound size={22} />}
|
||||
confirmLabel={pending?.enabled ? t("Enable", "启用") : t("Disable", "停用")}
|
||||
cancelLabel={t("Cancel", "取消")}
|
||||
message={pending?.item.name ?? ""}
|
||||
note={t(
|
||||
"The original is kept, so this can be undone here.",
|
||||
"Squid 会保留原始值,可在此页面恢复。",
|
||||
)}
|
||||
onConfirm={() => pending && void change(pending.item, pending.enabled)}
|
||||
onClose={() => setPending(null)}
|
||||
>
|
||||
<div className="confirm-path">
|
||||
<code>{pending?.item.command}</code>
|
||||
</div>
|
||||
{pending?.item.scope === "system" ? (
|
||||
<div className="confirm-warn">
|
||||
{t(
|
||||
"System-wide: changing it needs one authorisation.",
|
||||
"系统级条目,修改需要一次系统授权。",
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</ConfirmDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StartupRow({
|
||||
item,
|
||||
lang,
|
||||
busy,
|
||||
selectMode,
|
||||
selected,
|
||||
selectable,
|
||||
onToggleSelected,
|
||||
onOpen,
|
||||
onAsk,
|
||||
}: {
|
||||
item: StartupItem;
|
||||
lang: "zh" | "en";
|
||||
busy: boolean;
|
||||
selectMode: boolean;
|
||||
selected: boolean;
|
||||
selectable: boolean;
|
||||
onToggleSelected: () => void;
|
||||
onOpen: () => void;
|
||||
onAsk: (enabled: boolean) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const target = item.program ?? item.command;
|
||||
return (
|
||||
<li className={`item-row ${item.disabled ? "is-off" : ""} ${item.risks.length ? "is-risky" : ""}`}>
|
||||
{selectMode ? (
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
disabled={!selectable}
|
||||
onChange={onToggleSelected}
|
||||
label={t("Select startup item", "选择启动项")}
|
||||
/>
|
||||
) : null}
|
||||
<button className="item-main" onClick={onOpen}>
|
||||
<span className="item-copy">
|
||||
<strong>{item.name}</strong>
|
||||
<small title={target}>{shortPath(target, 76)}</small>
|
||||
</span>
|
||||
<span className="startup-meta">
|
||||
<span className="startup-source">{lang === "zh" ? SOURCE_LABEL[item.source][1] : SOURCE_LABEL[item.source][0]}</span>
|
||||
<span className={`status-chip is-${item.scope === "user" ? "info" : "neutral"}`}>
|
||||
{item.scope === "user" ? t("user", "用户") : t("system", "系统")}
|
||||
</span>
|
||||
{item.publisher ? (
|
||||
<span className="status-chip is-success">
|
||||
{t("signed", "已签名")} · {item.publisher}
|
||||
</span>
|
||||
) : item.signed ? null : (
|
||||
<span className="status-chip is-neutral">{t("unsigned", "未签名")}</span>
|
||||
)}
|
||||
{item.risks.map((risk) => (
|
||||
<span key={risk} className="risk-chip" title={t(RISK_LABEL[risk][0], RISK_LABEL[risk][1])}>
|
||||
<ShieldAlert size={11} />
|
||||
{t(RISK_LABEL[risk][0], RISK_LABEL[risk][1])}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
</button>
|
||||
{item.modifiable ? (
|
||||
<Toggle
|
||||
checked={!item.disabled}
|
||||
disabled={busy}
|
||||
label={t("Toggle startup item", "切换启动项")}
|
||||
onChange={(next) => onAsk(next)}
|
||||
/>
|
||||
) : (
|
||||
<span className="muted-note" title={item.readonlyReason ?? undefined}>
|
||||
<Lock size={14} />
|
||||
{item.readonlyReason ?? t("read-only", "只读")}
|
||||
</span>
|
||||
)}
|
||||
<button className="icon-button" title={t("Details", "详情")} onClick={onOpen}>
|
||||
<ChevronRight size={16} />
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function StartupDetail({
|
||||
item,
|
||||
lang,
|
||||
onInspectProcess,
|
||||
onScan,
|
||||
}: {
|
||||
item: StartupItem;
|
||||
lang: "zh" | "en";
|
||||
onInspectProcess: (filter: string) => void;
|
||||
onScan: (path: string) => Promise<void>;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const rows: [string, string][] = [];
|
||||
if (item.workingDirectory) rows.push([t("Working directory", "工作目录"), item.workingDirectory]);
|
||||
if (item.program) rows.push([t("Program", "程序"), item.program]);
|
||||
rows.push([t("Entry", "声明位置"), item.id]);
|
||||
if (item.modifiedMs)
|
||||
rows.push([t("Modified", "修改时间"), formatDate(new Date(item.modifiedMs).toISOString(), lang)]);
|
||||
rows.push([
|
||||
t("Signature", "签名"),
|
||||
item.publisher
|
||||
? item.publisher
|
||||
: item.signed
|
||||
? t("Signed, vendor unknown", "已签名,发布者未知")
|
||||
: t("No usable signature", "无可用签名"),
|
||||
]);
|
||||
return (
|
||||
<div className="item-detail">
|
||||
<div className="detail-command">
|
||||
<span>{t("Command", "命令")}</span>
|
||||
<code>{item.command || t("(nothing recorded)", "(未记录)")}</code>
|
||||
</div>
|
||||
{item.risks.length ? (
|
||||
<ul className="detail-risks">
|
||||
{item.risks.map((risk) => (
|
||||
<li key={risk}>
|
||||
<ShieldAlert size={13} />
|
||||
{t(RISK_LABEL[risk][0], RISK_LABEL[risk][1])}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
<dl className="detail-grid">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={`${label}-${value}`}>
|
||||
<dt>{label}</dt>
|
||||
<dd title={value}>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{!item.modifiable ? (
|
||||
<p className="detail-note">
|
||||
<Lock size={13} />
|
||||
{item.readonlyReason ??
|
||||
t(
|
||||
"Squid installs no privileged helper, so system-wide entries stay read-only.",
|
||||
"Squid 不安装特权 helper,系统级条目保持只读。",
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="detail-actions">
|
||||
{item.program ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<FileSearch size={14} />}
|
||||
onClick={() => void onScan(item.program as string)}
|
||||
>
|
||||
{t("Scan this file", "扫描该文件")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon={<ToggleRight size={14} />}
|
||||
onClick={() => onInspectProcess(item.program as string)}
|
||||
>
|
||||
{t("Find its process", "查看关联进程")}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -21,7 +21,10 @@ import {
|
|||
percent,
|
||||
} from "../lib/format";
|
||||
import type { ProcessSample, SystemSnapshot } from "../types";
|
||||
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
|
||||
import { ProcessTable } from "../components/ProcessTable";
|
||||
import {
|
||||
Button,
|
||||
ConfirmDialog,
|
||||
Gauge,
|
||||
InlineError,
|
||||
|
|
@ -37,16 +40,28 @@ export function SystemPage({
|
|||
error,
|
||||
loading,
|
||||
refresh,
|
||||
initialProcessFilter,
|
||||
security,
|
||||
onOpenStartup,
|
||||
}: {
|
||||
snapshot: SystemSnapshot | null;
|
||||
error: string | null;
|
||||
loading: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
initialProcessFilter: string | null;
|
||||
security: SecurityWorkspace;
|
||||
onOpenStartup: (query: string) => void;
|
||||
}) {
|
||||
const { t, lang } = useI18n();
|
||||
const { push } = useToast();
|
||||
const [victim, setVictim] = useState<ProcessSample | null>(null);
|
||||
const [stopping, setStopping] = useState(false);
|
||||
// Two tabs rather than a third page: performance and processes are the same
|
||||
// question asked at different resolutions, and the roadmap did not want a
|
||||
// separate "Processes" entry in a sidebar that is already at ten.
|
||||
const [tab, setTab] = useState<"performance" | "processes">(
|
||||
initialProcessFilter ? "processes" : "performance",
|
||||
);
|
||||
|
||||
const stop = async () => {
|
||||
if (!victim) return;
|
||||
|
|
@ -93,6 +108,35 @@ export function SystemPage({
|
|||
|
||||
{error ? <InlineError message={error} /> : null}
|
||||
|
||||
<div className="chip-row page-tabs" role="tablist">
|
||||
{(
|
||||
[
|
||||
["performance", t("Performance", "性能")],
|
||||
["processes", t("Processes", "进程")],
|
||||
] as ["performance" | "processes", string][]
|
||||
).map(([key, label]) => (
|
||||
<button
|
||||
key={key}
|
||||
role="tab"
|
||||
aria-selected={tab === key}
|
||||
className={`filter-chip ${tab === key ? "is-active" : ""}`}
|
||||
onClick={() => setTab(key)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === "processes" ? (
|
||||
<ProcessTable
|
||||
active
|
||||
initialFilter={initialProcessFilter}
|
||||
security={security}
|
||||
onOpenStartup={onOpenStartup}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className="system-performance" hidden={tab !== "performance"}>
|
||||
<div className="system-gauges">
|
||||
<section className="system-gauge-card">
|
||||
<div className="system-gauge-head">
|
||||
|
|
@ -279,6 +323,11 @@ export function SystemPage({
|
|||
<SectionTitle
|
||||
title={t("Top processes", "高占用进程")}
|
||||
subtitle={t("Sorted by processor usage.", "按处理器占用排序。")}
|
||||
action={
|
||||
<Button variant="ghost" size="sm" onClick={() => setTab("processes")}>
|
||||
{t("View all processes", "查看全部进程")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<div className="process-head">
|
||||
<span />
|
||||
|
|
@ -365,6 +414,7 @@ export function SystemPage({
|
|||
)}
|
||||
<MetricBar value={snapshot?.disk.activity ?? 0} tone="success" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(victim)}
|
||||
|
|
|
|||
1061
src/styles.css
1061
src/styles.css
File diff suppressed because it is too large
Load Diff
225
src/types.ts
225
src/types.ts
|
|
@ -6,6 +6,8 @@ export type PageId =
|
|||
| "purge"
|
||||
| "storage"
|
||||
| "system"
|
||||
| "security"
|
||||
| "startup"
|
||||
| "history"
|
||||
| "settings";
|
||||
|
||||
|
|
@ -291,3 +293,226 @@ export interface UndoResult {
|
|||
restored: number;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ security */
|
||||
|
||||
export type Confidence = "confirmed" | "suspicious" | "advisory";
|
||||
export type ScanMode = "quick" | "full" | "custom";
|
||||
export type ScanSchedule = "manual" | "on-launch" | "daily" | "weekly";
|
||||
|
||||
export interface Evidence {
|
||||
key: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface Finding {
|
||||
id: string;
|
||||
confidence: Confidence;
|
||||
path: string | null;
|
||||
displayPath: string | null;
|
||||
name: string;
|
||||
title: string;
|
||||
description: string;
|
||||
evidence: Evidence[];
|
||||
size: number;
|
||||
sha256: string | null;
|
||||
signed: boolean;
|
||||
publisher: string | null;
|
||||
foundAtMs: number;
|
||||
quarantined: boolean;
|
||||
ignored: boolean;
|
||||
}
|
||||
|
||||
export interface ScanGap {
|
||||
path: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface SecurityScan {
|
||||
scanId: string;
|
||||
mode: ScanMode;
|
||||
finishedMs: number;
|
||||
elapsedMs: number;
|
||||
cancelled: boolean;
|
||||
examined: number;
|
||||
cached: number;
|
||||
skipped: number;
|
||||
coverageComplete: boolean;
|
||||
gaps: ScanGap[];
|
||||
findings: Finding[];
|
||||
systemAdvisories: Finding[];
|
||||
confirmed: number;
|
||||
suspicious: number;
|
||||
advisory: number;
|
||||
clean: boolean;
|
||||
}
|
||||
|
||||
export interface ProtectionStatus {
|
||||
provider: string;
|
||||
known: boolean;
|
||||
definitions: string;
|
||||
definitionsDate: string;
|
||||
realtime: boolean | null;
|
||||
backgroundScans: boolean | null;
|
||||
launchScans: boolean | null;
|
||||
gatekeeper: boolean | null;
|
||||
lastScanDate: string;
|
||||
notes: string[];
|
||||
productName: string;
|
||||
}
|
||||
|
||||
export interface IntelStatus {
|
||||
builtinRules: number;
|
||||
installedRules: number;
|
||||
revision: number;
|
||||
published: string;
|
||||
signed: boolean;
|
||||
source: string;
|
||||
path: string;
|
||||
fallbackAvailable: boolean;
|
||||
}
|
||||
|
||||
export interface QuarantineEntry {
|
||||
id: string;
|
||||
originalPath: string;
|
||||
displayPath: string;
|
||||
stored: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
mode: number;
|
||||
modifiedMs: number;
|
||||
quarantinedMs: number;
|
||||
title: string;
|
||||
confidence: Confidence;
|
||||
evidence: Evidence[];
|
||||
}
|
||||
|
||||
export interface ActivityEntry {
|
||||
atMs: number;
|
||||
kind: string;
|
||||
detail: string;
|
||||
path: string | null;
|
||||
}
|
||||
|
||||
export interface SecuritySettings {
|
||||
scanSchedule: ScanSchedule;
|
||||
notifyOnFindings: boolean;
|
||||
autoQuarantine: boolean;
|
||||
updateRules: boolean;
|
||||
scanExclusions: string[];
|
||||
ignoredFindings: string[];
|
||||
quickRoots: string[];
|
||||
fullRoots: string[];
|
||||
quarantined: string[];
|
||||
}
|
||||
|
||||
export interface SecurityStatus {
|
||||
protection: ProtectionStatus;
|
||||
intel: IntelStatus;
|
||||
scan: SecurityScan | null;
|
||||
quarantine: QuarantineEntry[];
|
||||
quarantineSize: number;
|
||||
activity: ActivityEntry[];
|
||||
settings: SecuritySettings;
|
||||
permissions: PermissionStatus;
|
||||
paths: { quarantine: string; intel: string; startupBackups: string };
|
||||
confirmed: number;
|
||||
suspicious: number;
|
||||
}
|
||||
|
||||
export interface SecurityAction {
|
||||
message: string;
|
||||
status: SecurityStatus;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- startup */
|
||||
|
||||
export type StartupScope = "user" | "system";
|
||||
export type StartupSource =
|
||||
| "launch-agent"
|
||||
| "launch-daemon"
|
||||
| "login-item"
|
||||
| "registry-run"
|
||||
| "startup-folder"
|
||||
| "scheduled-task"
|
||||
| "service";
|
||||
export type StartupRisk =
|
||||
| "missing-target"
|
||||
| "in-temp-dir"
|
||||
| "unsigned"
|
||||
| "script-interpreter"
|
||||
| "recently-created"
|
||||
| "hidden-entry"
|
||||
| "hidden-home-directory";
|
||||
|
||||
export interface StartupItem {
|
||||
id: string;
|
||||
name: string;
|
||||
source: StartupSource;
|
||||
scope: StartupScope;
|
||||
command: string;
|
||||
program: string | null;
|
||||
workingDirectory: string | null;
|
||||
publisher: string | null;
|
||||
signed: boolean;
|
||||
systemVendor: boolean;
|
||||
disabled: boolean;
|
||||
modifiable: boolean;
|
||||
readonlyReason: string | null;
|
||||
hidden: boolean;
|
||||
modifiedMs: number | null;
|
||||
risks: StartupRisk[];
|
||||
}
|
||||
|
||||
export interface StartupView {
|
||||
items: StartupItem[];
|
||||
notes: string[];
|
||||
userCount: number;
|
||||
systemCount: number;
|
||||
disabledCount: number;
|
||||
actionableCount: number;
|
||||
riskyCount: number;
|
||||
sources: string[];
|
||||
}
|
||||
|
||||
export interface StartupChange {
|
||||
item: StartupItem;
|
||||
message: string;
|
||||
view: StartupView;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ processes */
|
||||
|
||||
export interface ProcessRow {
|
||||
pid: number;
|
||||
parent: number | null;
|
||||
name: string;
|
||||
command: string;
|
||||
program: string | null;
|
||||
workingDirectory: string | null;
|
||||
user: string;
|
||||
cpu: number;
|
||||
memory: number;
|
||||
startedMs: number | null;
|
||||
startupItem: string | null;
|
||||
signed: boolean;
|
||||
publisher: string | null;
|
||||
owned: boolean;
|
||||
}
|
||||
|
||||
export interface Trust {
|
||||
signed: boolean;
|
||||
adHoc: boolean;
|
||||
untrusted: boolean;
|
||||
signer: string | null;
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
export interface ProcessDetail {
|
||||
row: ProcessRow;
|
||||
sha256: string | null;
|
||||
trust: Trust;
|
||||
startup: StartupItem | null;
|
||||
parent: ProcessRow | null;
|
||||
stopNote: string | null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue