|
| 1 | +import importlib |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import traceback |
| 5 | +from collections.abc import Generator, Iterable |
| 6 | +from contextlib import contextmanager, suppress |
| 7 | +from types import ModuleType |
| 8 | +from typing import Callable, Optional |
| 9 | + |
| 10 | + |
| 11 | +class SideEffectDetectedError(Exception): |
| 12 | + pass |
| 13 | + |
| 14 | + |
| 15 | +_BLOCKED_OPEN_FLAGS = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_EXCL | os.O_TRUNC |
| 16 | + |
| 17 | + |
| 18 | +def accept(event: str, args: tuple) -> None: |
| 19 | + pass |
| 20 | + |
| 21 | + |
| 22 | +def reject(event: str, args: tuple) -> None: |
| 23 | + msg = f'codeflash has detected: {event}{args}".' |
| 24 | + raise SideEffectDetectedError(msg) |
| 25 | + |
| 26 | + |
| 27 | +def inside_module(modules: Iterable[ModuleType]) -> bool: |
| 28 | + files = {m.__file__ for m in modules} |
| 29 | + return any(frame.f_code.co_filename in files for frame, lineno in traceback.walk_stack(None)) |
| 30 | + |
| 31 | + |
| 32 | +def check_open(event: str, args: tuple) -> None: |
| 33 | + (filename_or_descriptor, mode, flags) = args |
| 34 | + if filename_or_descriptor in ("/dev/null", "nul"): |
| 35 | + # (no-op writes on unix/windows) |
| 36 | + return |
| 37 | + if flags & _BLOCKED_OPEN_FLAGS: |
| 38 | + msg = f"codeflash has detected: {event}({', '.join(map(repr, args))})." |
| 39 | + raise SideEffectDetectedError(msg) |
| 40 | + |
| 41 | + |
| 42 | +def check_msvcrt_open(event: str, args: tuple) -> None: |
| 43 | + print(args) |
| 44 | + (handle, flags) = args |
| 45 | + if flags & _BLOCKED_OPEN_FLAGS: |
| 46 | + msg = f"codeflash has detected: {event}({', '.join(map(repr, args))})." |
| 47 | + raise SideEffectDetectedError(msg) |
| 48 | + |
| 49 | + |
| 50 | +_MODULES_THAT_CAN_POPEN: Optional[set[ModuleType]] = None |
| 51 | + |
| 52 | + |
| 53 | +def modules_with_allowed_popen(): |
| 54 | + global _MODULES_THAT_CAN_POPEN |
| 55 | + if _MODULES_THAT_CAN_POPEN is None: |
| 56 | + allowed_module_names = ("_aix_support", "ctypes", "platform", "uuid") |
| 57 | + _MODULES_THAT_CAN_POPEN = set() |
| 58 | + for module_name in allowed_module_names: |
| 59 | + with suppress(ImportError): |
| 60 | + _MODULES_THAT_CAN_POPEN.add(importlib.import_module(module_name)) |
| 61 | + return _MODULES_THAT_CAN_POPEN |
| 62 | + |
| 63 | + |
| 64 | +def check_subprocess(event: str, args: tuple) -> None: |
| 65 | + if not inside_module(modules_with_allowed_popen()): |
| 66 | + reject(event, args) |
| 67 | + |
| 68 | + |
| 69 | +def check_sqlite_connect(event: str, args: tuple) -> None: |
| 70 | + if "codeflash_" in args[0]: |
| 71 | + accept(event, args) |
| 72 | + else: |
| 73 | + reject(event, args) |
| 74 | + |
| 75 | + |
| 76 | +_SPECIAL_HANDLERS = { |
| 77 | + "open": check_open, |
| 78 | + "subprocess.Popen": check_subprocess, |
| 79 | + "msvcrt.open_osfhandle": check_msvcrt_open, |
| 80 | + "sqlite3.connect": check_sqlite_connect, |
| 81 | +} |
| 82 | + |
| 83 | + |
| 84 | +def make_handler(event: str) -> Callable[[str, tuple], None]: |
| 85 | + special_handler = _SPECIAL_HANDLERS.get(event) |
| 86 | + if special_handler: |
| 87 | + return special_handler |
| 88 | + # Block certain events |
| 89 | + if event in ( |
| 90 | + "winreg.CreateKey", |
| 91 | + "winreg.DeleteKey", |
| 92 | + "winreg.DeleteValue", |
| 93 | + "winreg.SaveKey", |
| 94 | + "winreg.SetValue", |
| 95 | + "winreg.DisableReflectionKey", |
| 96 | + "winreg.EnableReflectionKey", |
| 97 | + ): |
| 98 | + return reject |
| 99 | + # Allow certain events. |
| 100 | + if event in ( |
| 101 | + # These seem not terribly dangerous to allow: |
| 102 | + "os.putenv", |
| 103 | + "os.unsetenv", |
| 104 | + "msvcrt.heapmin", |
| 105 | + "msvcrt.kbhit", |
| 106 | + # These involve I/O, but are hopefully non-destructive: |
| 107 | + "glob.glob", |
| 108 | + "msvcrt.get_osfhandle", |
| 109 | + "msvcrt.setmode", |
| 110 | + "os.listdir", # (important for Python's importer) |
| 111 | + "os.scandir", # (important for Python's importer) |
| 112 | + "os.chdir", |
| 113 | + "os.fwalk", |
| 114 | + "os.getxattr", |
| 115 | + "os.listxattr", |
| 116 | + "os.walk", |
| 117 | + "pathlib.Path.glob", |
| 118 | + "socket.gethostbyname", # (FastAPI TestClient uses this) |
| 119 | + "socket.__new__", # (FastAPI TestClient uses this) |
| 120 | + "socket.bind", # pygls's asyncio needs this on windows |
| 121 | + "socket.connect", # pygls's asyncio needs this on windows |
| 122 | + ): |
| 123 | + return accept |
| 124 | + # Block groups of events. |
| 125 | + event_prefix = event.split(".", 1)[0] |
| 126 | + if event_prefix in ( |
| 127 | + "os", |
| 128 | + "fcntl", |
| 129 | + "ftplib", |
| 130 | + "glob", |
| 131 | + "imaplib", |
| 132 | + "msvcrt", |
| 133 | + "nntplib", |
| 134 | + "os", |
| 135 | + "pathlib", |
| 136 | + "poplib", |
| 137 | + "shutil", |
| 138 | + "smtplib", |
| 139 | + "socket", |
| 140 | + "sqlite3", |
| 141 | + "subprocess", |
| 142 | + "telnetlib", |
| 143 | + "urllib", |
| 144 | + "webbrowser", |
| 145 | + ): |
| 146 | + return reject |
| 147 | + # Allow other events. |
| 148 | + return accept |
| 149 | + |
| 150 | + |
| 151 | +_HANDLERS: dict[str, Callable[[str, tuple], None]] = {} |
| 152 | +_ENABLED = True |
| 153 | + |
| 154 | + |
| 155 | +def audithook(event: str, args: tuple) -> None: |
| 156 | + if not _ENABLED: |
| 157 | + return |
| 158 | + handler = _HANDLERS.get(event) |
| 159 | + if handler is None: |
| 160 | + handler = make_handler(event) |
| 161 | + _HANDLERS[event] = handler |
| 162 | + handler(event, args) |
| 163 | + |
| 164 | + |
| 165 | +@contextmanager |
| 166 | +def opened_auditwall() -> Generator: |
| 167 | + global _ENABLED |
| 168 | + assert _ENABLED |
| 169 | + _ENABLED = False |
| 170 | + try: |
| 171 | + yield |
| 172 | + finally: |
| 173 | + _ENABLED = True |
| 174 | + |
| 175 | + |
| 176 | +def engage_auditwall() -> None: |
| 177 | + sys.dont_write_bytecode = True # disable .pyc file writing |
| 178 | + sys.addaudithook(audithook) |
| 179 | + |
| 180 | + |
| 181 | +def disable_auditwall() -> None: |
| 182 | + global _ENABLED |
| 183 | + assert _ENABLED |
| 184 | + _ENABLED = False |
0 commit comments