"""Misc. Utilities""" import os import re import shutil # Define some constants # List of banned command regex patterns (case-insensitive, word boundaries) BANNED_COMMANDS = [ # Dangerous recursive delete (match 'rm -rf /' or 'rm -rf /path'). # Original pattern used a trailing \b after '/', which failed to match # because '/' is a non-word char. Use lookahead for end or whitespace. r"\brm\s+-rf\s+/?(?=$|\s)", r"\bshutdown\b.*\bnow\b", # Immediate shutdown r"\breboot\b", # Reboot command r"\bmkfs\.(ext[234]|xfs|btrfs)\b", # Filesystem formatting r"\bdd\s+if=.*\b", # Disk overwrite r"\b:(){:|:&};:\b", # Fork bomb r"\bpoweroff\b", # Power off system r"\binit\s+0\b", # Runlevel 0 (shutdown) r"\bhalt\b", # Halt system r"\bdel\s+/f\s+/q\s+/s\s+C:\\", # Windows delete r"\bformat\s+[a-z]:", # Windows format ] # List of banned shell regex patterns (case-insensitive, word boundaries) BANNED_SHELLS = [ # r"\bsh\b", # r"\bbash\b", # r"\bzsh\b", # r"\bdash\b", r"\bpowershell\.exe\b", r"\bcmd\.exe\b", ] # List of candidate shell paths CANDIDATE_SHELLS = [ "/bin/bash", "/bin/sh", "/bin/zsh", "/usr/bin/bash", "/usr/bin/sh", "/usr/bin/zsh", "/bin/dash", "/usr/bin/dash", "powershell.exe", "cmd.exe", ] # List of available shells def _find_available_shells() -> list[str]: """Detect available shell executables on the system. Block banned shells.""" found = [] for shell in CANDIDATE_SHELLS: shell_path = \ shutil.which(shell) if not shell.startswith("/") else shell if shell_path and shutil.which(shell_path): if not any(re.search(pattern, shell_path) for pattern in BANNED_SHELLS): # noqa found.append(shell_path) elif shell.startswith("/") and os.path.exists(shell): if not any(re.search(pattern, shell) for pattern in BANNED_SHELLS): # noqa found.append(shell) # Remove duplicates while preserving order seen = set() unique_shells = [] for s in found: if s not in seen: unique_shells.append(s) seen.add(s) return unique_shells SHELLS = _find_available_shells() __all__ = ["SHELLS"]