File size: 8,084 Bytes
72bc633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8757788
 
 
 
 
 
 
 
 
 
 
72bc633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6abea2
72bc633
 
 
 
 
 
 
 
 
 
 
8757788
 
 
 
72bc633
58f6308
 
 
 
 
 
 
 
 
 
 
72bc633
58f6308
 
72bc633
 
8757788
 
72bc633
 
58f6308
72bc633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6abea2
72bc633
 
 
8757788
 
 
72bc633
58f6308
 
 
 
 
 
 
 
 
 
d6abea2
72bc633
58f6308
 
 
 
72bc633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58f6308
 
 
72bc633
 
 
 
 
58f6308
 
 
72bc633
 
58f6308
72bc633
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""
PatchHawk sandbox β€” Docker-based isolated code execution and
three-stage patch validation pipeline.

Execution constraints (Docker mode):
    --network none   (no outbound connections)
    --memory 256m    (hard memory cap)
    --cpus 0.5       (half a CPU core)

Falls back to local subprocess when use_docker=False (dev/CI only).
"""

import os
import shutil
import subprocess
import tempfile
import functools
from typing import Dict, Any, Optional

@functools.lru_cache(maxsize=1)
def is_docker_available() -> bool:
    """Check if Docker is installed and the daemon is reachable."""
    try:
        subprocess.run(["docker", "ps"], capture_output=True, check=True, timeout=2)
        return True
    except Exception:
        return False


# =====================================================================
# Code Execution
# =====================================================================


def run_code(
    code: str,
    timeout_sec: int = 5,
    use_docker: bool = True,
) -> Dict[str, Any]:
    """Execute *code* in an isolated sandbox and return telemetry."""
    temp_dir = tempfile.mkdtemp(prefix="patchhawk_sandbox_")
    script_path = os.path.join(temp_dir, "script.py")

    with open(script_path, "w", encoding="utf-8") as f:
        f.write(code)

    result: Dict[str, Any] = {
        "stdout": "",
        "stderr": "",
        "exit_code": -1,
        "network_blocked": use_docker,
        "file_writes": [],
    }

    try:
        # Check if Docker is actually usable
        effective_use_docker = use_docker and is_docker_available()

        if effective_use_docker:
            cmd = [
                "docker",
                "run",
                "--rm",
                "--network",
                "none",
                "--memory",
                "256m",
                "--cpus",
                "0.5",
                "-v",
                f"{temp_dir}:/app:rw",
                "patchhawk-sandbox:latest",
                "python",
                "/app/script.py",
            ]
        else:
            if use_docker:
                print("[SANDBOX] Docker requested but not available. Falling back to host python.")
            cmd = ["python3", script_path]

        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_sec)
        result["stdout"] = proc.stdout
        result["stderr"] = proc.stderr
        result["exit_code"] = proc.returncode

        # Record any new files the code wrote
        for fname in os.listdir(temp_dir):
            if fname != "script.py":
                result["file_writes"].append(fname)

    except subprocess.TimeoutExpired:
        result["stderr"] = "Execution timed out."
    except Exception as exc:
        result["stderr"] = f"Execution error: {exc}"
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)

    return result


def check_syntax(
    code: str,
    use_docker: bool = True,
) -> tuple:
    """Run ``python -m py_compile`` and return (ok: bool, error_msg: str)."""
    temp_dir = tempfile.mkdtemp(prefix="patchhawk_syntax_")
    script_path = os.path.join(temp_dir, "script.py")

    with open(script_path, "w", encoding="utf-8") as f:
        f.write(code)

    try:
        effective_use_docker = use_docker and is_docker_available()

        if effective_use_docker:
            cmd = [
                "docker",
                "run",
                "--rm",
                "--network",
                "none",
                "--memory",
                "256m",
                "--cpus",
                "0.5",
                "-v",
                f"{temp_dir}:/app:rw",
                "patchhawk-sandbox:latest",
                "python",
                "-m",
                "py_compile",
                "/app/script.py",
            ]
        else:
            cmd = ["python3", "-m", "py_compile", script_path]

        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
        if proc.returncode == 0:
            return True, ""
        return False, proc.stderr

    except subprocess.TimeoutExpired:
        return False, "Syntax check timed out"
    except Exception as exc:
        return False, f"Syntax check failed: {exc}"
    finally:
        shutil.rmtree(temp_dir, ignore_errors=True)


# =====================================================================
# Three-Stage Patch Validation
# =====================================================================


def validate_patch(
    scenario: dict,
    patch_code: str,
    use_docker: bool = True,
) -> tuple:
    """
    Returns (success: bool, message: str, details: dict).

    Stages:
        1. Syntax check β€” python -m py_compile on patched code
        2. Unit test execution β€” run unit_test_code against patched code
        3. Re-attack β€” compare malicious vs patched side-effects
    """
    details: dict = {}

    # ------------------------------------------------------------------
    # Stage 1 – Syntax
    # ------------------------------------------------------------------
    ok, err = check_syntax(patch_code, use_docker=use_docker)
    if not ok:
        details["error"] = err
        return False, "Syntax error", details

    # ------------------------------------------------------------------
    # Stage 2 – Unit test
    # ------------------------------------------------------------------
    test_code = scenario.get("unit_test_code")
    if test_code:
        combined = (
            "import sys, types\n"
            "mod = types.ModuleType('code')\n"
            f"exec('''{patch_code}''', mod.__dict__)\n"
            "sys.modules['code'] = mod\n"
            f"{test_code}\n"
            "print('TEST_SUCCESS')\n"
        )
        res = run_code(combined, timeout_sec=5, use_docker=use_docker)
        if res["exit_code"] != 0 or "TEST_SUCCESS" not in res["stdout"]:
            details["test_output"] = res["stderr"] or res["stdout"]
            return False, "Unit test failed", details

    # ------------------------------------------------------------------
    # Stage 3 – Re-attack verification
    # ------------------------------------------------------------------
    if scenario.get("type") == "true_positive" and scenario.get("attack_type"):
        attack_res = run_code(
            scenario["code_snippet"], timeout_sec=5, use_docker=use_docker
        )
        patch_res = run_code(patch_code, timeout_sec=5, use_docker=use_docker)

        vulnerability_remains = False

        # Check file-write side-effects
        if len(attack_res.get("file_writes", [])) > 0 and len(
            patch_res.get("file_writes", [])
        ) >= len(attack_res.get("file_writes", [])):
            vulnerability_remains = True

        # Isolate and match syntax tree against domain-specific threat heuristics
        attack_type = scenario["attack_type"]
        if attack_type == "typosquatting":
            if "pythonn" in patch_res.get("stderr", ""):
                vulnerability_remains = True
        elif attack_type == "obfuscated_exec":
            if (
                attack_res["stdout"].strip()
                and patch_res["stdout"] == attack_res["stdout"]
            ):
                vulnerability_remains = True
        elif attack_type == "subprocess_backdoor":
            if "nc" in patch_code or "subprocess.call" in patch_code:
                vulnerability_remains = True
        elif attack_type == "socket_exfil":
            if "socket" in patch_code and "connect" in patch_code:
                vulnerability_remains = True
        elif attack_type == "env_hijack":
            if "os.environ" in patch_code and "PATH" in patch_code:
                vulnerability_remains = True

        if vulnerability_remains:
            details["evidence"] = {
                "attack_telemetry": attack_res,
                "patch_telemetry": patch_res,
            }
            return False, "Vulnerability still accessible", details

    details["validation_log"] = "All checks passed successfully."
    return True, "Patch is valid", details