| 40 | |
| 41 | |
| 42 | class ToolExecutor: |
| 43 | def __init__(self): |
| 44 | pass |
| 45 | |
| 46 | @staticmethod |
| 47 | def init_sandbox_dir(): |
| 48 | if not _enable_sandbox: |
| 49 | # 不启用sandbox就不初始化目录 |
| 50 | return |
| 51 | try: |
| 52 | # 只初始化一次 |
| 53 | fd = os.open( |
| 54 | os.path.join(PROJECT_DIR, "tmp", "tool_executor_init_dir.lock"), os.O_CREAT | os.O_EXCL | os.O_WRONLY |
| 55 | ) |
| 56 | os.close(fd) |
| 57 | except FileExistsError: |
| 58 | # 文件已存在 → 已初始化过 |
| 59 | return |
| 60 | maxkb_logger.info("Init sandbox dir.") |
| 61 | try: |
| 62 | os.system("chmod -R g-rwx /dev/shm /dev/mqueue") |
| 63 | os.system("chmod o-rwx /run/postgresql") |
| 64 | except Exception as e: |
| 65 | maxkb_logger.warning(f"Exception: {e}", exc_info=True) |
| 66 | pass |
| 67 | if CONFIG.get("SANDBOX_TMP_DIR_ENABLED", "0") == "1": |
| 68 | os.system("chmod g+rwx /tmp") |
| 69 | # 初始化sandbox配置文件 |
| 70 | sandbox_lib_path = os.path.dirname(f"{_sandbox_path}/lib/sandbox.so") |
| 71 | sandbox_conf_file_path = f"{sandbox_lib_path}/.sandbox.conf" |
| 72 | if os.path.exists(sandbox_conf_file_path): |
| 73 | os.remove(sandbox_conf_file_path) |
| 74 | banned_hosts = CONFIG.get("SANDBOX_PYTHON_BANNED_HOSTS", "").strip() |
| 75 | allow_dl_paths = CONFIG.get("SANDBOX_PYTHON_ALLOW_DL_PATHS", "").strip() |
| 76 | allow_dl_open = CONFIG.get("SANDBOX_PYTHON_ALLOW_DL_OPEN", "0") |
| 77 | allow_subprocess = CONFIG.get("SANDBOX_PYTHON_ALLOW_SUBPROCESS", "0") |
| 78 | allow_syscall = CONFIG.get("SANDBOX_PYTHON_ALLOW_SYSCALL", "0") |
| 79 | if banned_hosts: |
| 80 | hostname = socket.gethostname() |
| 81 | local_ip = socket.gethostbyname(hostname) |
| 82 | banned_hosts = f"{banned_hosts},{local_ip}" |
| 83 | banned_hosts = ",".join( |
| 84 | s.strip() for s in banned_hosts.split(",") if s.strip() and s.strip().lower() != hostname.lower() |
| 85 | ) |
| 86 | with open(sandbox_conf_file_path, "w", encoding="utf-8") as f: |
| 87 | f.write(f"SANDBOX_PYTHON_BANNED_HOSTS={banned_hosts}\n") |
| 88 | f.write( |
| 89 | f"SANDBOX_PYTHON_ALLOW_DL_PATHS={','.join(sorted(set(filter(None, sys.path + _sandbox_python_sys_path + allow_dl_paths.split(',')))))}\n" |
| 90 | ) |
| 91 | f.write(f"SANDBOX_PYTHON_ALLOW_DL_OPEN={allow_dl_open}\n") |
| 92 | f.write(f"SANDBOX_PYTHON_ALLOW_SUBPROCESS={allow_subprocess}\n") |
| 93 | f.write(f"SANDBOX_PYTHON_ALLOW_SYSCALL={allow_syscall}\n") |
| 94 | os.system(f"chmod -R 550 {_sandbox_path}") |
| 95 | |
| 96 | try: |
| 97 | init_sandbox_dir() |
| 98 | except Exception as e: |
| 99 | maxkb_logger.error(f"Exception: {e}", exc_info=True) |