from __future__ import annotations import ast from typing import List, Optional, Set, Tuple from codestar.core.schemas import JudgeStatus DEFAULT_FORBIDDEN_MODULES = { # OS, process, filesystem, and low-level system access "os", "sys", "subprocess", "shutil", "socket", "http", "urllib", "urllib3", "requests", "httpx", "aiohttp", "multiprocessing", "ctypes", "cffi", "posix", "nt", "threading", "_thread", "signal", "winreg", "psutil", "pathlib", "importlib", "webbrowser", "ftplib", "smtplib", "poplib", "imaplib", "nntplib", "telnetlib", "xmlrpc", "wsgiref", "socketserver", "asyncio", "code", "codeop", "pty", "tty", "termios", "fcntl", "mmap", "resource", "concurrent", "concurrent.futures", "tempfile", "glob", "fnmatch", "stat", "fileinput", "filecmp", "io", "_io", "codecs", "linecache", "tarfile", "zipfile", "gzip", "bz2", "lzma", "zipimport", "ssl", "netrc", "platform", "getpass", "curses", "readline", "rlcompleter", # Code execution, introspection, and packaging escape vectors "codestar", "builtins", "sqlite3", "pickle", "_pickle", "shelve", "dbm", "marshal", "gc", "inspect", "pkgutil", "traceback", "dis", "runpy", "pydoc", "pdb", "bdb", "cmd", "timeit", "doctest", "logging", "venv", "ensurepip", "pip", "distutils", "setuptools", "pkg_resources", "sysconfig", "site", "atexit", "faulthandler", "tracemalloc", "modulefinder", "py_compile", "compileall", "ctypes", "secrets", "pg8000", "jwt", "fastapi", "uvicorn", "starlette", } DEFAULT_FORBIDDEN_BUILTINS = { "eval", "exec", "__import__", "open", "compile", "globals", "locals", "input", "breakpoint", "exit", "quit", "vars", "dir", "memoryview", } FORBIDDEN_DUNDER_ATTRS = { "__class__", "__base__", "__bases__", "__mro__", "__subclasses__", "__builtins__", "__loader__", "__globals__", "__closure__", "__code__", "__spec__", "__dict__", "__import__", "__getattribute__", "__setattr__", "__delattr__", "__reduce__", "__reduce_ex__", "__init_subclass__", "__func__", "__self__", "__module__", "__qualname__", # Frame & traceback escape attributes "f_globals", "f_locals", "f_builtins", "f_back", "f_code", "gi_frame", "cr_frame", "ag_frame", "tb_frame", "tb_next", } class SecurityChecker(ast.NodeVisitor): def __init__(self, forbidden_modules: Set[str], forbidden_calls: Set[str]): self.forbidden_modules = forbidden_modules self.forbidden_calls = forbidden_calls self.violations: List[str] = [] def visit_Import(self, node: ast.Import): for alias in node.names: base_mod = alias.name.split(".")[0] if base_mod in self.forbidden_modules or alias.name in self.forbidden_modules: self.violations.append(f"Forbidden module import: '{alias.name}' (line {node.lineno})") if alias.name in self.forbidden_calls: self.violations.append(f"Forbidden API import: '{alias.name}' (line {node.lineno})") self.generic_visit(node) def visit_ImportFrom(self, node: ast.ImportFrom): if node.module: base_mod = node.module.split(".")[0] if base_mod in self.forbidden_modules or node.module in self.forbidden_modules: self.violations.append(f"Forbidden module import from: '{node.module}' (line {node.lineno})") for alias in node.names: full_name = f"{node.module}.{alias.name}" if alias.name in self.forbidden_calls or full_name in self.forbidden_calls: self.violations.append(f"Forbidden API import: '{full_name}' (line {node.lineno})") self.generic_visit(node) def visit_Call(self, node: ast.Call): call_name = self._get_call_name(node.func) if call_name: if call_name == "__import__": self.violations.append(f"Forbidden builtin call: '{call_name}()' (line {node.lineno})") elif call_name in DEFAULT_FORBIDDEN_BUILTINS: self.violations.append(f"Dangerous builtin call: '{call_name}()' (line {node.lineno})") short_name = call_name.split(".")[-1] if call_name in self.forbidden_calls or short_name in self.forbidden_calls: self.violations.append(f"Forbidden API call: '{call_name}()' (line {node.lineno})") # Guard dynamic attribute reflection (blocks getattr(obj, "__" + "subclasses" + "__") bypasses) if call_name in ("getattr", "hasattr", "setattr", "delattr"): if len(node.args) >= 2: second_arg = node.args[1] if not (isinstance(second_arg, ast.Constant) and isinstance(second_arg.value, str)): self.violations.append( f"Forbidden dynamic attribute reflection via '{call_name}()' (line {node.lineno})" ) else: attr_val = second_arg.value if ( attr_val in FORBIDDEN_DUNDER_ATTRS or attr_val in DEFAULT_FORBIDDEN_BUILTINS or (attr_val.startswith("__") and attr_val.endswith("__")) ): self.violations.append( f"Forbidden security attribute access: '{attr_val}' (line {node.lineno})" ) self.generic_visit(node) def visit_Name(self, node: ast.Name): if node.id in ("__builtins__", "__loader__", "__spec__", "__globals__", "__import__"): self.violations.append(f"Forbidden security identifier access: '{node.id}' (line {node.lineno})") self.generic_visit(node) def visit_Attribute(self, node: ast.Attribute): if node.attr in FORBIDDEN_DUNDER_ATTRS: self.violations.append(f"Forbidden security attribute access: '{node.attr}' (line {node.lineno})") self.generic_visit(node) def _get_call_name(self, node: ast.AST) -> Optional[str]: if isinstance(node, ast.Name): return node.id elif isinstance(node, ast.Attribute): prefix = self._get_call_name(node.value) if prefix: return f"{prefix}.{node.attr}" return node.attr return None def check_code_ast( code: str, extra_forbidden_modules: Optional[List[str]] = None, extra_forbidden_calls: Optional[List[str]] = None, ) -> Tuple[bool, str, Optional[JudgeStatus]]: """ Statically analyzes code syntax and security rules. Returns: (is_valid, error_message, status) """ try: tree = ast.parse(code) except SyntaxError as e: return False, f"SyntaxError at line {e.lineno}: {e.msg}", JudgeStatus.CE except Exception as e: return False, f"Compile Error: {str(e)}", JudgeStatus.CE forbidden_modules = set(DEFAULT_FORBIDDEN_MODULES) if extra_forbidden_modules: forbidden_modules.update(extra_forbidden_modules) forbidden_calls = set() if extra_forbidden_calls: forbidden_calls.update(extra_forbidden_calls) checker = SecurityChecker(forbidden_modules, forbidden_calls) checker.visit(tree) if checker.violations: return False, " | ".join(checker.violations), JudgeStatus.SEC return True, "", None