Coverage for merco/sandbox/security.py: 100%

16 statements  

« prev     ^ index     » next       coverage.py v7.15.0, created at 2026-07-07 14:04 +0800

1"""安全检查""" 

2 

3import re 

4 

5 

6class SecurityChecker: 

7 """检查命令与内容的安全性""" 

8 

9 DANGEROUS_PATTERNS = [ 

10 r"rm\s+-rf\s+/", 

11 r"mkfs", 

12 r"dd\s+if=", 

13 r">\s*/dev/sd", 

14 r"chmod\s+777\s+/", 

15 r"wget.*\|\s*bash", 

16 r"curl.*\|\s*sh", 

17 ] 

18 

19 @classmethod 

20 def check_command(cls, command: str) -> tuple[bool, str]: 

21 """检查命令是否危险""" 

22 for pattern in cls.DANGEROUS_PATTERNS: 

23 if re.search(pattern, command, re.IGNORECASE): 

24 return False, f"Dangerous pattern detected: {pattern}" 

25 return True, "" 

26 

27 @classmethod 

28 def check_file_path(cls, path: str) -> tuple[bool, str]: 

29 """检查文件路径是否安全""" 

30 if ".." in path: 

31 return False, "Path traversal detected" 

32 if path.startswith("/proc") or path.startswith("/sys"): 

33 return False, "Access to system paths not allowed" 

34 return True, ""