feat: Linux 的指令也在沙盒裡跑(Landlock):私密資料夾讀不到也寫不到、shell 啟動檔改不了;沒有沙盒的電腦 /doctor 照實說
- AnyBot 用自己當沙盒(/proc/self/exe __anybot_sandbox … -- /bin/sh -c 指令):套上 Landlock 再變成 shell,互動終端機也包得到。 - Landlock 只能允許:通往私密資料夾的每一層一個個允許、跳過私密的那個;讀到處可以(名字列得出來)、寫除了私密資料夾和啟動檔都可以,跟 macOS 一樣;工作資料夾整個可寫。 - 核心沒有 Landlock:照舊跑、紀錄檔寫一次、/doctor 一行 ✗;Windows 也寫沒有沙盒。 - Linux 被擋時(Permission denied)結果後面附一句說明哪些地方不行。 已驗證:cargo test 588 通過(規劃:私密資料夾、附件只讀、啟動檔只讀、工作資料夾整個可寫、舊核心只用它認得的權限;參數來回);landlock.rs 用 Linux target 做過 cargo check 和 clippy -D warnings(含 Linux 才編的系統呼叫和測試);clippy -D warnings 乾淨。 未驗證:真的 Linux 核心上套上 Landlock(landlock_keeps_a_command_out 在 CI 的 anybot-linux 或一台 Linux 才會跑)、互動終端機在 Linux 上經過沙盒。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
bddef7a56f
commit
13a0987e53
|
|
@ -1035,7 +1035,7 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
|
|||
- 一律允許會記住指令的第一個字。
|
||||
- git、npm、pnpm、yarn、cargo、brew、pip、pip3、python3、docker、go 這 11 種會記住前兩個字,例如「npm install」。
|
||||
|
||||
### 沙盒(macOS 有提供時)
|
||||
### 沙盒(macOS 的 sandbox-exec、Linux 的 Landlock)
|
||||
|
||||
- 所有指令都在沙盒裡跑,下面三種例外(只在你的電腦上;Bot 自己的電腦一律在沙盒裡)。
|
||||
- 指令碰不到這些地方:AnyBot 的資料、.ssh、.gnupg、Library/Keychains、.aws、.config/gcloud。
|
||||
|
|
@ -1044,6 +1044,8 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。
|
|||
- `ps`、`top`,單獨或只接 grep、head、awk 這類不讀檔的過濾:它們要系統權限(setuid),沙盒裡一律「Operation not permitted」。
|
||||
- AppleScript:單獨一條 `osascript -e '…'`(不能跑腳本檔、JavaScript、heredoc),而且不含 do shell script、run script、終端機、keystroke、讀檔、ObjC、祕密資料夾的名字。在沙盒裡 AppleScript 指揮別的 App 一律被拒(-10004)。第一次會先問你,直接操作模式也問,選「一律允許」之後不再問。
|
||||
- 被沙盒擋下時(setuid 程式、-10004、App 的指令列當掉),結果後面會附一句說明是沙盒擋的、改用什麼,Bot 不會當成電腦壞了一直重試。
|
||||
- **Linux**(核心 5.13 以上、有開 Landlock):同樣那些私密資料夾讀不到也寫不到(聊天的附件、技能、.ssh 一樣只能讀),shell 的啟動檔(.bashrc、.profile、.bash_login、~/.config/autostart、~/.config/systemd、.xprofile…)改不了;sudo 這類提高權限的程式不能跑。AnyBot 用自己(`/proc/self/exe`)當沙盒把指令包起來再變成 /bin/sh,所以互動終端機也在沙盒裡。Landlock 只能「允許」、不能「除了這個」,所以和 macOS 不一樣的地方:資料夾裡有哪些名字到處都列得出來(內容讀不到);通往私密資料夾的那幾層(家目錄、~/.config、~/.local、~/.local/share)最上層不能新增檔案或資料夾,它們裡面的其他資料夾照常可以;工作資料夾整個可寫,裡面的 .git/hooks 擋不住。指令失敗出現 Permission denied 時,結果後面附一句「如果是 AnyBot 的指令沙盒擋的…」說明哪些地方不行。
|
||||
- 沒有沙盒的電腦照實說,不假裝有:Linux 核心沒有 Landlock(太舊或沒開)時 /doctor 一行「✗ 這台的指令沒有沙盒…」,紀錄檔也寫,指令照樣跑(和以前一樣),只靠上面的安全規則擋;Windows 還沒有沙盒,/doctor 也這樣寫。
|
||||
|
||||
### 在「Bot 的電腦」上
|
||||
|
||||
|
|
@ -1507,7 +1509,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
|||
|
||||
### 診斷(/doctor)
|
||||
|
||||
- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。
|
||||
- 聊天打 /doctor:這台電腦的 AnyBot 一項一行 ✓ 或 ✗:版本、資料夾、今天的紀錄檔;這台 ↔ 帳號伺服器(長連線的狀態);帳號伺服器是 *.ts.net 時,Tailscale 是直連還是走它在哪裡的中繼(`tailscale ping`;走中繼會寫延遲和「多半是中間擋了 UDP 41641」);帳號伺服器 ↔ 大腦(帳號伺服器說在不在線上);螢幕連不連得到大腦和原因;上次同步的大小和速度(1 MB 以上、每秒不到 300 KB 算慢);每個 Bot 用到的模型服務連不連得到(列模型清單);Bot 的電腦;每個開著的連接器;磁碟剩多少(少於 2 GB 算 ✗);指令有沒有沙盒(macOS 的 sandbox-exec、Linux 的 Landlock 第幾版,沒有就 ✗);上次內部出錯。要上網的檢查在背景跑,好了一次留一行。
|
||||
- 在連到大腦的螢幕電腦上檢查的是這台本身(大腦連不到時正是要用的時候),結果跳成提示;手機打的是大腦檢查自己。
|
||||
|
||||
### 自動審核的固定樣式規則
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ AnyBot 自己照顧自己:Bot 做事遇到 AnyBot 本身的問題會記成「
|
|||
## 子功能
|
||||
|
||||
- 待改進:一輪做完、自動整理做法時,AnyBot 本身的問題(工具回錯的結果、明明開著卻說找不到、一用就出錯、要繞路才做得到、Bot 一直誤用某個工具)另外記下來,不寫進技能。同一個工具的問題合併計次,最多留 50 條;出現 2 次以上的會標出來。
|
||||
- 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。
|
||||
- 診斷(/doctor):在聊天打 /doctor,一項一行 ✓/✗:版本和資料夾、紀錄檔在哪、這台 ↔ 帳號伺服器、Tailscale 是直連還是走它的中繼(走中繼很慢,多半是兩台之間擋了 UDP)、帳號伺服器 ↔ 大腦、上次同步的速度、每個 Bot 用的模型服務連不連得到、Bot 的電腦、每個連接器、磁碟、指令有沒有沙盒、上次內部出錯。在連到大腦的螢幕電腦上檢查的是這台(連不到大腦時也能用),結果跳成提示;手機打的檢查的是大腦。
|
||||
- 紀錄檔:AnyBot 自己的訊息寫在資料夾的 `logs/anybot-日期.log`(一天一個、留 7 天、一天最多 20 MB),同時照舊印在終端機(伺服器的 `make server-logs` 看得到)。等級用環境變數 ANYBOT_LOG(error、warn、info 預設、debug)。寫進去前先遮掉金鑰、Token、密碼(glpat-、ghp_、sk-、xai-、AKIA、Bearer、JWT、私鑰、名字像 TOKEN/SECRET/PASSWORD 的變數值 → ••••);手機上的步驟細節也一樣遮。
|
||||
- 當掉報告:程式內部出錯(任何一條執行緒)時寫 `logs/crash-時間.txt`(版本、執行緒、位置、訊息、backtrace,一樣遮過);下次打開在主要 Bot 的聊天留一行「AnyBot 上次執行時內部出錯…」(連到大腦的螢幕電腦是跳一則提示),並記一條待改進。每份報告只說一次。
|
||||
- 園丁每日報告(平日 8:44 起):過去一天失敗或被打斷的執行、走冤枉路的執行(10 步以上且 3 成以上沒成功)、被自動暫停的例行任務、重複出現的待改進。
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
|
|||
- 安全規則(你的電腦上):
|
||||
- 一律拒絕:sudo、su、rm -rf /、rm -rf ~、mkfs、dd、shutdown、reboot、diskutil erase、chmod -R 777 /。
|
||||
- 私密檔案不能讀也不能改:AnyBot 自己的資料、.git、.ssh、.gnupg、鑰匙圈、.aws、.env、.pem、.key、id_rsa 這類金鑰、credentials 等。
|
||||
- 指令沙盒:macOS 用 sandbox-exec,Linux 用 Landlock(核心 5.13 以上),私密資料夾讀不到也寫不到、shell 啟動檔改不了。Linux 上家目錄、~/.config、~/.local/share 的最上層不能新增東西(裡面的資料夾可以)。沒有沙盒的電腦(舊核心、Windows)/doctor 寫「這台的指令沒有沙盒」。
|
||||
- 直接做:讀工作資料夾裡的檔案;只用 24 種只看不改的指令(ls、cat、grep、git status…)。
|
||||
- 先問、可一律允許:改工作資料夾裡的檔案、其他指令、讀工作資料夾以外。
|
||||
- 每次問:改工作資料夾以外的檔案、含看不出內容的子指令、開互動 shell。
|
||||
|
|
@ -46,7 +47,7 @@ Bot 要動到你的電腦、對外送出或做收不回來的事時,先問你
|
|||
## 怎麼操作
|
||||
|
||||
- Bot:不能替你按允許,也不能點 AnyBot 的核准按鈕;被拒後不要再試同一件事,也不要換個寫法做。`update_settings` 改不了這些開關(打開「在這台電腦上執行」只有使用者能做)。要你親手做的步驟用 `hand_over_computer`,要你決定的用 `ask_person`([chat](chat.md))。
|
||||
- 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`。
|
||||
- 驗證:「在這台電腦上執行」選每次詢問,請 Bot 在你的電腦執行 `touch x`,要先看到「允許 {Bot} 在你的電腦上執行任務嗎?」;按「拒絕」後,這一輪 Bot 再試同樣的操作不會再跳卡片,步驟結果是「沒有執行,也沒有再問使用者…」;打開直接操作後請它刪一個檔案,要因「一律詢問」規則停下來問。打「/always-approve」後再請它在你的電腦執行 `printf ok`(訊息裡指名你的電腦),不該跳卡片、結果有 ok;用訊息管道傳同一句,照樣要你按;「/always-approve off」後又會問。Linux 上 /doctor 要有「指令沙盒:Linux 的 Landlock」,請 Bot 在你的電腦 `cat ~/.ssh/known_hosts` 可以、`cat` AnyBot 資料夾裡的 state.json 要失敗。自動測試:`cargo test agent::`、`cargo test tools::`、`cargo test policy::`、`cargo test always`、`cargo test landlock::`(真的套上 Landlock 的那個只在有 Landlock 的 Linux 跑)。
|
||||
|
||||
## 陷阱
|
||||
|
||||
|
|
|
|||
|
|
@ -83,8 +83,9 @@
|
|||
- 做法:評審可以用只看的工具(讀檔、web_fetch、截圖)查證;同一個「還沒達成」理由連兩次就暫停問;提示加「不要每輪提高標準」。
|
||||
- 做完:評審用工具讀檔確認的測試;同理由兩次暫停的測試。
|
||||
|
||||
### R6. Linux 的沙盒 ⬜
|
||||
### R6. Linux 的沙盒 ✅(真的核心上的測試要在 CI 的 anybot-linux 或一台 Linux 跑:這台 Mac 只驗了規劃和 Linux 的型別檢查)
|
||||
- 做法:Linux 電腦上的指令用 Landlock:寫入只限工作資料夾和 /tmp,私密檔案(protected_dirs)讀寫都擋;核心不支援時照實說(「這台的指令沒有沙盒」),不假裝有。
|
||||
- 實際:寫入沒有限在工作資料夾,而是跟 macOS 一樣「除了私密資料夾和 shell 啟動檔都可以」(只限工作資料夾會讓「改我的 ~/.config/xx」做不到,macOS 卻做得到)。Landlock 只能允許,所以通往私密資料夾的那幾層最上層不能新增東西、工作資料夾的 .git/hooks 擋不住。AnyBot 用自己當沙盒(`__anybot_sandbox`),互動終端機也包得到。
|
||||
- 做完:Linux 上的測試(CI 的 anybot-linux):寫工作資料夾外失敗、讀 ~/.ssh 失敗。
|
||||
|
||||
### R7. 長連線:還在傳就不算斷線、斷線後馬上重連、看得出是哪一段 ✅(帳號伺服器那端要 make update-server)
|
||||
|
|
|
|||
|
|
@ -65,6 +65,8 @@ impl App {
|
|||
}
|
||||
}
|
||||
}
|
||||
// (Commands for 「你的電腦」 run here, a screen of a brain too.)
|
||||
lines.push(crate::doctor::sandbox_line());
|
||||
match crate::doctor::free_mb(&data) {
|
||||
Some(mb) if mb < 2048 => lines.push(bad(format!("磁碟只剩 {mb} MB(快照、模型和 Bot 的電腦都要空間)"))),
|
||||
Some(mb) => lines.push(ok(format!("磁碟還有 {:.1} GB", mb as f64 / 1024.0))),
|
||||
|
|
|
|||
|
|
@ -67,6 +67,20 @@ pub fn ping_tailscale(host: &str) -> Option<Line> {
|
|||
None
|
||||
}
|
||||
|
||||
/// Whether commands on this computer run in a sandbox, and which.
|
||||
pub fn sandbox_line() -> Line {
|
||||
if cfg!(target_os = "macos") {
|
||||
return if std::path::Path::new("/usr/bin/sandbox-exec").exists() { ok("指令沙盒:macOS 的 sandbox-exec") } else { bad("這台的指令沒有沙盒:找不到 /usr/bin/sandbox-exec") };
|
||||
}
|
||||
if cfg!(target_os = "linux") {
|
||||
return match crate::landlock::abi() {
|
||||
Some(v) => ok(format!("指令沙盒:Linux 的 Landlock(第 {v} 版)")),
|
||||
None => bad(crate::landlock::NONE),
|
||||
};
|
||||
}
|
||||
bad("這台的指令沒有沙盒(Windows 還沒有):指令讀得到 .ssh 這類私密資料夾,只靠安全規則擋")
|
||||
}
|
||||
|
||||
/// Free space where the data folder is, in MB (None where `df` can't say).
|
||||
pub fn free_mb(dir: &Path) -> Option<u64> {
|
||||
let out = std::process::Command::new("df").args(["-Pk"]).arg(dir).output().ok()?;
|
||||
|
|
@ -106,6 +120,18 @@ mod tests {
|
|||
assert_eq!(tailscale_path("no reply"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sandbox_is_said_as_it_is() {
|
||||
let l = sandbox_line();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(l.ok && l.text.contains("sandbox-exec"), "{l:?}");
|
||||
} else if cfg!(target_os = "linux") {
|
||||
assert_eq!(l.ok, crate::landlock::abi().is_some(), "{l:?}");
|
||||
} else {
|
||||
assert!(!l.ok && l.text.contains("沒有沙盒"), "{l:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_crash_and_the_disk() {
|
||||
let d = std::env::temp_dir().join(format!("anybot-doctor-{}", std::process::id()));
|
||||
|
|
|
|||
|
|
@ -0,0 +1,422 @@
|
|||
//! Linux 的指令沙盒 (R6). Linux has no sandbox-exec: a command on the person's computer starts
|
||||
//! through AnyBot itself (`/proc/self/exe __anybot_sandbox … -- /bin/sh -c 指令`), which closes
|
||||
//! itself in with Landlock and then becomes the shell — the way sandbox-exec wraps it on macOS, so
|
||||
//! a 互動終端機 (pty.rs copies only the program and its arguments) is closed in too.
|
||||
//!
|
||||
//! Landlock only allows; it has no "but not this folder". So what macOS denies is left out of what
|
||||
//! is allowed: every entry on the way to a protected folder is allowed one by one, the protected
|
||||
//! one is skipped. Reading: everything but the protected folders (listing names works everywhere,
|
||||
//! contents don't). Writing: the same, also without the shell startup files; the work folder as a
|
||||
//! whole. What follows from allowing only: in a folder on the way to a protected one (the home
|
||||
//! folder, ~/.config, ~/.local/share…) nothing new can be made at its top level (in its other
|
||||
//! folders it can), and the work folder's .git/hooks stay writable (macOS denies them).
|
||||
//! A kernel without Landlock (before 5.13, or not turned on) is said as it is (`/doctor`, the
|
||||
//! log): commands run as they did, without a sandbox, never pretending to have one.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The first argument that makes AnyBot the sandbox instead of the app.
|
||||
pub const ARG: &str = "__anybot_sandbox";
|
||||
|
||||
/// Landlock's file system rights (linux/landlock.h).
|
||||
pub mod access {
|
||||
pub const EXECUTE: u64 = 1 << 0;
|
||||
pub const WRITE_FILE: u64 = 1 << 1;
|
||||
pub const READ_FILE: u64 = 1 << 2;
|
||||
pub const READ_DIR: u64 = 1 << 3;
|
||||
pub const REMOVE_DIR: u64 = 1 << 4;
|
||||
pub const REMOVE_FILE: u64 = 1 << 5;
|
||||
pub const MAKE_CHAR: u64 = 1 << 6;
|
||||
pub const MAKE_DIR: u64 = 1 << 7;
|
||||
pub const MAKE_REG: u64 = 1 << 8;
|
||||
pub const MAKE_SOCK: u64 = 1 << 9;
|
||||
pub const MAKE_FIFO: u64 = 1 << 10;
|
||||
pub const MAKE_BLOCK: u64 = 1 << 11;
|
||||
pub const MAKE_SYM: u64 = 1 << 12;
|
||||
/// Since version 2: moving or linking into another folder (without it, never allowed).
|
||||
pub const REFER: u64 = 1 << 13;
|
||||
/// Since version 3.
|
||||
pub const TRUNCATE: u64 = 1 << 14;
|
||||
/// Since version 5.
|
||||
pub const IOCTL_DEV: u64 = 1 << 15;
|
||||
}
|
||||
use access::*;
|
||||
|
||||
const READ: u64 = EXECUTE | READ_FILE;
|
||||
const WRITE: u64 = WRITE_FILE | REMOVE_DIR | REMOVE_FILE | MAKE_CHAR | MAKE_DIR | MAKE_REG | MAKE_SOCK | MAKE_FIFO | MAKE_BLOCK | MAKE_SYM | REFER | TRUNCATE | IOCTL_DEV;
|
||||
/// The rights a rule on a file (not a folder) may carry.
|
||||
const FILE_ONLY: u64 = EXECUTE | WRITE_FILE | READ_FILE | TRUNCATE | IOCTL_DEV;
|
||||
|
||||
/// What this kernel's Landlock (its version) can govern.
|
||||
pub fn handled(abi: u32) -> u64 {
|
||||
let mut h = (1 << 13) - 1;
|
||||
if abi >= 2 {
|
||||
h |= REFER;
|
||||
}
|
||||
if abi >= 3 {
|
||||
h |= TRUNCATE;
|
||||
}
|
||||
if abi >= 5 {
|
||||
h |= IOCTL_DEV;
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// What a command is kept from.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Spec {
|
||||
/// Neither read nor written: AnyBot's data, ~/.ssh, ~/.gnupg…
|
||||
pub hidden: Vec<PathBuf>,
|
||||
/// Inside those, what may still be read (never written): the chat's attachments, skills, ~/.ssh.
|
||||
pub readable: Vec<PathBuf>,
|
||||
/// Not written: shell startup files…
|
||||
pub no_write: Vec<PathBuf>,
|
||||
/// The work folder: read and written as a whole.
|
||||
pub work: PathBuf,
|
||||
}
|
||||
|
||||
impl Spec {
|
||||
/// As arguments for the sandbox (`-h`, `-r`, `-w`, `-C`, each with a path).
|
||||
pub fn to_args(&self) -> Vec<OsString> {
|
||||
let mut v = vec![];
|
||||
for (flag, paths) in [("-h", &self.hidden), ("-r", &self.readable), ("-w", &self.no_write)] {
|
||||
for p in paths {
|
||||
v.push(OsString::from(flag));
|
||||
v.push(p.clone().into_os_string());
|
||||
}
|
||||
}
|
||||
v.push("-C".into());
|
||||
v.push(self.work.clone().into_os_string());
|
||||
v
|
||||
}
|
||||
|
||||
/// Read back: the spec, then the program and its arguments (after `--`).
|
||||
pub fn from_args(args: &[OsString]) -> Result<(Spec, Vec<OsString>), String> {
|
||||
let mut s = Spec::default();
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == "--" {
|
||||
let rest: Vec<OsString> = it.cloned().collect();
|
||||
if rest.is_empty() {
|
||||
return Err("沒有要執行的程式".into());
|
||||
}
|
||||
return Ok((s, rest));
|
||||
}
|
||||
let p = PathBuf::from(it.next().ok_or_else(|| format!("{} 後面少了路徑", a.to_string_lossy()))?);
|
||||
match a.to_str() {
|
||||
Some("-h") => s.hidden.push(p),
|
||||
Some("-r") => s.readable.push(p),
|
||||
Some("-w") => s.no_write.push(p),
|
||||
Some("-C") => s.work = p,
|
||||
_ => return Err(format!("看不懂 {}", a.to_string_lossy())),
|
||||
}
|
||||
}
|
||||
Err("少了 --".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// The path as the kernel sees it (links resolved), also for one that isn't there yet.
|
||||
fn real(p: &Path) -> PathBuf {
|
||||
if let Ok(r) = std::fs::canonicalize(p) {
|
||||
return r;
|
||||
}
|
||||
match (p.parent(), p.file_name()) {
|
||||
(Some(parent), Some(name)) if parent != p => real(parent).join(name),
|
||||
_ => p.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything under `dir` but `avoid`: an entry not on the way to an avoided path as a whole, one
|
||||
/// on the way entry by entry. Links are skipped (what they point to has a path of its own).
|
||||
fn around(dir: &Path, avoid: &[PathBuf], grant: &mut dyn FnMut(PathBuf, bool)) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
if t.is_symlink() || avoid.contains(&p) {
|
||||
continue;
|
||||
}
|
||||
if t.is_dir() && avoid.iter().any(|a| a.starts_with(&p)) {
|
||||
around(&p, avoid, grant);
|
||||
} else {
|
||||
grant(p, t.is_dir());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a sandboxed command may do: (path, rights), each for everything under that path.
|
||||
pub fn plan(spec: &Spec, abi: u32) -> Vec<(PathBuf, u64)> {
|
||||
let hidden: Vec<PathBuf> = spec.hidden.iter().map(|p| real(p)).collect();
|
||||
let work = real(&spec.work);
|
||||
// (Inside the work folder nothing can be kept from writing: the folder is allowed whole.)
|
||||
let no_write: Vec<PathBuf> = hidden.iter().cloned().chain(spec.no_write.iter().map(|p| real(p)).filter(|p| !p.starts_with(&work))).collect();
|
||||
let mut rules: BTreeMap<PathBuf, (u64, bool)> = BTreeMap::new();
|
||||
let mut add = |p: PathBuf, r: u64, dir: bool| rules.entry(p).or_insert((0, dir)).0 |= r;
|
||||
let root = Path::new("/");
|
||||
add(root.to_path_buf(), READ_DIR, true);
|
||||
around(root, &hidden, &mut |p, dir| add(p, READ, dir));
|
||||
around(root, &no_write, &mut |p, dir| add(p, WRITE, dir));
|
||||
for r in spec.readable.iter().map(|r| real(r)) {
|
||||
if hidden.iter().any(|h| r.starts_with(h)) && r.exists() {
|
||||
let dir = r.is_dir();
|
||||
add(r, READ, dir);
|
||||
}
|
||||
}
|
||||
if !hidden.iter().any(|h| work.starts_with(h)) && work.is_dir() {
|
||||
add(work, READ | WRITE, true);
|
||||
}
|
||||
let h = handled(abi);
|
||||
rules.into_iter().map(|(p, (r, dir))| (p, r & h & if dir { u64::MAX } else { FILE_ONLY })).filter(|(_, r)| *r != 0).collect()
|
||||
}
|
||||
|
||||
/// The program AnyBot is (the sandbox runs as it). In `cargo test` that is the test runner, which
|
||||
/// can't be the sandbox: commands there run unwrapped unless a test names a real AnyBot.
|
||||
fn helper() -> Option<PathBuf> {
|
||||
if cfg!(test) {
|
||||
return std::env::var_os("ANYBOT_TEST_SANDBOX_EXE").map(PathBuf::from);
|
||||
}
|
||||
Some(PathBuf::from("/proc/self/exe"))
|
||||
}
|
||||
|
||||
/// This kernel's Landlock version (None: no Landlock here). Asked once.
|
||||
pub fn abi() -> Option<u32> {
|
||||
static ABI: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
|
||||
*ABI.get_or_init(|| {
|
||||
let v = sys::abi();
|
||||
if cfg!(target_os = "linux") && v.is_none() {
|
||||
log::warn!("{NONE}");
|
||||
}
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
/// What `/doctor` and the log say on a Linux without Landlock.
|
||||
pub const NONE: &str = "這台的指令沒有沙盒:Linux 核心沒有 Landlock(要 5.13 以上,而且有開:/sys/kernel/security/lsm 裡要有 landlock)。指令照樣能跑,但讀得到 .ssh 這類私密資料夾";
|
||||
|
||||
/// Commands here run in the Linux sandbox.
|
||||
pub fn active() -> bool {
|
||||
cfg!(target_os = "linux") && abi().is_some() && helper().is_some()
|
||||
}
|
||||
|
||||
/// `/bin/sh -c cmd` inside the sandbox (None: no sandbox here — run it as before).
|
||||
pub fn wrap(cmd: &str, spec: &Spec) -> Option<std::process::Command> {
|
||||
if !active() || spec.hidden.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut c = std::process::Command::new(helper()?);
|
||||
c.arg(ARG).args(spec.to_args()).args(["--", "/bin/sh", "-c", cmd]);
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// After a command failed this way it may have been the sandbox: a word for the bot.
|
||||
pub const NOTE: &str = "(如果是 AnyBot 的指令沙盒擋的,不是電腦壞了:在 Linux 上指令讀不到也寫不到 AnyBot 的資料和私密資料夾(.ssh、.gnupg、.aws…),改不了 shell 的啟動檔;家目錄、~/.config、~/.local、~/.local/share 這幾層的最上層不能新增檔案或資料夾,但它們裡面的其他資料夾可以。改在工作資料夾裡做,或請使用者自己做。)";
|
||||
|
||||
/// `anybot __anybot_sandbox … -- program args`: close this process in, then become the program.
|
||||
/// Anything wrong and the program doesn't run (never without the sandbox it was asked for).
|
||||
pub fn run_helper(args: &[OsString]) -> ! {
|
||||
let fail = |e: String| -> ! {
|
||||
eprintln!("AnyBot 的指令沙盒沒有套上,指令沒有執行:{e}");
|
||||
std::process::exit(126)
|
||||
};
|
||||
let (spec, program) = Spec::from_args(args).unwrap_or_else(|e| fail(e));
|
||||
let abi = sys::abi().unwrap_or_else(|| fail("這台的 Linux 核心沒有 Landlock".into()));
|
||||
sys::restrict(&plan(&spec, abi), handled(abi)).unwrap_or_else(|e| fail(e));
|
||||
exec(&program[0], &program[1..])
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn exec(program: &OsStr, args: &[OsString]) -> ! {
|
||||
use std::os::unix::process::CommandExt;
|
||||
let e = std::process::Command::new(program).args(args).exec();
|
||||
eprintln!("無法執行 {}:{e}", program.to_string_lossy());
|
||||
std::process::exit(127)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn exec(program: &OsStr, _: &[OsString]) -> ! {
|
||||
eprintln!("無法執行 {}:這台沒有指令沙盒", program.to_string_lossy());
|
||||
std::process::exit(126)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod sys {
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[repr(C)]
|
||||
struct RulesetAttr {
|
||||
handled_access_fs: u64,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
struct PathBeneath {
|
||||
allowed_access: u64,
|
||||
parent_fd: i32,
|
||||
}
|
||||
|
||||
const CREATE_RULESET_VERSION: u32 = 1;
|
||||
const RULE_PATH_BENEATH: u32 = 1;
|
||||
|
||||
pub fn abi() -> Option<u32> {
|
||||
// SAFETY: asking for the version: no attributes, no memory written.
|
||||
let v = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, std::ptr::null::<RulesetAttr>(), 0usize, CREATE_RULESET_VERSION) };
|
||||
(v > 0).then_some(v as u32)
|
||||
}
|
||||
|
||||
/// From now on this thread (and what it starts) may do only what `rules` allow.
|
||||
pub fn restrict(rules: &[(PathBuf, u64)], handled: u64) -> Result<(), String> {
|
||||
let os = || std::io::Error::last_os_error();
|
||||
let attr = RulesetAttr { handled_access_fs: handled };
|
||||
// SAFETY: attr lives across the call; the kernel reads size_of bytes of it.
|
||||
let fd = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr as *const RulesetAttr, std::mem::size_of::<RulesetAttr>(), 0u32) };
|
||||
if fd < 0 {
|
||||
return Err(format!("建立規則失敗:{}", os()));
|
||||
}
|
||||
// SAFETY: a new descriptor the kernel just gave us, owned only here.
|
||||
let ruleset = unsafe { OwnedFd::from_raw_fd(fd as i32) };
|
||||
for (p, rights) in rules {
|
||||
// (Gone since the plan was made: nothing to allow there.)
|
||||
let Ok(f) = std::fs::OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_CLOEXEC).open(p) else { continue };
|
||||
let rule = PathBeneath { allowed_access: *rights, parent_fd: f.as_raw_fd() };
|
||||
// SAFETY: rule lives across the call; both descriptors are open.
|
||||
let r = unsafe { libc::syscall(libc::SYS_landlock_add_rule, ruleset.as_raw_fd(), RULE_PATH_BENEATH, &rule as *const PathBeneath, 0u32) };
|
||||
if r < 0 {
|
||||
return Err(format!("允許「{}」失敗:{}", p.display(), os()));
|
||||
}
|
||||
}
|
||||
// SAFETY: plain prctl and syscall on this thread; the ruleset descriptor is open.
|
||||
if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
|
||||
return Err(format!("no_new_privs 失敗:{}", os()));
|
||||
}
|
||||
if unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset.as_raw_fd(), 0u32) } < 0 {
|
||||
return Err(format!("套上規則失敗:{}", os()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
mod sys {
|
||||
pub fn abi() -> Option<u32> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn restrict(_: &[(std::path::PathBuf, u64)], _: u64) -> Result<(), String> {
|
||||
Err("只有 Linux 有 Landlock".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tree(name: &str) -> PathBuf {
|
||||
let d = real(&std::env::temp_dir().join(format!("anybot-ll-{name}-{}", std::process::id())));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
for sub in ["home/.ssh", "home/.config/gcloud", "home/.config/nvim", "home/Documents", "home/data/attachments", "home/work/.git/hooks"] {
|
||||
std::fs::create_dir_all(d.join(sub)).unwrap();
|
||||
}
|
||||
for f in ["home/.bashrc", "home/notes.txt", "home/.ssh/id_ed25519", "home/data/state.json"] {
|
||||
std::fs::write(d.join(f), "x").unwrap();
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn rights(rules: &[(PathBuf, u64)], p: &Path) -> Option<u64> {
|
||||
rules.iter().find(|(q, _)| q == p).map(|(_, r)| *r)
|
||||
}
|
||||
|
||||
/// What is reachable from a rule list (Landlock's way: a rule covers everything under it).
|
||||
fn may(rules: &[(PathBuf, u64)], p: &Path, want: u64) -> bool {
|
||||
let got = rules.iter().filter(|(q, _)| p.starts_with(q)).fold(0, |a, (_, r)| a | r);
|
||||
got & want == want
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_leaves_out_what_macos_denies() {
|
||||
let d = tree("plan");
|
||||
let h = d.join("home");
|
||||
let spec = Spec { hidden: vec![h.join(".ssh"), h.join("data"), h.join(".config/gcloud"), h.join(".gnupg")], readable: vec![h.join("data/attachments"), h.join(".ssh")], no_write: vec![h.join(".bashrc"), h.join("work/.git/hooks")], work: h.join("work") };
|
||||
let r = plan(&spec, 5);
|
||||
// Secrets: neither read nor written; the attachments and ~/.ssh readable only.
|
||||
assert!(!may(&r, &h.join("data/state.json"), READ_FILE) && !may(&r, &h.join("data/state.json"), WRITE_FILE));
|
||||
assert!(!may(&r, &h.join(".config/gcloud/creds"), READ_FILE));
|
||||
assert!(may(&r, &h.join("data/attachments/p.png"), READ_FILE) && !may(&r, &h.join("data/attachments/p.png"), WRITE_FILE));
|
||||
assert!(may(&r, &h.join(".ssh/id_ed25519"), READ_FILE) && !may(&r, &h.join(".ssh/id_ed25519"), WRITE_FILE));
|
||||
// A folder not yet there (~/.gnupg) can't be made: its parent isn't allowed to make things.
|
||||
assert!(!may(&r, &h, MAKE_DIR));
|
||||
// The rest: read and write as before, the startup file read only.
|
||||
assert!(may(&r, &h.join("Documents/a.txt"), READ_FILE | WRITE_FILE | MAKE_REG));
|
||||
assert!(may(&r, &h.join(".config/nvim/init.lua"), READ_FILE | WRITE_FILE));
|
||||
assert!(may(&r, &h.join("notes.txt"), READ_FILE | WRITE_FILE));
|
||||
assert!(may(&r, &h.join(".bashrc"), READ_FILE) && !may(&r, &h.join(".bashrc"), WRITE_FILE));
|
||||
assert!(may(&r, Path::new("/usr/bin/env"), READ_FILE | EXECUTE));
|
||||
// The work folder whole (its .git/hooks too: Landlock can't carve inside it).
|
||||
assert!(may(&r, &h.join("work/new/file.rs"), READ_FILE | WRITE_FILE | MAKE_REG | REMOVE_FILE));
|
||||
assert!(may(&r, &h.join("work/.git/index.lock"), MAKE_REG));
|
||||
// Names can be listed everywhere; a file's rule carries only file rights.
|
||||
assert_eq!(rights(&r, Path::new("/")), Some(READ_DIR));
|
||||
assert_eq!(rights(&r, &h.join("notes.txt")).map(|x| x & !FILE_ONLY), Some(0));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_kernels_get_only_what_they_know() {
|
||||
assert_eq!(handled(1), (1 << 13) - 1);
|
||||
assert_eq!(handled(2) & REFER, REFER);
|
||||
assert_eq!(handled(4) & (TRUNCATE | IOCTL_DEV), TRUNCATE);
|
||||
assert_eq!(handled(6) & IOCTL_DEV, IOCTL_DEV);
|
||||
let d = tree("abi");
|
||||
let r = plan(&Spec { hidden: vec![d.join("home/.ssh")], work: d.join("home/work"), ..Default::default() }, 1);
|
||||
assert!(r.iter().all(|(_, x)| x & !handled(1) == 0), "{r:?}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_spec_goes_through_arguments() {
|
||||
let s = Spec { hidden: vec!["/h/.ssh".into(), "/h/data".into()], readable: vec!["/h/data/attachments".into()], no_write: vec!["/h/.bashrc".into()], work: "/h/工作區".into() };
|
||||
let mut args = s.to_args();
|
||||
args.extend(["--", "/bin/sh", "-c", "echo hi"].map(OsString::from));
|
||||
let (back, program) = Spec::from_args(&args).unwrap();
|
||||
assert_eq!(back, s);
|
||||
assert_eq!(program, ["/bin/sh", "-c", "echo hi"].map(OsString::from));
|
||||
assert!(Spec::from_args(&["-h".into()]).is_err());
|
||||
assert!(Spec::from_args(&["-C".into(), "/w".into(), "--".into()]).is_err());
|
||||
}
|
||||
|
||||
/// The real thing on a Linux with Landlock (CI's anybot-linux): a thread closed in can't read
|
||||
/// the secret or write outside, and still works in its folder.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn landlock_keeps_a_command_out() {
|
||||
let Some(abi) = sys::abi() else {
|
||||
eprintln!("這台沒有 Landlock:略過");
|
||||
return;
|
||||
};
|
||||
let d = tree("real");
|
||||
let h = d.join("home");
|
||||
let spec = Spec { hidden: vec![h.join("data")], readable: vec![h.join("data/attachments")], no_write: vec![h.join(".bashrc")], work: h.join("work") };
|
||||
std::fs::write(h.join("data/attachments/p.txt"), "photo").unwrap();
|
||||
let rules = plan(&spec, abi);
|
||||
let out = std::thread::spawn(move || {
|
||||
sys::restrict(&rules, handled(abi)).unwrap();
|
||||
let sh = |c: &str| std::process::Command::new("/bin/sh").arg("-c").arg(c).current_dir(&spec.work).output().unwrap();
|
||||
let said = |c: &str| String::from_utf8_lossy(&sh(c).stdout).trim().to_string();
|
||||
let h = spec.work.parent().unwrap().to_path_buf();
|
||||
vec![
|
||||
said(&format!("cat '{}' 2>/dev/null || echo HIDDEN", h.join("data/state.json").display())),
|
||||
said(&format!("cat '{}'", h.join("data/attachments/p.txt").display())),
|
||||
said(&format!("echo x >> '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join(".bashrc").display())),
|
||||
said("echo hi > mine.txt && cat mine.txt"),
|
||||
said(&format!("echo y > '{}' 2>/dev/null && echo WROTE || echo KEPT", h.join("Documents/a.txt").display())),
|
||||
]
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
assert_eq!(out, ["HIDDEN", "photo", "KEPT", "hi", "WROTE"]);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
|
|
@ -35,6 +35,7 @@ mod intents;
|
|||
mod i18n;
|
||||
mod i18n_table;
|
||||
mod icons;
|
||||
mod landlock;
|
||||
mod lantls;
|
||||
mod lock;
|
||||
mod macapps;
|
||||
|
|
@ -319,6 +320,11 @@ const USAGE: &str = "用法:
|
|||
資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)";
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
// Linux 的指令沙盒 (landlock.rs): AnyBot started as the sandbox around one command — nothing
|
||||
// of the app, and before reading the arguments as text (a path in them may not be).
|
||||
if std::env::args_os().nth(1).is_some_and(|a| a == landlock::ARG) {
|
||||
landlock::run_helper(&std::env::args_os().skip(2).collect::<Vec<_>>());
|
||||
}
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
// Before anything else: no data folder, no window.
|
||||
if matches!(args.get(1).map(String::as_str), Some("--version" | "-V")) {
|
||||
|
|
|
|||
11
src/tools.rs
11
src/tools.rs
|
|
@ -843,7 +843,7 @@ pub fn protected_dirs() -> Vec<PathBuf> {
|
|||
fn write_denied_paths(workdir: &Path) -> Vec<PathBuf> {
|
||||
let mut v = vec![workdir.join(".git/hooks"), workdir.join(".git/config")];
|
||||
if let Some(h) = dirs::home_dir() {
|
||||
for s in [".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile", ".profile", "Library/LaunchAgents"] {
|
||||
for s in [".zshrc", ".zshenv", ".zprofile", ".zlogin", ".bashrc", ".bash_profile", ".bash_login", ".bash_logout", ".profile", "Library/LaunchAgents", ".config/autostart", ".config/systemd", ".xprofile", ".xsessionrc", ".pam_environment"] {
|
||||
v.push(h.join(s));
|
||||
}
|
||||
}
|
||||
|
|
@ -1134,6 +1134,9 @@ pub const OSASCRIPT_GRANT: &str = "osascript:outside";
|
|||
/// A word for the bot when a command failed because of the sandbox, not because the program or
|
||||
/// the computer is broken — so it changes course instead of trying the same thing again.
|
||||
pub fn sandbox_note(cmd: &str, out: &str) -> Option<&'static str> {
|
||||
if crate::landlock::active() {
|
||||
return (out.contains("Permission denied") || out.contains("Operation not permitted")).then_some(crate::landlock::NOTE);
|
||||
}
|
||||
sandbox_exec()?;
|
||||
if runs_outside_sandbox(cmd) {
|
||||
return None;
|
||||
|
|
@ -1244,6 +1247,12 @@ pub fn build_command_sealed(cmd: &str, workdir: &Path, protected: &[PathBuf], re
|
|||
c.arg("-p").arg(profile).arg("/bin/sh").arg("-c").arg(cmd);
|
||||
c
|
||||
}
|
||||
// Linux: Landlock (landlock.rs), the same folders kept out; the bot's own sealed computer
|
||||
// there never runs commands (sealed_runs_commands).
|
||||
_ if seal.is_none() => {
|
||||
let spec = crate::landlock::Spec { hidden: protected.to_vec(), readable: readable.to_vec(), no_write: write_denied_paths(workdir), work: workdir.to_path_buf() };
|
||||
crate::landlock::wrap(cmd, &spec).unwrap_or_else(|| shell_of(cmd))
|
||||
}
|
||||
_ => shell_of(cmd),
|
||||
};
|
||||
for k in KEY_ENV_VARS.into_iter().chain(DANGEROUS_ENV_VARS) {
|
||||
|
|
|
|||
Loading…
Reference in New Issue