152 lines
6.8 KiB
Python
152 lines
6.8 KiB
Python
"""Compare a true installed baseline with the candidate overlay, blocking side effects."""
|
|
from pathlib import Path
|
|
import argparse
|
|
import contextlib
|
|
import hashlib
|
|
import importlib
|
|
import importlib.abc
|
|
import importlib.util
|
|
import json
|
|
import logging
|
|
import re
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import traceback
|
|
|
|
sys.dont_write_bytecode = True
|
|
logging.disable(logging.CRITICAL)
|
|
|
|
|
|
class ImportSideEffectBlocked(RuntimeError):
|
|
pass
|
|
|
|
|
|
class DiscardOutput:
|
|
def write(self, value): return len(value)
|
|
def flush(self): pass
|
|
|
|
|
|
NATIVE_LOOKUP_POLICY = 'ctypes-ldconfig-cache-v2'
|
|
|
|
|
|
def is_allowed_readonly_lookup(argv, kwargs, caller_module, caller_function):
|
|
"""One observed stdlib native-library cache lookup; no general process allowance."""
|
|
return (type(argv) in (list, tuple) and tuple(argv) == ('/sbin/ldconfig', '-p')
|
|
and caller_module == 'ctypes.util' and caller_function == '_findSoname_ldconfig'
|
|
and set(kwargs).issubset({'stdin', 'stdout', 'stderr', 'env', 'shell', 'close_fds'})
|
|
and kwargs.get('stdin') == subprocess.DEVNULL
|
|
and kwargs.get('stdout') == subprocess.PIPE and kwargs.get('stderr') == subprocess.DEVNULL
|
|
and kwargs.get('env') == {'LC_ALL': 'C', 'LANG': 'C'}
|
|
and kwargs.get('shell', False) is False and kwargs.get('close_fds', True) is True)
|
|
|
|
|
|
def readonly_popen_gate(original, denied, permits):
|
|
def checked(argv, *extra, **kwargs):
|
|
caller = sys._getframe(1)
|
|
if (not extra and is_allowed_readonly_lookup(argv, kwargs,
|
|
caller.f_globals.get('__name__'), caller.f_code.co_name)):
|
|
permits['CTYPES_LDCONFIG_CACHE_LIST'] = permits.get('CTYPES_LDCONFIG_CACHE_LIST', 0) + 1
|
|
# Fixed locale-only environment excludes inherited preload/loader settings.
|
|
return original(['/sbin/ldconfig', '-p'], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL, env={'LC_ALL': 'C', 'LANG': 'C'}, close_fds=True)
|
|
return denied(argv, *extra, **kwargs)
|
|
return checked
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--mode', choices=['baseline', 'candidate'], required=True)
|
|
parser.add_argument('--package', type=Path, required=True)
|
|
parser.add_argument('--installed', action='store_true')
|
|
args = parser.parse_args()
|
|
root = Path('/app/api')
|
|
package = args.package.resolve()
|
|
manifest = json.loads((package / 'manifest.json').read_text())
|
|
assert len(manifest['targets']) == 17
|
|
rows = manifest['targets']
|
|
for row in rows:
|
|
p = root / row['path']
|
|
expected = row['after_sha256'] if args.installed else row['before_sha256']
|
|
assert (hashlib.sha256(p.read_bytes()).hexdigest() if p.is_file() else None) == expected
|
|
body = (package / 'candidate' / row['path']).read_bytes()
|
|
assert hashlib.sha256(body).hexdigest() == row['after_sha256']
|
|
selected = rows if args.mode == 'candidate' else [r for r in rows if r['before_sha256'] is not None]
|
|
paths = {r['path'][:-3].replace('/', '.'): package / 'candidate' / r['path'] for r in rows}
|
|
class Overlay(importlib.abc.MetaPathFinder):
|
|
def find_spec(self, fullname, path=None, target=None):
|
|
if fullname in paths:
|
|
return importlib.util.spec_from_file_location(fullname, paths[fullname])
|
|
return None
|
|
if args.mode == 'candidate' and not args.installed:
|
|
sys.meta_path.insert(0, Overlay())
|
|
sys.path.insert(0, str(root))
|
|
observations = []
|
|
totals = {}
|
|
permits = {}
|
|
def safe_file(filename):
|
|
value = filename.replace('\\', '/')
|
|
if value.startswith(str(package / 'candidate') + '/'):
|
|
result = 'candidate/' + value[len(str(package / 'candidate')) + 1:]
|
|
elif value.startswith('/app/api/'):
|
|
result = 'api/' + value[len('/app/api/'):]
|
|
elif '/site-packages/' in value:
|
|
result = 'site-packages/' + value.split('/site-packages/', 1)[1]
|
|
elif value.startswith('<') and value.endswith('>'):
|
|
return '<diagnostic>'
|
|
else:
|
|
result = 'stdlib/' + Path(value).name
|
|
return result if re.fullmatch(r'[A-Za-z0-9_.\-/]{1,240}', result) else '<static-path-redacted>'
|
|
def guard(operation):
|
|
def blocked(*unused, **unused_keywords):
|
|
totals[operation] = totals.get(operation, 0) + 1
|
|
if len(observations) < 12:
|
|
stack = []
|
|
for frame in traceback.extract_stack(limit=18)[:-1]:
|
|
name = frame.name if re.fullmatch(r'[A-Za-z0-9_<>.]{1,100}', frame.name) else '<function>'
|
|
stack.append({'file': safe_file(frame.filename), 'line': frame.lineno, 'function': name})
|
|
observations.append({'operation': operation, 'stack': stack})
|
|
raise ImportSideEffectBlocked()
|
|
return blocked
|
|
socket.socket.connect = guard('SOCKET_CONNECT')
|
|
socket.socket.connect_ex = guard('SOCKET_CONNECT_EX')
|
|
socket.create_connection = guard('SOCKET_CREATE_CONNECTION')
|
|
socket.getaddrinfo = guard('DNS_GETADDRINFO')
|
|
subprocess.Popen = readonly_popen_gate(subprocess.Popen, guard('SUBPROCESS_START'), permits)
|
|
threading.Thread.start = guard('THREAD_START')
|
|
imported = []
|
|
failed_module = None
|
|
error_type = None
|
|
for row in selected:
|
|
module_name = row['path'][:-3].replace('/', '.')
|
|
try:
|
|
with contextlib.redirect_stdout(DiscardOutput()), contextlib.redirect_stderr(DiscardOutput()):
|
|
module = importlib.import_module(module_name)
|
|
expected = paths[module_name] if args.mode == 'candidate' and not args.installed else root / row['path']
|
|
assert Path(module.__file__).resolve() == expected.resolve()
|
|
imported.append(module_name)
|
|
except BaseException as error:
|
|
failed_module = module_name
|
|
error_type = type(error).__name__
|
|
break
|
|
result = {'mode': args.mode, 'ok': failed_module is None and not totals,
|
|
'imports_completed': failed_module is None, 'imported_count': len(imported),
|
|
'failed_module': failed_module, 'error_type': error_type,
|
|
'blocked_operations': totals, 'blocked_observations': observations,
|
|
'actual_network_permitted': False, 'actual_thread_start_permitted': False,
|
|
'arbitrary_subprocess_permitted': False, 'permitted_operations': permits,
|
|
'native_lookup_policy': NATIVE_LOOKUP_POLICY,
|
|
'source_values_or_traceback_text_exported': False}
|
|
print(json.dumps(result))
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:
|
|
raise SystemExit(main())
|
|
except Exception as error:
|
|
print(json.dumps({'ok': False, 'stage': 'diagnostic_preflight', 'error_type': type(error).__name__,
|
|
'error_details_redacted': True}))
|
|
raise SystemExit(1)
|