-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_ghost.py
More file actions
194 lines (161 loc) · 5.83 KB
/
shell_ghost.py
File metadata and controls
194 lines (161 loc) · 5.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
"""
Shell Ghost — Safe command execution layer for CIN Agent
Phosphor green aesthetic. No rm -rf here.
"""
import subprocess
import shlex
import logging
import json
import os
import re
from datetime import datetime
from pathlib import Path
logger = logging.getLogger("shell_ghost")
# Matches piping or redirecting into a shell interpreter, e.g.
# "curl http://x | bash", "wget ... |sh", "... | zsh".
# The literal DANGEROUS_PATTERNS entries only catch the exact "curl | bash"
# spacing; real-world commands include a URL in between, so this regex closes
# that gap regardless of surrounding text or whitespace.
_PIPE_TO_SHELL = re.compile(r"\|\s*(?:bash|sh|zsh|dash|ksh|fish)\b")
# ── Whitelists & Blacklists ────────────────────────────────────────────────
SAFE_COMMANDS = {
"ls", "ll", "la", "cat", "head", "tail", "echo", "pwd",
"df", "du", "free", "top", "htop", "ps", "uptime", "uname",
"whoami", "id", "hostname", "date", "cal", "which", "whereis",
"find", "grep", "wc", "sort", "uniq", "cut", "awk", "sed",
"mkdir", "touch", "cp", "mv", "chmod", "stat", "file",
"ping", "curl", "wget", "nslookup", "dig",
"python3", "pip", "pip3", "git",
"systemctl", "journalctl", "lsof", "netstat", "ss",
"env", "printenv", "set", "export",
"tar", "zip", "unzip", "gzip", "gunzip",
"ollama", "nvidia-smi", "lscpu", "lsmem",
}
DANGEROUS_PATTERNS = [
"rm -rf", "rm -fr", "sudo", "su ",
"> /dev/", "dd if=", "mkfs",
":(){:|:&};:", "fork bomb",
"chmod 777 /", "chown -R root",
"wget -O- | bash", "curl | bash", "curl | sh",
"; reboot", "; shutdown", "&& reboot",
">/etc/passwd", ">/etc/shadow",
]
CONFIRM_REQUIRED = [
"rm ", "rmdir", "mv ", "cp ", # destructive file ops
"kill ", "killall", "pkill", # process termination
"iptables", "ufw", # network rules
"crontab", # scheduled tasks
]
AUDIT_LOG = Path(os.getenv("CIN_DATA_DIR", "~/.cin_agent")).expanduser() / "audit.log"
def _audit(cmd: str, result: str, status: str):
AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
entry = {
"ts": datetime.now().isoformat(),
"cmd": cmd,
"status": status,
"result_len": len(result),
}
with open(AUDIT_LOG, "a") as f:
f.write(json.dumps(entry) + "\n")
def is_safe(cmd: str) -> tuple[bool, str]:
"""Returns (safe, reason). Reason is empty string if safe."""
cmd_lower = cmd.strip().lower()
# Check dangerous patterns first
for pattern in DANGEROUS_PATTERNS:
if pattern in cmd_lower:
return False, f"Blocked pattern detected: `{pattern}`"
# Block piping/redirecting into a shell interpreter regardless of the
# text in between (e.g. "curl http://x | bash").
if _PIPE_TO_SHELL.search(cmd_lower):
return False, "Blocked: piping into a shell interpreter"
# Extract base command
try:
parts = shlex.split(cmd)
except ValueError:
return False, "Could not parse command (unmatched quotes?)"
if not parts:
return False, "Empty command"
base = parts[0].split("/")[-1] # strip path prefix
if base not in SAFE_COMMANDS:
return False, f"`{base}` is not on the whitelist"
return True, ""
def needs_confirmation(cmd: str) -> bool:
cmd_lower = cmd.strip().lower()
return any(p in cmd_lower for p in CONFIRM_REQUIRED)
def execute(cmd: str, timeout: int = 30, dry_run: bool = False) -> dict:
"""
Execute a shell command safely.
Returns: {success, output, error, blocked, reason}
"""
safe, reason = is_safe(cmd)
if not safe:
_audit(cmd, "", "BLOCKED")
return {
"success": False,
"output": "",
"error": reason,
"blocked": True,
"reason": reason,
}
if dry_run:
return {
"success": True,
"output": f"[DRY RUN] Would execute: {cmd}",
"error": "",
"blocked": False,
"reason": "",
}
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
)
output = result.stdout.strip()
error = result.stderr.strip()
status = "OK" if result.returncode == 0 else f"EXIT_{result.returncode}"
_audit(cmd, output, status)
return {
"success": result.returncode == 0,
"output": output or error,
"error": error if result.returncode != 0 else "",
"blocked": False,
"reason": "",
"returncode": result.returncode,
}
except subprocess.TimeoutExpired:
_audit(cmd, "", "TIMEOUT")
return {
"success": False,
"output": "",
"error": f"Command timed out after {timeout}s",
"blocked": False,
"reason": "",
}
except Exception as e:
_audit(cmd, "", f"ERROR: {e}")
return {
"success": False,
"output": "",
"error": str(e),
"blocked": False,
"reason": "",
}
def create_file(path: str, content: str, overwrite: bool = False) -> dict:
"""Safe file creation."""
target = Path(path).expanduser()
if target.exists() and not overwrite:
return {
"success": False,
"error": f"File `{path}` already exists. Confirm overwrite?",
"needs_confirm": True,
}
try:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
_audit(f"create_file:{path}", content[:50], "OK")
return {"success": True, "path": str(target), "error": ""}
except Exception as e:
return {"success": False, "error": str(e)}