|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import base64 |
| 4 | +import os |
| 5 | +import time |
| 6 | +import uuid |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from fastapi import FastAPI |
| 10 | +from pydantic import BaseModel, Field |
| 11 | + |
| 12 | +try: |
| 13 | + import winrm # pywinrm |
| 14 | +except Exception: # pragma: no cover |
| 15 | + winrm = None # type: ignore |
| 16 | + |
| 17 | +app = FastAPI(title="provity-sandbox-controller", version="0.1.0") |
| 18 | + |
| 19 | + |
| 20 | +class ScanRequest(BaseModel): |
| 21 | + filename: str = Field(..., min_length=1, max_length=260) |
| 22 | + file_sha256: str = Field(..., min_length=64, max_length=64) |
| 23 | + file_b64: str = Field(..., min_length=1) |
| 24 | + timeout_sec: int = Field(20, ge=5, le=300) |
| 25 | + |
| 26 | + |
| 27 | +def _env(name: str, default: str | None = None) -> str | None: |
| 28 | + v = os.getenv(name) |
| 29 | + if v is None or not str(v).strip(): |
| 30 | + return default |
| 31 | + return v |
| 32 | + |
| 33 | + |
| 34 | +@app.get("/health") |
| 35 | +def health() -> dict[str, Any]: |
| 36 | + return {"ok": True, "service": "sandbox-controller"} |
| 37 | + |
| 38 | + |
| 39 | +def _max_bytes() -> int: |
| 40 | + mb = int(_env("SANDBOX_MAX_MB", "10") or "10") |
| 41 | + return max(1, mb) * 1024 * 1024 |
| 42 | + |
| 43 | + |
| 44 | +def _ps_escape_single_quotes(s: str) -> str: |
| 45 | + # For single-quoted PowerShell strings: ' -> '' |
| 46 | + return s.replace("'", "''") |
| 47 | + |
| 48 | + |
| 49 | +def _build_powershell_script(*, b64: str, filename: str, timeout_sec: int) -> str: |
| 50 | + # Minimal dynamic run + basic observability. |
| 51 | + # Returns JSON via ConvertTo-Json. |
| 52 | + safe_name = os.path.basename(filename) |
| 53 | + |
| 54 | + b64_escaped = _ps_escape_single_quotes(b64) |
| 55 | + name_escaped = _ps_escape_single_quotes(safe_name) |
| 56 | + |
| 57 | + return f""" |
| 58 | +$ErrorActionPreference = 'Stop' |
| 59 | +
|
| 60 | +$runId = [guid]::NewGuid().ToString() |
| 61 | +$baseDir = 'C:\\provity-sandbox' |
| 62 | +$runDir = Join-Path $baseDir ('run\\' + $runId) |
| 63 | +New-Item -ItemType Directory -Force -Path $runDir | Out-Null |
| 64 | +
|
| 65 | +$samplePath = Join-Path $runDir '{name_escaped}' |
| 66 | +
|
| 67 | +# Write file from base64 |
| 68 | +$bytes = [System.Convert]::FromBase64String('{b64_escaped}') |
| 69 | +[System.IO.File]::WriteAllBytes($samplePath, $bytes) |
| 70 | +
|
| 71 | +function Get-ProcSnapshot {{ |
| 72 | + try {{ |
| 73 | + Get-CimInstance Win32_Process | Select-Object ProcessId, Name, CommandLine, CreationDate |
| 74 | + }} catch {{ |
| 75 | + @() |
| 76 | + }} |
| 77 | +}} |
| 78 | +
|
| 79 | +function Get-NetSnapshot {{ |
| 80 | + try {{ |
| 81 | + Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess |
| 82 | + }} catch {{ |
| 83 | + @() |
| 84 | + }} |
| 85 | +}} |
| 86 | +
|
| 87 | +$beforeProc = Get-ProcSnapshot |
| 88 | +$beforeNet = Get-NetSnapshot |
| 89 | +
|
| 90 | +$start = Get-Date |
| 91 | +$proc = $null |
| 92 | +$exitCode = $null |
| 93 | +$note = @() |
| 94 | +
|
| 95 | +try {{ |
| 96 | + # Attempt to start the sample. Many installers need UI; this is best-effort. |
| 97 | + $proc = Start-Process -FilePath $samplePath -PassThru |
| 98 | + Start-Sleep -Seconds {timeout_sec} |
| 99 | +
|
| 100 | + if ($proc -and -not $proc.HasExited) {{ |
| 101 | + try {{ |
| 102 | + Stop-Process -Id $proc.Id -Force |
| 103 | + $note += 'Process terminated after timeout' |
| 104 | + }} catch {{ |
| 105 | + $note += ('Failed to terminate process: ' + $_.Exception.Message) |
| 106 | + }} |
| 107 | + }} |
| 108 | +
|
| 109 | + if ($proc) {{ |
| 110 | + try {{ $exitCode = $proc.ExitCode }} catch {{ $exitCode = $null }} |
| 111 | + }} |
| 112 | +}} catch {{ |
| 113 | + $note += ('Execution error: ' + $_.Exception.Message) |
| 114 | +}} |
| 115 | +
|
| 116 | +$afterProc = Get-ProcSnapshot |
| 117 | +$afterNet = Get-NetSnapshot |
| 118 | +
|
| 119 | +$elapsed = (Get-Date) - $start |
| 120 | +
|
| 121 | +# Diff processes by (ProcessId) presence |
| 122 | +$beforeIds = @{{}} |
| 123 | +foreach ($p in $beforeProc) {{ $beforeIds[[string]$p.ProcessId] = $true }} |
| 124 | +$newProc = @() |
| 125 | +foreach ($p in $afterProc) {{ |
| 126 | + if (-not $beforeIds.ContainsKey([string]$p.ProcessId)) {{ $newProc += $p }} |
| 127 | +}} |
| 128 | +
|
| 129 | +$result = [ordered]@{{ |
| 130 | + ok = $true |
| 131 | + run_id = $runId |
| 132 | + sample_path = $samplePath |
| 133 | + timeout_sec = {timeout_sec} |
| 134 | + exit_code = $exitCode |
| 135 | + elapsed_sec = [int][Math]::Round($elapsed.TotalSeconds) |
| 136 | + new_processes = $newProc |
| 137 | + net_connections = $afterNet |
| 138 | + notes = $note |
| 139 | +}} |
| 140 | +
|
| 141 | +$result | ConvertTo-Json -Depth 6 |
| 142 | +""".strip() |
| 143 | + |
| 144 | + |
| 145 | +def _run_winrm(*, script: str) -> str: |
| 146 | + host = _env("WINRM_HOST") |
| 147 | + user = _env("WINRM_USER") |
| 148 | + password = _env("WINRM_PASSWORD") |
| 149 | + transport = _env("WINRM_TRANSPORT", "ntlm") |
| 150 | + |
| 151 | + if not host or not user or not password: |
| 152 | + raise RuntimeError("WINRM is not configured (set WINRM_HOST/WINRM_USER/WINRM_PASSWORD)") |
| 153 | + if winrm is None: |
| 154 | + raise RuntimeError("pywinrm not installed") |
| 155 | + |
| 156 | + # NOTE: For MVP we keep this simple. In production, pin TLS, use HTTPS, and avoid plaintext creds. |
| 157 | + session = winrm.Session(host, auth=(user, password), transport=transport) |
| 158 | + r = session.run_ps(script) |
| 159 | + stdout = (r.std_out or b"").decode("utf-8", errors="replace") |
| 160 | + stderr = (r.std_err or b"").decode("utf-8", errors="replace") |
| 161 | + if r.status_code != 0: |
| 162 | + raise RuntimeError(f"WinRM status={r.status_code}. stderr={stderr[:400]}") |
| 163 | + return stdout.strip() or stderr.strip() |
| 164 | + |
| 165 | + |
| 166 | +@app.post("/scan") |
| 167 | +def scan(req: ScanRequest) -> dict[str, Any]: |
| 168 | + # Allow a mock mode for wiring/testing without a VM. |
| 169 | + mode = (_env("SANDBOX_MODE", "winrm") or "winrm").lower() |
| 170 | + |
| 171 | + raw = base64.b64decode(req.file_b64.encode("ascii"), validate=False) |
| 172 | + if len(raw) > _max_bytes(): |
| 173 | + return {"ok": False, "reason": "file too large", "max_bytes": _max_bytes()} |
| 174 | + |
| 175 | + if mode == "mock": |
| 176 | + return { |
| 177 | + "ok": True, |
| 178 | + "run_id": str(uuid.uuid4()), |
| 179 | + "reason": "mock", |
| 180 | + "elapsed_sec": 1, |
| 181 | + "new_processes": [], |
| 182 | + "net_connections": [], |
| 183 | + "notes": ["SANDBOX_MODE=mock"], |
| 184 | + } |
| 185 | + |
| 186 | + start = time.time() |
| 187 | + try: |
| 188 | + ps = _build_powershell_script(b64=req.file_b64, filename=req.filename, timeout_sec=req.timeout_sec) |
| 189 | + out = _run_winrm(script=ps) |
| 190 | + # PowerShell outputs JSON; return it as parsed dict if possible. |
| 191 | + import json |
| 192 | + |
| 193 | + data = json.loads(out) |
| 194 | + if isinstance(data, dict): |
| 195 | + data.setdefault("ok", True) |
| 196 | + data.setdefault("elapsed_sec", int(time.time() - start)) |
| 197 | + return data |
| 198 | + return {"ok": True, "raw": data, "elapsed_sec": int(time.time() - start)} |
| 199 | + except Exception as e: |
| 200 | + return {"ok": False, "reason": str(e), "elapsed_sec": int(time.time() - start)} |
0 commit comments