Compare commits
15 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
404d0b6e69 | |
|
|
22eb0fcddb | |
|
|
629cfc5207 | |
|
|
af61b9e4c0 | |
|
|
90faa9f8bb | |
|
|
51f9fdb085 | |
|
|
492c5b708a | |
|
|
e468c761c5 | |
|
|
29514edddb | |
|
|
ea1465d192 | |
|
|
37658ed61d | |
|
|
cea60cc6c1 | |
|
|
8490f9213c | |
|
|
eb8f899fe0 | |
|
|
6d9db8b700 |
|
|
@ -9,8 +9,9 @@
|
|||
/target/
|
||||
/src-tauri/target/
|
||||
/artifacts/
|
||||
/release/
|
||||
# scripts/release.sh 的产物:通用二进制 + tar.gz + sha256。
|
||||
# 发布走 GitHub Release 附件和 Homebrew formula,不进仓库。
|
||||
# 桌面发布包只存在于 origin 的 releases 分支,GitHub 只镜像源码。
|
||||
/dist/
|
||||
node_modules/
|
||||
.vite/
|
||||
|
|
@ -59,11 +60,5 @@ __pycache__/
|
|||
!.env.example
|
||||
*.local
|
||||
|
||||
# ── 显式纳管的发布产物 ───────────────────────────────────────────────
|
||||
!release/0.1.3/Squid-0.1.3-macOS-universal.dmg
|
||||
!release/0.1.3/Squid-Setup-0.1.3-win-x64.exe
|
||||
!release/0.1.4/Squid-0.1.4-macOS-universal.dmg
|
||||
!release/0.1.4/Squid-Setup-0.1.4-win-x64.exe
|
||||
|
||||
# 输入法/软件在 cwd 落的调试日志(sogou 等)
|
||||
debug.log
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -0,0 +1,130 @@
|
|||
# 更新日志 / Changelog
|
||||
|
||||
Squid 的重要变更记录在这里。版本号使用语义化版本,日期为发布日。
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 文档
|
||||
|
||||
- 新增中英文使用帮助、更新日志和当前版本发布说明。
|
||||
- 版权署名改为 mula.liu,许可证明确为 GPL-3.0-only。
|
||||
- GitHub 作为源码镜像,不承载 `releases` 分支;新增 `scripts/sync-github.sh` 同步脚本。构建物同时上传到 GitHub Releases,更新通道仍以 origin 为准。
|
||||
|
||||
## [0.1.14] - 2026-11-25
|
||||
|
||||
- 全站统一标准组件库:页签、卡片、行、状态标签、工具栏与搜索框使用同一套定义,不再由各模块自行实现。
|
||||
- 空间清理的“垃圾清理 / 重复文件 / 大文件”三个页签与设置页页签保持同一套样式。
|
||||
- 权限管理的开机启动项改用统一行布局,状态、来源、路径和操作位置与其他模块一致。
|
||||
- 精简设置页与各页面布局;一级标题下不再重复二级描述,标题末尾不再带句号。
|
||||
- 主界面的更新提示直接打开“设置 → 更新”分区。
|
||||
- macOS 隐藏仅支持 Windows 的系统维护模块;权限管理保留开机启动项。
|
||||
|
||||
## [0.1.13] - 2026-11-25
|
||||
|
||||
- 合并 dev 分支的空间清理、系统维护、权限管理与桌面小工具改造,左侧导航按功能合并为“维护 / 安全 / 洞察 / 桌面”四组。
|
||||
- 空间清理升级为“垃圾清理 / 重复文件 / 大文件”三页签,切换页签保留扫描结果与勾选状态。
|
||||
- 系统维护升级为“一键修复 / 隐私清理 / 系统优化”三页签。
|
||||
- 权限管理新增开机启动项分组、残留识别、系统项隐藏、右键菜单分组与进阶启动项。
|
||||
- 重复文件支持“本组一份不剩”,删除仍走回收站并可撤销。
|
||||
- 保留并接入安全扫描、隔离区与白名单机制;安全入口位于“安全”分组。
|
||||
- 概览页采用新的三列指标布局,所有页面一级标题下不再重复二级描述。
|
||||
- 主界面的更新提示现在直接打开“设置 → 更新”分区。
|
||||
- macOS 隐藏仅依赖 Windows 服务的“系统维护”,权限管理只保留开机启动项页签。
|
||||
- 前端统一为一套标准组件库:页签、卡片、行、状态标签、工具栏与搜索框不再由各模块自行定义;空间清理三个页签与设置页一致,权限管理的开机启动项信息与其他模块一致。
|
||||
|
||||
## [0.1.11] - 2026-11-22
|
||||
|
||||
- 设置页的“常规”和“清理”分区改为整行布局,删除方式仍并排显示,版面更清晰。
|
||||
- 所有应用页移除一级标题下的二级描述,并收紧标题间距,减少重复信息。
|
||||
- 安全页新增白名单机制:可按发布者、应用目录或提示类型信任正常软件。
|
||||
- 已信任内容不再出现在默认列表和托盘计数中,可在安全页“已信任”筛选和“设置 → 安全”中查看、撤销。
|
||||
- 已确认威胁永远不会被白名单静默,目录信任也会拒绝系统目录、下载目录等过宽范围。
|
||||
|
||||
## [0.1.10] - 2026-11-20
|
||||
|
||||
- 重做应用图标:改用扁平双色设计,橙色圆角底加奶油色鱿鱼,去掉渐变与投影。
|
||||
- 重绘菜单栏单色图标,采用同一鱿鱼轮廓;侧边栏与“关于”页改用满版图标。
|
||||
- 设置页改为“常规 / 清理 / 安全 / 更新 / 关于”五个分区,常用项更集中。
|
||||
- 移除各页面大标题末尾的句号,标题更简洁。
|
||||
|
||||
## [0.1.9] - 2026-11-19
|
||||
|
||||
- 实时监控新增 CPU 面板:总体占用曲线,以及按逻辑核心排列的渐变占用柱。
|
||||
- 大幅降低实时监控的常驻 CPU 占用:主窗口收进托盘、小工具折叠或关闭全部面板时停止轮询;小工具与概览共用 2 秒轻量采样缓存。
|
||||
- 修复小工具自适应尺寸与重新停靠互相触发的问题,避免持续 IPC、重复写配置和 CPU 空转。
|
||||
- 日常清理新增“升级安装包”分类:识别微信、企业微信、WPS 等应用升级后遗留的安装包,并支持“跳过升级包,只删其余”。
|
||||
- Windows 全链路的“废纸篓”文案改为系统名称“回收站”,macOS 继续显示“废纸篓”。
|
||||
|
||||
## [0.1.8] - 2026-11-18
|
||||
|
||||
- 桌面小工具整合进“实时监控”:不再占用独立侧栏入口,可在监控页直接显示或隐藏。
|
||||
- 小工具设置移到窗口顶部:点击齿轮下拉即可调整面板、刷新频率、不透明度、停靠角和折叠记忆。
|
||||
- 日常清理与应用卸载移除主按钮上方的页头说明,保留原有间距。
|
||||
- 修复存储空间把应用包装挂载(nullfs)误识别为磁盘卷、导致根卷重复显示的问题。
|
||||
- 规则包尚未发布时,更新提示改为明确说明,而不是显示 curl 404。
|
||||
- 合并 Windows 权限管理、硬件规格、内存保留量、GPU 占用与桌面小工具等开发分支特性。
|
||||
- 系统托盘改用透明单色模板图标;macOS 随浅色/深色菜单栏自动着色。
|
||||
- Windows 安装器继续采用覆盖安装,并保留用户设置。
|
||||
|
||||
## [0.1.7] - 2026-11-08
|
||||
|
||||
- 概览页按新设计重做:智能维护、本机配置(系统、型号、处理器、内存、主硬盘、显卡)、处理器/内存/存储指标卡与日常维护入口。
|
||||
- 应用卸载列表与卸载方案显示应用真实图标;图标按需加载并缓存,读取失败时回退首字母。
|
||||
- 修复电池健康度:改用系统报告的 Maximum Capacity,Apple Silicon 不再把百分比再除以设计容量。
|
||||
- 修复 CPU 统计:使用全局占用和全部逻辑核心,不再把第一个核心当总量。
|
||||
- 修复内存统计:按 `vm_stat` 实际页大小解析 compressor / wired,并按 1024 进制显示。
|
||||
- 概览“本机配置”新增显卡信息(macOS `system_profiler`、Windows 注册表、Linux `lspci`)。
|
||||
- 启动项页按 macOS / Windows 自己的分法重做:“登录项 / 后台程序”页签,按安装它的应用分组,系统自带条目默认隐藏。
|
||||
- 启动项读取从 8.65 秒降到 0.34 秒。
|
||||
- 修复启动项、进程表与信任状态共 4 处 IPC 字段名不一致。
|
||||
- 修复进程表“由启动项启动”标记与筛选,按可执行文件路径关联启动项。
|
||||
- 修复带点名称的特权 helper 被误报未签名;新增“无法读取签名”状态。
|
||||
- 全部下拉菜单改为应用内自绘组件,列表统一为扁平分隔线。
|
||||
- 菜单第一项改名“概览”,除概览外移除重复的页面小标题,精简 22 处重复说明和 14 处冗长文案。
|
||||
|
||||
## [0.1.6] - 2026-11-07
|
||||
|
||||
- 新增“安全”页:恶意软件扫描(快速 / 全盘 / 自定义,都可取消)、按“已确认 / 可疑 / 提示”分级的发现列表、隔离区与恢复。
|
||||
- 新增“启动项”页:LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以直接停用与恢复。
|
||||
- 实时监控增加“进程”页签:全量进程表,含签名状态与所属启动项,可结束当前用户的进程,或对已确认恶意的文件“结束并隔离”。
|
||||
- 系统防护状态只读展示:macOS 读取 XProtect 版本与定义日期、启动/后台扫描与 Gatekeeper;Windows 读取当前杀毒产品、实时保护与定义版本。
|
||||
- 侧栏新增“保护”分组,入口共 10 个;快捷键调整为 `⌘7`/`⌘8` 安全与启动项,历史记录与设置顺延到 `⌘9`/`⌘0`。
|
||||
- 托盘与系统通知显示保护状态与待处理发现数量;点击通知直接进入发现列表。
|
||||
- 可选的定时扫描(登录后 / 每天 / 每周)、“自动隔离已确认项”(默认关闭)与独立于清理白名单的安全排除项。
|
||||
- 规则包:内置规则离线可用;可下载更新,校验大小与 SHA-256,并在构建内无公钥时明确标注“仅校验哈希 · 未验签”。
|
||||
- 不上传任何文件名、哈希、发现或隔离文件;不安装后台服务、内核扩展与常驻特权 helper。
|
||||
- 修复:桌面端二进制此前从未被 strip(`src-tauri` 独立于根 workspace,没有继承 release 配置),现已补上,universal 二进制减少约 20 MiB。
|
||||
|
||||
## [0.1.5] - 2026-11-05
|
||||
|
||||
- 语言默认跟随系统;macOS、Windows 与 Linux 分别读取对应的系统语言设置。
|
||||
- 语言设置只保留中文与 English 两项,切换后托盘菜单同步更新。
|
||||
- 设置中新增开机自启开关,使用当前用户级启动项,无需管理员权限。
|
||||
- 软件更新下载完成后的“放弃”按钮改为与 Shift 一致的中性描边样式。
|
||||
- 统一 Nex 暖色设计语言:界面只使用橙色主色、暖中性色与成功/警告/危险状态色。
|
||||
- README 提供双语首页以及完整的简体中文版和英文版。
|
||||
|
||||
## [0.1.4] - 2026-11-05
|
||||
|
||||
- 恢复左侧完整菜单:维护组包含“电脑概览、日常清理、应用卸载、深度清理”,洞察组包含“存储空间、实时监控”。
|
||||
- 保留 0.1.3 的托盘行为,关闭窗口后继续运行,可从托盘进入日常清理、应用卸载和深度清理。
|
||||
- 保留精简后的软件更新面板:仅发现新版本时显示版本变化与更新说明。
|
||||
- 按当前桌面端、CLI/TUI、共用引擎、安全边界和发布流程重新整理 README。
|
||||
|
||||
## [0.1.3] - 2026-11-05
|
||||
|
||||
- 隐藏更新面板中“已是最新版本”的重复提示。
|
||||
- 主导航精简为概览、日常清理和应用卸载。
|
||||
- Squid 关闭窗口后继续驻留托盘,可从托盘执行清理和深度清理。
|
||||
- 打包 macOS、Windows 与更新清单产物。
|
||||
|
||||
## 0.1.0 - 0.1.2
|
||||
|
||||
- 0.1.0:首个 macOS 磁盘清理版本,包含 CLI 与 TUI。
|
||||
- 0.1.1 - 0.1.2:补齐 Windows 平台层、回收站后端、30 条 Windows 清理规则与桌面安装包。逐项发布说明未保留。
|
||||
|
||||
## 发布约定
|
||||
|
||||
- 桌面安装包不提交到 `main`,只发布在 origin 仓库的 `releases` 分支。
|
||||
- GitHub 仓库只镜像源码,不承载 `releases` 分支;桌面端更新清单仍指向 origin 的发布通道。
|
||||
- 每个版本的安装包都必须通过大小与 SHA256 校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
Squid
|
||||
Copyright (C) 2026 mula.liu
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, version 3 only (GPL-3.0-only).
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
14
Cargo.toml
|
|
@ -4,12 +4,13 @@ members = ["crates/*"]
|
|||
exclude = ["src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.0"
|
||||
version = "0.1.14"
|
||||
edition = "2021"
|
||||
rust-version = "1.80"
|
||||
rust-version = "1.95"
|
||||
license = "GPL-3.0-only"
|
||||
authors = ["squid contributors"]
|
||||
repository = "https://github.com/nexdev/squid"
|
||||
authors = ["mula.liu"]
|
||||
repository = "https://github.com/VulpineLiu/squid"
|
||||
homepage = "https://github.com/VulpineLiu/squid"
|
||||
description = "squid — one tool for cleaning, uninstalling, purging and monitoring your machine"
|
||||
|
||||
[workspace.dependencies]
|
||||
|
|
@ -18,6 +19,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"
|
||||
|
|
@ -35,9 +37,9 @@ plist = "1"
|
|||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
sha2 = "0.10"
|
||||
filetime = "0.2"
|
||||
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"] }
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,362 @@
|
|||
# Squid
|
||||
|
||||
[简体中文](README.zh-CN.md) · [Bilingual home](README.md) · [Usage guide](docs/USAGE.md) · [Changelog](CHANGELOG.md)
|
||||
|
||||
**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, 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.
|
||||
|
||||
## Product surfaces
|
||||
|
||||
| Surface | Stack | Binary |
|
||||
| --- | --- | --- |
|
||||
| Desktop app | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
|
||||
| CLI | Rust + clap | `squid` |
|
||||
| TUI | Rust + ratatui + crossterm | `squid state` |
|
||||
|
||||
The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share the same Rust workspace.
|
||||
|
||||
## Download and install
|
||||
|
||||
Current version **0.1.14** (2026-11-25). Desktop installers are published on the origin repository's `releases` branch:
|
||||
|
||||
| Platform | Installer |
|
||||
| --- | --- |
|
||||
| macOS 12+ | [`Squid-0.1.14-macOS-universal.dmg`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-0.1.14-macOS-universal.dmg) |
|
||||
| Windows 10/11 x64 | [`Squid-Setup-0.1.14-win-x64.exe`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-Setup-0.1.14-win-x64.exe) |
|
||||
|
||||
Release directory: <https://git.unissense.tech/mula/nex_squid/src/branch/releases>
|
||||
|
||||
Both installers are unsigned builds. On macOS, right-click **Open** the first time; on Windows, choose **More info** > **Run anyway** when SmartScreen appears. See the [usage guide](docs/USAGE.md) for installation, daily use, uninstall, and troubleshooting.
|
||||
|
||||
The same installers are attached to the [GitHub release](https://github.com/VulpineLiu/squid/releases/tag/v0.1.14). The GitHub repository does not carry the `releases` branch. The app still checks the origin update channel.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Description |
|
||||
| --- | --- |
|
||||
| Overview | Disk health, common actions, and CPU, memory, and storage summaries |
|
||||
| Daily cleanup | 38 built-in rules on macOS and 30 on Windows, covering app and browser caches, logs, crash reports, developer caches, Trash, and more |
|
||||
| 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. 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 |
|
||||
| Permissions (Windows) | Registry Run keys, startup folders and scheduled tasks, shell context-menu handlers, popup-window rules and a background watcher |
|
||||
| Desktop widget | A borderless board pinned from Real-time monitor, with CPU / memory / GPU rings, network and disk curves, and storage bars; all settings open from the top of the widget |
|
||||
| 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 |
|
||||
|
||||
Language settings offer only Simplified Chinese and English, with the current system language selected by default. A manual choice is saved as the interface language for this computer.
|
||||
|
||||
## Desktop app
|
||||
|
||||
### Sidebar
|
||||
|
||||
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only)
|
||||
- **Protection**: Security, Startup items
|
||||
- **Insights**: Storage, Real-time monitor
|
||||
- **Bottom**: History, Settings
|
||||
|
||||
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages, in the
|
||||
sidebar order. Windows maps `1`–`9` to Overview, Daily cleanup, Uninstall apps,
|
||||
Deep Clean, Permissions, Storage, Real-time monitor, Security and Startup items.
|
||||
macOS hides the Windows-only Permissions screen, so the later pages shift up by
|
||||
one.
|
||||
|
||||
### 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
|
||||
- Show / hide desktop widget
|
||||
- Quit Squid
|
||||
|
||||
The tray mark is transparent and monochrome: macOS receives it as a template
|
||||
image, so the system tints it correctly for light and dark menu bars; Windows and
|
||||
Linux show the same silhouette in gray.
|
||||
|
||||
The tray follows the active interface language. Reopening the app, double-clicking the app icon, or triggering the single-instance handler restores and focuses the main window. Only **Quit Squid** ends the process.
|
||||
|
||||
### Desktop widget
|
||||
|
||||
The desktop widget is switched on from Real-time monitor. It is a separate
|
||||
borderless Tauri window, not a WidgetKit extension. It shares the Real-time
|
||||
monitor sampler, refreshes at 2 / 5 / 10 seconds, and pauses while hidden.
|
||||
|
||||
- Every setting lives in the widget: click the gear at its top to open panel
|
||||
switches, refresh rate, dock corner, fold memory and opacity.
|
||||
- Up to four cards: status (CPU, memory and GPU when the OS exposes it), network,
|
||||
disk I/O and storage volumes.
|
||||
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
|
||||
non-focusable with `accept_first_mouse`, so it stays beside the desktop without
|
||||
taking keyboard focus from the current app.
|
||||
- On Windows it sits on the desktop layer through
|
||||
`SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)`.
|
||||
- The master switch is shared with the tray item; opacity is capped at 90–100%
|
||||
and settings persist in `widget.json`.
|
||||
|
||||
### Software updates
|
||||
|
||||
- The system information panel always shows the current OS version, architecture, and Squid version.
|
||||
- Version changes, release notes, and actions appear only when a newer version exists; there is no duplicate "up to date" message.
|
||||
- After a verified download, install and restart, or use the neutral outlined **Discard** button that matches Shift to remove the downloaded file.
|
||||
- Automatic checks are enabled by default and run at most once per day.
|
||||
- The manifest comes from the origin `releases` branch; GitHub mirrors source only and does not carry that branch.
|
||||
- Installers must match the manifest's size and SHA256. Builds with a release public key also verify the manifest's Ed25519 signature.
|
||||
|
||||
### Permissions and privacy
|
||||
|
||||
- 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, 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
|
||||
|
||||
**Settings → Startup** includes a launch-at-login switch. When enabled, Squid starts automatically after the current user signs in and keeps its tray entry available. The setting is user-level and requires no administrator access.
|
||||
|
||||
See [`docs/DESKTOP.md`](docs/DESKTOP.md) for details.
|
||||
|
||||
## Quick start
|
||||
|
||||
### Desktop development
|
||||
|
||||
Requirements:
|
||||
|
||||
- Node.js 20+ and pnpm
|
||||
- Stable Rust
|
||||
- macOS: Xcode Command Line Tools
|
||||
- Windows: MSVC Build Tools and WebView2 Runtime
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm desktop:dev
|
||||
```
|
||||
|
||||
A plain Vite page cannot call Tauri commands. Use `pnpm desktop:dev` when testing scans, deletion, system data, or updates.
|
||||
|
||||
### CLI / TUI
|
||||
|
||||
```bash
|
||||
cargo install --path crates/squid-cli
|
||||
# or
|
||||
cargo build --release -p squid-cli
|
||||
|
||||
squid state # TUI
|
||||
squid status # system snapshot
|
||||
squid clean --dry-run # preview cleanable items
|
||||
squid uninstall --list # installed apps
|
||||
squid purge ~/code # project build artefacts
|
||||
squid analyze ~/Library/Caches # storage analysis
|
||||
squid history # deletion ledger
|
||||
squid undo # restore the latest Trash session
|
||||
```
|
||||
|
||||
Common commands:
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `clean` | Clean caches, logs, browser and developer junk, crash reports, and Trash by rule |
|
||||
| `uninstall [NAME]` | Locate an app and build an app-plus-leftovers uninstall plan |
|
||||
| `purge [PATHS…]` | Remove project build folders, disk images, installers, and stale downloads |
|
||||
| `state` | Open the TUI with cleanup, uninstall, deep clean, storage, system, and history panels |
|
||||
| `status` | Print a CPU, memory, network, disk, battery, and process snapshot |
|
||||
| `analyze [PATH]` | Print a directory-size tree and the largest files |
|
||||
| `history` / `undo [ID]` | Review history or restore a Trash session |
|
||||
| `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.
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
crates/
|
||||
├── squid-core models, paths, safety policy, settings, deletion ledger, progress, cancellation
|
||||
├── 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
|
||||
|
||||
src/ React desktop interface
|
||||
src-tauri/ Tauri shell, commands, tray, permission checks, and updater
|
||||
scripts/ development, verification, and dual-platform release scripts
|
||||
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-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.
|
||||
|
||||
## Safety model
|
||||
|
||||
1. **Index-based deletion**: the desktop UI can only submit indexes from a scan, never arbitrary paths.
|
||||
2. **Revalidation before execution**: the Rust layer rebuilds each item and rechecks ownership, safety anchors, protected locations, the whitelist, and lock state.
|
||||
3. **Trash by default**: deletion mode defaults to `trash`; files are removed directly only when permanent deletion is explicitly selected.
|
||||
4. **Hard boundaries**: system roots, `/usr`, `/System`, `/Applications`, and similar locations cannot be recursively deleted. Symlinks are never followed.
|
||||
5. **Rule brakes**: rules support `protect`, `min_age_days`, `skip_if_running`, and `risky`.
|
||||
6. **Ledger and undo**: real deletions are recorded in a local JSON ledger; files still in Trash can be restored.
|
||||
7. **Process protection**: the process is sampled again before termination; Squid itself, PID 1, and critical system processes are refused.
|
||||
|
||||
The GUI and CLI use the same `squid-engine::delete` path, so behavior, locks, and audit results stay consistent.
|
||||
|
||||
## Data and configuration
|
||||
|
||||
| Purpose | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| Configuration and rules | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
|
||||
| History ledger | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
|
||||
| Delete destination | `~/.Trash` or permanent deletion | Recycle Bin or permanent deletion |
|
||||
|
||||
Linux uses XDG directories. The desktop app and CLI/TUI share configuration and history, so a cleanup from either surface is visible in the other.
|
||||
|
||||
Common configuration:
|
||||
|
||||
```toml
|
||||
delete_mode = "trash"
|
||||
history_keep = 60
|
||||
purge_min_age_days = 7
|
||||
purge_max_entries = 200000
|
||||
show_allocated = true
|
||||
# Empty or omitted means "follow system"; set "en" or "zh" to override
|
||||
language = ""
|
||||
whitelist = ["~/Library/Caches/ImportantApp"]
|
||||
disabled_rules = ["user-trash"]
|
||||
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
|
||||
```
|
||||
|
||||
Main environment variables:
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `SQUID_CONFIG_DIR` | Override the configuration directory |
|
||||
| `SQUID_STATE_DIR` | Override the state and history directory |
|
||||
| `SQUID_LANG` | Force the CLI/TUI language to `zh` or `en` |
|
||||
| `SQUID_UPDATE_URL` | Override the desktop update manifest URL for staging |
|
||||
| `SQUID_TRUECOLOR` / `NO_COLOR` | Control TUI color |
|
||||
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | Diagnose Windows console character width and layout |
|
||||
|
||||
`SQUID_LANG` is a CLI override. The desktop app's default language comes from the system and can be changed in the app.
|
||||
|
||||
## Development and verification
|
||||
|
||||
Frontend:
|
||||
|
||||
```bash
|
||||
pnpm check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Rust workspace:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace --no-fail-fast
|
||||
```
|
||||
|
||||
Tauri:
|
||||
|
||||
```bash
|
||||
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
|
||||
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
The TUI uses a real-pty smoke test; Windows consoles also have a capture, replay, and frame-check test:
|
||||
|
||||
```bash
|
||||
python3 -m pip install --user pyte
|
||||
python3 scripts/tui_smoke.py
|
||||
python3 scripts/tui-frame-check.py --selftest
|
||||
```
|
||||
|
||||
CI runs workspace tests, an MSVC target cross-check, the desktop frontend build, and the Tauri Rust check.
|
||||
|
||||
## Build and release
|
||||
|
||||
Keep the version identical in all four places:
|
||||
|
||||
- `Cargo.toml` workspace version
|
||||
- `src-tauri/Cargo.toml`
|
||||
- `src-tauri/tauri.conf.json`
|
||||
- `package.json`
|
||||
|
||||
Build installers:
|
||||
|
||||
```bash
|
||||
scripts/build-macos-release.sh
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
Artifacts:
|
||||
|
||||
```text
|
||||
artifacts/Squid-<version>-macOS-universal.dmg
|
||||
artifacts/Squid-Setup-<version>-win-x64.exe
|
||||
artifacts/SHA256SUMS.txt
|
||||
```
|
||||
|
||||
Publish to the update channel:
|
||||
|
||||
```bash
|
||||
scripts/publish-release.sh --notes /path/to/release-notes.md
|
||||
```
|
||||
|
||||
The publish script rebuilds the `releases` branch with `squid-update.json`, both installers, and an optional `squid-update.sig`. The manifest records exact size and SHA256, which the client verifies again after download.
|
||||
|
||||
See [`docs/RELEASE.md`](docs/RELEASE.md) for the full release, signing, and manifest process.
|
||||
|
||||
The GitHub repository receives source branches such as `main` only. It never receives `releases`; sync it with `scripts/sync-github.sh`, which strips release installers from GitHub history and therefore rewrites commit hashes. GitHub clones keep using the origin update channel.
|
||||
|
||||
## Platform status
|
||||
|
||||
| Platform | Status |
|
||||
| --- | --- |
|
||||
| macOS | Full desktop and CLI/TUI support; universal DMG |
|
||||
| Windows x64 | Desktop and CLI/TUI support; NSIS installer |
|
||||
| Linux | Platform layer and basic CLI/TUI support; built-in rules and desktop installers are not yet provided |
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Usage guide](docs/USAGE.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
- [Architecture](docs/ARCHITECTURE.md)
|
||||
- [Desktop app](docs/DESKTOP.md)
|
||||
- [Release and updates](docs/RELEASE.md)
|
||||
- [Security](docs/SECURITY.md)
|
||||
|
||||
## License
|
||||
|
||||
Squid is licensed under **GNU General Public License v3.0 only** (`GPL-3.0-only`).
|
||||
|
||||
Copyright © 2026 mula.liu. See [`LICENSE`](LICENSE) and [`COPYRIGHT`](COPYRIGHT).
|
||||
292
README.md
292
README.md
|
|
@ -1,279 +1,81 @@
|
|||
# Squid
|
||||
|
||||
**给你的电脑洗个澡。**
|
||||
**给你的电脑洗个澡。** · **Give your computer a bath.**
|
||||
|
||||
Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建的缓存与系统垃圾、卸载应用并处理残留、清理项目构建产物、分析磁盘占用,以及实时查看系统状态。
|
||||
[简体中文](README.zh-CN.md) · [English](README.en.md) · [使用帮助](docs/USAGE.zh-CN.md) · [Usage guide](docs/USAGE.md) · [更新日志](CHANGELOG.md)
|
||||
|
||||
桌面端、命令行与 TUI 共用同一套 Rust 扫描和删除引擎。清理规则、安全边界、删除账本与配置只维护一份,不依赖云端服务,也不需要 root。
|
||||
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 monitors live system health.
|
||||
|
||||
## 产品组成
|
||||
Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI 与 TUI 共用同一套 Rust 扫描和删除引擎,不依赖云端服务,也不需要 root。
|
||||
|
||||
| 入口 | 技术栈 | 二进制 |
|
||||
| --- | --- | --- |
|
||||
| 桌面应用 | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
|
||||
| 命令行 | Rust + clap | `squid` |
|
||||
| 终端界面 | Rust + ratatui + crossterm | `squid state` |
|
||||
## Download / 下载
|
||||
|
||||
桌面端支持 macOS 12+ 与 Windows 10/11 x64;CLI/TUI 使用同一个 Rust workspace。
|
||||
Latest release: **0.1.14** (2026-11-25).
|
||||
|
||||
## 功能
|
||||
|
||||
| 功能 | 说明 |
|
||||
| Platform | Package |
|
||||
| --- | --- |
|
||||
| 电脑概览 | 磁盘健康、常用操作入口与 CPU、内存、存储摘要 |
|
||||
| 日常清理 | macOS 38 条 / Windows 30 条内置规则,覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存与废纸篓等 |
|
||||
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
|
||||
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
|
||||
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
|
||||
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程 |
|
||||
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
|
||||
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
|
||||
| macOS 12+ | [`Squid-0.1.14-macOS-universal.dmg`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-0.1.14-macOS-universal.dmg) |
|
||||
| Windows 10/11 x64 | [`Squid-Setup-0.1.14-win-x64.exe`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-Setup-0.1.14-win-x64.exe) |
|
||||
|
||||
界面支持中文和英文,跟随 Squid 的语言设置与系统语言。
|
||||
Installers live on the origin repository's `releases` branch:
|
||||
<https://git.unissense.tech/mula/nex_squid/src/branch/releases>
|
||||
|
||||
## 桌面应用
|
||||
The same installers are attached to the [GitHub release](https://github.com/VulpineLiu/squid/releases/tag/v0.1.14). The GitHub repository does not carry the `releases` branch, and the app's update feed still points at the origin channel.
|
||||
|
||||
### 左侧菜单
|
||||
安装包发布在 origin 仓库的 `releases` 分支,并同步附到 [GitHub Release](https://github.com/VulpineLiu/squid/releases/tag/v0.1.14)。GitHub 不承载 `releases` 分支;应用更新仍从 origin 的发布通道检查。
|
||||
|
||||
- **维护**:电脑概览、日常清理、应用卸载、深度清理
|
||||
- **洞察**:存储空间、实时监控
|
||||
- **底部**:历史记录、设置
|
||||
## Highlights / 功能
|
||||
|
||||
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+8`(Windows)可以直接切换页面。
|
||||
- **Daily cleanup / 日常清理** — 38 macOS rules and 30 Windows rules for caches, logs, crash reports, developer data, upgrade installers, and Trash.
|
||||
- **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, reversible quarantine, and a trust allowlist. 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.
|
||||
- **Desktop widget / 桌面小工具** — Pin the Real-time monitor to the desktop as a focus-free board.
|
||||
- **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.
|
||||
|
||||
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
|
||||
界面默认跟随系统语言,可在设置中切换简体中文或 English。
|
||||
|
||||
- 打开 Squid
|
||||
- 日常清理
|
||||
- 应用卸载
|
||||
- 深度清理
|
||||
- 退出 Squid
|
||||
## Start / 开始
|
||||
|
||||
再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
|
||||
|
||||
### 软件更新
|
||||
|
||||
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。
|
||||
- 只有检测到更高版本时,才显示版本变化和更新说明;已经是最新版本时不显示额外提示。
|
||||
- 自动检查默认开启,每天最多检查一次。
|
||||
- 安装包必须通过 SHA256 与文件大小校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
|
||||
|
||||
### 权限与隐私
|
||||
|
||||
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
|
||||
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
|
||||
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用。
|
||||
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
|
||||
- 除更新检查和安装包下载外,应用不发起网络请求。
|
||||
|
||||
完整说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md)。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 桌面端开发
|
||||
|
||||
环境要求:
|
||||
|
||||
- Node.js 20+ 与 pnpm
|
||||
- Rust stable
|
||||
- macOS:Xcode Command Line Tools
|
||||
- Windows:MSVC Build Tools 与 WebView2 Runtime
|
||||
Desktop development:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm desktop:dev
|
||||
```
|
||||
|
||||
仅运行 Vite 页面时无法调用 Tauri 命令;需要验证扫描、删除、系统数据或更新流程时请使用 `pnpm desktop:dev`。
|
||||
|
||||
### CLI / TUI
|
||||
CLI / TUI:
|
||||
|
||||
```bash
|
||||
cargo install --path crates/squid-cli
|
||||
# 或
|
||||
cargo build --release -p squid-cli
|
||||
|
||||
squid state # TUI
|
||||
squid status # 系统快照
|
||||
squid clean --dry-run # 预览可清理内容
|
||||
squid uninstall --list # 已安装应用
|
||||
squid purge ~/code # 深度清理项目构建产物
|
||||
squid analyze ~/Library/Caches # 存储分析
|
||||
squid history # 历史账本
|
||||
squid undo # 还原最近一次废纸篓会话
|
||||
cargo install --path crates/squid-cli --locked
|
||||
squid state
|
||||
squid clean --dry-run
|
||||
```
|
||||
|
||||
常用命令:
|
||||
## Documentation / 文档
|
||||
|
||||
| 命令 | 作用 |
|
||||
| --- | --- |
|
||||
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告和废纸篓 |
|
||||
| `uninstall [NAME]` | 定位应用并生成“本体 + 残留”卸载计划 |
|
||||
| `purge [PATHS…]` | 清理项目构建目录、磁盘镜像、安装包与陈旧下载 |
|
||||
| `state` | 打开包含清理、卸载、深度清理、存储、系统和历史面板的 TUI |
|
||||
| `status` | 输出 CPU、内存、网络、磁盘、电池与进程快照 |
|
||||
| `analyze [PATH]` | 输出目录体积树与最大文件 |
|
||||
| `history` / `undo [ID]` | 查看历史或还原废纸篓会话 |
|
||||
| `whitelist add\|list\|remove` | 维护永不选中的保护路径 |
|
||||
| `rules` | 列出当前生效的规则 |
|
||||
| `doctor` | 检查权限、配置、历史文件和生效路径 |
|
||||
- [中文完整说明](README.zh-CN.md)
|
||||
- [Full English guide](README.en.md)
|
||||
- [中文使用帮助](docs/USAGE.zh-CN.md)
|
||||
- [English usage guide](docs/USAGE.md)
|
||||
- [更新日志 / Changelog](CHANGELOG.md)
|
||||
- [Architecture / 架构](docs/ARCHITECTURE.md)
|
||||
- [Nex design standard / 设计规范](docs/DESIGN.md)
|
||||
- [Desktop / 桌面端](docs/DESKTOP.md)
|
||||
- [Release and updates / 发布与更新](docs/RELEASE.md)
|
||||
- [Security / 安全](docs/SECURITY.md)
|
||||
|
||||
所有删除命令都支持 `--dry-run`;非交互环境必须使用 `-y/--yes`。完整参数请运行 `squid <command> --help`。
|
||||
## Project / 项目
|
||||
|
||||
## 架构
|
||||
- Source mirror: <https://github.com/VulpineLiu/squid>
|
||||
- Origin and update channel: <https://git.unissense.tech/mula/nex_squid>
|
||||
|
||||
```text
|
||||
crates/
|
||||
├── squid-core 模型、路径、安全策略、设置、删除账本、进度与取消
|
||||
├── squid-platform macOS / Linux / Windows 平台适配:应用、残留、卷、回收站、进程
|
||||
├── squid-rules TOML 规则引擎:模式展开、锚点、保护、年龄与风险标记
|
||||
├── squid-stats sysinfo 采样、趋势、电池、网络与磁盘活动
|
||||
├── squid-engine clean / uninstall / purge / analyze 与唯一删除通道
|
||||
├── squid-tui ratatui 终端界面
|
||||
└── squid-cli clap 命令行入口
|
||||
## License / 许可证
|
||||
|
||||
src/ React 桌面界面
|
||||
src-tauri/ Tauri 壳、命令适配、托盘、权限检查与更新器
|
||||
scripts/ 开发、验证与双平台发布脚本
|
||||
docs/ 架构、设计、桌面与发布规范
|
||||
```
|
||||
**GNU General Public License v3.0 only** (`GPL-3.0-only`).
|
||||
|
||||
核心依赖方向:
|
||||
|
||||
```text
|
||||
squid-core → squid-platform → squid-rules → squid-stats → squid-engine → squid-tui → squid-cli
|
||||
```
|
||||
|
||||
`src-tauri` 独立于根 Cargo workspace,但直接依赖 `squid-core`、`squid-platform`、`squid-stats` 与 `squid-engine`,桌面端不维护第二套清理实现。
|
||||
|
||||
更多设计见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md);Nex 系列统一颜色、字体和组件常量见 [`docs/DESIGN.md`](docs/DESIGN.md)。
|
||||
|
||||
## 安全模型
|
||||
|
||||
1. **索引式删除**:桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
|
||||
2. **执行前复验**:Rust 层重新构造扫描条目,并检查路径所有权、安全锚点、保护列表、白名单与锁定状态。
|
||||
3. **默认进废纸篓**:删除模式默认是 `trash`;只有显式选择永久删除才直接移除。
|
||||
4. **硬性禁区**:系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除;符号链接不会被跟随。
|
||||
5. **规则刹车**:规则支持 `protect`、`min_age_days`、`skip_if_running` 与 `risky` 标记。
|
||||
6. **账本与撤销**:真实删除记录到本地 JSON 账本,仍在废纸篓中的文件可以还原。
|
||||
7. **进程保护**:结束进程前重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
|
||||
|
||||
GUI 和 CLI 使用同一个 `squid-engine::delete` 通道,因此行为、锁定和审计结果一致。
|
||||
|
||||
## 数据与配置
|
||||
|
||||
| 用途 | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
|
||||
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
|
||||
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
|
||||
|
||||
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史,因此任一端产生的清理记录都能在另一端查看。
|
||||
|
||||
常用配置:
|
||||
|
||||
```toml
|
||||
delete_mode = "trash"
|
||||
history_keep = 60
|
||||
purge_min_age_days = 7
|
||||
purge_max_entries = 200000
|
||||
show_allocated = true
|
||||
language = "zh" # en | zh
|
||||
whitelist = ["~/Library/Caches/ImportantApp"]
|
||||
disabled_rules = ["user-trash"]
|
||||
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
|
||||
```
|
||||
|
||||
主要环境变量:
|
||||
|
||||
| 变量 | 作用 |
|
||||
| --- | --- |
|
||||
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
|
||||
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
|
||||
| `SQUID_LANG` | 强制 `zh` 或 `en` |
|
||||
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
|
||||
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
|
||||
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
|
||||
|
||||
## 开发与验证
|
||||
|
||||
前端:
|
||||
|
||||
```bash
|
||||
pnpm check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Rust workspace:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
Tauri:
|
||||
|
||||
```bash
|
||||
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
|
||||
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
TUI 使用真实 pty 冒烟测试;Windows 控制台另有“抓帧、复放、量框”验证:
|
||||
|
||||
```bash
|
||||
python3 -m pip install --user pyte
|
||||
python3 scripts/tui_smoke.py
|
||||
python3 scripts/tui-frame-check.py --selftest
|
||||
```
|
||||
|
||||
CI 同时执行 workspace 测试、MSVC 目标交叉检查、桌面前端构建和 Tauri Rust 检查。
|
||||
|
||||
## 打包与发布
|
||||
|
||||
版本必须同时写入以下四处:
|
||||
|
||||
- `Cargo.toml` workspace 版本
|
||||
- `src-tauri/Cargo.toml`
|
||||
- `src-tauri/tauri.conf.json`
|
||||
- `package.json`
|
||||
|
||||
构建安装包:
|
||||
|
||||
```bash
|
||||
scripts/build-macos-release.sh
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
产物:
|
||||
|
||||
```text
|
||||
artifacts/Squid-<version>-macOS-universal.dmg
|
||||
artifacts/Squid-Setup-<version>-win-x64.exe
|
||||
artifacts/SHA256SUMS.txt
|
||||
```
|
||||
|
||||
发布到更新通道:
|
||||
|
||||
```bash
|
||||
scripts/publish-release.sh --notes /path/to/release-notes.md
|
||||
```
|
||||
|
||||
发布脚本会重建 `releases` 分支,写入 `squid-update.json`、两个安装包和可选的 `squid-update.sig`。清单包含精确大小与 SHA256,客户端下载后再次校验。
|
||||
|
||||
完整发布流程、签名和清单格式见 [`docs/RELEASE.md`](docs/RELEASE.md)。
|
||||
|
||||
## 平台状态
|
||||
|
||||
| 平台 | 状态 |
|
||||
| --- | --- |
|
||||
| macOS | 桌面端与 CLI/TUI 完整支持,发布通用 DMG |
|
||||
| Windows x64 | 桌面端与 CLI/TUI 支持,发布 NSIS 安装包 |
|
||||
| Linux | 平台层与 CLI/TUI 基础实现;尚未提供内置 Linux 规则和桌面安装包 |
|
||||
|
||||
## 许可证
|
||||
|
||||
Squid 使用 **GNU General Public License v3.0 only**(`GPL-3.0-only`)。完整条款见 [`LICENSE`](LICENSE)。
|
||||
Copyright © 2026 mula.liu. See [`LICENSE`](LICENSE) and [`COPYRIGHT`](COPYRIGHT).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,342 @@
|
|||
# Squid
|
||||
|
||||
[English](README.en.md) · [返回双语首页](README.md) · [使用帮助](docs/USAGE.zh-CN.md) · [更新日志](CHANGELOG.md)
|
||||
|
||||
**给你的电脑洗个澡。**
|
||||
|
||||
Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建的缓存与系统垃圾、卸载应用并处理残留、清理项目构建产物、分析磁盘占用,以及实时查看系统状态。
|
||||
|
||||
桌面端、命令行与 TUI 共用同一套 Rust 扫描和删除引擎。清理规则、安全边界、删除账本与配置只维护一份,不依赖云端服务,也不需要 root。
|
||||
|
||||
## 产品组成
|
||||
|
||||
| 入口 | 技术栈 | 二进制 |
|
||||
| --- | --- | --- |
|
||||
| 桌面应用 | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
|
||||
| 命令行 | Rust + clap | `squid` |
|
||||
| 终端界面 | Rust + ratatui + crossterm | `squid state` |
|
||||
|
||||
桌面端支持 macOS 12+ 与 Windows 10/11 x64;CLI/TUI 使用同一个 Rust workspace。
|
||||
|
||||
## 下载与安装
|
||||
|
||||
当前版本 **0.1.14**(2026-11-25)。桌面安装包发布在 origin 仓库的 `releases` 分支:
|
||||
|
||||
| 平台 | 安装包 |
|
||||
| --- | --- |
|
||||
| macOS 12+ | [`Squid-0.1.14-macOS-universal.dmg`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-0.1.14-macOS-universal.dmg) |
|
||||
| Windows 10/11 x64 | [`Squid-Setup-0.1.14-win-x64.exe`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-Setup-0.1.14-win-x64.exe) |
|
||||
|
||||
发布目录:<https://git.unissense.tech/mula/nex_squid/src/branch/releases>
|
||||
|
||||
两个安装包都是未签名构建。macOS 首次打开请在访达中右键选择“打开”;Windows SmartScreen 提示时选择“更多信息” > “仍要运行”。完整的安装、使用、卸载与故障排查见[使用帮助](docs/USAGE.zh-CN.md)。
|
||||
|
||||
同一批安装包也会附到 [GitHub Release](https://github.com/VulpineLiu/squid/releases/tag/v0.1.14)。GitHub 不承载 `releases` 分支;应用更新仍从 origin 的发布通道检查。
|
||||
|
||||
## 功能
|
||||
|
||||
| 功能 | 说明 |
|
||||
| --- | --- |
|
||||
| 概览 | 磁盘健康、常用操作入口与 CPU、内存、存储摘要 |
|
||||
| 日常清理 | macOS 38 条 / Windows 30 条内置规则,覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存与废纸篓等 |
|
||||
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
|
||||
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
|
||||
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
|
||||
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 |
|
||||
| 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 |
|
||||
| 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 |
|
||||
| 权限管理(Windows) | 注册表 Run、启动文件夹与计划任务,右键菜单扩展,弹窗窗口规则与后台监听 |
|
||||
| 桌面小工具 | 在实时监控中一键固定到桌面的无边框看板:CPU / 内存 / GPU 圆环、网络与磁盘曲线、存储空间;设置从小工具顶部下拉打开 |
|
||||
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
|
||||
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
|
||||
|
||||
语言设置只提供简体中文与 English 两项,首次使用时默认选中当前系统语言。手动选择会保存为该电脑上的界面语言。
|
||||
|
||||
## 桌面应用
|
||||
|
||||
### 左侧菜单
|
||||
|
||||
- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows)
|
||||
- **保护**:安全、启动项
|
||||
- **洞察**:存储空间、实时监控
|
||||
- **底部**:历史记录、设置
|
||||
|
||||
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+9`(Windows)按上面的侧栏顺序切换页面。
|
||||
Windows 上 `1`–`9` 依次是概览、日常清理、应用卸载、深度清理、权限管理、存储空间、实时监控、安全、启动项;macOS 隐藏 Windows 专属的权限管理,后续页面顺延。
|
||||
|
||||
### 常驻托盘
|
||||
|
||||
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
|
||||
|
||||
- 打开 Squid
|
||||
- 保护状态(只读状态行)
|
||||
- 扫描恶意软件
|
||||
- 管理启动项
|
||||
- 日常清理
|
||||
- 应用卸载
|
||||
- 深度清理
|
||||
- 显示/隐藏桌面小工具
|
||||
- 退出 Squid
|
||||
|
||||
托盘图标是透明单色素材:macOS 使用模板图标,由系统按浅色/深色菜单栏自动着色;Windows 与 Linux 显示同一轮廓的灰色图标。
|
||||
|
||||
托盘菜单跟随当前界面语言。再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
|
||||
|
||||
### 桌面小工具
|
||||
|
||||
桌面小工具由“实时监控”页面统一开关,是一个独立的无边框 Tauri 窗口,不是 WidgetKit 扩展。它复用实时监控的采样器,按 2 / 5 / 10 秒节奏刷新,隐藏时暂停采样。
|
||||
|
||||
- 设置全部位于小工具本身:点击顶部齿轮即可下拉打开面板、更新频率、边角停靠、折叠记忆与面板开关。
|
||||
- 最多四张卡片:运行状态(CPU、内存、系统暴露的 GPU 占用)、网络、存储读写、存储空间。
|
||||
- macOS 上使用 `BelowNormal` 窗口层级、出现在所有 Space,并设置为不可获得焦点且接受首次点击,因此贴着桌面显示、不会抢走当前应用的键盘焦点。
|
||||
- Windows 上通过 `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` 停在桌面层。
|
||||
- 总开关与托盘菜单同步;不透明度限制在 90–100%,配置保存在 `widget.json`。
|
||||
|
||||
### 软件更新
|
||||
|
||||
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。
|
||||
- 只有检测到更高版本时,才显示版本变化、更新说明和操作按钮;已经是最新版本时不显示额外提示。
|
||||
- 下载完成后可安装并重启,或用与 Shift 一致的中性描边“放弃”按钮清除已下载文件。
|
||||
- 自动检查默认开启,每天最多检查一次。
|
||||
- 更新清单来自项目 origin 的 `releases` 分支;GitHub 仅镜像源码,不承载发布分支。
|
||||
- 安装包必须通过 SHA256 与文件大小校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
|
||||
|
||||
### 权限与隐私
|
||||
|
||||
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
|
||||
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
|
||||
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用;安全页会把覆盖范围标为「受限」,不会显示成干净。
|
||||
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
|
||||
- 除更新检查、安装包下载与规则包下载外,应用不发起网络请求。**任何内容都不会上传**:
|
||||
文件名、哈希、扫描结果与被隔离的文件都不会离开这台电脑。
|
||||
- 安全扫描不安装 daemon、内核扩展或特权 helper。实时防护仍由 XProtect / Defender 承担,
|
||||
Squid 只读取它们的状态,不会替你关闭,也不会替你调用 `xprotect update`。
|
||||
|
||||
### 开机自启
|
||||
|
||||
“设置 → 启动”提供开机自启开关。启用后 Squid 会在当前用户登录时自动启动并保留托盘入口;该设置只写入当前用户级启动项,不需要管理员权限。
|
||||
|
||||
完整说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md)。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 桌面端开发
|
||||
|
||||
环境要求:
|
||||
|
||||
- Node.js 20+ 与 pnpm
|
||||
- Rust stable
|
||||
- macOS:Xcode Command Line Tools
|
||||
- Windows:MSVC Build Tools 与 WebView2 Runtime
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm desktop:dev
|
||||
```
|
||||
|
||||
仅运行 Vite 页面时无法调用 Tauri 命令;需要验证扫描、删除、系统数据或更新流程时请使用 `pnpm desktop:dev`。
|
||||
|
||||
### CLI / TUI
|
||||
|
||||
```bash
|
||||
cargo install --path crates/squid-cli
|
||||
# 或
|
||||
cargo build --release -p squid-cli
|
||||
|
||||
squid state # TUI
|
||||
squid status # 系统快照
|
||||
squid clean --dry-run # 预览可清理内容
|
||||
squid uninstall --list # 已安装应用
|
||||
squid purge ~/code # 深度清理项目构建产物
|
||||
squid analyze ~/Library/Caches # 存储分析
|
||||
squid history # 历史账本
|
||||
squid undo # 还原最近一次废纸篓会话
|
||||
```
|
||||
|
||||
常用命令:
|
||||
|
||||
| 命令 | 作用 |
|
||||
| --- | --- |
|
||||
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告和废纸篓 |
|
||||
| `uninstall [NAME]` | 定位应用并生成“本体 + 残留”卸载计划 |
|
||||
| `purge [PATHS…]` | 清理项目构建目录、磁盘镜像、安装包与陈旧下载 |
|
||||
| `state` | 打开包含清理、卸载、深度清理、存储、系统和历史面板的 TUI |
|
||||
| `status` | 输出 CPU、内存、网络、磁盘、电池与进程快照 |
|
||||
| `analyze [PATH]` | 输出目录体积树与最大文件 |
|
||||
| `history` / `undo [ID]` | 查看历史或还原废纸篓会话 |
|
||||
| `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`。
|
||||
|
||||
## 架构
|
||||
|
||||
```text
|
||||
crates/
|
||||
├── squid-core 模型、路径、安全策略、设置、删除账本、进度与取消
|
||||
├── squid-platform macOS / Linux / Windows 平台适配:应用、残留、卷、回收站、进程
|
||||
├── squid-rules TOML 规则引擎:模式展开、锚点、保护、年龄与风险标记
|
||||
├── squid-stats sysinfo 采样、趋势、电池、网络与磁盘活动
|
||||
├── squid-engine clean / uninstall / purge / analyze 与唯一删除通道
|
||||
├── squid-tui ratatui 终端界面
|
||||
└── squid-cli clap 命令行入口
|
||||
|
||||
src/ React 桌面界面
|
||||
src-tauri/ Tauri 壳、命令适配、托盘、权限检查与更新器
|
||||
scripts/ 开发、验证与双平台发布脚本
|
||||
docs/ 架构、设计、桌面与发布规范
|
||||
```
|
||||
|
||||
`src-tauri` 独立于根 Cargo workspace,但直接依赖 `squid-core`、`squid-platform`、`squid-stats` 与 `squid-engine`,桌面端不维护第二套清理实现。
|
||||
|
||||
更多设计见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md);Nex 系列统一颜色、字体、组件和语言规范见 [`docs/DESIGN.md`](docs/DESIGN.md)。
|
||||
|
||||
## 安全模型
|
||||
|
||||
1. **索引式删除**:桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
|
||||
2. **执行前复验**:Rust 层重新构造扫描条目,并检查路径所有权、安全锚点、保护列表、白名单与锁定状态。
|
||||
3. **默认进废纸篓**:删除模式默认是 `trash`;只有显式选择永久删除才直接移除。
|
||||
4. **硬性禁区**:系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除;符号链接不会被跟随。
|
||||
5. **规则刹车**:规则支持 `protect`、`min_age_days`、`skip_if_running` 与 `risky` 标记。
|
||||
6. **账本与撤销**:真实删除记录到本地 JSON 账本,仍在废纸篓中的文件可以还原。
|
||||
7. **进程保护**:结束进程前重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
|
||||
|
||||
GUI 和 CLI 使用同一个 `squid-engine::delete` 通道,因此行为、锁定和审计结果一致。
|
||||
|
||||
## 数据与配置
|
||||
|
||||
| 用途 | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
|
||||
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
|
||||
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
|
||||
|
||||
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史,因此任一端产生的清理记录都能在另一端查看。
|
||||
|
||||
常用配置:
|
||||
|
||||
```toml
|
||||
delete_mode = "trash"
|
||||
history_keep = 60
|
||||
purge_min_age_days = 7
|
||||
purge_max_entries = 200000
|
||||
show_allocated = true
|
||||
# language 留空或删除表示跟随系统;也可手动设为 "en" 或 "zh"
|
||||
language = ""
|
||||
whitelist = ["~/Library/Caches/ImportantApp"]
|
||||
disabled_rules = ["user-trash"]
|
||||
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
|
||||
```
|
||||
|
||||
主要环境变量:
|
||||
|
||||
| 变量 | 作用 |
|
||||
| --- | --- |
|
||||
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
|
||||
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
|
||||
| `SQUID_LANG` | 强制 CLI/TUI 使用 `zh` 或 `en` |
|
||||
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
|
||||
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
|
||||
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
|
||||
|
||||
`SQUID_LANG` 是命令行覆盖项;桌面界面的默认语言来自系统设置,并可在应用内修改。
|
||||
|
||||
## 开发与验证
|
||||
|
||||
前端:
|
||||
|
||||
```bash
|
||||
pnpm check
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Rust workspace:
|
||||
|
||||
```bash
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace --no-fail-fast
|
||||
```
|
||||
|
||||
Tauri:
|
||||
|
||||
```bash
|
||||
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
|
||||
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
TUI 使用真实 pty 冒烟测试;Windows 控制台另有“抓帧、复放、量框”验证:
|
||||
|
||||
```bash
|
||||
python3 -m pip install --user pyte
|
||||
python3 scripts/tui_smoke.py
|
||||
python3 scripts/tui-frame-check.py --selftest
|
||||
```
|
||||
|
||||
CI 同时执行 workspace 测试、MSVC 目标交叉检查、桌面前端构建和 Tauri Rust 检查。
|
||||
|
||||
## 打包与发布
|
||||
|
||||
版本必须同时写入以下四处:
|
||||
|
||||
- `Cargo.toml` workspace 版本
|
||||
- `src-tauri/Cargo.toml`
|
||||
- `src-tauri/tauri.conf.json`
|
||||
- `package.json`
|
||||
|
||||
构建安装包:
|
||||
|
||||
```bash
|
||||
scripts/build-macos-release.sh
|
||||
scripts/build-windows-release.sh
|
||||
```
|
||||
|
||||
产物:
|
||||
|
||||
```text
|
||||
artifacts/Squid-<version>-macOS-universal.dmg
|
||||
artifacts/Squid-Setup-<version>-win-x64.exe
|
||||
artifacts/SHA256SUMS.txt
|
||||
```
|
||||
|
||||
发布到更新通道:
|
||||
|
||||
```bash
|
||||
scripts/publish-release.sh --notes /path/to/release-notes.md
|
||||
```
|
||||
|
||||
发布脚本会重建 `releases` 分支,写入 `squid-update.json`、两个安装包和可选的 `squid-update.sig`。清单包含精确大小与 SHA256,客户端下载后再次校验。
|
||||
|
||||
完整发布流程、签名和清单格式见 [`docs/RELEASE.md`](docs/RELEASE.md)。
|
||||
|
||||
GitHub 仓库只保留源码分支(当前为 `main`),不承载 `releases`。同步使用 `scripts/sync-github.sh`;该脚本会从 GitHub 历史中剔除发布安装包,因此 GitHub 的提交哈希与 origin 不同。GitHub 上的源码镜像继续使用 origin 的发布通道。
|
||||
|
||||
## 平台状态
|
||||
|
||||
| 平台 | 状态 |
|
||||
| --- | --- |
|
||||
| macOS | 桌面端与 CLI/TUI 完整支持,发布通用 DMG |
|
||||
| Windows x64 | 桌面端与 CLI/TUI 支持,发布 NSIS 安装包 |
|
||||
| Linux | 平台层与 CLI/TUI 基础实现;尚未提供内置 Linux 规则和桌面安装包 |
|
||||
|
||||
## 文档
|
||||
|
||||
- [使用帮助](docs/USAGE.zh-CN.md)
|
||||
- [更新日志](CHANGELOG.md)
|
||||
- [架构说明](docs/ARCHITECTURE.md)
|
||||
- [桌面端说明](docs/DESKTOP.md)
|
||||
- [发布与更新](docs/RELEASE.md)
|
||||
- [安全说明](docs/SECURITY.md)
|
||||
|
||||
## 许可证
|
||||
|
||||
Squid 使用 **GNU General Public License v3.0 only**(`GPL-3.0-only`)。
|
||||
|
||||
Copyright © 2026 mula.liu。完整条款见 [`LICENSE`](LICENSE),版权与授权声明见 [`COPYRIGHT`](COPYRIGHT)。
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
Squid 0.1.14
|
||||
|
||||
- 全站统一标准组件库:页签、卡片、行、状态标签、工具栏与搜索框使用同一套定义,不再由各模块自行实现。
|
||||
- 空间清理的“垃圾清理 / 重复文件 / 大文件”三个页签与设置页页签保持同一套样式。
|
||||
- 权限管理的开机启动项改用统一行布局,状态、来源、路径和操作位置与其他模块一致。
|
||||
- 精简设置页与各页面布局;一级标题下不再重复二级描述,标题末尾不再带句号。
|
||||
- 主界面的更新提示直接打开“设置 → 更新”分区。
|
||||
- macOS 隐藏仅支持 Windows 的系统维护模块;权限管理保留开机启动项。
|
||||
|
||||
macOS 与 Windows 安装包均为未签名构建。macOS 首次打开请在访达中右键选择“打开”;Windows SmartScreen 提示时选择“更多信息” > “仍要运行”。
|
||||
|
|
@ -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,641 @@
|
|||
//! `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::Metered { .. }
|
||||
| Event::Group { .. }
|
||||
| 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;
|
||||
|
|
@ -82,6 +84,8 @@ enum Command {
|
|||
Rules,
|
||||
/// Report permissions, settings and ledger health
|
||||
Doctor,
|
||||
/// Malware scan, login-item inventory and quarantine
|
||||
Guard(guard::GuardArgs),
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
|
|
@ -245,7 +249,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();
|
||||
}
|
||||
|
|
@ -302,7 +306,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 {
|
||||
|
|
@ -311,7 +315,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(),
|
||||
|
|
@ -396,12 +400,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 {
|
||||
|
|
@ -409,13 +414,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;
|
||||
}
|
||||
|
|
@ -424,7 +429,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();
|
||||
|
|
@ -445,7 +450,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();
|
||||
|
|
@ -630,7 +635,7 @@ fn with_progress<T>(
|
|||
result
|
||||
}
|
||||
|
||||
fn bullet() -> String {
|
||||
pub(crate) fn bullet() -> String {
|
||||
if COLOR.load(Ordering::Relaxed) {
|
||||
"●".to_string()
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ rayon.workspace = true
|
|||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.58", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Security",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Com",
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -405,6 +405,10 @@ pub struct AppInfo {
|
|||
pub name: String,
|
||||
pub bundle_id: Option<String>,
|
||||
pub path: PathBuf,
|
||||
/// The file or bundle the desktop icon is read from. `path` may be an
|
||||
/// install directory or an uninstall helper, neither of which carries the
|
||||
/// icon the user recognises.
|
||||
pub icon_source: Option<PathBuf>,
|
||||
pub version: Option<String>,
|
||||
pub size: Bytes,
|
||||
/// Where the app was found: /Applications, ~/Applications, Homebrew Cask…
|
||||
|
|
|
|||
|
|
@ -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,18 +36,185 @@ 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,
|
||||
/// 小工具 · 截图识字 master switch (engine download stays on disk either way).
|
||||
pub screenshot_enabled: bool,
|
||||
/// Two-key global hotkey that wakes the capture overlay, e.g. `Alt+D`.
|
||||
pub screenshot_hotkey: String,
|
||||
/// 安全查杀 realtime posture: `power` (引擎按需拉起、空闲休眠),
|
||||
/// `performance` (clamd 常驻) or `manual` (仅手动/计划扫描).
|
||||
pub security_mode: String,
|
||||
/// Whether Squid registers itself with Windows Security Center (WSC).
|
||||
pub security_takeover: bool,
|
||||
/// Optional ClamAV database mirror host (freshclam `DatabaseMirror`);
|
||||
/// empty means the official CDN with the built-in fallback list.
|
||||
pub clamav_mirror: String,
|
||||
/// 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>,
|
||||
/// Software the user trusts. Matching findings stay visible in the trusted
|
||||
/// filter but stop counting as outstanding. Confirmed threats are never
|
||||
/// matched, whatever is in here.
|
||||
pub allowlist: Vec<AllowEntry>,
|
||||
}
|
||||
|
||||
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(),
|
||||
allowlist: 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
|
||||
}
|
||||
|
||||
pub fn allow(&mut self, kind: AllowKind, value: impl Into<String>) -> bool {
|
||||
let value = value.into().trim().to_string();
|
||||
if value.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if self
|
||||
.allowlist
|
||||
.iter()
|
||||
.any(|entry| entry.kind == kind && entry.value.eq_ignore_ascii_case(&value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.allowlist.push(AllowEntry { kind, value });
|
||||
true
|
||||
}
|
||||
|
||||
pub fn remove_allow(&mut self, kind: AllowKind, value: &str) -> bool {
|
||||
let before = self.allowlist.len();
|
||||
self.allowlist
|
||||
.retain(|entry| !(entry.kind == kind && entry.value.eq_ignore_ascii_case(value)));
|
||||
self.allowlist.len() != before
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AllowKind {
|
||||
Publisher,
|
||||
Path,
|
||||
Evidence,
|
||||
}
|
||||
|
||||
impl AllowKind {
|
||||
pub fn parse(value: &str) -> Option<AllowKind> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"publisher" => Some(AllowKind::Publisher),
|
||||
"path" | "folder" => Some(AllowKind::Path),
|
||||
"evidence" | "kind" => Some(AllowKind::Evidence),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AllowEntry {
|
||||
pub kind: AllowKind,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
|
|
@ -65,11 +232,7 @@ impl Default for Settings {
|
|||
language: None,
|
||||
history_keep: 60,
|
||||
desktop_setup_reviewed: false,
|
||||
screenshot_enabled: false,
|
||||
screenshot_hotkey: "Alt+D".into(),
|
||||
security_mode: "power".into(),
|
||||
security_takeover: false,
|
||||
clamav_mirror: String::new(),
|
||||
security: SecuritySettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -348,13 +511,34 @@ fn system_locale() -> Option<Locale> {
|
|||
None
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
fn system_locale() -> Option<Locale> {
|
||||
// Linux and Windows describe the language through the environment only,
|
||||
// and step 3 of `detect` has already read every bit of it.
|
||||
use windows::Win32::Globalization::GetUserDefaultUILanguage;
|
||||
|
||||
// The environment is not a reliable proxy for the Windows display
|
||||
// language: Explorer and the Store may run under a different UI locale.
|
||||
let langid = unsafe { GetUserDefaultUILanguage() };
|
||||
Some(locale_from_langid(langid))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn system_locale() -> Option<Locale> {
|
||||
// Linux describes the language through the environment, already read by
|
||||
// step 3 of `detect`.
|
||||
None
|
||||
}
|
||||
|
||||
/// Windows LANGIDs pack a primary language in the low ten bits.
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn locale_from_langid(langid: u16) -> Locale {
|
||||
const PRIMARY_CHINESE: u16 = 0x04;
|
||||
if langid & 0x03ff == PRIMARY_CHINESE {
|
||||
Locale::Zh
|
||||
} else {
|
||||
Locale::En
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience for reports that want the "freed" number in display units.
|
||||
pub fn display_size(settings: &Settings, logical: Bytes, allocated: Bytes) -> Bytes {
|
||||
if settings.show_allocated && !allocated.is_zero() {
|
||||
|
|
@ -464,6 +648,16 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_langid_uses_the_primary_language() {
|
||||
assert_eq!(locale_from_langid(0x0004), Locale::Zh);
|
||||
assert_eq!(locale_from_langid(0x0804), Locale::Zh, "zh-CN");
|
||||
assert_eq!(locale_from_langid(0x0404), Locale::Zh, "zh-TW");
|
||||
assert_eq!(locale_from_langid(0x0409), Locale::En, "en-US");
|
||||
assert_eq!(locale_from_langid(0x0809), Locale::En, "en-GB");
|
||||
assert_eq!(locale_from_langid(0x0411), Locale::En, "ja-JP fallback");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn squid_lang_beats_the_desktop_locale() {
|
||||
assert_eq!(
|
||||
|
|
@ -497,5 +691,17 @@ mod tests {
|
|||
let older = "history_keep = 60\n";
|
||||
let restored: Settings = toml::from_str(older).unwrap();
|
||||
assert!(!restored.desktop_setup_reviewed);
|
||||
assert!(restored.security.allowlist.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trust_rules_are_deduplicated_and_removable() {
|
||||
let mut security = SecuritySettings::default();
|
||||
assert!(security.allow(AllowKind::Publisher, " Example Ltd "));
|
||||
assert!(!security.allow(AllowKind::Publisher, "example ltd"));
|
||||
assert!(security.allow(AllowKind::Path, "/Applications/Example.app"));
|
||||
assert_eq!(security.allowlist.len(), 2);
|
||||
assert!(security.remove_allow(AllowKind::Publisher, "EXAMPLE LTD"));
|
||||
assert_eq!(security.allowlist.len(), 1);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -257,7 +257,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 {
|
||||
|
|
@ -584,6 +584,7 @@ mod tests {
|
|||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn page_files_hide_only_at_the_volume_root() {
|
||||
// Paths are matched lexically; nothing has to exist on disk.
|
||||
|
|
|
|||
|
|
@ -595,6 +595,7 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn workbuddy_session_snapshots_are_never_walked() {
|
||||
assert!(excluded_subtree(Path::new(
|
||||
|
|
|
|||
|
|
@ -471,6 +471,7 @@ mod tests {
|
|||
name: "Demo".into(),
|
||||
bundle_id: Some("com.example.Demo".into()),
|
||||
path: PathBuf::from(path),
|
||||
icon_source: None,
|
||||
version: Some("1.0".into()),
|
||||
size: Bytes(1_000),
|
||||
source: source.into(),
|
||||
|
|
|
|||
|
|
@ -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,138 @@
|
|||
//! User trust rules for findings that are not threats.
|
||||
//!
|
||||
//! The scanner is intentionally conservative: an unsigned login item is worth
|
||||
//! telling a person about. A real machine also has hundreds of those from
|
||||
//! ordinary software, so the answer cannot be to lower the detector until it
|
||||
//! stops seeing them. It is to let the user name the publisher, folder or
|
||||
//! advisory class they trust.
|
||||
//!
|
||||
//! Two limits are deliberate. A confirmed finding is never matched, and an
|
||||
//! evidence-class rule only applies to advisory findings. Trust can quiet a
|
||||
//! note; it cannot hide a published threat.
|
||||
|
||||
use crate::findings::{Confidence, Evidence, Finding};
|
||||
use squid_core::paths;
|
||||
use squid_core::settings::{AllowEntry, AllowKind};
|
||||
|
||||
/// Evidence classes that describe ordinary software rather than a published
|
||||
/// threat. These are the only classes an evidence rule may quiet.
|
||||
pub const TRUSTABLE_EVIDENCE: [&str; 4] = ["startup", "unsigned", "writable", "missing"];
|
||||
|
||||
pub fn evidence_kind(evidence: &Evidence) -> Option<&'static str> {
|
||||
let key = evidence.key();
|
||||
let kind = key.split(':').next()?;
|
||||
TRUSTABLE_EVIDENCE
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|known| *known == kind)
|
||||
}
|
||||
|
||||
pub fn is_allowlisted(finding: &Finding, allowlist: &[AllowEntry]) -> bool {
|
||||
if finding.confidence == Confidence::Confirmed {
|
||||
return false;
|
||||
}
|
||||
allowlist.iter().any(|entry| match entry.kind {
|
||||
AllowKind::Publisher => finding
|
||||
.signed
|
||||
.then_some(finding.publisher.as_deref())
|
||||
.flatten()
|
||||
.is_some_and(|publisher| publisher.trim().eq_ignore_ascii_case(entry.value.trim())),
|
||||
AllowKind::Path => finding.path.as_deref().is_some_and(|path| {
|
||||
let trusted = paths::expand(&entry.value);
|
||||
paths::same_path(&trusted, path) || paths::is_within(&trusted, path)
|
||||
}),
|
||||
AllowKind::Evidence => {
|
||||
finding.confidence == Confidence::Advisory
|
||||
&& finding
|
||||
.evidence
|
||||
.iter()
|
||||
.filter_map(evidence_kind)
|
||||
.any(|kind| kind == entry.value.trim().to_ascii_lowercase())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn finding(confidence: Confidence) -> Finding {
|
||||
Finding {
|
||||
id: "scan#1".into(),
|
||||
confidence,
|
||||
path: Some(PathBuf::from(
|
||||
"/Applications/Example.app/Contents/MacOS/Example",
|
||||
)),
|
||||
display_path: Some("/Applications/Example.app".into()),
|
||||
name: "Example".into(),
|
||||
title: "Example".into(),
|
||||
description: String::new(),
|
||||
evidence: vec![Evidence::Unsigned {
|
||||
path: PathBuf::from("/Applications/Example.app/Contents/MacOS/Example"),
|
||||
note: None,
|
||||
}],
|
||||
size: 1,
|
||||
sha256: None,
|
||||
signed: true,
|
||||
publisher: Some("Example Software Ltd".into()),
|
||||
found_at_ms: 0,
|
||||
quarantined: false,
|
||||
ignored: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn rule(kind: AllowKind, value: &str) -> AllowEntry {
|
||||
AllowEntry {
|
||||
kind,
|
||||
value: value.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_publisher_or_bundle_folder_quiets_an_advisory() {
|
||||
let finding = finding(Confidence::Advisory);
|
||||
assert!(is_allowlisted(
|
||||
&finding,
|
||||
&[rule(AllowKind::Publisher, "example software ltd")]
|
||||
));
|
||||
assert!(is_allowlisted(
|
||||
&finding,
|
||||
&[rule(AllowKind::Path, "/Applications/Example.app")]
|
||||
));
|
||||
assert!(is_allowlisted(
|
||||
&finding,
|
||||
&[rule(AllowKind::Evidence, "unsigned")]
|
||||
));
|
||||
assert!(!is_allowlisted(
|
||||
&finding,
|
||||
&[rule(AllowKind::Path, "/Applications/Other.app")]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_evidence_rule_never_hides_a_suspicious_or_confirmed_finding() {
|
||||
assert!(!is_allowlisted(
|
||||
&finding(Confidence::Suspicious),
|
||||
&[rule(AllowKind::Evidence, "unsigned")]
|
||||
));
|
||||
assert!(!is_allowlisted(
|
||||
&finding(Confidence::Confirmed),
|
||||
&[
|
||||
rule(AllowKind::Evidence, "unsigned"),
|
||||
rule(AllowKind::Publisher, "Example Software Ltd"),
|
||||
rule(AllowKind::Path, "/Applications"),
|
||||
]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_publisher_rule_requires_a_signed_file() {
|
||||
let mut unsigned = finding(Confidence::Advisory);
|
||||
unsigned.signed = false;
|
||||
assert!(!is_allowlisted(
|
||||
&unsigned,
|
||||
&[rule(AllowKind::Publisher, "Example Software Ltd")]
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -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,61 @@
|
|||
//! 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 allowlist;
|
||||
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,13 +15,31 @@ 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"
|
||||
serde_json.workspace = true
|
||||
sysinfo.workspace = true
|
||||
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",
|
||||
"Win32_System_Registry",
|
||||
"Win32_Globalization",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_System_IO",
|
||||
] }
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]
|
||||
file_icon_provider = "1.0.2"
|
||||
png = "0.17"
|
||||
windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading", "Win32_System_Registry", "Win32_Globalization", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_System_IO"] }
|
||||
|
|
|
|||
|
|
@ -111,6 +111,7 @@ pub fn app_from_bundle(
|
|||
name,
|
||||
bundle_id: bundle.bundle_id.clone(),
|
||||
path: path.clone(),
|
||||
icon_source: Some(path.clone()),
|
||||
version: bundle
|
||||
.short_version
|
||||
.clone()
|
||||
|
|
@ -144,6 +145,32 @@ pub fn app_from_bundle(
|
|||
Some(app)
|
||||
}
|
||||
|
||||
/// Render an application's system icon as PNG bytes.
|
||||
///
|
||||
/// macOS and Windows let the file manager do the work, so the result is the
|
||||
/// same icon Finder or Explorer shows, including HiDPI-safe source artwork.
|
||||
/// Linux has no equivalent without a GTK dependency; the desktop falls back to
|
||||
/// the app's initial.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub fn icon_png(app: &AppInfo, size: u16) -> Option<Vec<u8>> {
|
||||
let source = app.icon_source.as_ref()?;
|
||||
let icon = file_icon_provider::get_file_icon(source, size).ok()?;
|
||||
let mut output = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut output, icon.width, icon.height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header().ok()?;
|
||||
writer.write_image_data(&icon.pixels).ok()?;
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
pub fn icon_png(_app: &AppInfo, _size: u16) -> Option<Vec<u8>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Match "is this app running" against the process executable list.
|
||||
pub fn is_running(dir_name: &str, executable: Option<&str>, running: &[String]) -> bool {
|
||||
let mut candidates: Vec<String> = Vec::with_capacity(3);
|
||||
|
|
@ -169,3 +196,20 @@ pub fn stem_lower(path: &Path) -> String {
|
|||
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
fn a_system_icon_is_encoded_as_png() {
|
||||
let app = AppInfo {
|
||||
name: "Squid".into(),
|
||||
icon_source: std::env::current_exe().ok(),
|
||||
..Default::default()
|
||||
};
|
||||
let png = icon_png(&app, 32).expect("the running executable has a system icon");
|
||||
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ pub mod currency;
|
|||
pub mod leftovers;
|
||||
pub mod permissions;
|
||||
pub mod process;
|
||||
pub mod process_table;
|
||||
pub mod protection;
|
||||
pub mod startup;
|
||||
pub mod trust;
|
||||
#[cfg(unix)]
|
||||
pub mod volumes;
|
||||
|
||||
|
|
@ -106,6 +110,10 @@ pub trait Platform: Send + Sync {
|
|||
fn display_name(&self) -> String;
|
||||
fn os_version(&self) -> String;
|
||||
fn hardware_model(&self) -> String;
|
||||
/// Display adapter(s), when the platform exposes a stable name.
|
||||
fn graphics_adapter(&self) -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Directories to scan for installed applications.
|
||||
fn app_sources(&self) -> Vec<AppSource>;
|
||||
|
|
|
|||
|
|
@ -112,6 +112,29 @@ impl Platform for Linux {
|
|||
.to_string()
|
||||
}
|
||||
|
||||
fn graphics_adapter(&self) -> String {
|
||||
run("lspci", &[])
|
||||
.map(|text| {
|
||||
text.lines()
|
||||
.filter(|line| {
|
||||
line.contains("VGA compatible controller")
|
||||
|| line.contains("3D controller")
|
||||
|| line.contains("Display controller")
|
||||
})
|
||||
.filter_map(|line| line.split_once(": ").map(|(_, value)| value.trim()))
|
||||
.map(|value| {
|
||||
value
|
||||
.split_once(": ")
|
||||
.map(|(_, name)| name.trim())
|
||||
.unwrap_or(value)
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ")
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn app_sources(&self) -> Vec<AppSource> {
|
||||
[
|
||||
("/usr/share/applications", "System", 1, true),
|
||||
|
|
@ -193,6 +216,7 @@ impl Platform for Linux {
|
|||
name: desktop.name.clone(),
|
||||
bundle_id: Some(id.clone()),
|
||||
path: path.clone(),
|
||||
icon_source: None,
|
||||
version: None,
|
||||
size: Bytes::ZERO,
|
||||
source: source.label.clone(),
|
||||
|
|
@ -224,6 +248,7 @@ impl Platform for Linux {
|
|||
.unwrap_or_else(|| id.to_string()),
|
||||
bundle_id: Some(id.to_string()),
|
||||
path: PathBuf::from(format!("flatpak:{id}")),
|
||||
icon_source: None,
|
||||
version: None,
|
||||
size: cols
|
||||
.get(2)
|
||||
|
|
|
|||
|
|
@ -74,6 +74,25 @@ impl Platform for MacOs {
|
|||
parts.join(" · ")
|
||||
}
|
||||
|
||||
fn graphics_adapter(&self) -> String {
|
||||
run(
|
||||
"/usr/sbin/system_profiler",
|
||||
&["SPDisplaysDataType", "-detailLevel", "mini"],
|
||||
)
|
||||
.map(|text| {
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
line.trim()
|
||||
.strip_prefix("Chipset Model:")
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ")
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn app_sources(&self) -> Vec<AppSource> {
|
||||
let mut sources = vec![
|
||||
AppSource {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,242 @@
|
|||
//! 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)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
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,748 @@
|
|||
//! 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)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
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);
|
||||
};
|
||||
if let Some(found) = cache()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.get(&key)
|
||||
.cloned()
|
||||
{
|
||||
return found;
|
||||
}
|
||||
// Asked with no lock held: the question costs a subprocess, so holding the
|
||||
// cache across it would make every bulk caller take these one at a time.
|
||||
let trust = assess_uncached(path);
|
||||
let mut cache = cache()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
// 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.
|
||||
///
|
||||
/// The header decides, not the name. A macOS privileged helper is called
|
||||
/// `us.zoom.ZoomDaemon` and a Windows one `com.microsoft.autoupdate.helper`, where
|
||||
/// the last dot is part of the name rather than an extension; judging by extension
|
||||
/// never asked about a signed helper whose name happens to contain a dot. Reading
|
||||
/// eight bytes is close to free next to the subprocess being avoided, and it is the
|
||||
/// same question the signature actually answers.
|
||||
pub fn might_be_executable(path: &Path) -> bool {
|
||||
/// Bundles are signed as a unit, so the directory itself is the question.
|
||||
const BUNDLES: [&str; 4] = ["app", "framework", "bundle", "xpc"];
|
||||
|
||||
let extension = || {
|
||||
path.extension()
|
||||
.map(|ext| ext.to_string_lossy().to_lowercase())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
if path.is_dir() {
|
||||
return BUNDLES.contains(&extension().as_str());
|
||||
}
|
||||
match header(path) {
|
||||
Some(head) => header_is_executable(&head),
|
||||
// Nothing to read: an executable the current user may run but not open is
|
||||
// common among root-owned helpers, and `codesign` may still answer for it.
|
||||
None => {
|
||||
BUNDLES.contains(&extension().as_str())
|
||||
|| ["dylib", "so", "exe", "dll", "sys"].contains(&extension().as_str())
|
||||
|| extension().is_empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first eight bytes, or `None` when the file cannot be opened.
|
||||
fn header(path: &Path) -> Option<[u8; 8]> {
|
||||
use std::io::Read;
|
||||
let mut file = std::fs::File::open(path).ok()?;
|
||||
let mut head = [0_u8; 8];
|
||||
file.read_exact(&mut head).ok()?;
|
||||
Some(head)
|
||||
}
|
||||
|
||||
fn header_is_executable(head: &[u8; 8]) -> bool {
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,7 @@ const PSEUDO_FS: &[&str] = &[
|
|||
"rpc_pipefs",
|
||||
"nsfs",
|
||||
"autofs",
|
||||
"nullfs",
|
||||
"msdos",
|
||||
"anon:osd",
|
||||
"SMB",
|
||||
|
|
@ -90,6 +91,16 @@ pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec<Volume> {
|
|||
if text.starts_with("/System/Volumes/Data") && !out.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Application wrappers (for example an app that mounts its bundle at a
|
||||
// temporary path) are not disks a person can manage. Finder only shows
|
||||
// real volumes at `/` and under `/Volumes`.
|
||||
if cfg!(target_os = "macos")
|
||||
&& text != "/"
|
||||
&& !text.starts_with("/Volumes/")
|
||||
&& !text.starts_with("/System/Volumes/")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some((total, free)) = statvfs_for(&mount.mount_point) {
|
||||
let key = (total.as_u64(), free.as_u64());
|
||||
if seen_capacity.contains(&key) {
|
||||
|
|
@ -266,4 +277,19 @@ mod tests {
|
|||
}];
|
||||
assert!(volumes_from_mounts(&mounts).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_wrapper_mounts_are_not_volumes() {
|
||||
let mount_point = std::env::temp_dir();
|
||||
let mounts = vec![MountEntry {
|
||||
mount_point: mount_point.clone(),
|
||||
device: "/Applications/X.app/Wrapper".into(),
|
||||
fstype: "nullfs".into(),
|
||||
}];
|
||||
assert!(
|
||||
volumes_from_mounts(&mounts).is_empty(),
|
||||
"a nullfs app wrapper at {} must not look like a disk",
|
||||
mount_point.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -257,6 +257,26 @@ fn uninstall_program(uninstall_string: &str) -> Option<PathBuf> {
|
|||
candidate.exists().then_some(candidate)
|
||||
}
|
||||
|
||||
/// `DisplayIcon` is a path with an optional icon index, usually quoted:
|
||||
/// `"C:\Program Files\App\app.exe",0`. The file manager accepts the path
|
||||
/// without the index and returns the application's default icon.
|
||||
fn display_icon_path(value: Option<String>) -> Option<PathBuf> {
|
||||
let raw = value?.trim().to_string();
|
||||
let unquoted = raw
|
||||
.strip_prefix('"')
|
||||
.and_then(|value| value.split('"').next())
|
||||
.unwrap_or(&raw)
|
||||
.trim();
|
||||
let without_index = unquoted
|
||||
.rsplit_once(',')
|
||||
.filter(|(_, index)| index.trim().parse::<i32>().is_ok())
|
||||
.map(|(path, _)| path)
|
||||
.unwrap_or(unquoted)
|
||||
.trim();
|
||||
let path = PathBuf::from(without_index);
|
||||
path.exists().then_some(path)
|
||||
}
|
||||
|
||||
impl Platform for Windows {
|
||||
fn id(&self) -> PlatformId {
|
||||
PlatformId::Windows
|
||||
|
|
@ -297,6 +317,27 @@ impl Platform for Windows {
|
|||
None => String::new(),
|
||||
}
|
||||
}
|
||||
fn graphics_adapter(&self) -> String {
|
||||
let Ok(class) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
|
||||
r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}",
|
||||
KEY_READ,
|
||||
) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut adapters = Vec::new();
|
||||
for name in class.enum_keys().flatten() {
|
||||
let Ok(adapter) = class.open_subkey_with_flags(&name, KEY_READ) else {
|
||||
continue;
|
||||
};
|
||||
let Some(description) = str_value(&adapter, "DriverDesc") else {
|
||||
continue;
|
||||
};
|
||||
if !adapters.contains(&description) {
|
||||
adapters.push(description);
|
||||
}
|
||||
}
|
||||
adapters.join(" · ")
|
||||
}
|
||||
fn app_sources(&self) -> Vec<AppSource> {
|
||||
let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
|
||||
let mut dirs: Vec<PathBuf> = vec![
|
||||
|
|
@ -398,6 +439,7 @@ impl Platform for Windows {
|
|||
name: display_name,
|
||||
bundle_id: None,
|
||||
path,
|
||||
icon_source: display_icon_path(str_value(&key, "DisplayIcon")),
|
||||
version: str_value(&key, "DisplayVersion"),
|
||||
size,
|
||||
source,
|
||||
|
|
|
|||
|
|
@ -65,6 +65,9 @@ fn macos_battery() -> Option<Battery> {
|
|||
battery.cycle_count = cycles;
|
||||
battery.temperature_c = temp;
|
||||
}
|
||||
if let Some(health) = maximum_capacity() {
|
||||
battery.health_percent = Some(health);
|
||||
}
|
||||
Some(battery)
|
||||
}
|
||||
|
||||
|
|
@ -129,19 +132,77 @@ fn battery_details() -> Option<(Option<u8>, Option<u32>, Option<f32>)> {
|
|||
.ok()
|
||||
.filter(|output| output.status.success())?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let design = find_number(&text, "DesignCapacity");
|
||||
let max = find_number(&text, "MaxCapacity");
|
||||
let health = match (design, max) {
|
||||
(Some(design), Some(max)) if design > 0 => {
|
||||
Some(((max as f64 / design as f64) * 100.0).round() as u8)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let health = health_from_ioreg(&text);
|
||||
let cycles = find_number(&text, "CycleCount").map(|value| value as u32);
|
||||
let temp = find_number(&text, "Temperature").map(|tenths| tenths as f32 / 100.0);
|
||||
Some((health, cycles, temp))
|
||||
}
|
||||
|
||||
/// macOS already publishes the same figure it shows in System Settings. Read it
|
||||
/// once every ten minutes rather than deriving it from `MaxCapacity`, which on
|
||||
/// Apple Silicon is a percentage rather than a mAh reading.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn maximum_capacity() -> Option<u8> {
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
static CACHE: Mutex<Option<(Instant, Option<u8>)>> = Mutex::new(None);
|
||||
let stale = CACHE
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| *guard)
|
||||
.map(|(at, _)| at.elapsed() > Duration::from_secs(600))
|
||||
.unwrap_or(true);
|
||||
if !stale {
|
||||
return CACHE
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.and_then(|(_, health)| health));
|
||||
}
|
||||
let output = std::process::Command::new("/usr/sbin/system_profiler")
|
||||
.arg("SPPowerDataType")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success());
|
||||
let health = output
|
||||
.as_ref()
|
||||
.and_then(|output| parse_maximum_capacity(&String::from_utf8_lossy(&output.stdout)));
|
||||
if let Ok(mut guard) = CACHE.lock() {
|
||||
*guard = Some((Instant::now(), health));
|
||||
}
|
||||
health
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn parse_maximum_capacity(text: &str) -> Option<u8> {
|
||||
let line = text
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("Maximum Capacity:"))?;
|
||||
let value = line.split_once(':')?.1.trim().trim_end_matches('%').trim();
|
||||
value
|
||||
.parse::<u8>()
|
||||
.ok()
|
||||
.filter(|value| (1..=100).contains(value))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn health_from_ioreg(text: &str) -> Option<u8> {
|
||||
let design = find_number(text, "DesignCapacity")?;
|
||||
if design == 0 {
|
||||
return None;
|
||||
}
|
||||
// `MaxCapacity` is a percentage on Apple Silicon. The raw/nominal fields are
|
||||
// the actual mAh readings and are the only values that can form a ratio.
|
||||
let maximum = find_number(text, "AppleRawMaxCapacity")
|
||||
.filter(|value| *value > 0)
|
||||
.or_else(|| find_number(text, "NominalChargeCapacity").filter(|value| *value > 0))?;
|
||||
Some(
|
||||
((maximum as f64 / design as f64) * 100.0)
|
||||
.round()
|
||||
.min(100.0) as u8,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn find_number(text: &str, key: &str) -> Option<u64> {
|
||||
let (_, after) = text.split_once(&format!("\"{key}\""))?;
|
||||
|
|
@ -228,6 +289,21 @@ mod tests {
|
|||
assert!(parse_pmset(text).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn maximum_capacity_is_read_from_the_os_health_figure() {
|
||||
let text = " Health Information:\n Cycle Count: 516\n Maximum Capacity: 86%\n";
|
||||
assert_eq!(parse_maximum_capacity(text), Some(86));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn apple_silicon_health_ignores_the_percentage_in_max_capacity() {
|
||||
let text =
|
||||
"\"DesignCapacity\" = 6075\n\"MaxCapacity\" = 100\n\"AppleRawMaxCapacity\" = 4911\n";
|
||||
assert_eq!(health_from_ioreg(text), Some(81));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
fn hhmm_parsing() {
|
||||
|
|
|
|||
|
|
@ -117,6 +117,7 @@ pub struct HostInfo {
|
|||
pub os_name: String,
|
||||
pub os_version: String,
|
||||
pub hardware: String,
|
||||
pub gpu: String,
|
||||
pub hostname: String,
|
||||
pub user: String,
|
||||
pub arch: String,
|
||||
|
|
@ -129,6 +130,7 @@ impl HostInfo {
|
|||
os_name: platform.display_name(),
|
||||
os_version: platform.os_version(),
|
||||
hardware: platform.hardware_model(),
|
||||
gpu: platform.graphics_adapter(),
|
||||
hostname: hostname(),
|
||||
user: std::env::var("USER")
|
||||
.or_else(|_| std::env::var("USERNAME"))
|
||||
|
|
@ -643,30 +645,13 @@ fn vm_stat_details() -> Option<(Bytes, Bytes)> {
|
|||
let now = now_ms();
|
||||
let previous = LAST.swap(now, Ordering::Relaxed);
|
||||
static CACHE: std::sync::Mutex<Option<(Bytes, Bytes)>> = std::sync::Mutex::new(None);
|
||||
if now - previous > 5_000 || previous == 0 {
|
||||
let page_size = 4096u64;
|
||||
if now.saturating_sub(previous) > 5_000 || previous == 0 {
|
||||
let output = std::process::Command::new("/usr/bin/vm_stat")
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|out| out.status.success())?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let mut compressor_pages = 0u64;
|
||||
let mut wired_pages = 0u64;
|
||||
for line in text.lines() {
|
||||
let mut parts = line.split(':');
|
||||
let key = parts.next()?.trim();
|
||||
let value = parts.next()?.trim().trim_end_matches('.').replace(' ', "");
|
||||
let pages: u64 = value.parse().unwrap_or(0);
|
||||
match key {
|
||||
"Occupied by compressor" => compressor_pages = pages,
|
||||
"Wired Pages" => wired_pages = pages,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let value = (
|
||||
Bytes(compressor_pages * page_size),
|
||||
Bytes(wired_pages * page_size),
|
||||
);
|
||||
let value = parse_vm_stat(&text)?;
|
||||
if let Ok(mut guard) = CACHE.lock() {
|
||||
*guard = Some(value);
|
||||
}
|
||||
|
|
@ -676,6 +661,42 @@ fn vm_stat_details() -> Option<(Bytes, Bytes)> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Apple Silicon uses 16 KiB pages, Intel Macs use 4 KiB. The header states the
|
||||
/// size, and the two fields squid reports use different labels than older
|
||||
/// versions of `vm_stat`; both facts made the previous parser return zero.
|
||||
fn parse_vm_stat(text: &str) -> Option<(Bytes, Bytes)> {
|
||||
let header = text.lines().next()?;
|
||||
let (_, after_size) = header.split_once("page size of ")?;
|
||||
let page_size: u64 = after_size
|
||||
.chars()
|
||||
.take_while(|character| character.is_ascii_digit())
|
||||
.collect::<String>()
|
||||
.parse()
|
||||
.ok()?;
|
||||
let mut compressor_pages = 0u64;
|
||||
let mut wired_pages = 0u64;
|
||||
for line in text.lines().skip(1) {
|
||||
let Some((key, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let pages: u64 = value
|
||||
.trim()
|
||||
.trim_end_matches('.')
|
||||
.replace(' ', "")
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
match key.trim().trim_matches('"') {
|
||||
"Pages occupied by compressor" => compressor_pages = pages,
|
||||
"Pages wired down" => wired_pages = pages,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some((
|
||||
Bytes(compressor_pages.saturating_mul(page_size)),
|
||||
Bytes(wired_pages.saturating_mul(page_size)),
|
||||
))
|
||||
}
|
||||
|
||||
fn net_rates(networks: &Networks, seconds: f64) -> NetRate {
|
||||
let mut rx = 0u64;
|
||||
let mut tx = 0u64;
|
||||
|
|
@ -966,6 +987,18 @@ mod tests {
|
|||
assert_eq!(stats.percent_used(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vm_stat_uses_the_reported_page_size_and_fields() {
|
||||
let text = "\
|
||||
Mach Virtual Memory Statistics: (page size of 16384 bytes)\n\
|
||||
Pages free: 96476.\n\
|
||||
Pages wired down: 122963.\n\
|
||||
Pages occupied by compressor: 151882.\n";
|
||||
let (compressed, wired) = parse_vm_stat(text).expect("vm_stat");
|
||||
assert_eq!(wired, Bytes(122_963 * 16_384));
|
||||
assert_eq!(compressed, Bytes(151_882 * 16_384));
|
||||
}
|
||||
|
||||
/// The feature, end to end: a sample that still describes its pid stops it.
|
||||
#[test]
|
||||
fn a_process_stops_when_its_sample_asks_it_to() {
|
||||
|
|
|
|||
|
|
@ -2604,6 +2604,7 @@ mod tests {
|
|||
name: "SquidTest".to_string(),
|
||||
bundle_id: Some("com.nexsquid.test".to_string()),
|
||||
path: bundle.clone(),
|
||||
icon_source: None,
|
||||
version: Some("1.0".to_string()),
|
||||
size: Bytes(0),
|
||||
source: "test".to_string(),
|
||||
|
|
@ -2701,6 +2702,7 @@ mod tests {
|
|||
name: "SquidTest".into(),
|
||||
bundle_id: Some("com.example.SquidTest".into()),
|
||||
path: path.clone(),
|
||||
icon_source: None,
|
||||
version: None,
|
||||
size: Bytes(0),
|
||||
source: "test".into(),
|
||||
|
|
|
|||
|
|
@ -555,7 +555,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()
|
||||
|
|
|
|||
|
|
@ -2045,6 +2045,7 @@ mod tests {
|
|||
name: "Demo".into(),
|
||||
bundle_id: Some("com.example.Demo".into()),
|
||||
path: "/Applications/Demo.app".into(),
|
||||
icon_source: None,
|
||||
version: Some("1.0".into()),
|
||||
size: Bytes(1 << 20),
|
||||
source: "Applications".into(),
|
||||
|
|
@ -2609,6 +2610,7 @@ mod tests {
|
|||
.map(|index| AppInfo {
|
||||
name: format!("Sq{index:02}"),
|
||||
path: format!("/Applications/Sq{index:02}.app").into(),
|
||||
icon_source: None,
|
||||
source: "Applications".into(),
|
||||
size: Bytes(1 << 20),
|
||||
..Default::default()
|
||||
|
|
|
|||
|
|
@ -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。约定:
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Nex 应用视觉规范
|
||||
|
||||
版本:1.0
|
||||
版本:1.1
|
||||
状态:Nex 系列应用统一标准
|
||||
基准实现:`nex_shift` 的主色系
|
||||
|
||||
|
|
@ -12,7 +12,8 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
|
|||
- 主操作、选中态、焦点环和进度使用 Nex 主色。
|
||||
- 页面底色、卡片和正文使用暖中性色,不使用冷蓝色底。
|
||||
- 绿色、红色、黄色只表达成功、危险和警告,不作为品牌主色。
|
||||
- 分类色可以保留各自的语义色,但不得替代主操作色。
|
||||
- 图表、分类和装饰只使用主色、暖中性色或成功/警告/危险状态色。
|
||||
- 不引入蓝色、紫色、青色、粉色等第二品牌色;状态色也不得用于装饰。
|
||||
- 新界面必须引用 `src/styles.css` 中的 `--nex-*` 常量,不写新的主色十六进制值。
|
||||
|
||||
## 2. 品牌常量
|
||||
|
|
@ -39,6 +40,19 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
|
|||
主色高亮需要透明度时使用 `rgba(var(--nex-primary-rgb), α)`,其中
|
||||
`--nex-primary-rgb` 为 `242, 106, 51`。
|
||||
|
||||
### 状态色
|
||||
|
||||
| 常量 | 值 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `--nex-success` / `-strong` / `-soft` | `#17865F` / `#126D4C` / `#E7F8F1` | 完成、安全、已授权 |
|
||||
| `--nex-warning` / `-strong` / `-soft` | `#A97729` / `#8C6C40` / `#FFF8E9` | 警告、需要注意 |
|
||||
| `--nex-danger` / `-strong` / `-soft` | `#C85A62` / `#A64048` / `#FFEDEF` | 错误、危险操作 |
|
||||
|
||||
对应的 `--nex-success-rgb`、`--nex-warning-rgb`、`--nex-danger-rgb`
|
||||
用于状态色透明度。组件通过 `.tone-primary`、`.tone-success`、
|
||||
`.tone-warning`、`.tone-danger`、`.tone-neutral` 五种语义色调取色,
|
||||
不新增分类专用色调。
|
||||
|
||||
## 3. 图标渐变
|
||||
|
||||
应用图标的品牌渐变沿用 Shift:
|
||||
|
|
@ -47,7 +61,8 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
|
|||
- 中段 `#FF6B35`
|
||||
- 终点 `#C66BFF`
|
||||
|
||||
图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。
|
||||
图标主体允许保留应用图标自身的暖橙渐变与粉色高光;它们属于图标资产,
|
||||
不得扩展为界面装饰色。图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。
|
||||
|
||||
### 侧栏品牌锁定
|
||||
|
||||
|
|
@ -95,18 +110,26 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
|
|||
- 正文不使用纯黑;标题使用 `--nex-ink-strong`。
|
||||
- 更新面板面向使用者,只展示当前系统版本、版本状态、更新说明、进度与操作;
|
||||
更新地址、安装包文件名和哈希留在后端校验流程中,不进入常规界面。
|
||||
- 下载完成后的“放弃”使用中性描边按钮:34px 高、9px 圆角、暖白半透明表面、
|
||||
`--nex-ink` 文字;悬停仅切换主色描边与白色表面,与 Shift 保持一致。
|
||||
- 软件更新不再重复显示“已是最新版本”;当前版本只在系统信息面板中展示,
|
||||
只有发现更新包时才展开版本变化与操作区。
|
||||
|
||||
## 6. 旧变量兼容
|
||||
## 6. 语言与本地化
|
||||
|
||||
现有组件仍引用 `--blue`、`--blue-deep`、`--blue-soft`。这三个变量已经
|
||||
分别别名为 `--nex-primary`、`--nex-primary-strong`、`--nex-primary-soft`,
|
||||
因此不会再渲染蓝色。新增代码应直接使用 `--nex-*` 常量;迁移旧组件时
|
||||
可以逐步移除 `--blue-*` 别名,但不得改回独立颜色值。
|
||||
- 首次启动默认跟随系统语言:macOS 读取 `AppleLocale` / `AppleLanguages`,
|
||||
Windows 读取 `GetUserDefaultUILanguage`,Linux 读取标准 locale 环境变量。
|
||||
- 设置中只提供“简体中文”和“English”两个语言选项;尚未手动选择时,选中项反映当前系统语言。
|
||||
- 手动选择语言会写入 `config.toml` 的 `language`,后续启动继续使用该选择。
|
||||
- 托盘菜单与主界面使用同一语言,并在切换后立即刷新。
|
||||
- 当前支持中文与英文,其他系统语言回退到英文。
|
||||
|
||||
## 7. 验收
|
||||
|
||||
- 全应用不出现蓝色主按钮、蓝色选中态或蓝色焦点环。
|
||||
- 全应用不出现蓝色、紫色、青色或粉色界面装饰;品牌色只有橙色。
|
||||
- 状态色只用于成功、警告和危险,不作为卡片或图表的分类装饰色。
|
||||
- 页面底色为 `#F5EEE7`,面板为暖白,不使用冷蓝渐变。
|
||||
- Settings、首次启动权限卡和更新面板共享同一套主色。
|
||||
- 应用图标与界面使用同一组暖色品牌常量。
|
||||
- 正文和标签不小于 11px,标题使用统一字号阶梯,不出现 7–10px 的正文。
|
||||
- 默认语言与系统一致,切换语言后主界面和托盘同步更新。
|
||||
|
|
|
|||
115
docs/DESKTOP.md
115
docs/DESKTOP.md
|
|
@ -45,22 +45,119 @@ 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 |
|
||||
| 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 |
|
||||
| Permissions (Windows) | Startup entries from Run keys, startup folders and scheduled tasks; shell context-menu handlers; popup-window rules and the popup watcher |
|
||||
| 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, plus the desktop-widget switch. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
|
||||
| Desktop widget | A borderless desktop-layer monitor opened from Real-time monitor, with status rings, network and disk curves, storage bars, and all settings in a dropdown at the top of the widget |
|
||||
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
|
||||
| Settings | Language, 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`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+9` on Windows switch screens, in sidebar
|
||||
order. On Windows: `1` overview, `2` daily cleanup, `3` uninstall apps,
|
||||
`4` deep clean, `5` permissions, `6` storage, `7` real-time monitor,
|
||||
`8` security, `9` startup items. macOS omits the Windows-only Permissions
|
||||
screen, so `5`–`8` shift up by one.
|
||||
|
||||
The sidebar groups these into **Maintenance** (overview, daily cleanup,
|
||||
uninstall apps, deep clean, and Permissions on Windows), **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.
|
||||
Use **Quit Squid** in the same menu to stop the background process.
|
||||
the window, start a malware scan, and jump directly to Security, Startup items,
|
||||
Daily cleanup, Uninstall apps, Deep Clean or the desktop widget. 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.
|
||||
|
||||
The tray mark is a transparent monochrome asset. macOS receives it with
|
||||
`.icon_as_template(true)`, so the system draws it in the correct menu-bar colour
|
||||
for light and dark appearances instead of pasting a coloured square onto the
|
||||
bar. Windows and Linux keep the same silhouette in gray.
|
||||
|
||||
## Permissions (Windows)
|
||||
|
||||
The Permissions screen is a Windows-only destination and is hidden from the
|
||||
macOS sidebar, where the Startup items screen already covers LaunchAgents,
|
||||
LaunchDaemons and login items with the same safety rules. On Windows it lists:
|
||||
|
||||
- startup entries from `Run` keys, startup folders and scheduled tasks;
|
||||
- shell context-menu handlers grouped by file, folder, desktop, drive and
|
||||
all-object surfaces;
|
||||
- popup windows with rules to block or allow them and a background watcher.
|
||||
|
||||
Every enable/disable action goes through the backend's inventory; the page never
|
||||
submits a raw registry or filesystem path.
|
||||
|
||||
## Desktop widget
|
||||
|
||||
The desktop widget is switched on from Real-time monitor and is a separate Tauri
|
||||
webview window labelled `widget`, not a WidgetKit extension. It shares the live
|
||||
sampler with the Real-time monitor but polls at its own 2/5/10-second cadence and
|
||||
pauses while hidden.
|
||||
|
||||
- The gear at the top of the widget opens a dropdown containing every setting:
|
||||
panel switches, opacity, refresh rate, dock corner and fold memory.
|
||||
- Up to four cards: status rings (CPU, memory, and GPU when the OS exposes a
|
||||
busy counter), network throughput, disk I/O, and storage volumes.
|
||||
- The window is borderless, transparent and resizable only by its content. It
|
||||
docks to a chosen corner and remembers a manual drag position.
|
||||
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
|
||||
non-focusable with `accept_first_mouse`, so it sits with the desktop and never
|
||||
takes keyboard focus from the app you are using.
|
||||
- On Windows it is parked with `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` for
|
||||
the same desktop-layer behaviour.
|
||||
- Opacity is capped to 90–100% so text stays readable over busy wallpapers.
|
||||
The master switch and the tray item share one state; settings persist in
|
||||
`widget.json` beside `manage.json`.
|
||||
|
||||
**Settings → Startup** registers the app for the current user only. macOS
|
||||
uses a user LaunchAgent, Windows uses the current-user Run key, and Linux uses
|
||||
an XDG autostart desktop entry. Enabling or disabling launch at login does not
|
||||
require administrator access.
|
||||
|
||||
## Safety boundary
|
||||
|
||||
|
|
@ -105,7 +202,9 @@ scanning if you do not want those prompts.
|
|||
|
||||
The update implementation mirrors `nex_shift`:
|
||||
|
||||
- A build derives its feed from the git `origin` remote or `SQUID_UPDATE_URL`.
|
||||
- A build bakes the origin release feed by default; `SQUID_UPDATE_URL`
|
||||
overrides it. The GitHub repository mirrors source only and does not carry
|
||||
the `releases` branch, so a GitHub clone still updates from origin.
|
||||
- The feed is an orphan `releases` branch containing installers and
|
||||
`squid-update.json`.
|
||||
- The manifest always provides exact byte size and SHA256; both are checked
|
||||
|
|
@ -115,6 +214,8 @@ The update implementation mirrors `nex_shift`:
|
|||
bytes.
|
||||
- The application checks at most once a day when automatic checks are enabled;
|
||||
the last-check day lives in `updates.json`.
|
||||
- A verified download can be installed and restarted, or discarded with the
|
||||
neutral outlined action shared with `nex_shift`.
|
||||
- macOS mounts the DMG after exit and swaps `Squid.app` with rollback on failure.
|
||||
- Windows waits for `squid-desktop.exe` to exit, runs the same NSIS installer
|
||||
silently, then relaunches it from `%LOCALAPPDATA%\Programs\Squid`.
|
||||
|
|
|
|||
|
|
@ -14,6 +14,16 @@
|
|||
Squid uses the same release model as `nex_shift`: a git branch is the update
|
||||
server. No object storage or release API is required.
|
||||
|
||||
There are two remotes:
|
||||
|
||||
- `origin` is the canonical repository and the update channel. It carries the
|
||||
orphan `releases` branch.
|
||||
- GitHub is a public source mirror. It receives `main` only and must never
|
||||
receive `releases`. Its history is rewritten to drop `release/`, `*.dmg` and
|
||||
`*.exe`, so its commit hashes differ from origin. Installer assets are
|
||||
attached to GitHub Releases for direct download; the app's update feed still
|
||||
points at origin.
|
||||
|
||||
## Artifact names
|
||||
|
||||
Both installers must carry the exact version from `src-tauri/tauri.conf.json`:
|
||||
|
|
@ -64,37 +74,6 @@ toolchain instead of `cargo-xwin`. The installer is per-user and installs to:
|
|||
The executable inside is `squid-desktop.exe`, matching both the NSIS installer
|
||||
and the update handoff script.
|
||||
|
||||
### Three editions (0.2.0+)
|
||||
|
||||
One version number ships three feature editions, gated by cargo features in
|
||||
`src-tauri/Cargo.toml` (`default = ["screenshot","security"]`):
|
||||
|
||||
| 版本 | features | setup 名 | artifact 键 |
|
||||
| --- | --- | --- | --- |
|
||||
| 完整 full | default | `Squid-Setup-<ver>-win-x64.exe` | `windows` |
|
||||
| Pro | `screenshot` only | `Squid-Pro-Setup-<ver>-win-x64.exe` | `windows-pro` |
|
||||
| Lite | none | `Squid-Lite-Setup-<ver>-win-x64.exe` | `windows-lite` |
|
||||
|
||||
Build each edition on Windows (pnpm build once, then per edition):
|
||||
|
||||
```bash
|
||||
# full
|
||||
cargo build --release --features tauri/custom-protocol && pnpm exec tauri bundle
|
||||
# pro(--no-default-features 必须走 cargo 直调;tauri build 不透传它)
|
||||
cargo build --release --no-default-features --features "screenshot,tauri/custom-protocol" && pnpm exec tauri bundle
|
||||
# lite
|
||||
cargo build --release --no-default-features --features tauri/custom-protocol && pnpm exec tauri bundle
|
||||
```
|
||||
|
||||
`tauri bundle` only re-runs NSIS over the current `target/release/` exe — so
|
||||
`cargo build` decides the edition, `bundle` packages it, and the output
|
||||
`Squid_<ver>_x64-setup.exe` is renamed per edition while copying into
|
||||
`release/<ver>/`. The Rust edition is baked in (`edition_name()` →
|
||||
`bootstrap.edition`); the frontend hides the pages per edition, and
|
||||
`update.rs` prefers the edition artifact key with a plain-`windows` fallback.
|
||||
Verify each exe with string probes (`wsc-last-error` ⇒ security,
|
||||
`bin/snow_shot.exe` ⇒ screenshot) before staging.
|
||||
|
||||
### 360/电脑管家 environments: ship 一键安装.bat (mandatory)
|
||||
|
||||
On the developer machine (and other boxes running 腾讯电脑管家/360), the
|
||||
|
|
@ -165,6 +144,28 @@ scripts/publish-release.sh --dry-run --key ~/.config/squid-release/release.ed255
|
|||
scripts/publish-release.sh --no-push --key ~/.config/squid-release/release.ed25519
|
||||
```
|
||||
|
||||
The script pushes `releases` to `origin` only. Push the source mirror with the
|
||||
sync script, which strips release installers from GitHub history:
|
||||
|
||||
```bash
|
||||
git push origin main
|
||||
scripts/sync-github.sh
|
||||
gh release create v<version> \
|
||||
--repo VulpineLiu/squid \
|
||||
--title "Squid <version>" \
|
||||
--notes-file artifacts/RELEASE_NOTES.md \
|
||||
artifacts/Squid-<version>-macOS-universal.dmg \
|
||||
artifacts/Squid-Setup-<version>-win-x64.exe \
|
||||
artifacts/SHA256SUMS.txt \
|
||||
artifacts/README-macOS.txt \
|
||||
artifacts/README-Windows-x64.txt \
|
||||
artifacts/一键安装.bat
|
||||
```
|
||||
|
||||
Do not run `git push github main` from the working repository: its history still
|
||||
contains the release installers, and the GitHub mirror has a different commit
|
||||
graph.
|
||||
|
||||
The branch contains:
|
||||
|
||||
```text
|
||||
|
|
@ -176,22 +177,33 @@ Squid-Setup-<version>-win-x64.exe
|
|||
|
||||
## Feed URL
|
||||
|
||||
`src-tauri/build.rs` derives the manifest URL from `origin`:
|
||||
`src-tauri/build.rs` bakes a fixed default feed rather than deriving it from
|
||||
whatever remote a checkout happens to use:
|
||||
|
||||
| Remote | Feed |
|
||||
| --- | --- |
|
||||
| Gitea / Forgejo | `https://host/owner/repo/raw/branch/releases/squid-update.json` |
|
||||
| GitHub | `https://github.com/owner/repo/raw/releases/squid-update.json` |
|
||||
| GitLab | `https://gitlab.example/owner/repo/-/raw/releases/squid-update.json` |
|
||||
```text
|
||||
https://git.unissense.tech/mula/nex_squid/raw/branch/releases/squid-update.json
|
||||
```
|
||||
|
||||
`SQUID_UPDATE_URL` overrides it at build time. The same variable at runtime
|
||||
overrides the baked value, which is useful for staging feeds:
|
||||
This is deliberate: GitHub clones have `origin` pointing at GitHub, which does
|
||||
not carry the `releases` branch. A GitHub clone must still update from the
|
||||
origin channel.
|
||||
|
||||
For forks or staging feeds, `SQUID_UPDATE_URL` overrides the default at build
|
||||
time. The same variable at runtime overrides the baked value:
|
||||
|
||||
```bash
|
||||
SQUID_UPDATE_URL=https://host/owner/repo/raw/branch/staging/squid-update.json \
|
||||
open Squid.app
|
||||
```
|
||||
|
||||
The matching raw-file layouts are:
|
||||
|
||||
| Host | Feed |
|
||||
| --- | --- |
|
||||
| Gitea / Forgejo | `https://host/owner/repo/raw/branch/releases/squid-update.json` |
|
||||
| GitHub | `https://github.com/owner/repo/raw/releases/squid-update.json` |
|
||||
| GitLab | `https://gitlab.example/owner/repo/-/raw/releases/squid-update.json` |
|
||||
|
||||
## Manifest
|
||||
|
||||
Schema version 1:
|
||||
|
|
@ -245,4 +257,4 @@ Keep these four values equal:
|
|||
- `package.json`
|
||||
|
||||
Then run frontend checks, Rust tests (including `src-tauri`), build both
|
||||
installers, and publish.
|
||||
installers, update `CHANGELOG.md` and `RELEASE_NOTES.md`, and publish.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -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 的限制,见上。
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,265 @@
|
|||
# Squid Usage Guide
|
||||
|
||||
For Squid 0.1.14. See [`README.en.md`](../README.en.md) for the project overview and [`CHANGELOG.md`](../CHANGELOG.md) for version history.
|
||||
|
||||
## 1. Download and install
|
||||
|
||||
Desktop installers are published on the origin repository's `releases` branch and attached to the GitHub release. The GitHub repository does not carry that branch.
|
||||
|
||||
- Release directory: <https://git.unissense.tech/mula/nex_squid/src/branch/releases>
|
||||
- Update manifest: <https://git.unissense.tech/mula/nex_squid/raw/branch/releases/squid-update.json>
|
||||
|
||||
Current version 0.1.14:
|
||||
|
||||
| Platform | Installer |
|
||||
| --- | --- |
|
||||
| macOS 12+ | [`Squid-0.1.14-macOS-universal.dmg`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-0.1.14-macOS-universal.dmg) |
|
||||
| Windows 10/11 x64 | [`Squid-Setup-0.1.14-win-x64.exe`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-Setup-0.1.14-win-x64.exe) |
|
||||
|
||||
Both installers are unsigned builds. Verify their exact size and SHA256 against `SHA256SUMS.txt` in the release directory.
|
||||
|
||||
### macOS
|
||||
|
||||
1. Open the DMG and drag `Squid.app` into Applications.
|
||||
2. On first launch, right-click `Squid` in Finder and choose **Open**.
|
||||
3. If macOS reports that the app is damaged, remove the download quarantine flag and open it again:
|
||||
|
||||
```bash
|
||||
xattr -dr com.apple.quarantine /Applications/Squid.app
|
||||
open /Applications/Squid.app
|
||||
```
|
||||
|
||||
4. Squid needs no root access and installs no background service, kernel extension, or privileged helper.
|
||||
|
||||
### Windows
|
||||
|
||||
1. Run `Squid-Setup-<version>-win-x64.exe`.
|
||||
2. If SmartScreen appears, choose **More info** > **Run anyway**.
|
||||
3. The default install location is `%LOCALAPPDATA%\Programs\Squid`; no administrator rights are required.
|
||||
4. If the installer cannot write to `%TEMP%` (some 360 / PC Manager environments), use `一键安装.bat` from the release directory. It copies the installer to `%TEMP%` on drive C: and starts it there.
|
||||
5. If Squid opens a blank window, install the Microsoft Edge WebView2 Evergreen Runtime and relaunch:
|
||||
<https://developer.microsoft.com/microsoft-edge/webview2/>
|
||||
|
||||
## 2. First launch
|
||||
|
||||
- The interface follows the system language by default. Switch between Simplified Chinese and English in **Settings → General**.
|
||||
- The first launch shows an optional permission-readiness card once. It does not force a system permission prompt and does not block startup.
|
||||
- Closing the main window only hides it; Squid keeps running in the tray. Only **Quit Squid** in the tray menu ends the process.
|
||||
- **Settings → Startup** enables launch at login. It writes a user-level startup item and needs no administrator access.
|
||||
|
||||
## 3. Desktop app
|
||||
|
||||
### Sidebar
|
||||
|
||||
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only)
|
||||
- **Protection**: Security, Startup items
|
||||
- **Insights**: Storage, Real-time monitor
|
||||
- **Bottom**: History, Settings
|
||||
|
||||
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages in sidebar order. macOS hides the Windows-only Permissions screen, so later pages shift up.
|
||||
|
||||
### Daily cleanup
|
||||
|
||||
1. Open **Daily cleanup** and choose a scan scope.
|
||||
2. Review results by category; each category can be unchecked independently.
|
||||
3. Choose the deletion mode: Trash / Recycle Bin by default, or explicit permanent deletion.
|
||||
4. Start cleanup and confirm the dialog.
|
||||
|
||||
Rules cover app and browser caches, logs, crash reports, developer caches, upgrade installers, and Trash / Recycle Bin. macOS ships 38 built-in rules; Windows ships 30. Every CLI delete command supports `--dry-run`; the desktop app scans before you select anything.
|
||||
|
||||
### Uninstall apps
|
||||
|
||||
1. Open **Uninstall apps** and search for an app.
|
||||
2. Squid builds one plan containing the app bundle plus preferences, caches, containers, or AppData leftovers.
|
||||
3. Review every item, then confirm.
|
||||
|
||||
Leftover matching excludes common document extensions so user documents are not treated as app leftovers.
|
||||
|
||||
### Deep Clean
|
||||
|
||||
Deep Clean finds rebuildable build output such as `node_modules`, disk images, installers, and stale downloads. Edit `purge_roots` to change the default project roots; `purge_min_age_days` protects projects that are still in use.
|
||||
|
||||
### Storage
|
||||
|
||||
Choose a folder and Squid measures it level by level, listing the largest children and files. Storage analysis reads only folders you choose or configure; file contents are never uploaded.
|
||||
|
||||
### Real-time monitor and processes
|
||||
|
||||
- Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds.
|
||||
- The **Processes** tab lists every process with its signature status and startup entry.
|
||||
- Before ending a process, Squid samples it again and checks the name. Squid itself, PID 1, and critical system processes are refused.
|
||||
- The monitor can be pinned as a desktop widget; all widget settings open from the gear at its top.
|
||||
|
||||
### Security
|
||||
|
||||
- Reads XProtect / Defender state; it never turns protection off or changes it for you.
|
||||
- Scans by hash, YARA rule, and heuristic, grading findings as confirmed / suspicious / advisory.
|
||||
- Confirmed findings can be quarantined and restored.
|
||||
- The Security page can trust normal software by publisher, app folder, or advisory class. Confirmed threats are never silently allowlisted.
|
||||
- File names, hashes, findings, and quarantined files are never uploaded.
|
||||
|
||||
### Startup items and Permissions
|
||||
|
||||
- **Startup items** lists LaunchAgents, LaunchDaemons, login items, registry Run/RunOnce keys, startup folders, scheduled tasks, and services. Entries owned by the current user can be disabled and re-enabled.
|
||||
- Windows **Permissions** groups startup entries by app and adds shell context-menu extensions, popup-window rules, and a background watcher.
|
||||
|
||||
### History and undo
|
||||
|
||||
Every real deletion is recorded in a local ledger. Items still in Trash / Recycle Bin can be restored from **History**. On the CLI, use `squid history` and `squid undo`.
|
||||
|
||||
### Software updates
|
||||
|
||||
- Automatic checks run at most once a day; check manually in **Settings → Updates**.
|
||||
- The manifest comes from the origin `releases` branch, not from GitHub.
|
||||
- Installers must match the manifest's exact size and SHA256. Builds with a release public key also verify the manifest's Ed25519 signature.
|
||||
- After a verified download, install and restart, or discard the downloaded file.
|
||||
|
||||
## 4. CLI and TUI
|
||||
|
||||
Install:
|
||||
|
||||
```bash
|
||||
cargo install --path crates/squid-cli --locked
|
||||
```
|
||||
|
||||
Or build from source:
|
||||
|
||||
```bash
|
||||
cargo build --release -p squid-cli
|
||||
```
|
||||
|
||||
Common commands:
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `squid state` | Open the TUI |
|
||||
| `squid status` | Print a system snapshot |
|
||||
| `squid clean --dry-run` | Preview cleanable items |
|
||||
| `squid clean -y` | Run cleanup by rule |
|
||||
| `squid uninstall --list` | List installed apps |
|
||||
| `squid uninstall <NAME>` | Build an app-plus-leftovers uninstall plan |
|
||||
| `squid purge <PATH>` | Remove project build artefacts |
|
||||
| `squid analyze <PATH>` | Print a directory-size tree and largest files |
|
||||
| `squid history` | Review the deletion ledger |
|
||||
| `squid undo [ID]` | Restore the latest or a named Trash session |
|
||||
| `squid whitelist add\|list\|remove` | Maintain protected paths |
|
||||
| `squid rules` | List active rules |
|
||||
| `squid doctor` | Check permissions, configuration, history, and effective paths |
|
||||
| `squid guard status` | Report XProtect / Defender state, rule-pack version, startup counts, and quarantine size |
|
||||
| `squid guard scan [PATHS…]` | Scan for malware; `--full`, `--json`, `-y` to auto-quarantine confirmed findings |
|
||||
| `squid guard startup` | List login/startup entries; `--all`, `--risky` |
|
||||
| `squid guard quarantine <ID>` / `restore <ID>` | Quarantine or restore a finding |
|
||||
| `squid guard held` | List quarantine contents and reasons |
|
||||
|
||||
Every delete command supports `--dry-run`. Non-interactive environments must pass `-y/--yes` or Squid refuses the deletion. Run `squid <command> --help` for complete options.
|
||||
|
||||
## 5. Configuration and data
|
||||
|
||||
| Purpose | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| Configuration and rules | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
|
||||
| History ledger | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
|
||||
| Delete destination | `~/.Trash` or permanent deletion | Recycle Bin or permanent deletion |
|
||||
|
||||
Linux uses XDG directories. The desktop app and CLI/TUI share configuration and history.
|
||||
|
||||
Common configuration (`config.toml`):
|
||||
|
||||
```toml
|
||||
delete_mode = "trash"
|
||||
history_keep = 60
|
||||
purge_min_age_days = 7
|
||||
purge_max_entries = 200000
|
||||
show_allocated = true
|
||||
# Empty means "follow system"; set "en" or "zh" to override
|
||||
language = ""
|
||||
whitelist = ["~/Library/Caches/ImportantApp"]
|
||||
disabled_rules = ["user-trash"]
|
||||
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
|
||||
```
|
||||
|
||||
Main environment variables:
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `SQUID_CONFIG_DIR` | Override the configuration directory |
|
||||
| `SQUID_STATE_DIR` | Override the state and history directory |
|
||||
| `SQUID_LANG` | Force the CLI/TUI language to `zh` or `en` |
|
||||
| `SQUID_UPDATE_URL` | Override the desktop update manifest URL for staging |
|
||||
| `SQUID_TRUECOLOR` / `NO_COLOR` | Control TUI color |
|
||||
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | Diagnose Windows console character width and layout |
|
||||
|
||||
## 6. Safety model
|
||||
|
||||
1. The desktop UI can only submit indexes from a scan, never arbitrary paths.
|
||||
2. Before execution, Squid rebuilds each item and rechecks ownership, safety anchors, protected locations, the whitelist, and lock state.
|
||||
3. Deletion goes to Trash / Recycle Bin by default; permanent deletion must be explicit.
|
||||
4. System roots, `/usr`, `/System`, `/Applications`, and similar locations cannot be recursively deleted. Symlinks are never followed.
|
||||
5. Every real deletion is recorded in a local ledger; items still in Trash can be restored.
|
||||
6. Before ending a process, Squid samples it again and refuses critical system processes.
|
||||
|
||||
## 7. Uninstall
|
||||
|
||||
### macOS
|
||||
|
||||
1. Quit Squid.
|
||||
2. Move `/Applications/Squid.app` to the Trash.
|
||||
3. To remove configuration and history as well:
|
||||
|
||||
```bash
|
||||
rm -rf "$HOME/Library/Application Support/squid"
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
1. Uninstall Squid from **Settings → Apps**.
|
||||
2. To remove configuration and history as well, delete `%APPDATA%\squid`.
|
||||
|
||||
### CLI
|
||||
|
||||
```bash
|
||||
cargo uninstall squid-cli
|
||||
```
|
||||
|
||||
## 8. Troubleshooting
|
||||
|
||||
### macOS says the app is damaged
|
||||
|
||||
This is Gatekeeper quarantine on an unsigned build, not a damaged file. If right-click **Open** is not enough:
|
||||
|
||||
```bash
|
||||
xattr -dr com.apple.quarantine /Applications/Squid.app
|
||||
```
|
||||
|
||||
### Windows opens a blank window
|
||||
|
||||
Install the WebView2 Evergreen Runtime and relaunch Squid.
|
||||
|
||||
### Windows installer cannot write temporary files
|
||||
|
||||
When the installer runs from a non-system drive or a folder restricted by endpoint protection, NSIS may fail to unpack into `%TEMP%`. Copy it to `%TEMP%` on drive C: and run it there, or use `一键安装.bat` from the release directory.
|
||||
|
||||
### Cleanup finds less than expected
|
||||
|
||||
Check Full Disk Access on macOS, plus `whitelist`, `disabled_rules`, and the Security page's trusted list. Without Full Disk Access, TCC-protected locations are skipped and the Security page reports coverage as limited.
|
||||
|
||||
### Update check fails
|
||||
|
||||
Confirm the origin release channel is reachable:
|
||||
|
||||
<https://git.unissense.tech/mula/nex_squid/raw/branch/releases/squid-update.json>
|
||||
|
||||
In a proxy or offline environment, set `SQUID_UPDATE_URL` to a reachable mirror of the manifest.
|
||||
|
||||
### TUI layout is wrong
|
||||
|
||||
Try `SQUID_TRUECOLOR=0` or `NO_COLOR=1`. On Windows consoles, use `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` to diagnose character width and layout.
|
||||
|
||||
## 9. More documentation
|
||||
|
||||
- [Project overview](../README.en.md)
|
||||
- [Changelog](../CHANGELOG.md)
|
||||
- [Architecture](ARCHITECTURE.md)
|
||||
- [Desktop app](DESKTOP.md)
|
||||
- [Release and updates](RELEASE.md)
|
||||
- [Security](SECURITY.md)
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
# Squid 使用帮助
|
||||
|
||||
适用于 Squid 0.1.14。项目说明见 [`README.zh-CN.md`](../README.zh-CN.md),版本历史见 [`CHANGELOG.md`](../CHANGELOG.md)。
|
||||
|
||||
## 1. 下载与安装
|
||||
|
||||
Squid 的桌面安装包发布在 origin 仓库的 `releases` 分支,并同步附到 GitHub Release。GitHub 不承载这个分支。
|
||||
|
||||
- 发布目录:<https://git.unissense.tech/mula/nex_squid/src/branch/releases>
|
||||
- 更新清单:<https://git.unissense.tech/mula/nex_squid/raw/branch/releases/squid-update.json>
|
||||
|
||||
当前版本 0.1.14:
|
||||
|
||||
| 平台 | 安装包 |
|
||||
| --- | --- |
|
||||
| macOS 12+ | [`Squid-0.1.14-macOS-universal.dmg`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-0.1.14-macOS-universal.dmg) |
|
||||
| Windows 10/11 x64 | [`Squid-Setup-0.1.14-win-x64.exe`](https://git.unissense.tech/mula/nex_squid/raw/branch/releases/Squid-Setup-0.1.14-win-x64.exe) |
|
||||
|
||||
两个安装包都是未签名构建。校验文件大小和 SHA256 的方法见发布目录中的 `SHA256SUMS.txt`。
|
||||
|
||||
### macOS
|
||||
|
||||
1. 打开 DMG,把 `Squid.app` 拖进“应用程序”。
|
||||
2. 第一次启动请在访达中右键 `Squid`,选择“打开”。
|
||||
3. 如果系统提示“已损坏,无法打开”,去掉下载隔离属性后再启动:
|
||||
|
||||
```bash
|
||||
xattr -dr com.apple.quarantine /Applications/Squid.app
|
||||
open /Applications/Squid.app
|
||||
```
|
||||
|
||||
4. Squid 不需要 root,也不会安装后台服务、内核扩展或特权 helper。
|
||||
|
||||
### Windows
|
||||
|
||||
1. 运行 `Squid-Setup-<version>-win-x64.exe`。
|
||||
2. SmartScreen 提示时选择“更多信息” > “仍要运行”。
|
||||
3. 默认安装到 `%LOCALAPPDATA%\Programs\Squid`,不需要管理员权限。
|
||||
4. 如果安装器无法把临时文件写入 `%TEMP%`(部分 360 / 电脑管家环境),使用发布目录里的 `一键安装.bat`:它先把安装包复制到 C 盘的 `%TEMP%`,再启动安装。
|
||||
5. 如果启动后窗口空白,安装 Microsoft Edge WebView2 Evergreen Runtime 后重试:
|
||||
<https://developer.microsoft.com/microsoft-edge/webview2/>
|
||||
|
||||
## 2. 首次启动
|
||||
|
||||
- 界面语言默认跟随系统,可在“设置 → 常规”切换简体中文或 English。
|
||||
- 首次启动会显示一次可选的权限检查卡片,不会强制弹出系统权限窗口,也不会阻止应用启动。
|
||||
- 关闭主窗口只会隐藏窗口,Squid 继续驻留托盘;只有托盘菜单里的“退出 Squid”才会结束进程。
|
||||
- “设置 → 启动”可以打开开机自启。它只写入当前用户级启动项,不需要管理员权限。
|
||||
|
||||
## 3. 桌面端
|
||||
|
||||
### 左侧菜单
|
||||
|
||||
- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows)
|
||||
- **保护**:安全、启动项
|
||||
- **洞察**:存储空间、实时监控
|
||||
- **底部**:历史记录、设置
|
||||
|
||||
macOS 使用 `⌘1`–`⌘8`,Windows 使用 `Ctrl+1`–`Ctrl+9` 按侧栏顺序切换页面。macOS 隐藏 Windows 专属的权限管理,后面的页面顺延。
|
||||
|
||||
### 日常清理
|
||||
|
||||
1. 打开“日常清理”,选择扫描范围。
|
||||
2. 扫描完成后按分类检查结果;每个分类都可以单独取消勾选。
|
||||
3. 选择删除方式:默认进废纸篓/回收站,也可以显式选择永久删除。
|
||||
4. 点击清理,并在确认框中确认。
|
||||
|
||||
规则覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存、升级安装包和废纸篓/回收站。macOS 内置 38 条规则,Windows 内置 30 条规则。所有删除命令都支持 `--dry-run`(CLI),桌面端则先扫描再选择。
|
||||
|
||||
### 应用卸载
|
||||
|
||||
1. 打开“应用卸载”,搜索应用名称。
|
||||
2. 选中应用后,Squid 会把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划。
|
||||
3. 检查计划中的每一项,确认后执行。
|
||||
|
||||
残留匹配会排除常见文档后缀,避免把用户文档当成应用残留。
|
||||
|
||||
### 深度清理
|
||||
|
||||
“深度清理”查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载。默认项目根目录可以在配置里的 `purge_roots` 修改;`purge_min_age_days` 用来保护近期仍在使用的项目。
|
||||
|
||||
### 存储空间
|
||||
|
||||
选择一个目录后,Squid 逐层测量目录体积,并列出最大子项和最大文件。存储分析只在用户选择或配置目录后读取,文件内容不会上传。
|
||||
|
||||
### 实时监控与进程
|
||||
|
||||
- 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程。
|
||||
- “进程”页签列出全部进程及其签名状态与启动项来源。
|
||||
- 结束进程前 Squid 会重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
|
||||
- 可以把实时监控固定成桌面小工具;小工具设置从顶部齿轮下拉打开。
|
||||
|
||||
### 安全
|
||||
|
||||
- 读取 XProtect / Defender 状态,不会替你关闭或修改系统防护。
|
||||
- 按哈希、YARA 规则与启发式扫描恶意软件,发现分为“已确认 / 可疑 / 提示”三级。
|
||||
- 已确认项可以隔离,也可以从隔离区恢复。
|
||||
- 安全页支持按发布者、应用目录或提示类型信任正常软件;已确认威胁不会被白名单静默。
|
||||
- 不上传文件名、哈希、扫描结果或被隔离的文件。
|
||||
|
||||
### 启动项与权限管理
|
||||
|
||||
- “启动项”列出 LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以停用和恢复。
|
||||
- Windows 的“权限管理”按软件分组启动项,并提供右键菜单扩展、弹窗规则与后台监听。
|
||||
|
||||
### 历史记录与撤销
|
||||
|
||||
每次真实删除都会写入本地账本。仍在废纸篓/回收站中的内容可以在“历史记录”里还原;CLI 使用 `squid history` 和 `squid undo`。
|
||||
|
||||
### 软件更新
|
||||
|
||||
- 默认每天最多自动检查一次,也可以在“设置 → 更新”手动检查。
|
||||
- 更新清单来自 origin 的 `releases` 分支,不来自 GitHub。
|
||||
- 安装包必须匹配清单中的精确大小和 SHA256;带发布公钥的构建还会校验清单的 Ed25519 签名。
|
||||
- 下载完成后可以安装并重启,或清除已下载文件。
|
||||
|
||||
## 4. CLI 与 TUI
|
||||
|
||||
安装:
|
||||
|
||||
```bash
|
||||
cargo install --path crates/squid-cli --locked
|
||||
```
|
||||
|
||||
或者从源码构建:
|
||||
|
||||
```bash
|
||||
cargo build --release -p squid-cli
|
||||
```
|
||||
|
||||
常用命令:
|
||||
|
||||
| 命令 | 作用 |
|
||||
| --- | --- |
|
||||
| `squid state` | 打开 TUI |
|
||||
| `squid status` | 输出系统快照 |
|
||||
| `squid clean --dry-run` | 预览可清理内容 |
|
||||
| `squid clean -y` | 按规则执行清理 |
|
||||
| `squid uninstall --list` | 列出已安装应用 |
|
||||
| `squid uninstall <NAME>` | 生成应用本体加残留的卸载计划 |
|
||||
| `squid purge <PATH>` | 清理项目构建产物 |
|
||||
| `squid analyze <PATH>` | 输出目录体积树与最大文件 |
|
||||
| `squid history` | 查看删除账本 |
|
||||
| `squid undo [ID]` | 还原最近一次或指定废纸篓会话 |
|
||||
| `squid whitelist add\|list\|remove` | 维护保护路径 |
|
||||
| `squid rules` | 列出当前生效的规则 |
|
||||
| `squid doctor` | 检查权限、配置、历史文件和生效路径 |
|
||||
| `squid guard status` | 报告 XProtect / Defender 状态、规则包版本、启动项数量与隔离区占用 |
|
||||
| `squid guard scan [PATHS…]` | 扫描恶意软件;`--full` 全盘,`--json` 输出 JSON,`-y` 自动隔离已确认项 |
|
||||
| `squid guard startup` | 列出登录/启动条目;`--all` 含系统自带,`--risky` 只看需注意的 |
|
||||
| `squid guard quarantine <ID>` / `restore <ID>` | 隔离或恢复指定发现 |
|
||||
| `squid guard held` | 列出隔离区内容与原因 |
|
||||
|
||||
所有删除命令都支持 `--dry-run`。非交互环境必须显式使用 `-y/--yes`,否则 Squid 会拒绝执行删除。完整参数运行 `squid <command> --help`。
|
||||
|
||||
## 5. 配置与数据
|
||||
|
||||
| 用途 | macOS | Windows |
|
||||
| --- | --- | --- |
|
||||
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
|
||||
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
|
||||
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
|
||||
|
||||
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史。
|
||||
|
||||
常用配置(`config.toml`):
|
||||
|
||||
```toml
|
||||
delete_mode = "trash"
|
||||
history_keep = 60
|
||||
purge_min_age_days = 7
|
||||
purge_max_entries = 200000
|
||||
show_allocated = true
|
||||
# 留空表示跟随系统;也可以设为 "en" 或 "zh"
|
||||
language = ""
|
||||
whitelist = ["~/Library/Caches/ImportantApp"]
|
||||
disabled_rules = ["user-trash"]
|
||||
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
|
||||
```
|
||||
|
||||
常用环境变量:
|
||||
|
||||
| 变量 | 作用 |
|
||||
| --- | --- |
|
||||
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
|
||||
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
|
||||
| `SQUID_LANG` | 强制 CLI/TUI 使用 `zh` 或 `en` |
|
||||
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
|
||||
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
|
||||
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
|
||||
|
||||
## 6. 安全边界
|
||||
|
||||
1. 桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
|
||||
2. 执行前重新构造并校验路径所有权、安全锚点、保护列表、白名单和锁定状态。
|
||||
3. 默认删除到废纸篓/回收站;永久删除必须显式选择。
|
||||
4. 系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除,符号链接不会被跟随。
|
||||
5. 每次真实删除写入本地账本,仍可还原的内容可以撤销。
|
||||
6. 结束进程前重新采样并核对名称,拒绝关键系统进程。
|
||||
|
||||
## 7. 卸载
|
||||
|
||||
### macOS
|
||||
|
||||
1. 退出 Squid。
|
||||
2. 把 `/Applications/Squid.app` 移到废纸篓。
|
||||
3. 如需同时删除配置和历史:
|
||||
|
||||
```bash
|
||||
rm -rf "$HOME/Library/Application Support/squid"
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
1. 在“设置 → 应用”中卸载 Squid。
|
||||
2. 如需同时删除配置和历史,删除 `%APPDATA%\squid`。
|
||||
|
||||
### CLI
|
||||
|
||||
```bash
|
||||
cargo uninstall squid-cli
|
||||
```
|
||||
|
||||
## 8. 故障排查
|
||||
|
||||
### macOS 提示“已损坏,无法打开”
|
||||
|
||||
这是未签名构建被 Gatekeeper 隔离,不是文件损坏。右键“打开”仍然不行时:
|
||||
|
||||
```bash
|
||||
xattr -dr com.apple.quarantine /Applications/Squid.app
|
||||
```
|
||||
|
||||
### Windows 启动后窗口空白
|
||||
|
||||
安装 WebView2 Evergreen Runtime 后重新启动 Squid。
|
||||
|
||||
### Windows 安装器提示无法写入临时文件
|
||||
|
||||
安装包在非系统盘或受端点防护限制的目录运行时,NSIS 可能无法解压到 `%TEMP%`。把安装包复制到 C 盘的 `%TEMP%` 再运行,或使用发布目录里的 `一键安装.bat`。
|
||||
|
||||
### 清理结果比预期少
|
||||
|
||||
检查是否授予了完整磁盘访问(macOS),以及 `whitelist`、`disabled_rules` 和安全页的“已信任”列表。没有完整磁盘访问时,受 TCC 保护的位置会被跳过,安全页会把覆盖范围标为“受限”。
|
||||
|
||||
### 更新检查失败
|
||||
|
||||
确认能访问 origin 的发布通道:
|
||||
|
||||
<https://git.unissense.tech/mula/nex_squid/raw/branch/releases/squid-update.json>
|
||||
|
||||
代理或离线环境可以设置 `SQUID_UPDATE_URL` 指向可访问的镜像清单。
|
||||
|
||||
### TUI 排版异常
|
||||
|
||||
尝试设置 `SQUID_TRUECOLOR=0`、`NO_COLOR=1`,或在 Windows 控制台设置 `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` 排查字符宽度。
|
||||
|
||||
## 9. 更多文档
|
||||
|
||||
- [项目说明](../README.zh-CN.md)
|
||||
- [更新日志](../CHANGELOG.md)
|
||||
- [架构说明](ARCHITECTURE.md)
|
||||
- [桌面端说明](DESKTOP.md)
|
||||
- [发布与更新](RELEASE.md)
|
||||
- [安全说明](SECURITY.md)
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 417 KiB |
|
|
@ -1,190 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
:root {
|
||||
--primary: #f26a33; --primary-strong: #d94f1f; --primary-soft: #fff0e7; --primary-tint: #fff7f2;
|
||||
--primary-rgb: 242,106,51; --ink: #342019; --muted: #7d6256; --muted-soft: #a98f80;
|
||||
--line: rgba(89,51,34,.1); --paper: #fbf7f2; --canvas: #f5eee7;
|
||||
--green: #19a974; --green-soft: #e5f8f0; --orange: #ee844c; --red: #e65a62;
|
||||
}
|
||||
body { width: 1320px; background: var(--canvas); color: var(--ink);
|
||||
font-family: "Segoe UI", "Microsoft YaHei", sans-serif; font-size: 14px; font-weight: 540;
|
||||
padding: 30px 40px 44px; }
|
||||
h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
|
||||
.sub { color: var(--muted); font-size: 13.5px; margin-bottom: 24px; }
|
||||
h2 { font-size: 15px; font-weight: 700; margin: 30px 0 10px; color: var(--primary-strong); }
|
||||
h2 span { color: var(--muted-soft); font-weight: 540; font-size: 12.5px; margin-left: 8px; }
|
||||
.app { background: #fffdfb; border: 1px solid var(--line); border-radius: 16px;
|
||||
box-shadow: 0 14px 34px rgba(89,51,34,.08); padding: 26px 30px 24px; }
|
||||
.eyebrow { color: var(--primary-strong); font-size: 12px; font-weight: 650; letter-spacing: .12em; }
|
||||
.title { font-size: 22px; font-weight: 720; margin: 6px 0 4px; }
|
||||
.desc { color: var(--muted); font-size: 13.5px; margin-bottom: 18px; }
|
||||
.btn { border-radius: 10px; padding: 10px 18px; font-size: 13.5px; font-weight: 620;
|
||||
border: 1px solid var(--line); background: #fff; color: var(--ink); }
|
||||
.btn.primary { background: linear-gradient(145deg, #ff9664, var(--primary) 55%, var(--primary-strong));
|
||||
color: #fff; border: none; box-shadow: 0 6px 14px rgba(var(--primary-rgb),.25); }
|
||||
.btn.ghost { border-color: rgba(var(--primary-rgb),.3); color: var(--primary-strong); }
|
||||
.btn.sm { padding: 6px 12px; font-size: 12.5px; border-radius: 9px; }
|
||||
.chip { display:inline-block; font-size: 11.5px; border-radius: 999px; padding: 3px 10px; background: #fff;
|
||||
border: 1px solid var(--line); color: var(--muted); }
|
||||
.chip.ok { color: var(--green); border-color: rgba(25,169,116,.35); background: var(--green-soft); }
|
||||
|
||||
.main-card { border: 1px solid rgba(var(--primary-rgb),.25); border-radius: 14px; padding: 18px 22px;
|
||||
background: linear-gradient(135deg, var(--primary-tint), #fff); display: flex; align-items: center; gap: 18px; }
|
||||
.app-ic { width: 54px; height: 54px; border-radius: 14px; background: linear-gradient(145deg,#6ea8ff,#3f6fd8);
|
||||
color: #fff; display: flex; align-items: center; justify-content: center; font-size: 24px; flex: 0 0 auto;
|
||||
box-shadow: 0 6px 14px rgba(63,111,216,.3); }
|
||||
.main-card b { font-size: 15.5px; }
|
||||
.main-card small { display: block; color: var(--muted); margin-top: 3px; font-size: 12.5px; line-height: 1.6; }
|
||||
.kbd { font-family: Consolas, monospace; font-size: 11.5px; background: #fff; border: 1px solid var(--line);
|
||||
border-bottom-width: 2.5px; border-radius: 6px; padding: 2px 8px; color: var(--ink); }
|
||||
|
||||
.items { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 12px; margin-top: 14px; }
|
||||
.item { border: 1px solid var(--line); border-radius: 12px; background: var(--paper); padding: 12px 14px; }
|
||||
.item b { font-size: 13px; display: flex; align-items: center; gap: 6px; }
|
||||
.item small { display: block; color: var(--muted-soft); font-size: 11.5px; margin-top: 6px; line-height: 1.6; }
|
||||
.item .st { font-size: 10.5px; border-radius: 999px; padding: 1px 7px; margin-left: auto; }
|
||||
.st.on { color: var(--green); background: var(--green-soft); }
|
||||
.st.off { color: var(--muted-soft); background: rgba(89,51,34,.06); }
|
||||
|
||||
.hist { margin-top: 14px; border: 1px solid var(--line); border-radius: 12px; background: #fff; }
|
||||
.hist-h { display: flex; align-items: center; padding: 12px 16px 8px; font-size: 14px; font-weight: 700; }
|
||||
.hist-h .acts { margin-left: auto; display: flex; gap: 8px; }
|
||||
.hrow { display: flex; align-items: center; gap: 12px; padding: 10px 16px; border-top: 1px dashed var(--line); }
|
||||
.thumb { width: 62px; height: 38px; border-radius: 7px; border: 1px solid var(--line); flex: 0 0 auto;
|
||||
background: linear-gradient(135deg, #dfe8f5, #f6e8dd); position: relative; overflow: hidden; }
|
||||
.thumb i { position: absolute; left: 6px; right: 6px; height: 3px; border-radius: 2px; background: rgba(52,32,25,.18); }
|
||||
.thumb i:nth-child(1) { top: 8px; } .thumb i:nth-child(2) { top: 16px; width: 60%; right: auto; }
|
||||
.thumb i:nth-child(3) { top: 24px; width: 78%; right: auto; }
|
||||
.hrow .meta { flex: 1 1 auto; min-width: 0; }
|
||||
.hrow .meta b { font-size: 13px; font-weight: 640; }
|
||||
.hrow .meta small { display: block; color: var(--muted); font-size: 11.5px; margin-top: 2px;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-family: Consolas, monospace; }
|
||||
.hrow .char { color: var(--muted-soft); font-size: 11.5px; flex: 0 0 auto; }
|
||||
.fine { color: var(--muted-soft); font-size: 11.5px; margin-top: 10px; }
|
||||
.two { display: grid; grid-template-columns: 1.4fr 1fr; gap: 14px; }
|
||||
|
||||
/* capture overlay mock */
|
||||
.cap { background: linear-gradient(160deg, #2c2a33, #1c1b22); border-radius: 16px; padding: 30px 34px 26px;
|
||||
position: relative; min-height: 460px; overflow: hidden; }
|
||||
.fake-window { background: #f7f5f2; border-radius: 10px; box-shadow: 0 18px 44px rgba(0,0,0,.45); overflow: hidden; }
|
||||
.fw-bar { background: #e9e5df; padding: 8px 12px; font-size: 12px; color: #6b6257; display: flex; gap: 6px; }
|
||||
.fw-bar i { width: 10px; height: 10px; border-radius: 50%; background: #d6cdc2; }
|
||||
.fw-body { padding: 14px 16px; }
|
||||
.fw-line { height: 10px; border-radius: 4px; background: #ded8d0; margin-bottom: 10px; }
|
||||
.dim { display: none; }
|
||||
.sel { position: absolute; left: 74px; top: 84px; width: 560px; height: 300px; border: 2px solid var(--primary);
|
||||
border-radius: 4px; box-shadow: 0 0 0 9999px rgba(20,18,24,.55); }
|
||||
.handle { position: absolute; width: 9px; height: 9px; background: #fff; border: 2px solid var(--primary); border-radius: 2px; }
|
||||
.sel .size { position: absolute; left: 0; top: -26px; background: var(--primary); color: #fff; font-size: 11.5px;
|
||||
padding: 3px 9px; border-radius: 6px; font-family: Consolas, monospace; }
|
||||
.toolbar { position: absolute; left: 74px; top: 402px; background: #fff; border-radius: 10px;
|
||||
box-shadow: 0 10px 26px rgba(0,0,0,.35); display: flex; padding: 6px; gap: 4px; }
|
||||
.tbtn { width: 34px; height: 30px; border-radius: 7px; display: flex; align-items: center; justify-content: center;
|
||||
font-size: 14px; color: #4a4238; }
|
||||
.tbtn.hl { background: var(--primary-soft); color: var(--primary-strong); }
|
||||
.tsep { width: 1px; background: var(--line); margin: 4px 4px; }
|
||||
.ocr-pop { position: absolute; right: 40px; top: 84px; width: 360px; background: #fffdfb; border-radius: 12px;
|
||||
box-shadow: 0 18px 44px rgba(0,0,0,.4); padding: 14px 16px; }
|
||||
.ocr-pop h4 { font-size: 13px; display: flex; align-items: center; gap: 8px; }
|
||||
.ocr-pop h4 .tag { font-size: 10.5px; background: var(--green-soft); color: var(--green); border-radius: 999px; padding: 1px 8px; margin-left: auto; }
|
||||
.ocr-text { margin-top: 10px; background: #f6f2ec; border-radius: 8px; padding: 10px 12px; font-size: 12.5px;
|
||||
line-height: 1.7; color: var(--ink); max-height: 190px; overflow: hidden; }
|
||||
.ocr-text .sel-hl { background: rgba(242,106,51,.22); border-radius: 3px; }
|
||||
.ocr-acts { display: flex; gap: 8px; margin-top: 10px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Squid 小工具 · 截图识字(B1:snow-shot 引擎,纯离线 OCR)</h1>
|
||||
<div class="sub">Squid 负责入口、快捷键、结果归档与设置;截图框选 / 标注 / 识字浮层由 snow-shot 完成(随包分发,进程解耦)。</div>
|
||||
|
||||
<h2>① Squid 内「小工具 › 截图识字」页 <span class="en">入口 + 设置 + 识别历史</span></h2>
|
||||
<div class="app">
|
||||
<div class="eyebrow">UTILITIES</div>
|
||||
<div class="title">截图识字</div>
|
||||
<div class="desc">框选屏幕任意区域:可标注、贴图、长截图、录屏,一键提取文字 —— 全程离线,画面不出本机。</div>
|
||||
|
||||
<div class="main-card">
|
||||
<div class="app-ic">✂</div>
|
||||
<div>
|
||||
<b>截图识字引擎 · snow-shot 1.6.0 · 已就绪(离线识别)</b>
|
||||
<small>识别模型已就位(PaddleOCR · 中文/英文,约 15 MB)· 更新:自动跟随 Squid 更新 · 许可:GPL-3(随包附协议)</small>
|
||||
</div>
|
||||
<div style="margin-left:auto; display:flex; gap:10px; align-items:center;">
|
||||
<span style="font-size:12.5px;color:var(--muted)">快捷键 <span class="kbd">Ctrl</span> + <span class="kbd">Alt</span> + <span class="kbd">A</span></span>
|
||||
<button class="btn primary">开始截图</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="items">
|
||||
<div class="item"><b>📥 保存位置 <span class="st on">接管</span></b>
|
||||
<small>图片\Squid 截图<br>命名按时间自动<br><button class="btn sm" style="margin-top:6px">打开文件夹</button></small></div>
|
||||
<div class="item"><b>🌙 跟随开机 <span class="st on">开</span></b>
|
||||
<small>登录后热键即生效<br>未开也能从本页启动<br><button class="btn sm" style="margin-top:6px">设置</button></small></div>
|
||||
<div class="item"><b>📋 识文自动复制 <span class="st on">开</span></b>
|
||||
<small>点「提取文字」后自动进剪贴板<br>并记入下方历史<br><button class="btn sm" style="margin-top:6px">设置</button></small></div>
|
||||
<div class="item"><b>🧩 划词翻译 <span class="st off">未装</span></b>
|
||||
<small>需 B2 增强包 Umi-OCR<br>(HTTP 接口联动,可选)<br><button class="btn sm ghost" style="margin-top:6px">了解</button></small></div>
|
||||
</div>
|
||||
|
||||
<div class="hist">
|
||||
<div class="hist-h">识别历史 <small style="color:var(--muted-soft);font-weight:540;margin-left:8px">点行=重新复制文字 · 保留 30 天</small>
|
||||
<div class="acts"><button class="btn sm">导出全部</button><button class="btn sm">清空</button></div></div>
|
||||
<div class="hrow"><div class="thumb"><i></i><i></i><i></i></div>
|
||||
<div class="meta"><b>今天 17:42 · 报价单截图</b><small>图片\Squid 截图\2026-11-25 174215.png</small></div>
|
||||
<span class="char">326 字</span><button class="btn sm ghost">复制文字</button><button class="btn sm">打开图</button></div>
|
||||
<div class="hrow"><div class="thumb"><i></i><i></i><i></i></div>
|
||||
<div class="meta"><b>今天 15:08 · 报错弹窗</b><small>图片\Squid 截图\2026-11-25 150803.png</small></div>
|
||||
<span class="char">88 字</span><button class="btn sm ghost">复制文字</button><button class="btn sm">打开图</button></div>
|
||||
<div class="hrow"><div class="thumb"><i></i><i></i><i></i></div>
|
||||
<div class="meta"><b>昨天 21:36 · 会议纪要长截图</b><small>图片\Squid 截图\2026-11-24 213644.png</small></div>
|
||||
<span class="char">1,204 字</span><button class="btn sm ghost">复制文字</button><button class="btn sm">打开图</button></div>
|
||||
</div>
|
||||
<p class="fine">冷启动:首次按热键约 1 秒拉起引擎,之后常驻秒开;引擎崩溃不影响 Squid,托盘与本页都能重启它。</p>
|
||||
</div>
|
||||
|
||||
<h2>② 截图中的浮层(snow-shot 实机风格) <span class="en">框选 → 标注工具条 → 提取文字结果卡</span></h2>
|
||||
<div class="cap">
|
||||
<div style="position:absolute; left:60px; top:60px; width:600px;">
|
||||
<div class="fake-window">
|
||||
<div class="fw-bar"><i></i><i></i><i></i> 发票明细 - 浏览器</div>
|
||||
<div class="fw-body">
|
||||
<div class="fw-line" style="width:88%"></div><div class="fw-line" style="width:70%"></div>
|
||||
<div class="fw-line" style="width:92%"></div><div class="fw-line" style="width:55%"></div>
|
||||
<div class="fw-line" style="width:80%"></div><div class="fw-line" style="width:64%;margin-bottom:0"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dim"></div>
|
||||
<div class="sel"><span class="size">560 × 300</span></div>
|
||||
<div class="toolbar">
|
||||
<span class="tbtn">✏</span><span class="tbtn">▭</span><span class="tbtn">→</span><span class="tbtn">M</span>
|
||||
<span class="tbtn">▦</span><span class="tbtn">🔍</span>
|
||||
<span class="tsep"></span>
|
||||
<span class="tbtn hl">文</span><span class="tbtn">📌</span><span class="tbtn">⬇</span>
|
||||
<span class="tsep"></span>
|
||||
<span class="tbtn hl" style="width:auto;padding:0 10px;font-size:12px">完成 ✓</span><span class="tbtn">✕</span>
|
||||
</div>
|
||||
<div class="ocr-pop">
|
||||
<h4>提取文字 <span class="tag">离线识别 · 0.6 秒</span></h4>
|
||||
<div class="ocr-text">
|
||||
电子发票(普通发票)<br>
|
||||
发票号码:<span class="sel-hl">24502000000018234567</span><br>
|
||||
开票日期:2026年11月20日<br>
|
||||
购买方:某某科技有限公司<br>
|
||||
金额合计:<span class="sel-hl">¥1,280.00</span> 税率 6%<br>
|
||||
……
|
||||
</div>
|
||||
<div class="ocr-acts">
|
||||
<button class="btn sm primary">复制全部</button>
|
||||
<button class="btn sm">保留换行</button>
|
||||
<button class="btn sm">合并段落</button>
|
||||
<button class="btn sm" style="margin-left:auto">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 271 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 598 KiB |
|
|
@ -1,245 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
:root {
|
||||
--primary: #f26a33; --primary-strong: #d94f1f; --primary-soft: #fff0e7; --primary-tint: #fff7f2;
|
||||
--primary-rgb: 242,106,51; --ink: #342019; --muted: #7d6256; --muted-soft: #a98f80;
|
||||
--line: rgba(89,51,34,.1); --line-strong: rgba(89,51,34,.16);
|
||||
--paper: #fbf7f2; --canvas: #f5eee7;
|
||||
--green: #19a974; --green-soft: #e5f8f0; --orange: #ee844c; --orange-soft: #fff0e7;
|
||||
--red: #e65a62; --red-soft: #ffeaeb; --violet: #7668e8; --violet-soft: #efedff;
|
||||
}
|
||||
body { width: 1320px; background: var(--canvas); color: var(--ink);
|
||||
font-family: "Segoe UI", "Microsoft YaHei", sans-serif; font-size: 14px; font-weight: 540;
|
||||
padding: 30px 40px 44px; }
|
||||
h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
|
||||
.sub { color: var(--muted); font-size: 13.5px; margin-bottom: 24px; }
|
||||
h2 { font-size: 15px; font-weight: 700; margin: 30px 0 10px; color: var(--primary-strong); }
|
||||
h2 span { color: var(--muted-soft); font-weight: 540; font-size: 12.5px; margin-left: 8px; }
|
||||
.app { background: #fffdfb; border: 1px solid var(--line); border-radius: 16px;
|
||||
box-shadow: 0 14px 34px rgba(89,51,34,.08); overflow: hidden; padding: 26px 30px 24px; }
|
||||
.eyebrow { color: var(--primary-strong); font-size: 12px; font-weight: 650; letter-spacing: .12em; }
|
||||
.title { font-size: 22px; font-weight: 720; margin: 6px 0 4px; }
|
||||
.desc { color: var(--muted); font-size: 13.5px; margin-bottom: 18px; }
|
||||
.btn { border-radius: 10px; padding: 10px 18px; font-size: 13.5px; font-weight: 620;
|
||||
border: 1px solid var(--line); background: #fff; color: var(--ink); }
|
||||
.btn.primary { background: linear-gradient(145deg, #ff9664, var(--primary) 55%, var(--primary-strong));
|
||||
color: #fff; border: none; box-shadow: 0 6px 14px rgba(var(--primary-rgb),.25); }
|
||||
.btn.ghost { border-color: rgba(var(--primary-rgb),.3); color: var(--primary-strong); }
|
||||
.btn.sm { padding: 6px 12px; font-size: 12.5px; border-radius: 9px; }
|
||||
.card { border: 1px solid var(--line); border-radius: 14px; background: var(--paper); padding: 16px 18px; }
|
||||
|
||||
/* status hero */
|
||||
.hero { display: flex; align-items: center; gap: 22px; border-radius: 14px; padding: 18px 22px; }
|
||||
.hero.ok { background: linear-gradient(135deg, var(--green-soft), #f2fbf7); border: 1px solid rgba(25,169,116,.35); }
|
||||
.hero.warn { background: linear-gradient(135deg, var(--orange-soft), #fff8f2); border: 1px solid rgba(238,132,76,.4); }
|
||||
.shield { width: 56px; height: 56px; border-radius: 16px; display: flex; align-items: center;
|
||||
justify-content: center; font-size: 26px; color: #fff; flex: 0 0 auto; }
|
||||
.shield.ok { background: linear-gradient(145deg, #35c48d, var(--green)); box-shadow: 0 6px 14px rgba(25,169,116,.3); }
|
||||
.shield.warn { background: linear-gradient(145deg, #ffab77, var(--orange)); box-shadow: 0 6px 14px rgba(238,132,76,.3); }
|
||||
.hero-main { flex: 1 1 auto; }
|
||||
.hero-main b { font-size: 17px; font-weight: 700; display: block; }
|
||||
.hero-main .who { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
|
||||
.hero-main .who em { font-style: normal; color: var(--primary-strong); font-weight: 640; }
|
||||
.chips { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.chip { font-size: 11.5px; border-radius: 999px; padding: 3px 10px; background: #fff;
|
||||
border: 1px solid var(--line); color: var(--muted); }
|
||||
.chip.ok { color: var(--green); border-color: rgba(25,169,116,.35); background: var(--green-soft); }
|
||||
.chip.warn { color: #b06a24; border-color: rgba(238,132,76,.45); background: var(--orange-soft); }
|
||||
.hero-acts { display: flex; flex-direction: column; gap: 8px; flex: 0 0 auto; }
|
||||
|
||||
/* scan grid */
|
||||
.grid3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; margin-top: 14px; }
|
||||
.scan-card { display: flex; flex-direction: column; gap: 8px; }
|
||||
.scan-card .ic { width: 34px; height: 34px; border-radius: 10px; display: flex; align-items: center;
|
||||
justify-content: center; font-size: 16px; }
|
||||
.scan-card b { font-size: 14.5px; }
|
||||
.scan-card small { color: var(--muted); font-size: 12px; line-height: 1.5; flex: 1 1 auto; }
|
||||
|
||||
/* cleanbar reuse */
|
||||
.cleanbar { border: 1px solid rgba(var(--primary-rgb),.4); border-radius: 12px; padding: 12px 16px;
|
||||
background: #fff; margin-top: 14px; box-shadow: 0 8px 22px rgba(var(--primary-rgb),.12); }
|
||||
.cb-row { display: flex; align-items: center; gap: 12px; }
|
||||
.cb-row b { font-size: 14px; font-weight: 650; }
|
||||
.cb-cur { font-family: Consolas, monospace; font-size: 11.5px; color: var(--muted-soft); margin-top: 3px; }
|
||||
.pct { margin-left: auto; font-family: Consolas, monospace; color: var(--primary-strong); font-weight: 700; }
|
||||
.track { height: 10px; border-radius: 999px; background: rgba(89,51,34,.08); margin-top: 10px; overflow: hidden; }
|
||||
.fill { height: 100%; width: 44%; border-radius: 999px;
|
||||
background: repeating-linear-gradient(115deg, rgba(255,255,255,.28) 0 10px, rgba(255,255,255,0) 10px 24px),
|
||||
linear-gradient(90deg, #ff9a68, var(--primary)); }
|
||||
|
||||
/* threats */
|
||||
.threats { margin-top: 14px; border: 1px solid rgba(230,90,98,.35); border-radius: 12px;
|
||||
background: var(--red-soft); padding: 12px 16px; }
|
||||
.threats h3 { font-size: 13.5px; color: #a33a42; margin-bottom: 8px; }
|
||||
.trow { display: flex; align-items: center; gap: 10px; padding: 7px 4px; border-top: 1px dashed rgba(230,90,98,.25); font-size: 12.5px; }
|
||||
.trow .fam { color: #fff; background: var(--red); border-radius: 6px; padding: 1px 8px; font-family: Consolas, monospace; font-size: 11px; }
|
||||
.trow .p { flex: 1 1 auto; font-family: Consolas, monospace; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.trow .eng { font-size: 11px; color: var(--violet); background: var(--violet-soft); border-radius: 999px; padding: 1px 8px; }
|
||||
|
||||
/* realtime feed */
|
||||
.rt { margin-top: 14px; border: 1px solid var(--line); border-radius: 12px; background: #fff; padding: 12px 16px; }
|
||||
.rt h3 { font-size: 13px; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
|
||||
.live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 3px rgba(25,169,116,.18); }
|
||||
.rt-row { display: flex; gap: 10px; font-family: Consolas, monospace; font-size: 12px; color: var(--muted);
|
||||
padding: 5px 0; border-top: 1px dashed var(--line); align-items: center; }
|
||||
.rt-row .st { font-size: 11px; border-radius: 999px; padding: 1px 8px; font-family: "Segoe UI", "Microsoft YaHei", sans-serif; }
|
||||
.rt-row .st.clean { color: var(--green); background: var(--green-soft); }
|
||||
.rt-row .st.hot { color: #fff; background: var(--red); }
|
||||
.rt-row time { color: var(--muted-soft); font-size: 11px; flex: 0 0 52px; }
|
||||
.rt-row .f { flex: 1 1 auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* takeover card */
|
||||
.take { margin-top: 14px; border: 1px solid rgba(var(--primary-rgb),.35); border-radius: 14px;
|
||||
background: linear-gradient(135deg, var(--primary-tint), #fff); padding: 16px 18px; }
|
||||
.take-row { display: flex; align-items: center; gap: 14px; }
|
||||
.take b { font-size: 14.5px; }
|
||||
.take small { display: block; color: var(--muted); margin-top: 3px; font-size: 12px; line-height: 1.55; }
|
||||
.switch { margin-left: auto; width: 46px; height: 26px; border-radius: 999px; background: var(--primary);
|
||||
position: relative; flex: 0 0 auto; box-shadow: inset 0 1px 3px rgba(0,0,0,.12); }
|
||||
.switch::after { content: ""; position: absolute; width: 20px; height: 20px; border-radius: 50%;
|
||||
background: #fff; top: 3px; right: 3px; box-shadow: 0 2px 5px rgba(0,0,0,.2); }
|
||||
.take-detail { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
|
||||
|
||||
/* dialog */
|
||||
.dlg-back { background: rgba(52,32,25,.4); border-radius: 16px; padding: 34px 60px; }
|
||||
.dlg { max-width: 560px; margin: 0 auto; background: #fffdfb; border-radius: 16px;
|
||||
box-shadow: 0 24px 60px rgba(52,32,25,.35); padding: 22px 26px; }
|
||||
.dlg h3 { font-size: 16px; font-weight: 720; display: flex; align-items: center; gap: 10px; }
|
||||
.dlg h3 .warn-ic { width: 26px; height: 26px; border-radius: 50%; background: var(--orange);
|
||||
color: #fff; display: inline-flex; align-items: center; justify-content: center; font-size: 15px; }
|
||||
.dlg ul { margin: 12px 0 4px 20px; color: var(--muted); font-size: 13px; line-height: 1.9; }
|
||||
.dlg ul li b { color: var(--ink); }
|
||||
.dlg .conflict { margin: 10px 0 0; padding: 10px 12px; border-radius: 10px; background: var(--orange-soft);
|
||||
border: 1px solid rgba(238,132,76,.4); font-size: 12.5px; color: #8a5a2b; line-height: 1.6; }
|
||||
.dlg .acts { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
|
||||
.fine { color: var(--muted-soft); font-size: 11.5px; margin-top: 10px; }
|
||||
|
||||
.sec-title { font-size: 14px; font-weight: 700; margin: 18px 0 8px; display: flex; align-items: center; gap: 8px; }
|
||||
.sec-title small { color: var(--muted-soft); font-weight: 540; }
|
||||
.two-col { display: grid; grid-template-columns: 1.25fr 1fr; gap: 14px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Squid 安全页 · ClamAV 引擎 + WSC 接管 产品方案图</h1>
|
||||
<div class="sub">沿用应用主题与 CleanBar 交互语言;实时防护 = Squid 热点目录监控 + clamd 本地毫秒扫描(ClamWin/ClamShield 同架构)。</div>
|
||||
|
||||
<h2>① 安全页 · 平时状态 <span class="en">接管完成,绿态;顶部分区即"我管理着你"</span></h2>
|
||||
<div class="app">
|
||||
<div class="eyebrow">SECURITY</div>
|
||||
<div class="title">安全查杀</div>
|
||||
<div class="desc">Squid 已接管 Windows 安全中心 · 实时防护守护 6 个高危目录 · 双引擎按需查杀</div>
|
||||
|
||||
<div class="hero ok">
|
||||
<div class="shield ok">🛡</div>
|
||||
<div class="hero-main">
|
||||
<b>设备正在受到保护 · 由 Squid 管理</b>
|
||||
<div class="who">Windows 安全中心显示:「病毒和威胁防护由于 <em>Squid</em> 提供,保持最新状态」· Windows Defender 已转为被动模式</div>
|
||||
<div class="chips">
|
||||
<span class="chip ok">● 实时防护 开(守护 6 目录)</span>
|
||||
<span class="chip ok">ClamAV 库 2026-11-25 · 今日已更新</span>
|
||||
<span class="chip ok">Defender 库 2026-11-25(被动,可用)</span>
|
||||
<span class="chip">上次全盘 今天 09:30 · 未发现威胁</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-acts">
|
||||
<button class="btn primary">快速查杀</button>
|
||||
<button class="btn ghost">全盘查杀</button>
|
||||
<button class="btn sm">脱机查杀(重启)</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-title">今日实时防护记录 <small>· 新文件落地即扫,共 1,214 个,1 个被拦截</small></div>
|
||||
<div class="rt">
|
||||
<h3><span class="live-dot"></span>热点目录实时监控 · 运行中(clamd 常驻 · 内存 320 MB · 空闲 5 分钟自动休眠)</h3>
|
||||
<div class="rt-row"><time>17:42</time><span class="f">C:\Users\34798\Downloads\setup-x64(1).exe</span><span class="eng">ClamAV</span><span class="st hot">拦截:疑似打包器 PUA</span></div>
|
||||
<div class="rt-row"><time>16:05</time><span class="f">D:\Temp\照片备份.7z → 解压 84 个文件</span><span class="eng">ClamAV</span><span class="st clean">安全 ×84</span></div>
|
||||
<div class="rt-row"><time>13:11</time><span class="f">E:\(U盘)\投标书-final.docx</span><span class="eng">ClamAV</span><span class="st clean">安全</span></div>
|
||||
</div>
|
||||
|
||||
<div class="take">
|
||||
<div class="take-row">
|
||||
<div>
|
||||
<b>接管 Windows 安全中心</b>
|
||||
<small>Squid 常驻后台,每 12 小时向安全中心报到(心跳);关闭开关将立刻注销,Windows Defender 自动恢复主动模式。</small>
|
||||
</div>
|
||||
<div class="switch"></div>
|
||||
</div>
|
||||
<div class="take-detail">
|
||||
<span class="chip ok">WSC 登记 已生效</span>
|
||||
<span class="chip ok">心跳 上次 17:00 · 正常</span>
|
||||
<span class="chip">开机自启 开</span>
|
||||
<span class="chip">卸载将自动注销</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-title">引擎与病毒库</div>
|
||||
<div class="grid3">
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--violet-soft);color:var(--violet)">⚙</span>
|
||||
<b>ClamAV 引擎(主)</b>
|
||||
<small>程序 22 MB 已就绪 · 病毒库 main+daily 213 MB<br><span style="font-family:Consolas,monospace">TUNA 国内镜像:开</span></small>
|
||||
<div><button class="btn sm">更新病毒库</button> <button class="btn sm">管理</button></div>
|
||||
</div>
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--green-soft);color:var(--green)">✓</span>
|
||||
<b>Windows Defender(第二意见)</b>
|
||||
<small>被动模式随时候命:全盘可交给它跑一遍,与 ClamAV 结果互补;库更新由系统托管。</small>
|
||||
<div><button class="btn sm ghost">用 Defender 全盘复查</button></div>
|
||||
</div>
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--primary-soft);color:var(--primary-strong)">⏱</span>
|
||||
<b>计划任务</b>
|
||||
<small>每天 09:30 快速查杀(启动项/服务/下载/浏览器目录);每周日全盘。错过不补跑,合盖休眠自动顺延。</small>
|
||||
<div><button class="btn sm">调整计划</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>② 查杀进行中 + 发现威胁 <span class="en">复用 CleanBar;威胁行带引擎来源徽标</span></h2>
|
||||
<div class="app">
|
||||
<div class="sec-title" style="margin-top:0">全盘查杀 · 引擎 ClamAV(库已加载内存)</div>
|
||||
<div class="cleanbar">
|
||||
<div class="cb-row">
|
||||
<span style="color:var(--primary);font-size:16px">◌</span>
|
||||
<div>
|
||||
<b>正在扫描 486,213 / 1,102,908 个文件 · 已用 6 分 12 秒</b>
|
||||
<div class="cb-cur">当前:C:\Users\34798\Documents\客户资料\合同-2023.zip · 发现威胁 2 · 已跳过压缩包内层 12,401</div>
|
||||
</div>
|
||||
<span class="pct">44%</span>
|
||||
<button class="btn sm" style="margin-left:12px">暂停</button>
|
||||
</div>
|
||||
<div class="track"><div class="fill"></div></div>
|
||||
</div>
|
||||
<div class="threats">
|
||||
<h3>发现 2 个威胁(处理前不会动它们)</h3>
|
||||
<div class="trow"><span class="fam">Eicar-Test-Signature</span><span class="p">C:\Users\34798\Downloads\clamavtest\eicar.txt</span><span class="eng">ClamAV</span><button class="btn sm">定位</button><button class="btn sm ghost">隔离</button></div>
|
||||
<div class="trow"><span class="fam">Trojan.GenericKD.46872</span><span class="p">D:\Soft\crack\patcher.exe</span><span class="eng">Defender 复查</span><button class="btn sm">定位</button><button class="btn sm ghost">隔离</button></div>
|
||||
</div>
|
||||
<p class="fine">隔离 = 移入 Squid 私有隔离区(可一键还原,同「历史」体系);不直接删除,避免误杀炸裂。</p>
|
||||
</div>
|
||||
|
||||
<h2>③ 开启接管时的确认弹窗 <span class="en">诚实告知:Defender 转被动,Squid 顶上</span></h2>
|
||||
<div class="app" style="padding:0">
|
||||
<div class="dlg-back">
|
||||
<div class="dlg">
|
||||
<h3><span class="warn-ic">!</span>接管 Windows 安全中心?</h3>
|
||||
<ul>
|
||||
<li>「Windows 安全中心」将显示 <b>由 Squid 提供保护</b>;</li>
|
||||
<li><b>Windows Defender 实时防护转为被动</b>,改由 Squid 热点实时监控 + ClamAV 引擎顶上;</li>
|
||||
<li>Defender 引擎仍保留,可作全盘复查的<b>第二意见</b>;</li>
|
||||
<li>Squid 需要<b>开机常驻</b>(托盘,内存约 40 MB + clamd 320 MB),关闭开关或卸载即自动还原。</li>
|
||||
</ul>
|
||||
<div class="conflict">检测到本机当前由「<b>腾讯电脑管家</b>」接管安全中心。开启前请先在管家中关闭「病毒防护」,否则两个产品会互相挤占登记。 <button class="btn sm">打开管家设置</button></div>
|
||||
<div class="acts">
|
||||
<button class="btn">保持现状</button>
|
||||
<button class="btn primary">确认接管</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 326 KiB |
|
|
@ -1,237 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
:root {
|
||||
--primary: #f26a33; --primary-strong: #d94f1f; --primary-soft: #fff0e7; --primary-tint: #fff7f2;
|
||||
--primary-rgb: 242,106,51; --ink: #342019; --muted: #7d6256; --muted-soft: #a98f80;
|
||||
--line: rgba(89,51,34,.1); --line-strong: rgba(89,51,34,.16);
|
||||
--paper: #fbf7f2; --canvas: #f5eee7;
|
||||
--green: #19a974; --green-soft: #e5f8f0; --orange: #ee844c; --orange-soft: #fff0e7;
|
||||
--red: #e65a62; --red-soft: #ffeaeb; --violet: #7668e8; --violet-soft: #efedff;
|
||||
}
|
||||
body { width: 1320px; background: var(--canvas); color: var(--ink);
|
||||
font-family: "Segoe UI", "Microsoft YaHei", sans-serif; font-size: 14px; font-weight: 540;
|
||||
padding: 30px 40px 44px; }
|
||||
h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
|
||||
.sub { color: var(--muted); font-size: 13.5px; margin-bottom: 24px; }
|
||||
h2 { font-size: 15px; font-weight: 700; margin: 30px 0 10px; color: var(--primary-strong); }
|
||||
h2 span { color: var(--muted-soft); font-weight: 540; font-size: 12.5px; margin-left: 8px; }
|
||||
.app { background: #fffdfb; border: 1px solid var(--line); border-radius: 16px;
|
||||
box-shadow: 0 14px 34px rgba(89,51,34,.08); padding: 26px 30px 24px; }
|
||||
.eyebrow { color: var(--primary-strong); font-size: 12px; font-weight: 650; letter-spacing: .12em; }
|
||||
.title { font-size: 22px; font-weight: 720; margin: 6px 0 4px; }
|
||||
.desc { color: var(--muted); font-size: 13.5px; margin-bottom: 18px; }
|
||||
.btn { border-radius: 10px; padding: 10px 18px; font-size: 13.5px; font-weight: 620;
|
||||
border: 1px solid var(--line); background: #fff; color: var(--ink); }
|
||||
.btn.primary { background: linear-gradient(145deg, #ff9664, var(--primary) 55%, var(--primary-strong));
|
||||
color: #fff; border: none; box-shadow: 0 6px 14px rgba(var(--primary-rgb),.25); }
|
||||
.btn.ghost { border-color: rgba(var(--primary-rgb),.3); color: var(--primary-strong); }
|
||||
.btn.sm { padding: 6px 12px; font-size: 12.5px; border-radius: 9px; }
|
||||
.card { border: 1px solid var(--line); border-radius: 14px; background: var(--paper); padding: 16px 18px; }
|
||||
.chip { display:inline-block; font-size: 11.5px; border-radius: 999px; padding: 3px 10px; background: #fff;
|
||||
border: 1px solid var(--line); color: var(--muted); }
|
||||
.chip.ok { color: var(--green); border-color: rgba(25,169,116,.35); background: var(--green-soft); }
|
||||
.chip.warn { color: #b06a24; border-color: rgba(238,132,76,.45); background: var(--orange-soft); }
|
||||
.hero { display: flex; align-items: center; gap: 22px; border-radius: 14px; padding: 18px 22px;
|
||||
background: linear-gradient(135deg, var(--green-soft), #f2fbf7); border: 1px solid rgba(25,169,116,.35); }
|
||||
.shield { width: 56px; height: 56px; border-radius: 16px; display: flex; align-items: center;
|
||||
justify-content: center; font-size: 26px; color: #fff; flex: 0 0 auto;
|
||||
background: linear-gradient(145deg, #35c48d, var(--green)); box-shadow: 0 6px 14px rgba(25,169,116,.3); }
|
||||
.hero-main { flex: 1 1 auto; }
|
||||
.hero-main b { font-size: 17px; font-weight: 700; display: block; }
|
||||
.hero-main .who { font-size: 12.5px; color: var(--muted); margin-top: 3px; }
|
||||
.hero-main .who em { font-style: normal; color: var(--primary-strong); font-weight: 640; }
|
||||
.chips { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.hero-acts { display: flex; flex-direction: column; gap: 8px; flex: 0 0 auto; }
|
||||
.sec-title { font-size: 14px; font-weight: 700; margin: 20px 0 10px; display: flex; align-items: center; gap: 8px; }
|
||||
.sec-title small { color: var(--muted-soft); font-weight: 540; }
|
||||
|
||||
/* modes */
|
||||
.modes { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
|
||||
.mode { border: 1.5px solid var(--line); border-radius: 14px; background: #fff; padding: 14px 16px 12px; position: relative; }
|
||||
.mode.on { border-color: var(--primary); background: linear-gradient(180deg, var(--primary-tint), #fff);
|
||||
box-shadow: 0 8px 20px rgba(var(--primary-rgb),.12); }
|
||||
.mode .head { display: flex; align-items: center; gap: 8px; }
|
||||
.mode .head b { font-size: 14.5px; }
|
||||
.mode .rec { font-size: 10.5px; background: var(--primary); color: #fff; border-radius: 999px; padding: 1px 8px; }
|
||||
.mode .memo { margin-top: 8px; color: var(--muted); font-size: 12px; line-height: 1.7; }
|
||||
.mode .memo b { color: var(--ink); font-weight: 640; }
|
||||
.mode .cost { margin-top: 9px; display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.radio { width: 16px; height: 16px; border-radius: 50%; border: 1.5px solid var(--line-strong); margin-left: auto; }
|
||||
.mode.on .radio { border: 5px solid var(--primary); }
|
||||
.mode .apply { position: absolute; right: 14px; bottom: 12px; opacity: 0; }
|
||||
.mode:not(.on):hover .apply { opacity: 1; }
|
||||
.mode-note { margin-top: 10px; color: var(--muted-soft); font-size: 11.5px; }
|
||||
|
||||
.rt { border: 1px solid var(--line); border-radius: 12px; background: #fff; padding: 12px 16px; }
|
||||
.rt h3 { font-size: 13px; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
|
||||
.live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 3px rgba(25,169,116,.18); }
|
||||
.idle-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted-soft); }
|
||||
.rt-row { display: flex; gap: 10px; font-family: Consolas, monospace; font-size: 12px; color: var(--muted);
|
||||
padding: 5px 0; border-top: 1px dashed var(--line); align-items: center; }
|
||||
.rt-row .st { font-size: 11px; border-radius: 999px; padding: 1px 8px; font-family: "Segoe UI", "Microsoft YaHei", sans-serif; }
|
||||
.rt-row .st.clean { color: var(--green); background: var(--green-soft); }
|
||||
.rt-row .st.hot { color: #fff; background: var(--red); }
|
||||
.rt-row time { color: var(--muted-soft); font-size: 11px; flex: 0 0 52px; }
|
||||
.rt-row .f { flex: 1 1 auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.rt-row .eng { color: var(--violet); background: var(--violet-soft); border-radius: 999px; padding: 1px 8px;
|
||||
font-size: 11px; font-family: "Segoe UI", "Microsoft YaHei", sans-serif; }
|
||||
|
||||
.take { border: 1px solid rgba(var(--primary-rgb),.35); border-radius: 14px;
|
||||
background: linear-gradient(135deg, var(--primary-tint), #fff); padding: 16px 18px; }
|
||||
.take-row { display: flex; align-items: center; gap: 14px; }
|
||||
.take b { font-size: 14.5px; }
|
||||
.take small { display: block; color: var(--muted); margin-top: 3px; font-size: 12px; line-height: 1.55; }
|
||||
.switch { margin-left: auto; width: 46px; height: 26px; border-radius: 999px; background: var(--primary);
|
||||
position: relative; flex: 0 0 auto; }
|
||||
.switch::after { content: ""; position: absolute; width: 20px; height: 20px; border-radius: 50%;
|
||||
background: #fff; top: 3px; right: 3px; box-shadow: 0 2px 5px rgba(0,0,0,.2); }
|
||||
.take-detail { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
|
||||
|
||||
.grid3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
|
||||
.scan-card { display: flex; flex-direction: column; gap: 8px; }
|
||||
.scan-card .ic { width: 34px; height: 34px; border-radius: 10px; display: flex; align-items: center;
|
||||
justify-content: center; font-size: 16px; }
|
||||
.scan-card b { font-size: 14.5px; }
|
||||
.scan-card small { color: var(--muted); font-size: 12px; line-height: 1.5; flex: 1 1 auto; }
|
||||
|
||||
.cleanbar { border: 1px solid rgba(var(--primary-rgb),.4); border-radius: 12px; padding: 12px 16px;
|
||||
background: #fff; margin-top: 14px; box-shadow: 0 8px 22px rgba(var(--primary-rgb),.12); }
|
||||
.cb-row { display: flex; align-items: center; gap: 12px; }
|
||||
.cb-row b { font-size: 14px; font-weight: 650; }
|
||||
.cb-cur { font-family: Consolas, monospace; font-size: 11.5px; color: var(--muted-soft); margin-top: 3px; }
|
||||
.pct { margin-left: auto; font-family: Consolas, monospace; color: var(--primary-strong); font-weight: 700; }
|
||||
.track { height: 10px; border-radius: 999px; background: rgba(89,51,34,.08); margin-top: 10px; overflow: hidden; }
|
||||
.fill { height: 100%; width: 44%; border-radius: 999px;
|
||||
background: repeating-linear-gradient(115deg, rgba(255,255,255,.28) 0 10px, rgba(255,255,255,0) 10px 24px),
|
||||
linear-gradient(90deg, #ff9a68, var(--primary)); }
|
||||
.threats { margin-top: 14px; border: 1px solid rgba(230,90,98,.35); border-radius: 12px;
|
||||
background: var(--red-soft); padding: 12px 16px; }
|
||||
.threats h3 { font-size: 13.5px; color: #a33a42; margin-bottom: 8px; }
|
||||
.trow { display: flex; align-items: center; gap: 10px; padding: 7px 4px; border-top: 1px dashed rgba(230,90,98,.25); font-size: 12.5px; }
|
||||
.trow .fam { color: #fff; background: var(--red); border-radius: 6px; padding: 1px 8px; font-family: Consolas, monospace; font-size: 11px; }
|
||||
.trow .p { flex: 1 1 auto; font-family: Consolas, monospace; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.fine { color: var(--muted-soft); font-size: 11.5px; margin-top: 10px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Squid 安全页 v2 · 三档防护模式</h1>
|
||||
<div class="sub">改名并备注模式解释;clamd 内存改用实测口径(节能模式按需拉起)。</div>
|
||||
|
||||
<div class="app">
|
||||
<div class="eyebrow">SECURITY</div>
|
||||
<div class="title">安全查杀</div>
|
||||
<div class="desc">Squid 已接管 Windows 安全中心 · 节能模式下常驻仅约 100 MB(较 Defender 实时防护省 200 MB+)</div>
|
||||
|
||||
<div class="hero">
|
||||
<div class="shield">🛡</div>
|
||||
<div class="hero-main">
|
||||
<b>设备正在受到保护 · 由 Squid 管理</b>
|
||||
<div class="who">Windows 安全中心显示:「病毒和威胁防护由 <em>Squid</em> 提供」· Windows Defender 实时服务已停用</div>
|
||||
<div class="chips">
|
||||
<span class="chip ok">● 实时防护 开(节能模式)</span>
|
||||
<span class="chip ok">ClamAV 库 2026-11-25 · 今日已更新</span>
|
||||
<span class="chip warn">clamd 当前休眠 · 需要时 5–15 秒拉起</span>
|
||||
<span class="chip">上次全盘 今天 09:30 · 未发现威胁</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hero-acts">
|
||||
<button class="btn primary">快速查杀</button>
|
||||
<button class="btn ghost">全盘查杀</button>
|
||||
<button class="btn sm">脱机查杀(重启)</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-title">实时防护模式 <small>· 三档,随时可切;当前:节能模式</small></div>
|
||||
<div class="modes">
|
||||
<div class="mode on">
|
||||
<div class="head"><b>节能模式</b><span class="rec">推荐</span><span class="radio"></span></div>
|
||||
<div class="memo">常驻只有 Squid 本体(目录监听 + 计划 + 心跳,约 <b>100 MB</b>)。高危目录有新文件时才拉起 clamd,<b>扫描后 5 分钟无活动自动休眠</b>;识别结果约延迟 10 秒弹出。</div>
|
||||
<div class="cost"><span class="chip ok">平时最省内存</span><span class="chip">较 Defender 净省 200 MB+</span></div>
|
||||
<button class="btn sm apply">切换</button>
|
||||
</div>
|
||||
<div class="mode">
|
||||
<div class="head"><b>性能模式</b><span class="radio"></span></div>
|
||||
<div class="memo">clamd <b>24 小时常驻</b>,新文件落地<b>毫秒级</b>出结果、无拉起延迟。代价是引擎与病毒库全程驻留内存(约 <b>650–900 MB</b>),适合内存充裕、下载频繁的主力机。</div>
|
||||
<div class="cost"><span class="chip warn">内存 +650–900 MB</span><span class="chip">实时最快</span></div>
|
||||
<button class="btn sm apply">切换</button>
|
||||
</div>
|
||||
<div class="mode">
|
||||
<div class="head"><b>手动模式</b><span class="radio"></span></div>
|
||||
<div class="memo">不做实时监控,只保留<b>手动查杀与每日计划扫描</b>。Squid 可完全退出;接管开着的话,安全中心会在 7 天后提示「防护已过期」。</div>
|
||||
<div class="cost"><span class="chip">零常驻</span><span class="chip warn">无实时防护</span></div>
|
||||
<button class="btn sm apply">切换</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mode-note">备注:节能/性能模式的差别只在 clamd 是否常驻;目录监听与拦截处置逻辑相同。切换即时生效,无需重启。</div>
|
||||
|
||||
<div class="sec-title">今日实时防护记录 <small>· 新文件落地即排队检查,共 1,214 个,1 个被拦截</small></div>
|
||||
<div class="rt">
|
||||
<h3><span class="live-dot"></span>热点目录监控运行中 · 6 个目录 · clamd 休眠中(今日被拉起 37 次,平均每次 2.4 分钟)</h3>
|
||||
<div class="rt-row"><time>17:42</time><span class="f">C:\Users\34798\Downloads\setup-x64(1).exe</span><span class="eng">ClamAV</span><span class="st hot">拦截:疑似打包器 PUA</span></div>
|
||||
<div class="rt-row"><time>16:05</time><span class="f">D:\Temp\照片备份.7z → 解压 84 个文件</span><span class="eng">ClamAV</span><span class="st clean">安全 ×84</span></div>
|
||||
<div class="rt-row"><time>13:11</time><span class="f">E:\(U盘)\投标书-final.docx</span><span class="eng">ClamAV</span><span class="st clean">安全</span></div>
|
||||
</div>
|
||||
|
||||
<div class="take" style="margin-top:14px">
|
||||
<div class="take-row">
|
||||
<div>
|
||||
<b>接管 Windows 安全中心</b>
|
||||
<small>Squid 常驻时向安全中心持续报到(心跳);关闭开关将立刻注销,Windows Defender 自动恢复主动模式。</small>
|
||||
</div>
|
||||
<div class="switch"></div>
|
||||
</div>
|
||||
<div class="take-detail">
|
||||
<span class="chip ok">WSC 登记 已生效</span>
|
||||
<span class="chip ok">心跳 上次 17:00 · 正常</span>
|
||||
<span class="chip">开机自启 开</span>
|
||||
<span class="chip">卸载将自动注销</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-title">引擎与病毒库</div>
|
||||
<div class="grid3">
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--violet-soft);color:var(--violet)">⚙</span>
|
||||
<b>ClamAV 引擎(主)</b>
|
||||
<small>程序 22 MB 已就绪 · 病毒库 213 MB · 常驻状态随防护模式变化(当前休眠)<br><span style="font-family:Consolas,monospace">TUNA 国内镜像:开</span></small>
|
||||
<div><button class="btn sm">更新病毒库</button> <button class="btn sm">管理</button></div>
|
||||
</div>
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--green-soft);color:var(--green)">✓</span>
|
||||
<b>Windows Defender(第二意见)</b>
|
||||
<small>实时服务已停用(由 Squid 接管);引擎保留,全盘可交给它复查一遍,与 ClamAV 结果互补。</small>
|
||||
<div><button class="btn sm ghost">用 Defender 全盘复查</button></div>
|
||||
</div>
|
||||
<div class="card scan-card">
|
||||
<span class="ic" style="background:var(--primary-soft);color:var(--primary-strong)">⏱</span>
|
||||
<b>计划任务</b>
|
||||
<small>每天 09:30 快速查杀(启动项/服务/下载/浏览器目录);每周日全盘。合盖休眠自动顺延,错过不补跑。</small>
|
||||
<div><button class="btn sm">调整计划</button></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sec-title">查杀进行中(样式沿用 CleanBar)+ 威胁列表</div>
|
||||
<div class="cleanbar">
|
||||
<div class="cb-row">
|
||||
<span style="color:var(--primary);font-size:16px">◌</span>
|
||||
<div>
|
||||
<b>正在扫描 486,213 / 1,102,908 个文件 · 已用 6 分 12 秒</b>
|
||||
<div class="cb-cur">当前:C:\Users\34798\Documents\客户资料\合同-2023.zip · 发现威胁 2</div>
|
||||
</div>
|
||||
<span class="pct">44%</span>
|
||||
<button class="btn sm" style="margin-left:12px">暂停</button>
|
||||
</div>
|
||||
<div class="track"><div class="fill"></div></div>
|
||||
</div>
|
||||
<div class="threats">
|
||||
<div class="trow" style="border-top:0"><span class="fam">Eicar-Test-Signature</span><span class="p">C:\Users\34798\Downloads\clamavtest\eicar.txt</span><span class="eng" style="color:var(--violet);background:var(--violet-soft);border-radius:999px;padding:1px 8px;font-size:11px">ClamAV</span><button class="btn sm">定位</button><button class="btn sm ghost">隔离</button></div>
|
||||
<div class="trow"><span class="fam">Trojan.GenericKD.46872</span><span class="p">D:\Soft\crack\patcher.exe</span><span class="eng" style="color:var(--violet);background:var(--violet-soft);border-radius:999px;padding:1px 8px;font-size:11px">Defender 复查</span><button class="btn sm">定位</button><button class="btn sm ghost">隔离</button></div>
|
||||
</div>
|
||||
<p class="fine">隔离 = 移入 Squid 私有隔离区(可一键还原,接入「历史」体系);不直接删除,避免误杀。</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
10
package.json
10
package.json
|
|
@ -1,8 +1,15 @@
|
|||
{
|
||||
"name": "squid-desktop",
|
||||
"private": true,
|
||||
"version": "0.2.0",
|
||||
"version": "0.1.14",
|
||||
"type": "module",
|
||||
"author": "mula.liu",
|
||||
"license": "GPL-3.0-only",
|
||||
"homepage": "https://github.com/VulpineLiu/squid",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/VulpineLiu/squid.git"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite --port 1420 --strictPort",
|
||||
"build": "tsc && vite build",
|
||||
|
|
@ -17,6 +24,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",
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@
|
|||
# Intel 上都能装,bottle 交给 `brew tap-new` 的 CI 去做。
|
||||
class Squid < Formula
|
||||
desc "Clean, uninstall, purge and watch a Mac from the terminal"
|
||||
homepage "https://github.com/nexdev/squid"
|
||||
version "0.1.0"
|
||||
homepage "https://github.com/VulpineLiu/squid"
|
||||
version "0.1.11"
|
||||
sha256 "REPLACE_WITH_DIST_SQUID_TARBALL_SHA256"
|
||||
url "https://github.com/nexdev/squid/releases/download/v#{version}/squid-#{version}-universal-apple-darwin.tar.gz"
|
||||
url "https://github.com/VulpineLiu/squid/releases/download/v#{version}/squid-#{version}-universal-apple-darwin.tar.gz"
|
||||
license "GPL-3.0-only"
|
||||
|
||||
# 也可以直接从源码装(不需要预先发 release):
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
Squid 0.1.10 - 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。
|
||||
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
|
||||
运行 Squid 才能修改,界面会给出明确提示。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.10-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
|
||||
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.10-win-x64.exe -Algorithm SHA256
|
||||
|
||||
提示
|
||||
----
|
||||
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
|
||||
上右键退出),否则安装程序无法替换正在运行的程序文件。
|
||||
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
|
||||
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
|
||||
按方便程度排序:
|
||||
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
|
||||
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
|
||||
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
|
||||
3) 使用便携包 Squid-0.1.10-portable-win-x64.zip,解压后把 Squid 目录
|
||||
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
|
||||
- 桌面小工具在安装后默认开启,会出现在屏幕右上角;新版新增 CPU 面板
|
||||
(总占用曲线 + 每核渐变占用柱),可在主程序「桌面小工具」页开关各面板。
|
||||
- 清理新增「升级安装包」分类:应用升级后留在 AppData 的安装包(微信、
|
||||
企业微信、WPS 等),放置超过 7 天才会被找出;删除确认时可一键跳过。
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
Squid 0.1.10 更新说明
|
||||
|
||||
新增
|
||||
- 空间清理全面对齐专业清理工具的扫描体验(借鉴 Mole):
|
||||
· 扫描时实时显示「已统计 12.8 万个文件 · 38.2 GB」滚动计数,进度条在真正
|
||||
完成前最多走到 99%,不再出现「满了但还在转」的错觉;
|
||||
· 各分类不再干等:哪个分类先算完就先在扫描界面出现(项数 + 大小);
|
||||
· 清理点与文件行显示「12 个月未使用」休眠标签(超过 90 天没再写入的绿色
|
||||
标注),配合大小一起帮你决定删不删;
|
||||
· node_modules 等项目产物新增「可删依据」面板:锁文件 / 安装记录 / 有无
|
||||
手工修改 / Git 状态 / 目录年龄逐条列出,被手改过的目录会红色警示;
|
||||
· 低风险清理(≤40 项、不含升级包、复核全部通过)不再弹窗,底部绿色
|
||||
确认条一步完成(Esc 取消);含升级包或大批量仍走确认对话框,对话框内
|
||||
新增「刚刚逐路径复核过 N 项」折叠面板,展示删除前的最后一轮锁 / 白名单
|
||||
/ 应用运行 / 路径消失复核结果;
|
||||
· 清理完成后新增「有 N 项本次未处理」分组页:按原因(应用正在运行 /
|
||||
需要管理员 / 已消失 / 白名单 / 受保护)归类,每组给下一步操作按钮;
|
||||
· 结果列表可一键「导出清单」,生成 Markdown 文件(含每一项路径、大小、
|
||||
依据与受保护项),方便留档或反馈。
|
||||
- 存储空间页新增「隐藏的吃空间大户」:Windows 更新缓存、休眠文件、页面文件、
|
||||
WinSxS 组件库、手机备份、90 天前的下载,逐项给出大小与下一步(查看 /
|
||||
复制释放命令);同页文件夹测量结果缓存 10 分钟,秒开时标注「缓存数据 ·
|
||||
上次测量 X 分钟前」并可一键重新测量,删除文件后缓存自动作废。
|
||||
- 微信 / QQ 聊天文件、浏览器离线应用数据(IndexedDB)、搜狗词库等「看起来像
|
||||
缓存、实际是你的文件」的目录,现在会以待解锁行出现在扫描结果里并写明原因,
|
||||
引擎在删除层也强制拒删。
|
||||
- 设置 → 受保护的位置新增「消费审计」:每条白名单规则标注最近扫描是否命中,
|
||||
从未命中的过期规则一眼可见。
|
||||
- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包
|
||||
(微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。
|
||||
只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件
|
||||
不会被误删;应用正在运行时相关安装包自动锁定。删除确认时会提示升级包数量
|
||||
与大小,可一键「跳过升级包,只删其余」。
|
||||
- 桌面小工具新增「CPU」面板:总体占用率历史曲线 + 整行渐变占用柱,一根柱对应
|
||||
一个逻辑核心;柱色随占用率在绿→黄→橙→红之间连续渐变(含柱内纵向微渐变),
|
||||
悬停显示「核心 N: xx%」(编号与任务管理器一致从 0 开始);核心较多时柱宽自动
|
||||
收窄。管理页与桌面设置弹层可独立开关该面板。
|
||||
|
||||
优化
|
||||
- 桌面常驻 CPU 占用大幅下降(实测本机构从约 8.5% 全机总占用降至 0.2%):
|
||||
小工具改用轻量采样(跳过全机逐进程枚举,那是旧版每秒最贵的一步)、两个
|
||||
窗口共享同一次采样、小工具折叠或主窗口收进托盘后完全停止采样。实时监控
|
||||
页打开时才有完整进程表,功能不受影响。
|
||||
- 修复小工具窗口自身的自适应尺寸回环(尺寸→重锚定→再触发自适应无限循环),
|
||||
该回环会让主进程与小工具渲染进程空转互叫并频繁写配置文件;修复后小工具
|
||||
开着时 Squid 全家 CPU 占用接近 0%。
|
||||
|
||||
修复
|
||||
- 权限管理:修复开机启动项开关点了没反应 / 立刻弹回的问题——所有启动项
|
||||
(当前用户、所有用户、32 位、启动文件夹、服务、计划任务)统一改用最小
|
||||
注册表权限写入,遇到「拒绝访问」自动发起一次系统管理员授权(UAC)后重试
|
||||
并回读核实;开关失败时现在有红色气泡提示原因(此前只在页面顶部一闪而过)。
|
||||
- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题
|
||||
出现一次,子行文字与标题对齐)。
|
||||
- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有
|
||||
进入结果列表的派生缓存,点击后视图停留在扫描瞬间);「可选」角标不再
|
||||
遮挡复选框。
|
||||
- 权限管理:修复大量启动项/服务显示通用图标的问题——服务壳程序(如微软
|
||||
Edge 提权服务、电脑管家 qmbsrv、H3C SpaceAgent)自身不含图标资源,
|
||||
现改为回退读取注册表 App Paths、卸载信息 DisplayIcon 与同目录主程序
|
||||
图标,让每一行显示真正的软件图标。
|
||||
- 深度清理:默认检查目录(~/code 等 macOS 风格)在本机全都不存在时不再报
|
||||
「请先选择目录」,自动回退到用户主目录扫描;「要检查的项目目录」旁新增
|
||||
「浏览…」按钮可直接多选文件夹;扫描出错信息此前会被静默吞掉,现在会以
|
||||
红色横幅显示。
|
||||
- 托盘交互:左键单击/双击图标 = 直接打开主界面,右键 = 弹出菜单(原先
|
||||
左键也会弹菜单)。
|
||||
|
||||
调整
|
||||
- 开机启动项对齐电脑管家的分组管理:每个软件一组,组标题带总开关(一键开/关
|
||||
该软件的全部启动项)与状态(全部开启 / 部分开启 3/10 / 已全部关闭);细项
|
||||
默认折叠,点开才可逐项单独控制;搜索时自动展开。无法归属到具体软件的条目
|
||||
(无名服务、计划任务、系统组件)统一归入排在最后的「其他软件」组,归属判定
|
||||
与管家一致:读取二进制自带的产品名/文件说明,模板占位文字不算。
|
||||
- 深度扫描目录改为全自动发现,界面不再提供目录配置:自动扫描每个磁盘根目录下
|
||||
一层的项目容器(repos/code/dev/projects/work/src/documents 等)与用户主目录
|
||||
(桌面/文档浅层兜底),不存在的目录概念从此消失;实测本机自动命中约 21 GB
|
||||
构建产物。高级用户仍可在配置文件 purge_roots 里追加目录(自动生效);
|
||||
设置栏仅保留「仅处理早于 N 天」。
|
||||
- 界面移除「Git 保护」开关:删前用 git 复核被跟踪目录本来就是永远执行的
|
||||
安全兜底,不该做成可关选项;确需绕过时走命令行 squid purge --all。
|
||||
- 空间清理对齐电脑管家的「清理点」粒度:规则类分类(系统垃圾 / 日志 /
|
||||
浏览器缓存等)展开后先按清理点汇总(如「Windows 更新下载缓存 441 MB ·
|
||||
1 个位置」),点开清理点才显示具体路径;悬停清理点可「忽略」(加入保护
|
||||
名单,可随时撤销)或「查看路径」;受安全策略保护、无法删除的项目默认
|
||||
不再刷屏,折叠为一行说明并提供「仍然显示」;应用正在运行、需要管理员
|
||||
等可操作锁定仍照常显示原因。「回收站 / 项目产物 / 开发文件」保持平铺。
|
||||
- 空间清理改版(参照电脑管家布局):取消「分类卡片 + 下方大列表」双层
|
||||
结构,分类即列表、一屏一层;分「已为你默认勾选 / 需要你手动勾选」两区,
|
||||
点击分类行展开该分类子项(再点收起),点击子项整行直接在资源管理器中
|
||||
定位文件位置,只有点小方框才改勾选;顶部常驻「已选中 xxx 可清理文件」
|
||||
汇总条(取消全选 / 立即清理随时可点)。
|
||||
- 「日常清理」与「深度清理」合并为一个「空间清理」页:一次扫描同时检查缓存
|
||||
垃圾与项目构建目录,结果汇总为一份清单。默认只勾选日常清理项,「升级安装
|
||||
包 / 项目产物 / 开发文件」三类为可选(虚线卡片 + 可选角标),勾选后与日常
|
||||
项合并成一次清理。深度扫描目录、文件年龄(3/7/30 天)、Git 保护收进页面
|
||||
顶部设置栏;扫描与删除全程有步骤条与实时进度;侧边栏与托盘菜单同步精简,
|
||||
快捷键重排(Ctrl+2 = 空间清理)。
|
||||
- 桌面小工具 Win+D 常驻:按下「显示桌面」后小工具约 2 秒内自动回到桌面
|
||||
(窗口保持桌面层:在壁纸与图标之上、其他软件窗口之下;自己关闭/折叠
|
||||
不会把它叫回来)。
|
||||
- Windows 上所有「废纸篓」文案改为「回收站」(清理、卸载、历史、设置等随系统
|
||||
名称联动);macOS 仍为「废纸篓」。
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
c718a5bd7550586d9c3cfa156ec4b8b6fa80731c9bcd91f55d80a53e02796564 Squid-Setup-0.1.10-win-x64.exe
|
||||
7bfd6a22639cb8a97370d71047ed281cecbd5cd06aed6a104957638cdc9f252f Squid-0.1.10-portable-win-x64.zip
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -1,5 +0,0 @@
|
|||
@echo off
|
||||
rem 360/QQPC Manager blocks unsigned installers started from non-system
|
||||
rem drives when they unpack into TEMP. Copy the setup to %TEMP% on C: first.
|
||||
copy /Y "%~dp0Squid-Setup-0.1.10-win-x64.exe" "%TEMP%\" >nul
|
||||
start "" "%TEMP%\Squid-Setup-0.1.10-win-x64.exe"
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
Squid 0.1.11 - 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。
|
||||
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
|
||||
运行 Squid 才能修改,界面会给出明确提示。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.11-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
|
||||
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.11-win-x64.exe -Algorithm SHA256
|
||||
|
||||
提示
|
||||
----
|
||||
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
|
||||
上右键退出),否则安装程序无法替换正在运行的程序文件。
|
||||
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
|
||||
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
|
||||
按方便程度排序:
|
||||
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
|
||||
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
|
||||
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
|
||||
3) 使用便携包 Squid-0.1.11-portable-win-x64.zip,解压后把 Squid 目录
|
||||
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
|
||||
- 本版本主打「洞察 + 维护」两条线:新增重复文件(三级漏斗 + 智能保留)、
|
||||
大文件、存储空间矩形图三个洞察页;新增系统维护(6 项一键修复)、隐私
|
||||
清理、系统优化(可逆开关 + 一键恢复默认)三个维护页;清理分类新增
|
||||
「AI 工具与模型」(Ollama / HuggingFace / AI 桌面端缓存,模型永不默认
|
||||
勾选)。除隐私页(有意绕过回收站、逐条入历史)外,删除均走回收站可撤销。
|
||||
- 桌面小工具修复远程桌面问题:RDP 连接/断开会改变主屏分辨率,旧版会让
|
||||
小工具被 Windows 摆到屏幕中间;现在检测到屏幕尺寸变化会自动重新归位
|
||||
到设定角落(手动拖动过的位置会保留,且始终在屏幕范围内)。
|
||||
- 应用卸载新增「安装不完整」检测(MSI 状态 + 文件双缺失)与红色徽章,
|
||||
可一键清理残留注册表记录;安装来源自动标注 winget / scoop /
|
||||
Chocolatey / JetBrains Toolbox / Microsoft Store 徽章。
|
||||
- 权限管理新增「进阶启动项」页签:Winlogon 登录链、AppInit_DLLs、
|
||||
IFEO 调试器、BHO 与自动启动服务,逐行数字签名核验(微软 / 已知厂商 /
|
||||
无数字签名 / 红色签名失效),首次打开该页签才执行签名核验,不拖慢
|
||||
权限管理主视图。
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
Squid 0.1.11 更新说明
|
||||
|
||||
新增
|
||||
- 重复文件独立页:三级漏斗找重复(按大小分组 → 头/中/尾 16KB 采样哈希 →
|
||||
SHA-256 全量校验),页面上「已遍历 → 同大小候选 → 采样命中 → 全量校验
|
||||
确认」四个数字实时更新;磁盘哈希缓存让第二次扫描只做增量。智能选择每组
|
||||
自动保留一份(路径最短或最旧的一份;个人资产优先保留更珍贵的那份),
|
||||
微信 FileStorage 里的副本自动标记「个人文件」并锁定,不会被默认勾选
|
||||
误删;「忽略本组」一键让某组从此不再出现。删除全部走回收站,历史记录
|
||||
里可一键撤销。实测本机 3.4 万个文件约 1 秒完成全漏斗。
|
||||
- 大文件独立页:全部磁盘 / C / D / E 范围,≥100MB / 500MB / 1GB 阈值,
|
||||
按视频 / 归档 / 安装包 / 镜像类型过滤;180 天没动过的标「休眠」;OneDrive、
|
||||
坚果云等同步目录里的文件提示「网盘可能有副本」;ISO/VHD 等系统关键文件
|
||||
默认隐藏并提示可能正被挂载,删除走回收站。
|
||||
- 存储空间页新增「矩形图」视图:面积即占用,一眼看出哪个目录在吃空间,
|
||||
点格子直接下钻;与列表共用 10 分钟测量缓存,两种视图秒切。
|
||||
- 清理新增「AI 工具与模型」分类:Ollama 按模型逐行列出(共享层只算给
|
||||
独占它的模型,绝不重复计费;备注写明删除后 ollama pull 可原样恢复),
|
||||
HuggingFace 缓存按仓库列出,Codex / Claude / ChatGPT 桌面端缓存与更新包
|
||||
单独成行。模型是您下载的数字资产,永远不默认勾选;纯缓存项预先勾好。
|
||||
- 系统维护页:6 个白名单一键修复任务(搜索索引重建、图标缓存、网络重置、
|
||||
音频服务、Windows 更新组件、SFC+DISM 系统文件修复),每项带风险徽章、
|
||||
预计耗时与硬性超时;命令固定、绝不拼接 shell;全局互斥保证同一时刻只有
|
||||
一个任务在跑;日志逐行实时滚动;需要管理员的步骤只弹一次 UAC。
|
||||
- 隐私清理页:浏览器历史与 Cookie(浏览器在运行时自动锁定并提示先完全
|
||||
退出,含 WAL/SHM 附属文件)、最近使用文件与跳转列表、剪贴板历史、活动
|
||||
历史。本页删除有意绕过回收站(半恢复的浏览器 profile 比删掉更糟),
|
||||
但每一笔仍逐条写入历史记录可审计。
|
||||
- 系统优化页:少而稳的可逆开关目录(窗口透明、文件扩展名、小组件联网、
|
||||
定位、最近添加的文件),每项都先在真机验证后才上架;首次修改前记录系统
|
||||
原值,顶部「恢复全部默认」一键还原;已经是目标状态的行显示无操作。
|
||||
- 权限管理新增「进阶启动项」页签:Winlogon Shell/Userinit 登录链、
|
||||
AppInit_DLLs 全局注入、IFEO 调试器(可劫持任意程序启动)、浏览器 BHO、
|
||||
自动启动服务。每行带数字签名徽章(微软签名 / 已知厂商 / 无数字签名 /
|
||||
红色签名失效),异常登录链与劫持一眼可见;所有改动原样记录可回退,
|
||||
页面懒加载不拖慢权限管理主视图。
|
||||
- 应用卸载增强:MSI 产品状态 + 安装目录与卸载器双重缺失检测,「安装不完整」
|
||||
的应用挂红色徽章,点进去可一键清理残留的注册表记录(HKLM 走一次 UAC,
|
||||
取消授权不会假装成功);识别安装来源并标注徽章:winget / scoop /
|
||||
Chocolatey / JetBrains Toolbox / Microsoft Store。
|
||||
|
||||
修复
|
||||
- 桌面小组件不再在远程桌面连接 / 断开后跑到屏幕中间:原因是对端接入会
|
||||
改写控制台显示设备、分辨率随之变化,Windows 按旧的小几何把窗口摆到
|
||||
中间。现在心跳检测到主屏尺寸任何变化都会把小工具重新归位到设定角落并
|
||||
压回桌面层;手动拖动过的位置会被保留,但始终夹在屏幕范围内。
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
196d6382bded50d5d8dd0593240b016adf8c9cb5e2f95e610d8d1bf029a158be Squid-Setup-0.1.11-win-x64.exe
|
||||
4349e178016a8596ce56c2ed0ab31013cfa7eefe13b0aac68b9eca8a7f022be5 Squid-0.1.11-portable-win-x64.zip
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,13 +0,0 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.11",
|
||||
"date": "2026-11-24",
|
||||
"notes": "Squid 0.1.11 更新说明\n\n新增\n- 重复文件独立页:三级漏斗找重复(按大小分组 → 头/中/尾 16KB 采样哈希 →\n SHA-256 全量校验),页面上「已遍历 → 同大小候选 → 采样命中 → 全量校验\n 确认」四个数字实时更新;磁盘哈希缓存让第二次扫描只做增量。智能选择每组\n 自动保留一份(路径最短或最旧的一份;个人资产优先保留更珍贵的那份),\n 微信 FileStorage 里的副本自动标记「个人文件」并锁定,不会被默认勾选\n 误删;「忽略本组」一键让某组从此不再出现。删除全部走回收站,历史记录\n 里可一键撤销。实测本机 3.4 万个文件约 1 秒完成全漏斗。\n- 大文件独立页:全部磁盘 / C / D / E 范围,≥100MB / 500MB / 1GB 阈值,\n 按视频 / 归档 / 安装包 / 镜像类型过滤;180 天没动过的标「休眠」;OneDrive、\n 坚果云等同步目录里的文件提示「网盘可能有副本」;ISO/VHD 等系统关键文件\n 默认隐藏并提示可能正被挂载,删除走回收站。\n- 存储空间页新增「矩形图」视图:面积即占用,一眼看出哪个目录在吃空间,\n 点格子直接下钻;与列表共用 10 分钟测量缓存,两种视图秒切。\n- 清理新增「AI 工具与模型」分类:Ollama 按模型逐行列出(共享层只算给\n 独占它的模型,绝不重复计费;备注写明删除后 ollama pull 可原样恢复),\n HuggingFace 缓存按仓库列出,Codex / Claude / ChatGPT 桌面端缓存与更新包\n 单独成行。模型是您下载的数字资产,永远不默认勾选;纯缓存项预先勾好。\n- 系统维护页:6 个白名单一键修复任务(搜索索引重建、图标缓存、网络重置、\n 音频服务、Windows 更新组件、SFC+DISM 系统文件修复),每项带风险徽章、\n 预计耗时与硬性超时;命令固定、绝不拼接 shell;全局互斥保证同一时刻只有\n 一个任务在跑;日志逐行实时滚动;需要管理员的步骤只弹一次 UAC。\n- 隐私清理页:浏览器历史与 Cookie(浏览器在运行时自动锁定并提示先完全\n 退出,含 WAL/SHM 附属文件)、最近使用文件与跳转列表、剪贴板历史、活动\n 历史。本页删除有意绕过回收站(半恢复的浏览器 profile 比删掉更糟),\n 但每一笔仍逐条写入历史记录可审计。\n- 系统优化页:少而稳的可逆开关目录(窗口透明、文件扩展名、小组件联网、\n 定位、最近添加的文件),每项都先在真机验证后才上架;首次修改前记录系统\n 原值,顶部「恢复全部默认」一键还原;已经是目标状态的行显示无操作。\n- 权限管理新增「进阶启动项」页签:Winlogon Shell/Userinit 登录链、\n AppInit_DLLs 全局注入、IFEO 调试器(可劫持任意程序启动)、浏览器 BHO、\n 自动启动服务。每行带数字签名徽章(微软签名 / 已知厂商 / 无数字签名 /\n 红色签名失效),异常登录链与劫持一眼可见;所有改动原样记录可回退,\n 页面懒加载不拖慢权限管理主视图。\n- 应用卸载增强:MSI 产品状态 + 安装目录与卸载器双重缺失检测,「安装不完整」\n 的应用挂红色徽章,点进去可一键清理残留的注册表记录(HKLM 走一次 UAC,\n 取消授权不会假装成功);识别安装来源并标注徽章:winget / scoop /\n Chocolatey / JetBrains Toolbox / Microsoft Store。\n\n修复\n- 桌面小组件不再在远程桌面连接 / 断开后跑到屏幕中间:原因是对端接入会\n 改写控制台显示设备、分辨率随之变化,Windows 按旧的小几何把窗口摆到\n 中间。现在心跳检测到主屏尺寸任何变化都会把小工具重新归位到设定角落并\n 压回桌面层;手动拖动过的位置会被保留,但始终夹在屏幕范围内。\n",
|
||||
"artifacts": {
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.1.11-win-x64.exe",
|
||||
"sha256": "196d6382bded50d5d8dd0593240b016adf8c9cb5e2f95e610d8d1bf029a158be",
|
||||
"size": 3850501
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
@echo off
|
||||
rem 360/QQPC Manager blocks unsigned installers started from non-system
|
||||
drive when they unpack into TEMP. Copy the setup to %TEMP% on C: first.
|
||||
copy /Y "%~dp0Squid-Setup-0.1.11-win-x64.exe" "%TEMP%\" >nul
|
||||
start "" "%TEMP%\Squid-Setup-0.1.11-win-x64.exe"
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
Squid 0.1.12 - 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。
|
||||
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
|
||||
运行 Squid 才能修改,界面会给出明确提示。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.12-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
|
||||
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.12-win-x64.exe -Algorithm SHA256
|
||||
|
||||
提示
|
||||
----
|
||||
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
|
||||
上右键退出),否则安装程序无法替换正在运行的程序文件。
|
||||
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
|
||||
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
|
||||
按方便程度排序:
|
||||
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
|
||||
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
|
||||
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
|
||||
3) 使用便携包 Squid-0.1.12-portable-win-x64.zip,解压后把 Squid 目录
|
||||
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
|
||||
- 本版本是导航整合版:空间清理(垃圾清理/重复文件/大文件)与系统维护
|
||||
(一键修复/隐私清理/系统优化)各收成一个三页签页面;一级目录
|
||||
「存储空间」移除(与大文件重叠)。所有功能与删除保护不变。
|
||||
- 桌面小组件「回到本机跑到桌面中间」彻底修复:改为每秒比对实际位置与
|
||||
应在位置,谁动它都回位(含 RDP 会话切换、系统重摆、第三方软件移动);
|
||||
手动拖动会自动宽限,不跟手打架。
|
||||
- 「定位」按钮在含空格路径(如 Package Cache)下跳错文件夹的问题已在
|
||||
0.1.11 修复,本版本一并携带。
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
Squid 0.1.12 更新说明
|
||||
|
||||
调整
|
||||
- 左侧导航大整合,功能一个不少、入口少一半:
|
||||
· 「空间清理」升级为三页签:垃圾清理 / 重复文件 / 大文件。页签标题带
|
||||
实时计数徽标(不点进去也知道有没有货);切换页签不清结果——扫描状态、
|
||||
勾选、正在跑的任务全部保留;进入哪个页签才扫哪个,不再拖慢首屏。
|
||||
· 「系统维护」升级为三页签:一键修复 / 隐私清理 / 系统优化。隐私清理与
|
||||
系统优化从桌面组并入;修复任务运行中切页签,日志照常滚动。
|
||||
· 一级目录「存储空间」整页移除(与「大文件」定位重叠),矩形图随之
|
||||
下线;「洞察」组只剩实时监控,「桌面」组只剩桌面小工具。
|
||||
· 快捷键重排:1 概览 · 2 空间清理 · 3 应用卸载 · 4 权限管理 · 5 系统维护
|
||||
· 6 实时监控 · 7 小工具 · 8 历史 · 9 设置,0 开关小工具。
|
||||
|
||||
修复
|
||||
- 桌面小组件「远程被别人连过之后,回到本机就跑到桌面中间」:上一版只在
|
||||
屏幕分辨率变化时归位,但 RDP 接入时本机会话直接断开、回到本机解锁时
|
||||
分辨率从未变过——是 Windows 在会话重连时按旧几何重新摆放了窗口。现在
|
||||
心跳每秒比对小组件实际位置与应在位置(设定角落或您拖动记住的点),
|
||||
任何偏差立即拉回并重新压回桌面层;正在拖动时自动宽限,不会跟手打架。
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
d37472a3930e4f9c3b970fcbbbbe2d351e7fadde1d129310024b590a0ea633b4 Squid-Setup-0.1.12-win-x64.exe
|
||||
886062f7ee42d83e15510956459d91bdf8c7df2c755c7aa52310a715c599c30e Squid-0.1.12-portable-win-x64.zip
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,13 +0,0 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.12",
|
||||
"date": "2026-11-24",
|
||||
"notes": "Squid 0.1.12 更新说明\n\n调整\n- 左侧导航大整合,功能一个不少、入口少一半:\n · 「空间清理」升级为三页签:垃圾清理 / 重复文件 / 大文件。页签标题带\n 实时计数徽标(不点进去也知道有没有货);切换页签不清结果——扫描状态、\n 勾选、正在跑的任务全部保留;进入哪个页签才扫哪个,不再拖慢首屏。\n · 「系统维护」升级为三页签:一键修复 / 隐私清理 / 系统优化。隐私清理与\n 系统优化从桌面组并入;修复任务运行中切页签,日志照常滚动。\n · 一级目录「存储空间」整页移除(与「大文件」定位重叠),矩形图随之\n 下线;「洞察」组只剩实时监控,「桌面」组只剩桌面小工具。\n · 快捷键重排:1 概览 · 2 空间清理 · 3 应用卸载 · 4 权限管理 · 5 系统维护\n · 6 实时监控 · 7 小工具 · 8 历史 · 9 设置,0 开关小工具。\n\n修复\n- 桌面小组件「远程被别人连过之后,回到本机就跑到桌面中间」:上一版只在\n 屏幕分辨率变化时归位,但 RDP 接入时本机会话直接断开、回到本机解锁时\n 分辨率从未变过——是 Windows 在会话重连时按旧几何重新摆放了窗口。现在\n 心跳每秒比对小组件实际位置与应在位置(设定角落或您拖动记住的点),\n 任何偏差立即拉回并重新压回桌面层;正在拖动时自动宽限,不会跟手打架。\n",
|
||||
"artifacts": {
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.1.12-win-x64.exe",
|
||||
"sha256": "d37472a3930e4f9c3b970fcbbbbe2d351e7fadde1d129310024b590a0ea633b4",
|
||||
"size": 3843385
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
@echo off
|
||||
rem 360/QQPC Manager blocks unsigned installers started from non-system
|
||||
drives when they unpack into TEMP. Copy the setup to %TEMP% on C: first.
|
||||
copy /Y "%~dp0Squid-Setup-0.1.12-win-x64.exe" "%TEMP%\" >nul
|
||||
start "" "%TEMP%\Squid-Setup-0.1.12-win-x64.exe"
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
Squid 0.1.13 - 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。
|
||||
- 权限管理页中,机单(HKLM)范围的启动项开关与删除、系统服务需要以
|
||||
管理员身份运行 Squid(或同意一次 UAC 提权)才能修改,界面会给出
|
||||
明确提示;UAC 被取消时状态不会被假装成已修改。
|
||||
|
||||
安装
|
||||
----
|
||||
1. 运行 Squid-Setup-0.1.13-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
|
||||
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.13-win-x64.exe -Algorithm SHA256
|
||||
|
||||
提示
|
||||
----
|
||||
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
|
||||
上右键退出),否则安装程序无法替换正在运行的程序文件。
|
||||
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
|
||||
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
|
||||
按方便程度排序:
|
||||
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
|
||||
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
|
||||
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
|
||||
3) 使用便携包 Squid-0.1.13-portable-win-x64.zip,解压后把
|
||||
squid-desktop.exe 覆盖到安装目录(先退出托盘中的 Squid)。
|
||||
- 本版本重点:开机启动项学习芒果磁盘——残留项识别与一键删除、状态
|
||||
筛选段、「显示系统项」开关、来源/时机/签名芯片;重复文件的保留
|
||||
副本现在也可以勾选完全删除(有醒目警告);大文件不再列页面文件;
|
||||
修复重复文件清理按钮红底深红字看不清的问题。
|
||||
- 上一版的桌面小组件位置守卫、空间清理/系统维护三页签整合继续有效。
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
Squid 0.1.13 更新说明
|
||||
|
||||
新增
|
||||
- 开机启动项大升级(权限管理内,位置不变):
|
||||
· 状态筛选段:全部 / 已启用 / 已禁用 / 残留,每档带实时计数,一点即筛。
|
||||
· 残留项自动识别:程序文件已不在磁盘上、只剩启动配置的,标红并给出
|
||||
「删除启动项」按钮——只删注册表值/快捷方式/计划任务本身,绝不动
|
||||
程序文件;残留服务改为「禁用」而非卸载,删除前弹窗讲清影响范围。
|
||||
· 「显示系统项」开关:微软签名或位于 Windows 目录的启动项默认折进
|
||||
「系统组件」组隐藏,列表只剩真正拖累开机的第三方软件。
|
||||
· 每行显示来源与路径明细,展开可见完整命令行,并可一键「打开所在
|
||||
文件夹」。
|
||||
- 重复文件:保留副本也可以勾选了。勾上即「本组一份不剩」,行与组标题
|
||||
变琥珀警示,顶部汇总显示有几组将被完全删除,确认条同时变红并要求
|
||||
「确认完全删除」;删除仍走回收站,可从历史撤销。
|
||||
- 右键菜单扩展按软件分组:同一个软件注册在多个菜单位置的条目合并成一张
|
||||
卡片(组头 = 软件图标 + 名称 + 开启状态 + 组级总开关),和开机启动项
|
||||
同一套样式;认不出归属的落入「其他软件」。菜单位置类别与计数不变。
|
||||
|
||||
调整
|
||||
- 重复文件扫描不再进入 WorkBuddy 的会话快照目录:任何盘符上的
|
||||
`.workbuddy\workspace\sessions\…` 整棵子树直接跳过——那是智能体自己
|
||||
生成的文件副本,列出来只会重复劳动。
|
||||
- 电脑概览页排版改版:处理器与内存合并为一张卡(上下分布),存储空间卡
|
||||
加宽、每个盘符收成一行的表格感排版(盘符|进度条|用量与容量),日常
|
||||
维护三个入口竖排进右列——指标行按 30% / 42% / 28% 三列分布,区块间距
|
||||
整体加大,页面更透气。
|
||||
- 「开始智能扫描」不再停留在概览页:点击立即跳转到空间清理页,两阶段
|
||||
扫描(缓存垃圾 → 构建残留)在那边继续执行;「空间清理」快捷卡同此。
|
||||
- 套件归组:同一厂商装在 Program Files 下多个子目录的产品(如新华三
|
||||
H3C Workspace 的 SpaceAgent、摄像头/打印机/USB/串并口重定向等一组服务,
|
||||
每个程序都不带产品名信息)自动合并为一组「H3C Workspace」,不再散成
|
||||
单行组和「其他软件」;带真实产品名的软件不受影响。
|
||||
- 电脑概览继续微调:页头三行文字(问候/标题/副标题)间距拉开、整块连同
|
||||
下方模块适度下移,页面不再顶格;处理器/内存的进度条左缘与图标对齐;
|
||||
明细小字(CPU 型号、进程数)与存储卡的盘符信息统一字号与颜色;
|
||||
「实时监控」按钮升级为与「开始智能扫描」同款的橙色主按钮。
|
||||
- 角色名不再自成一组:WinFsp 的启动服务自称「Windows File System Proxy」,
|
||||
看着像系统组件实为第三方库,此前在启动列表里开了一个独立的假软件组;
|
||||
现在这类「Windows/Microsoft + Proxy/Host/Service…)」的角色名一律归入
|
||||
「其他软件」,真实产品名不受影响。
|
||||
- 清理全程有反馈(垃圾清理 / 重复文件 / 大文件三处统一):点下清理后,
|
||||
底部确认条就地变成长条进度器——橙色流光进度条 + 「正在清理 N / M 个
|
||||
文件 · 已释放 X」实时计数 + 当前正在删的文件路径,再久也不像卡死;
|
||||
超过 10 秒出现「转入后台」,进度缩成右下角小胶囊随时点回。完成后原地
|
||||
变绿「清理完成 · N 个已移入回收站 · 释放 X · 用时 Y」,可一键查看历史
|
||||
撤销,5 秒自动收起;有删不掉的变琥珀色并写明原因(占用/权限/已消失),
|
||||
「查看原因并处理」直达按原因分组的处置建议。
|
||||
- 软件图标获取机制加强:不带任何图标资源的「更新服务」类小程序,现在会
|
||||
按它自己声称归属的产品去卸载注册表里借图标——腾讯会议的
|
||||
`WemeetUpdateSvc.exe`(单独躺在 `Tencent\UpdateSvr\`,自己零图标)取到
|
||||
腾讯会议图标,企业微信的 `WXWorkUpgrader.exe` 经 `WXWorkService` 顺到
|
||||
`WXWork.exe` 的图标;同名厂商目录、App Paths、同目录兄弟程序的既有兜底
|
||||
顺序不变,实在认不出的仍显示中性占位,绝不张冠李戴。
|
||||
- 商店应用归组修复:ChatGPT 等微软商店安装的应用此前因为读不到程序信息
|
||||
而全部堆在「其他软件」,现在按安装包名自动归组(ChatGPT 独立成组,带
|
||||
自己的图标);「其他软件」组头改用中性九宫格图标,不再借用组内某个
|
||||
软件的图标误导。
|
||||
- 空间清理三个页签统一扫描交互:同一颗大号「开始扫描」主按钮,固定在各
|
||||
自配置栏的最右侧(垃圾清理原先孤悬的小按钮、重复文件的「开始查找」、
|
||||
大文件的小按钮全部归一);未扫描 → 开始扫描,扫描中 → 扫描中…,扫过
|
||||
之后 → 重新扫描,三页文案与状态一致;大文件页补上扫描前的引导空态。
|
||||
- 大文件扫描不再列出 pagefile.sys / swapfile.sys——系统全程持有,谁都
|
||||
删不掉,列出来只会误导;hiberfil.sys 保留并注明可「关闭休眠」释放。
|
||||
- 权限管理开机启动项与进阶启动项共用同一套签名核验批处理:一次系统
|
||||
调用覆盖整页,翻页不再重复等待。
|
||||
|
||||
移除
|
||||
- 电脑概览右上角的「智能扫描」大按钮(与卡内的「开始智能扫描」重复)。
|
||||
|
||||
修复
|
||||
- 重复文件「清理 N 个副本」按钮深红字压在红底上看不清:移除页面级
|
||||
配色覆盖,回归全局危险按钮样式(红底白字),并禁止页面再覆盖按钮
|
||||
颜色。
|
||||
- 打开权限管理(开机启动项 / 进阶启动项)时会闪出一个黑色命令行窗口:
|
||||
批量签名核验调用 PowerShell 时漏了隐藏窗口标志,GUI 程序拉起控制台
|
||||
程序就会新建窗口;现已全部静默。同类漏网(清理扫描里的 git 探测)
|
||||
一并堵上。
|
||||
- 一键安装.bat 重写:先自动退出正在运行的 Squid、前台同步安装、每步
|
||||
有进度输出与错误码,不再出现「双击后只剩空命令行」的无响应窗口。
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
69e0d9009e91f5119ea2c607abfc9129083ec2c85de7beb88090451867e5c5be Squid-Setup-0.1.13-win-x64.exe
|
||||
0d95918cdfb2fed04556b7ca03eadc0fb6c9a13aa2fd144c184626df63eaeb7e Squid-0.1.13-portable-win-x64.zip
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -1,41 +0,0 @@
|
|||
@echo off
|
||||
rem Squid one-click installer.
|
||||
rem Copies the setup to %TEMP% first: some security suites (e.g. PC Manager)
|
||||
rem block unsigned installers launched from non-system drives.
|
||||
setlocal
|
||||
title Squid Setup
|
||||
set "PKG=%~dp0Squid-Setup-0.1.13-win-x64.exe"
|
||||
|
||||
if not exist "%PKG%" (
|
||||
echo [ERROR] Setup file not found next to this script:
|
||||
echo %PKG%
|
||||
echo Keep this .bat in the same folder as the setup .exe.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [1/3] Stopping a running Squid if any...
|
||||
taskkill /F /IM squid-desktop.exe >nul 2>&1
|
||||
rem The kill is asynchronous; give the OS a moment to release the exe lock.
|
||||
ping -n 3 127.0.0.1 >nul
|
||||
|
||||
echo [2/3] Copying installer to temp folder...
|
||||
copy /Y "%PKG%" "%TEMP%\Squid-Setup-0.1.13-win-x64.exe" >nul
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Copy to %TEMP% failed. Free up disk space or retry.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [3/3] Installing silently, please wait...
|
||||
"%TEMP%\Squid-Setup-0.1.13-win-x64.exe" /S
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Installer exited with code %ERRORLEVEL%.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Squid 0.1.13 installed successfully.
|
||||
echo (If a previous Squid was running it was closed by this script.)
|
||||
pause
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
Squid 0.1.3 - 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.3-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.3-win-x64.exe -Algorithm SHA256
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7 Squid-0.1.3-macOS-universal.dmg
|
||||
64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b Squid-Setup-0.1.3-win-x64.exe
|
||||
56fc98cb26b7ea24959eea9b043e96d9dfa0b635ee049d3c263f0be58d9b3960 README-Windows-x64.txt
|
||||
Binary file not shown.
Binary file not shown.
|
|
@ -1,18 +0,0 @@
|
|||
{
|
||||
"schema": 1,
|
||||
"version": "0.1.3",
|
||||
"date": "2026-11-05",
|
||||
"notes": "Squid 0.1.3\n\n- 软件更新仅在发现新版本时显示版本变化与更新说明。\n- 左侧导航精简为「电脑概览、日常清理、应用卸载」。\n- 关闭主窗口后常驻托盘;托盘菜单提供「日常清理、应用卸载、深度清理」及退出。\n- macOS 与 Windows 同步发布 0.1.3。",
|
||||
"artifacts": {
|
||||
"macos": {
|
||||
"file": "Squid-0.1.3-macOS-universal.dmg",
|
||||
"sha256": "d44c41f88496652384380ceca1bff24656acb815f78fc32a57a35f29dce5c6d7",
|
||||
"size": 10688482
|
||||
},
|
||||
"windows": {
|
||||
"file": "Squid-Setup-0.1.3-win-x64.exe",
|
||||
"sha256": "64619e91347b64c3fa3e1ac69b1148667e06c920e756a473b370a4abaf82de2b",
|
||||
"size": 3343118
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
Squid 0.1.4 - 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.4-win-x64.exe。
|
||||
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
|
||||
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
|
||||
|
||||
更新
|
||||
----
|
||||
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
|
||||
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
|
||||
还会验证清单的 Ed25519 签名。
|
||||
|
||||
校验
|
||||
----
|
||||
PowerShell:
|
||||
Get-FileHash .\Squid-Setup-0.1.4-win-x64.exe -Algorithm SHA256
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue