File size: 7,239 Bytes
27cdb3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
Command Safety Layer — Whitelist/blocklist enforcement for sandbox commands.

Validates commands before execution to prevent destructive operations.
"""

from __future__ import annotations

import re
import shlex
from dataclasses import dataclass
from typing import List, Tuple


# Commands that are allowed to execute in the sandbox
COMMAND_WHITELIST: List[str] = [
    "pip", "pip3", "python", "python3",
    "apt-get", "npm",
    "kill", "pkill",
    "export", "source", "unset",
    "systemctl",
    "flask", "uvicorn",
    "cat", "ls", "echo", "mkdir", "rm", "cp", "mv",
    "sed", "grep", "awk", "head", "tail", "wc",
    "ps", "lsof", "curl", "wget",
    "chmod", "chown",
    "touch", "tee",
    "bash", "sh",
    "cd", "pwd", "which", "env", "printenv",
    "true", "false", "test",
    "xargs",
]

# Patterns that are absolutely forbidden (destructive commands)
BLOCKLIST_PATTERNS: List[str] = [
    r"rm\s+-rf\s+/\s*$",           # rm -rf /
    r"rm\s+-rf\s+/\*",             # rm -rf /*
    r"rm\s+--no-preserve-root",     # rm --no-preserve-root
    r":\(\)\s*\{\s*:\|:\s*&\s*\}\s*;\s*:",  # fork bomb
    r"dd\s+if=",                    # dd (disk destroyer)
    r"mkfs\.",                      # mkfs (format disk)
    r"chmod\s+777\s+/\s*$",        # chmod 777 /
    r"chmod\s+-R\s+777\s+/",       # chmod -R 777 /
    r">\s*/dev/sda",               # write to raw disk
    r"mv\s+/\s+",                  # mv / somewhere
    r"wget.*\|\s*sh",              # pipe download to shell
    r"curl.*\|\s*sh",              # pipe download to shell
    r"curl.*\|\s*bash",            # pipe download to bash
    r"(?:^|&&|\|\||;)\s*(?:/sbin/)?shutdown\b",  # shutdown invocation
    r"(?:^|&&|\|\||;)\s*(?:/sbin/)?reboot\b",    # reboot invocation
    r"(?:^|&&|\|\||;)\s*(?:/sbin/)?init\s+0\b", # init 0 halt invocation
    r"(?:^|&&|\|\||;)\s*(?:/sbin/)?halt\b",      # halt invocation
]

# Patterns involving sudo + destructive operations
SUDO_DANGEROUS_PATTERNS: List[str] = [
    r"sudo\s+rm",
    r"sudo\s+dd",
    r"sudo\s+mkfs",
    r"sudo\s+chmod\s+777",
    r"sudo\s+shutdown",
    r"sudo\s+reboot",
    r"sudo\s+halt",
    r"sudo\s+init",
]


@dataclass
class SafetyCheckResult:
    """Result of a command safety check.

    Attributes:
        is_safe: Whether the command passed safety checks.
        is_whitelisted: Whether the base command is in the whitelist.
        is_blocked: Whether the command matches a blocklist pattern.
        reason: Human-readable reason if the command was rejected.
        matched_pattern: The blocklist pattern that matched, if any.
    """

    is_safe: bool
    is_whitelisted: bool
    is_blocked: bool
    reason: str = ""
    matched_pattern: str = ""


class CommandSafetyChecker:
    """Validates commands against whitelist and blocklist rules.

    Usage:
        checker = CommandSafetyChecker()
        result = checker.check("pip install flask")
        if result.is_safe:
            # execute command
    """

    def __init__(
        self,
        extra_whitelist: List[str] | None = None,
        extra_blocklist: List[str] | None = None,
    ) -> None:
        """Initialize the safety checker.

        Args:
            extra_whitelist: Additional commands to allow.
            extra_blocklist: Additional regex patterns to block.
        """
        self.whitelist = set(COMMAND_WHITELIST)
        if extra_whitelist:
            self.whitelist.update(extra_whitelist)

        self.blocklist = list(BLOCKLIST_PATTERNS)
        if extra_blocklist:
            self.blocklist.extend(extra_blocklist)

        self.sudo_patterns = list(SUDO_DANGEROUS_PATTERNS)

    def check(self, command: str) -> SafetyCheckResult:
        """Check if a command is safe to execute.

        Args:
            command: The shell command string to validate.

        Returns:
            SafetyCheckResult with safety determination and reason.
        """
        command = command.strip()

        if not command:
            return SafetyCheckResult(
                is_safe=False, is_whitelisted=False, is_blocked=False,
                reason="Empty command",
            )

        # Check blocklist first (highest priority)
        blocked, pattern = self._check_blocklist(command)
        if blocked:
            return SafetyCheckResult(
                is_safe=False, is_whitelisted=False, is_blocked=True,
                reason=f"Command matches dangerous pattern: {pattern}",
                matched_pattern=pattern,
            )

        # Check sudo + destructive combos
        sudo_blocked, sudo_pattern = self._check_sudo_dangerous(command)
        if sudo_blocked:
            return SafetyCheckResult(
                is_safe=False, is_whitelisted=False, is_blocked=True,
                reason=f"Dangerous sudo command: {sudo_pattern}",
                matched_pattern=sudo_pattern,
            )

        # Check whitelist
        base_cmd = self._extract_base_command(command)
        is_whitelisted = base_cmd in self.whitelist

        if not is_whitelisted:
            return SafetyCheckResult(
                is_safe=False, is_whitelisted=False, is_blocked=False,
                reason=f"Command '{base_cmd}' is not in the whitelist",
            )

        return SafetyCheckResult(
            is_safe=True, is_whitelisted=True, is_blocked=False,
        )

    def _check_blocklist(self, command: str) -> Tuple[bool, str]:
        """Check command against blocklist patterns."""
        for pattern in self.blocklist:
            if re.search(pattern, command, re.IGNORECASE):
                return True, pattern
        return False, ""

    def _check_sudo_dangerous(self, command: str) -> Tuple[bool, str]:
        """Check for sudo combined with destructive operations."""
        for pattern in self.sudo_patterns:
            if re.search(pattern, command, re.IGNORECASE):
                return True, pattern
        return False, ""

    def _extract_base_command(self, command: str) -> str:
        """Extract the base command from a shell command string.

        Handles pipes, redirections, env vars, and command chains.
        """
        # Strip leading env variable assignments
        cmd = command.strip()
        while re.match(r'^[A-Za-z_][A-Za-z0-9_]*=\S+\s+', cmd):
            cmd = re.sub(r'^[A-Za-z_][A-Za-z0-9_]*=\S+\s+', '', cmd, count=1)

        # Handle command chains (&&, ||, ;) — check each segment
        for sep in ['&&', '||', ';']:
            if sep in cmd:
                first_part = cmd.split(sep)[0].strip()
                return self._extract_base_command(first_part)

        # Handle pipes — check the first command
        if '|' in cmd:
            first_part = cmd.split('|')[0].strip()
            return self._extract_base_command(first_part)

        # Handle subshell $(...)
        cmd = re.sub(r'\$\([^)]*\)', '', cmd).strip()

        # Get the first token
        try:
            tokens = shlex.split(cmd)
        except ValueError:
            tokens = cmd.split()

        if not tokens:
            return ""

        base = tokens[0]
        # Strip path (e.g., /usr/bin/pip -> pip)
        if '/' in base:
            base = base.rsplit('/', 1)[-1]
        return base