浏览代码

```
fix(security): 优化命令注入检测正则表达式

- 修改系统命令函数调用的正则匹配模式,增加参数验证
- 调整管道符检测逻辑,避免匹配单纯竖线字符
- 优化分号检测规则,防止误匹配HTML实体符号
- 更新危险命令识别模式,提高匹配精度
- 新增反引号命令检测,防止代码块中反引号被误判
```

shichen 5 月之前
父节点
当前提交
aa442abef0
共有 1 个文件被更改,包括 11 次插入9 次删除
  1. 11 9
      app/middleware/SecurityMiddleware.php

+ 11 - 9
app/middleware/SecurityMiddleware.php

@@ -208,18 +208,20 @@ class SecurityMiddleware
208 208
     protected function detectCommandInjection(string $input): bool
209 209
     {
210 210
         $patterns = [
211
-            // 系统命令
212
-            '/(?:system|exec|shell_exec|passthru|proc_open|popen|pcntl_exec)\s*\(/i',
211
+            // 系统命令函数调用(更精确的匹配)
212
+            '/(?:system|exec|shell_exec|passthru|proc_open|popen|pcntl_exec)\s*\(\s*[\'\"\$\w]/i',
213 213
 
214
-            // 管道符
215
-            '/\|\s*\w+/',
216
-            '/;\s*\w+/',
214
+            // 管道符后跟命令(避免匹配单纯的|字符)
215
+            '/\|\s*(?:rm\s|cat\s|ls\s|wget\s|curl\s|nc\s|sh\s|bash\s)/i',
217 216
 
218
-            // 危险命令
219
-            '/\b(?:rm\s+-|cat\s+\/|wget\s+|curl\s+|nc\s+)\b/i',
217
+            // 分号后跟命令(避免匹配HTML实体如 )
218
+            '/;\s*(?:rm\s|cat\s|ls\s|wget\s|curl\s|nc\s|sh\s|bash\s|\$\w+)/i',
220 219
 
221
-            // 反引号
222
-            '/`.*?`/',
220
+            // 危险命令(更精确的匹配)
221
+            '/\b(?:rm\s+-(?:rf?|i)\b|cat\s+\/\w|wget\s+http|curl\s+http|nc\s+-[lv])\b/i',
222
+
223
+            // 反引号包裹命令(避免匹配代码块中的反引号)
224
+            '/`\s*(?:rm\s|cat\s|ls\s|wget\s|curl\s|nc\s|sh\s|bash\s)/i',
223 225
         ];
224 226
 
225 227
         foreach ($patterns as $pattern) {