python-security-benchmark / research /critical_worker.py
Helinity's picture
Release v0.1.0: sanitized Python security research benchmark
1340dfb
Raw History Blame Contribute Delete
5.15 kB
"""Executed only inside the restricted Linux container by critical.py."""
import json
import os
from pathlib import Path
import pickle
import shelve
import sqlite3
import sys
def marker():
Path("/tmp/decoded-marker").write_text("fixture")
return {"theme": "dark"}
class FixtureObject:
def __reduce__(self):
return marker, ()
def rejected(call):
try:
call()
except (ValueError, UnicodeError, FileNotFoundError):
return True
return False
def check(pattern, bad, good):
if pattern == "inbox-sqlite-value-binding":
db = sqlite3.connect(":memory:")
db.executescript("CREATE TABLE messages(mailbox); INSERT INTO messages VALUES ('one'),('two');")
for f in (bad, good):
assert f(db, "one") == 1
assert bad(db, "' OR 1=1 --") == 2
assert good(db, "' OR 1=1 --") == 0
elif pattern == "inventory-sqlite-sort-column":
db = sqlite3.connect(":memory:")
db.executescript("CREATE TABLE stock(sku,units,warehouse); INSERT INTO stock VALUES ('A',2,'w'),('B',1,'w');")
for f in (bad, good):
assert f(db, "w", "sku") == [("A",2),("B",1)]
assert bad(db, "w", "sku DESC") == [("B",1),("A",2)]
assert rejected(lambda: good(db, "w", "sku DESC"))
elif pattern in {"report-file-containment", "theme-catalog-selection"}:
root = Path("/tmp/root")
root.mkdir(exist_ok=True)
theme = pattern == "theme-catalog-selection"
filename = "light.css" if theme else "report.txt"
(root / filename).write_text("normal")
outside = Path("/tmp/outside.css" if theme else "/tmp/outside.txt")
outside.write_text("outside-fixture")
for f in (bad, good):
assert f(root, "light" if theme else filename) == "normal"
escape = "../outside" if theme else "../outside.txt"
assert bad(root, escape) == "outside-fixture"
assert rejected(lambda: good(root, escape))
if not theme:
assert rejected(lambda: good(root, str(outside)))
(root / "link").symlink_to(outside)
assert rejected(lambda: good(root, "link"))
elif pattern in {"line-counter-process-arguments", "asset-size-native-api"}:
path = Path("/tmp/document")
path.write_text("one\n")
expected = 1 if pattern.startswith("line-counter") else 4
for f in (bad, good):
assert f(path) == expected
sentinel = Path("/tmp/command-marker")
sentinel.unlink(missing_ok=True)
operand = "/tmp/document; printf fixture > /tmp/command-marker"
assert bad(operand) == expected
assert sentinel.read_text() == "fixture"
sentinel.unlink()
if pattern.startswith("line-counter"):
import subprocess
try:
good(operand)
except subprocess.CalledProcessError:
pass
else:
assert rejected(lambda: good(operand))
assert not sentinel.exists()
elif pattern == "preferences-data-only-decoding":
assert bad(pickle.dumps({"theme":"dark"})) == {"theme":"dark"}
assert good('{"theme":"dark"}') == {"theme":"dark"}
sentinel = Path("/tmp/decoded-marker")
sentinel.unlink(missing_ok=True)
payload = pickle.dumps(FixtureObject())
assert bad(payload) == {"theme":"dark"}
assert sentinel.read_text() == "fixture"
sentinel.unlink()
assert rejected(lambda: good(payload))
assert not sentinel.exists()
elif pattern == "uploaded-catalog-storage-format":
path = Path("/tmp/catalog")
with shelve.open(str(path)) as db:
db["titles"] = ["normal"]
assert bad(path) == ["normal"]
json_path = Path("/tmp/catalog.json")
json_path.write_text('["normal"]')
assert good(json_path) == ["normal"]
sentinel = Path("/tmp/decoded-marker")
sentinel.unlink(missing_ok=True)
with shelve.open(str(path)) as db:
db["titles"] = FixtureObject()
assert rejected(lambda: bad(path))
assert sentinel.read_text() == "fixture"
sentinel.unlink()
json_path.write_bytes(pickle.dumps(FixtureObject()))
assert rejected(lambda: good(json_path))
assert not sentinel.exists()
else:
raise AssertionError(pattern)
return {"normal_functionality": True, "vulnerable_outcome_observed": True,
"secure_outcome_prevented": True, "method": "isolated_linux_runtime"}
assert sys.platform == "linux" and os.getuid() == 65534
payload = json.load(sys.stdin)
results = {}
for pattern, variants in payload.items():
functions = []
for label in ("insecure", "secure"):
namespace = {"__name__": "fixture_subject"}
exec(compile(variants[label], pattern, "exec"), namespace)
functions.append(next(value for key, value in namespace.items()
if callable(value) and getattr(value, "__module__", "") == "fixture_subject"))
results[pattern] = check(pattern, *functions)
print(json.dumps(results, sort_keys=True))