"""Local Docker transport shared by every attack family. Images must already be available to the selected local Docker daemon. No registry login, image pull, resource service or host Docker socket mount is performed by this module. Stopped containers are kept for inspection. """ from __future__ import annotations import hashlib import json import os from pathlib import Path, PurePosixPath import re import shlex import subprocess import time import uuid class DockerError(RuntimeError): pass class CommandError(DockerError): def __init__(self, message, events): super().__init__(message) self.events = events def validate_image(value, *, required=True): if not value and not required: return "" if (not isinstance(value, str) or not value or value.startswith('-') or re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/@:+-]*', value) is None): raise ValueError('Provide a native Docker image with --image or docker.image') return value def docker_settings(value=None, *, required=False): value = dict(value or {}) unknown = set(value) - {'image', 'platform', 'cpus', 'memory', 'shm_size', 'privileged', 'task_resources', 'security_opt', 'cap_add'} if unknown: raise ValueError('Unsupported docker setting: ' + ', '.join(sorted(unknown))) result = {'image': validate_image(value.get('image', ''), required=required), 'platform': value.get('platform', 'linux/amd64'), 'cpus': str(value.get('cpus', '4')), 'memory': str(value.get('memory', '8g')), 'shm_size': str(value.get('shm_size', '2g')), 'privileged': value.get('privileged', True), 'security_opt': value.get('security_opt', []), 'cap_add': value.get('cap_add', []), 'task_resources': value.get('task_resources', {})} if result['platform'] != 'linux/amd64': raise ValueError('The bundled native runtime requires linux/amd64') try: if not 0 < float(result['cpus']) < 100000: raise ValueError except (ValueError, TypeError): raise ValueError('docker.cpus must be a positive number') from None for key in ('memory', 'shm_size'): if re.fullmatch(r'[1-9][0-9]*(?:[bkmgBKMG](?:[iI]?[bB])?)?', result[key]) is None: raise ValueError('docker.' + key + ' must be a Docker memory size, for example 8g') result[key] = result[key].lower().replace('ib', '').replace('i', '') if not isinstance(result['privileged'], bool) or not isinstance(result['task_resources'], dict): raise ValueError('docker.privileged must be boolean and task_resources must be an object') for key in ('security_opt', 'cap_add'): values = result[key] if not isinstance(values, list) or any( not isinstance(item, str) or not item.strip() or item != item.strip() or any(ord(char) < 32 or ord(char) == 127 for char in item) for item in values): raise ValueError('docker.' + key + ' must be a list of nonempty literal strings') result[key] = list(dict.fromkeys(values)) if any(re.fullmatch(r'(?:CAP_)?[A-Z][A-Z0-9_]*', cap) is None for cap in result['cap_add']): raise ValueError('docker.cap_add must contain Docker capability names such as SYS_ADMIN') if sum(option.startswith('seccomp=') for option in result['security_opt']) > 1: raise ValueError('docker.security_opt may select only one seccomp profile') for task, overrides in result['task_resources'].items(): if not isinstance(task, str) or not isinstance(overrides, dict): raise ValueError('docker.task_resources maps task IDs to resource settings') if set(overrides) - {'cpus', 'memory', 'shm_size'}: raise ValueError('Task overrides may change cpus, memory and shm_size only') docker_settings({**result, 'task_resources': {}, **overrides}, required=required) return result def resolve_security_options(value, base): """Resolve seccomp files relative to the configuration, independent of cwd.""" result = dict(value) options = [] for option in docker_settings(value)['security_opt']: if option.startswith('seccomp=') and option != 'seccomp=unconfined': name = option.split('=', 1)[1] if not name: raise ValueError('docker.security_opt requires a seccomp profile file') path = Path(name) path = (base / path).resolve() if not path.is_absolute() else path.resolve() try: profile = json.loads(path.read_text()) except (OSError, ValueError): raise ValueError('Cannot read the Docker seccomp profile: ' + str(path)) from None if not isinstance(profile, dict) or not isinstance(profile.get('defaultAction'), str): raise ValueError('Invalid Docker seccomp profile: ' + str(path)) option = 'seccomp=' + str(path) options.append(option) result['security_opt'] = options return result def settings_for_task(value, task): result = docker_settings(value) overrides = result['task_resources'].get(task, {}) return docker_settings({**result, **overrides}) def load_settings(path): value = json.loads(Path(path).read_text()) settings = resolve_security_options(value.get('docker', value), Path(path).resolve().parent) return docker_settings(settings, required=True) def memory_bytes(value): """Translate Docker memory units to the original adapters' byte quantity.""" value = docker_settings({'memory': value})['memory'].removesuffix('b') multiplier = {'k': 1024, 'm': 1024**2, 'g': 1024**3} return int(value[:-1]) * multiplier[value[-1]] if value[-1] in multiplier else int(value) def _path(value): path = PurePosixPath(str(value)) if not path.is_absolute() or '..' in path.parts or '\x00' in str(path): raise ValueError('Expected an absolute container path without parent traversal') return str(path) class DockerRuntime: def __init__(self, settings=None): self.settings = docker_settings(settings) self.owner = uuid.uuid4().hex self.containers = set() self._checked = False @staticmethod def _call(arguments, *, data=None, timeout=120, stdout=None): try: return subprocess.run(['docker', *map(str, arguments)], input=data, stdout=subprocess.PIPE if stdout is None else stdout, stderr=subprocess.PIPE, timeout=timeout, check=False) except FileNotFoundError as exc: raise DockerError('Docker CLI is missing; install Docker Engine or Docker Desktop') from exc except subprocess.TimeoutExpired as exc: raise DockerError('Local Docker command timed out') from exc def check_local(self): if self._checked: return endpoint = os.environ.get('DOCKER_HOST', '') # DOCKER_CONTEXT overrides DOCKER_HOST in the Docker CLI. if os.environ.get('DOCKER_CONTEXT') or not endpoint: result = self._call(['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}']) if result.returncode: raise DockerError('Cannot inspect the current Docker context') endpoint = result.stdout.decode().strip() if not endpoint.startswith(('unix://', 'npipe://')): raise DockerError('Select a local Docker context using a Unix socket or Windows named pipe') result = self._call(['info', '--format', '{{.OSType}}']) if result.returncode or result.stdout.strip() != b'linux': raise DockerError('A running local Docker daemon in Linux-container mode is required') self._checked = True def image_info(self, image=None): image = validate_image(image or self.settings['image']) self.check_local() result = self._call(['image', 'inspect', image]) if result.returncode: raise DockerError('The specified image is not loaded locally; load it with docker load before running') value = json.loads(result.stdout)[0] if value.get('Os') != 'linux' or value.get('Architecture') != 'amd64': raise DockerError('The native image must be a Linux amd64 image') if re.fullmatch(r'sha256:[0-9a-f]{64}', value.get('Id', '')) is None: raise DockerError('Docker did not return an immutable local image ID') return value def start(self, *, settings=None, ports=(), mounts=(), environment=None, workdir=None): settings = docker_settings(settings or self.settings, required=True) image = self.image_info(settings['image']) name = 'manipulationarena-' + uuid.uuid4().hex[:16] command = ['run', '--detach', '--pull=never', '--name', name, '--label', 'manipulationarena.owner=' + self.owner, '--platform', settings['platform'], '--init', '--cpus', settings['cpus'], '--memory', settings['memory'], '--shm-size', settings['shm_size'], '--add-host', 'host.docker.internal:host-gateway', '--entrypoint', '/bin/sh'] if settings['privileged']: command.append('--privileged') for option in settings['security_opt']: command.extend(['--security-opt', option]) for capability in settings['cap_add']: command.extend(['--cap-add', capability]) for port in ports: if not isinstance(port, int) or not 1 <= port <= 65535: raise ValueError('Invalid container port') command.extend(['--publish', '127.0.0.1::' + str(port)]) for source, destination, readonly in mounts: source = str(Path(source).resolve()) if ',' in source or ',' in str(destination): raise ValueError('Docker bind paths must not contain commas') command.extend(['--mount', 'type=bind,source=' + source + ',target=' + _path(destination) + (',readonly' if readonly else '')]) launch_environment = {**(environment or {}), 'MANIPULATIONARENA_RUNTIME': 'local-docker'} for key, value in launch_environment.items(): if re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', key) is None or '\x00' in value: raise ValueError('Invalid container environment') command.extend(['--env', key + '=' + value]) if workdir: command.extend(['--workdir', _path(workdir)]) command.extend([image['Id'], '-c', 'exec sleep infinity']) result = self._call(command, timeout=120) if result.returncode: # Avoid echoing arguments containing private configuration. raise DockerError('Could not start the local container; check image, resources and Docker permissions') container = result.stdout.decode().strip() if re.fullmatch(r'[0-9a-f]{12,64}', container) is None: raise DockerError('Docker returned an invalid container ID') self.containers.add(container) from . import native_startup prepared = self._call(['exec', '-i', container, 'python3', '-c', Path(native_startup.__file__).read_text()], timeout=30) if prepared.returncode: self.stop(container) raise DockerError('Native startup preparation failed; inspect /run/manipulationarena/startup.json in the stopped container') return container def _owned(self, container): if container not in self.containers: raise DockerError('Container does not belong to this runtime instance') def execute(self, container, command, *, timeout=120): self._owned(container) if not isinstance(command, str) or not command.strip() or timeout <= 0: raise ValueError('A nonempty command and positive timeout are required') result = self._call(['exec', '-i', '--workdir', '/', container, 'timeout', '--signal=TERM', '--kill-after=5s', str(timeout) + 's', '/bin/bash', '-c', command], timeout=timeout + 15) return {'rc': result.returncode, 'stdout': result.stdout.decode('utf-8', 'replace'), 'stderr': result.stderr.decode('utf-8', 'replace')} def put_bytes(self, container, path, data, *, mode='600', timeout=180): self._owned(container) path = _path(path) if re.fullmatch(r'0?[0-7]{3}', str(mode)) is None or not isinstance(data, bytes): raise ValueError('Invalid file mode or binary payload') script = ('import os,pathlib,sys; p=pathlib.Path(sys.argv[1]); ' 'p.parent.mkdir(parents=True,exist_ok=True,mode=0o700); ' 'p.write_bytes(sys.stdin.buffer.read()); os.chmod(p,int(sys.argv[2],8))') result = self._call(['exec', '-i', container, 'python3', '-c', script, path, mode], data=data, timeout=timeout) return result.returncode == 0 def get_bytes(self, container, path, *, timeout=120): self._owned(container) script = ('import pathlib,sys; p=pathlib.Path(sys.argv[1]); ' 'sys.exit(44) if not p.is_file() else sys.stdout.buffer.write(p.read_bytes())') result = self._call(['exec', container, 'python3', '-c', script, _path(path)], timeout=timeout) if result.returncode == 44: return None if result.returncode: raise DockerError('Could not read the container file') return result.stdout def download_archive(self, container, source_dir, local_path, *, timeout=1800): source = PurePosixPath(_path(source_dir)) archive = '/tmp/arena-evidence-' + uuid.uuid4().hex + '.tar.gz' result = self.execute(container, 'tar -czf ' + shlex.quote(archive) + ' -C ' + shlex.quote(str(source.parent)) + ' ' + shlex.quote(source.name) + ' && sha256sum ' + shlex.quote(archive), timeout=timeout) expected = result['stdout'].split()[0] if result['stdout'].split() else '' if result['rc'] or re.fullmatch(r'[0-9a-f]{64}', expected) is None: raise DockerError('Could not archive container evidence') target = Path(local_path) target.parent.mkdir(parents=True, exist_ok=True) if target.exists() and (not target.is_file() or target.stat().st_size != 0): raise DockerError('Evidence destination already exists; choose a fresh path') copied = self._call(['cp', container + ':' + archive, str(target)], timeout=timeout) if copied.returncode or hashlib.sha256(target.read_bytes()).hexdigest() != expected: raise DockerError('Container evidence transfer failed its checksum') return {'path': str(target), 'sha256': expected, 'bytes': target.stat().st_size} def bridge_url(self, container, port=18099): self._owned(container) result = self._call(['inspect', '--format', '{{json .NetworkSettings.Ports}}', container]) if result.returncode: raise DockerError('Cannot inspect the local container bridge') bindings = json.loads(result.stdout).get(str(port) + '/tcp') or [] if len(bindings) != 1 or bindings[0].get('HostIp') != '127.0.0.1': raise DockerError('The file bridge must be published on loopback only') return 'http://127.0.0.1:' + str(int(bindings[0]['HostPort'])) def detail(self, container): self._owned(container) result = self._call(['inspect', '--format', '{{json .State}}', container]) if result.returncode: raise DockerError('Cannot inspect the local container') return {'id': container, 'status': json.loads(result.stdout)} def stop(self, container): self._owned(container) result = self._call(['stop', '--time', '10', container], timeout=30) if result.returncode: raise DockerError('Could not stop the local container; inspect it using docker ps -a') return True def parse_command_events(raw): try: events = [json.loads(line) for line in raw.splitlines() if line.strip()] except json.JSONDecodeError as exc: raise CommandError('Malformed local command events', []) from exc if any(event.get('type') == 'error' for event in events): raise CommandError('Local container command failed', events) if not any(event.get('type') == 'execution_complete' for event in events): raise CommandError('Local command observation is incomplete', events) return events class LocalPlane: """Preserve the native adapter's execution protocol using local Docker.""" def __init__(self, settings, **_): self.settings = docker_settings(settings, required=True) self.runtime = DockerRuntime(self.settings) self._resources = {} def create_environment(self, *, name, volumes=(), cpu=None, memory=None, **_): if volumes: raise DockerError('The local Blue container uses file transfer rather than host data mounts') key = 'local-' + uuid.uuid4().hex self._resources[key] = docker_settings({**self.settings, **({'cpus': str(cpu)} if cpu is not None else {}), **({'memory': str(memory).replace('Gi', 'g').replace('Mi', 'm')} if memory is not None else {})}) return key def create_sandbox(self, environment_id, **_): if environment_id not in self._resources: raise DockerError('Unknown local container specification') return self.runtime.start(settings=self._resources[environment_id], ports=(18099,)) def wait_until_running(self, container, **_): if not self.runtime.detail(container)['status'].get('Running'): raise DockerError('The local container is not running') def command(self, container, command, *, timeout=90): result = self.runtime.execute(container, command, timeout=timeout) events = [{'type': stream, 'text': result[stream]} for stream in ('stdout', 'stderr') if result[stream]] events.append({'type': 'error', 'error': {'evalue': str(result['rc'])}} if result['rc'] else {'type': 'execution_complete'}) raw = '\n'.join(json.dumps(event) for event in events) + '\n' parse_command_events(raw) return {**result, 'output': raw, 'events': events, 'container_id': container} def details(self, container): return self.runtime.detail(container) def terminate(self, container): return self.runtime.stop(container) def delete_environment(self, environment_id, **_): self._resources.pop(environment_id, None) class ContainerClient: """Process-adapter transport; all file operations stay inside its container.""" def __init__(self, settings=None, **_): self.settings = docker_settings(settings, required=True) self.runtime = DockerRuntime(self.settings) self.container_id = None self.destroyed = False self.diagnostics_path = None @property def sandbox_id(self): # Kept only for the original artifact-writing protocol. return self.container_id def create(self): self.container_id = self.runtime.start() return self.container_id def detail(self): return self.runtime.detail(self.container_id) def execute(self, command, timeout=120): return self.runtime.execute(self.container_id, command, timeout=timeout) def put_bytes(self, path, data, mode='600', timeout=180): return self.runtime.put_bytes(self.container_id, path, data, mode=mode, timeout=timeout) def get_bytes(self, path, timeout=120): return self.runtime.get_bytes(self.container_id, path, timeout=timeout) def download_archive(self, source_dir, local_path, timeout=1800): return self.runtime.download_archive(self.container_id, source_dir, local_path, timeout=timeout) def destroy(self): if self.container_id and not self.destroyed: self.runtime.stop(self.container_id) self.destroyed = True return True