hasCommandInjection 检测命令注入
(cmd string)
| 645 | |
| 646 | // hasCommandInjection 检测命令注入 |
| 647 | func (ls *LocalSandbox) hasCommandInjection(cmd string) bool { |
| 648 | // 检测常见的命令注入模式 |
| 649 | injectionPatterns := []string{ |
| 650 | "`", // 反引号命令替换 |
| 651 | "$(", // 命令替换 |
| 652 | "$((", // 算术扩展 |
| 653 | "${", // 参数扩展(可能危险) |
| 654 | "\n", // 换行符注入 |
| 655 | "\r", // 回车符注入 |
| 656 | "\x00", // 空字节注入 |
| 657 | } |
| 658 | |
| 659 | for _, pattern := range injectionPatterns { |
| 660 | // 允许在引号内使用这些字符 |
| 661 | if strings.Contains(cmd, pattern) { |
| 662 | // 简单检查:如果不在引号内,则可能是注入 |
| 663 | if !ls.isInQuotes(cmd, strings.Index(cmd, pattern)) { |
| 664 | // 对于 $( 和 ${ 做更宽松的检查,因为它们在脚本中很常见 |
| 665 | if pattern == "$(" || pattern == "${" { |
| 666 | // 只在偏执模式下阻止 |
| 667 | if ls.securityLevel >= SecurityLevelParanoid { |
| 668 | return true |
| 669 | } |
| 670 | } else { |
| 671 | return true |
| 672 | } |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | return false |
| 678 | } |
| 679 | |
| 680 | // isInQuotes 检查位置是否在引号内 |
| 681 | func (ls *LocalSandbox) isInQuotes(s string, pos int) bool { |
no test coverage detected