Exec 执行命令
(ctx context.Context, cmd string, opts *ExecOptions)
| 373 | |
| 374 | // Exec 执行命令 |
| 375 | func (ls *LocalSandbox) Exec(ctx context.Context, cmd string, opts *ExecOptions) (*ExecResult, error) { |
| 376 | startTime := time.Now() |
| 377 | cmdName := ls.extractCommandName(cmd) |
| 378 | |
| 379 | // 1. 检查是否为排除命令(直接执行,但仍有关键安全检查) |
| 380 | if ls.isExcludedCommand(cmd) { |
| 381 | result, err := ls.execDirect(ctx, cmd, opts) |
| 382 | if err != nil { |
| 383 | return nil, err |
| 384 | } |
| 385 | ls.recordAudit(cmd, opts, result, startTime, false, "excluded_command") |
| 386 | return result, nil |
| 387 | } |
| 388 | |
| 389 | // 2. 检查是否在阻止列表 |
| 390 | if ls.blockedCommands[cmdName] { |
| 391 | ls.recordAudit(cmd, opts, nil, startTime, true, "command in blocklist") |
| 392 | return &ExecResult{ |
| 393 | Code: 1, |
| 394 | Stdout: "", |
| 395 | Stderr: fmt.Sprintf("Command '%s' is blocked by security policy", cmdName), |
| 396 | }, nil |
| 397 | } |
| 398 | |
| 399 | // 3. 严格模式:检查命令白名单 |
| 400 | if ls.securityLevel >= SecurityLevelStrict { |
| 401 | if !allowedCommands[cmdName] && !ls.isExcludedCommand(cmd) { |
| 402 | ls.recordAudit(cmd, opts, nil, startTime, true, "command not in whitelist") |
| 403 | return &ExecResult{ |
| 404 | Code: 1, |
| 405 | Stdout: "", |
| 406 | Stderr: fmt.Sprintf("Command '%s' is not in the allowed list (strict mode)", cmdName), |
| 407 | }, nil |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // 4. 安全检查:阻止危险命令 |
| 412 | if blockReason := ls.checkDangerousCommand(cmd); blockReason != "" { |
| 413 | ls.recordAudit(cmd, opts, nil, startTime, true, blockReason) |
| 414 | return &ExecResult{ |
| 415 | Code: 1, |
| 416 | Stdout: "", |
| 417 | Stderr: "Dangerous command blocked: " + blockReason, |
| 418 | }, nil |
| 419 | } |
| 420 | |
| 421 | // 5. 路径安全检查 |
| 422 | if ls.securityLevel >= SecurityLevelStrict { |
| 423 | if pathIssue := ls.checkPathSecurity(cmd); pathIssue != "" { |
| 424 | ls.recordAudit(cmd, opts, nil, startTime, true, pathIssue) |
| 425 | return &ExecResult{ |
| 426 | Code: 1, |
| 427 | Stdout: "", |
| 428 | Stderr: "Path security violation: " + pathIssue, |
| 429 | }, nil |
| 430 | } |
| 431 | } |
| 432 |