File size: 10,603 Bytes
2eee48c | 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 | """One preparation and execution interface for every attack family."""
from __future__ import annotations
import copy
import os
from pathlib import Path
import shutil
import subprocess
import sys
from .config import Configuration, role_environment, write_role_configs
from .dataset import AttackUnit
from .io import inside, read_json, write_json
from .sources import materialize
def _outside_release(root: Path, output: Path) -> Path:
output = output.resolve()
if output == root or root in output.parents:
raise ValueError("Keep execution workspaces outside the public dataset directory")
return output
def resolve_plan_paths(plan: dict, dataset_root: Path, engine_root: Path) -> dict:
"""Resolve portable source references in an external execution copy."""
if 'tool_package' in plan:
plan['tool_package']['package_dir'] = str(inside(dataset_root, plan['tool_package']['package_dir']))
metadata = plan.get('generation_metadata')
if metadata is not None:
task = inside(dataset_root, metadata['source_task_dir'])
metadata['source_task_dir'] = str(task)
for item in metadata.get('included_files', []):
reference = item['path']
if reference.startswith('engine://'):
source = inside(engine_root, reference[len('engine://'):])
elif item.get('sandbox_path'):
source = inside(dataset_root, reference)
else:
source = inside(task, reference)
if not source.is_file():
raise ValueError('Required native source file is missing: ' + str(source))
item['path'] = str(source)
return plan
def prepare(unit: AttackUnit, output: Path, configuration: Configuration | None = None,
*, profile: str | None = None) -> dict:
"""Create an isolated, inspectable workspace without running a model or a task."""
output = _outside_release(unit.root, output)
row = unit.metadata
if configuration:
from .blue_runtime import check_output_budget, unit_output_budget
check_output_budget(configuration.roles['blue'].capabilities, unit_output_budget(unit))
selected_profile = row.get("engine_profile", row["family"])
if profile is not None and profile != selected_profile:
raise ValueError("This unit is bound to engine profile " + selected_profile)
plan = copy.deepcopy(unit.load_plan())
output.mkdir(parents=True, exist_ok=False, mode=0o700)
engine = output / "engine"
mapping = materialize(unit.root, selected_profile, engine)
if mapping["family"] != row["family"]:
raise ValueError("Engine profile belongs to a different attack family")
resolve_plan_paths(plan, unit.root, engine)
plan_file = output / "attack_plan.json"
write_json(plan_file, plan)
record = {"schema_version": "manipulationarena-execution-v1", "unit_key": row["unit_key"],
"family": row["family"], "task_id": row["task_id"],
"attack_channel": row["attack_channel"], "plan_file": str(plan_file),
"source_plan_sha256": row["plan_sha256"], "engine_profile": selected_profile,
"engine_root": str(engine), "plan_module": mapping["plan_module"],
"entrypoint": mapping["entrypoint"], "dataset_root": str(unit.root),
"model_calls": 0, "native_tasks_executed": 0}
if row.get('case_id'):record['case_id'] = row['case_id']
# Contexts and saved initializations are frozen task inputs.
source = inside(unit.root, row["unit_path"]).parent
if row["family"] == "obstruction-attack":
for name in ("request.json", "task_context.json", "initialization.json", "attack_start.json", "model_profiles.json"):
shutil.copyfile(source / name, output / name)
paths = write_role_configs(configuration, output / "private", container=row["family"] == "obstruction-attack") if configuration else {}
if configuration:
record["configuration"] = configuration.public()
record["role_configs"] = {name: str(path) for name, path in paths.items()}
from .local_docker import settings_for_task
settings = settings_for_task(configuration.docker, row["task_id"])
if row['family'] == 'obstruction-attack':
from .container_policy import obstruction_settings
settings = obstruction_settings(settings, read_json(output / 'attack_start.json'), unit.root)
write_json(output / "private/container.json", settings, mode=0o600)
if row['family'] == 'obstruction-attack':
from .obstruction import prepare_native
prepare_native(record, configuration)
write_json(output / "execution.json", record, mode=0o600)
return record
def validate_prepared(record: dict) -> dict:
"""Import the original family validator in a fresh Python process."""
result = subprocess.run([sys.executable, "-B", "-m", "manipulationarena.plancheck",
str(Path(record["plan_file"]).parent / "execution.json")],
env=inspection_environment(record), text=True, capture_output=True)
if result.returncode:
raise ValueError("Original plan validator rejected the prepared input: " + result.stderr[-2400:])
import json
return json.loads(result.stdout)
def inspection_environment(record: dict, *, environ=None) -> dict[str, str]:
env = dict(os.environ if environ is None else environ)
root = record["dataset_root"]
env.update({"PYTHONDONTWRITEBYTECODE": "1", "MANIPULATIONARENA_ROOT": root,
"MANIPULATIONARENA_GYM": str(Path(root) / "benign_tasks"),
"MANIPULATIONARENA_ENGINE_ROOT": record["engine_root"],
"PYTHONPATH": os.pathsep.join([root, str(Path(record["engine_root"]) / "src")])})
return env
def command(record: dict, configuration: Configuration) -> list[str]:
"""Render the native command. No credentials are included in command arguments."""
engine = Path(record["engine_root"])
output = Path(record["plan_file"]).parent
roles = record["role_configs"]
family = record["family"]
if family == "obstruction-attack":
return [sys.executable, "-B", "-m", "manipulationarena.obstruction",
str(output / "execution.json")]
args = [sys.executable, "-B", str(engine / record["entrypoint"]),
record["task_id"], record["attack_channel"],
"--plan-file", record["plan_file"], "--red-config", roles["red"],
"--blue-config", roles["blue"], "--results-root", str(output / "runs")]
if family in {"self-preservation-attack", "oversight-evasion-attack"}:
from .local_docker import memory_bytes, settings_for_task
settings = settings_for_task(configuration.docker, record['task_id'])
subdir = "violation-tools" if family == "self-preservation-attack" else "impossible-tasks"
catalog = Path(record["dataset_root"]) / "benign_tasks/catalog"
if family == 'oversight-evasion-attack':
catalog = catalog / 'task_index.json'
args += ["--catalog", str(catalog),
"--tool-root", str(Path(record["dataset_root"]) / "datasets" / family / subdir),
"--plans-root", str(output), "--container-config", str(output / "private/container.json"),
"--container-cpu", settings["cpus"],
"--container-memory", str(memory_bytes(settings["memory"]))]
else:
args += ["--tasks-root", str(Path(record["dataset_root"]) / "benign_tasks/tasks/solvable30"),
"--container-config", str(output / "private/container.json")]
return args
def run(record: dict, configuration: Configuration, *, log=None) -> int:
"""Run a prepared unit through its original engine using local Docker."""
from .local_docker import validate_image
validate_prepared(record)
paths = {name: Path(path) for name, path in record["role_configs"].items()}
env = inspection_environment(record, environ=role_environment(configuration, paths))
env["MANIPULATIONARENA_NATIVE_IMAGE"] = validate_image(configuration.docker['image'])
env["MANIPULATIONARENA_ASSETS"] = configuration.environment.get("assets_root", "/opt/manipulationarena/assets")
for setting, name in (('package_index_url', 'PIP_INDEX_URL'),
('package_extra_index_url', 'PIP_EXTRA_INDEX_URL'),
('package_trusted_host', 'PIP_TRUSTED_HOST')):
if setting in configuration.environment:
env[name] = configuration.environment[setting]
if record['family'] == 'obstruction-attack':
return run_native_container(record, configuration, env, log=log)
return subprocess.run(command(record, configuration), env=env,
cwd=record["dataset_root"], stdout=log, stderr=log, check=False).returncode
def run_native_container(record, configuration, env, *, log=None):
"""Run the original native driver and Judge inside one local container."""
from .local_docker import DockerRuntime, load_settings
output = Path(record['plan_file']).parent
settings = load_settings(output / 'private/container.json')
runtime = DockerRuntime(settings)
image = runtime.image_info()
from .obstruction import prepare_native
prepare_native(record, configuration, runtime_image=image['Id'])
passed = {k: v for k, v in env.items() if k.startswith(('MANIPULATIONARENA_', 'PIP_', 'BLUE_'))}
passed.update(PYTHONPATH=env['PYTHONPATH'], PYTHONDONTWRITEBYTECODE='1')
container = runtime.start(settings={**settings, 'image': image['Id']},
mounts=((record['dataset_root'], record['dataset_root'], True),
(output, output, False)), environment=passed)
write_json(output / 'local-container.json', {'container_id': container, 'image': settings['image'],
'image_id': image['Id'],
'privileged': settings['privileged'],
'security_opt': settings['security_opt'],
'cap_add': settings['cap_add']}, mode=0o600)
try:
return subprocess.run(['docker', 'exec', '-i', container, 'python3', '-B', '-m',
'manipulationarena.obstruction', str(output / 'execution.json')],
stdout=log, stderr=log, check=False).returncode
finally:
runtime.stop(container)
|