| 1 | import { parse } from "shell-quote"; |
| 2 | import { ToolPolicy } from "./types.js"; |
| 3 | |
| 4 | /** |
| 5 | * Token types from shell-quote |
| 6 | */ |
| 7 | interface ShellOperator { |
| 8 | op: string; // '||', '&&', '|', ';', '>', '>>', '<', '&' |
| 9 | } |
| 10 | |
| 11 | interface GlobPattern { |
| 12 | op: "glob"; |
| 13 | pattern: string; |
| 14 | } |
| 15 | |
| 16 | interface CommentToken { |
| 17 | comment: string; |
| 18 | } |
| 19 | |
| 20 | type ParsedToken = string | ShellOperator | GlobPattern | CommentToken; |
| 21 | |
| 22 | /** |
| 23 | * Evaluates the security policy for a terminal command. |
| 24 | * |
| 25 | * This function uses shell-quote for proper tokenization, then implements |
| 26 | * defense-in-depth security validation for terminal commands. |
| 27 | * |
| 28 | * @param basePolicy The base policy configured for the tool |
| 29 | * @param command The command string to evaluate |
| 30 | * @returns The security policy to apply: 'disabled', 'allowedWithPermission', or 'allowedWithoutPermission' |
| 31 | */ |
| 32 | export function evaluateTerminalCommandSecurity( |
| 33 | basePolicy: ToolPolicy, |
| 34 | command: string | null | undefined, |
| 35 | ): ToolPolicy { |
| 36 | // If tool is already disabled, keep it disabled |
| 37 | if (basePolicy === "disabled") { |
| 38 | return "disabled"; |
| 39 | } |
| 40 | |
| 41 | // Handle null/undefined/empty commands |
| 42 | if (!command || typeof command !== "string") { |
| 43 | return basePolicy; |
| 44 | } |
| 45 | |
| 46 | // Normalize command for analysis |
| 47 | const normalizedCommand = command.trim(); |
| 48 | if (normalizedCommand === "") { |
| 49 | return basePolicy; |
| 50 | } |
| 51 | |
| 52 | try { |
| 53 | // Parse the command into tokens using shell-quote |
| 54 | const tokens = parse(normalizedCommand); |
| 55 | |
| 56 | // Evaluate security of the parsed tokens |
| 57 | return evaluateTokensSecurity(tokens, basePolicy, normalizedCommand); |
| 58 | } catch (error) { |
| 59 | // If parsing fails, be conservative and require permission |
| 60 | console.error("Failed to parse command:", error); |
| 61 | return "allowedWithPermission"; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Checks if a token is a shell operator |
| 67 | */ |
| 68 | function isOperator(token: ParsedToken): token is ShellOperator { |
| 69 | return typeof token === "object" && "op" in token && token.op !== "glob"; |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Checks if a token is a glob pattern |
| 74 | */ |
| 75 | function isGlob(token: ParsedToken): token is GlobPattern { |
| 76 | return typeof token === "object" && "op" in token && token.op === "glob"; |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Checks if a token is a comment |
| 81 | */ |
| 82 | function isComment(token: ParsedToken): token is CommentToken { |
| 83 | return typeof token === "object" && "comment" in token; |
| 84 | } |
| 85 | |
| 86 | /** |
| 87 | * Evaluates the security of parsed shell tokens, handling variable expansion |
| 88 | */ |
| 89 | function evaluateTokensSecurity( |
| 90 | tokens: ParsedToken[], |
| 91 | basePolicy: ToolPolicy, |
| 92 | originalCommand: string, |
| 93 | ): ToolPolicy { |
| 94 | // Check for empty strings that might indicate variable expansion |
| 95 | const hasEmptyStrings = tokens.some((t) => typeof t === "string" && t === ""); |
| 96 | |
| 97 | if (hasEmptyStrings) { |
| 98 | // Check if original command has legitimate empty quotes |
| 99 | const hasEmptyQuotes = |
| 100 | originalCommand.includes('""') || originalCommand.includes("''"); |
| 101 | // Check for variable patterns |
| 102 | const hasVariablePatterns = /\$[\w{]/.test(originalCommand); |
| 103 | |
| 104 | if (!hasEmptyQuotes || hasVariablePatterns) { |
| 105 | // Variable expansion detected - evaluate both interpretations |
| 106 | |
| 107 | // 1. Evaluate with empty strings as-is |
| 108 | const policyWithEmpty = evaluateTokens( |
| 109 | tokens, |
| 110 | basePolicy, |
| 111 | originalCommand, |
| 112 | ); |
| 113 | |
| 114 | // 2. Evaluate without empty strings |
| 115 | const tokensWithoutEmpty = tokens.filter((t) => t !== ""); |
| 116 | const policyWithoutEmpty = |
| 117 | tokensWithoutEmpty.length > 0 |
| 118 | ? evaluateTokens(tokensWithoutEmpty, basePolicy, originalCommand) |
| 119 | : basePolicy; |
| 120 | |
| 121 | // Variable expansion always requires at least permission |
| 122 | return getMostRestrictive( |
| 123 | policyWithEmpty, |
| 124 | policyWithoutEmpty, |
| 125 | "allowedWithPermission", |
| 126 | ); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // Normal evaluation for commands without variable expansion |
| 131 | return evaluateTokens(tokens, basePolicy, originalCommand); |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * Core token evaluation logic |
| 136 | */ |
| 137 | function evaluateTokens( |
| 138 | tokens: ParsedToken[], |
| 139 | basePolicy: ToolPolicy, |
| 140 | originalCommand: string, |
| 141 | ): ToolPolicy { |
| 142 | let mostRestrictivePolicy = basePolicy; |
| 143 | let currentCommand: string[] = []; |
| 144 | |
| 145 | for (let i = 0; i < tokens.length; i++) { |
| 146 | const token = tokens[i]; |
| 147 | |
| 148 | // Skip comments - they don't affect execution |
| 149 | if (isComment(token)) { |
| 150 | continue; |
| 151 | } |
| 152 | |
| 153 | // Check if token is an operator |
| 154 | if (isOperator(token)) { |
| 155 | // Evaluate the current command before the operator |
| 156 | if (currentCommand.length > 0) { |
| 157 | const commandPolicy = evaluateSingleCommand( |
| 158 | currentCommand, |
| 159 | originalCommand, |
| 160 | ); |
| 161 | mostRestrictivePolicy = getMostRestrictive( |
| 162 | mostRestrictivePolicy, |
| 163 | commandPolicy, |
| 164 | ); |
| 165 | |
| 166 | // If we found a disabled command, return immediately |
| 167 | if (mostRestrictivePolicy === "disabled") { |
| 168 | return "disabled"; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // Reset for next command |
| 173 | currentCommand = []; |
| 174 | |
| 175 | // Handle pipe operator specially - check if piping to dangerous command |
| 176 | if ((token as ShellOperator).op === "|") { |
| 177 | const pipePolicy = evaluatePipeChain(tokens, i); |
| 178 | mostRestrictivePolicy = getMostRestrictive( |
| 179 | mostRestrictivePolicy, |
| 180 | pipePolicy, |
| 181 | ); |
| 182 | if (mostRestrictivePolicy === "disabled") { |
| 183 | return "disabled"; |
| 184 | } |
| 185 | } |
| 186 | } else if (isGlob(token)) { |
| 187 | // Handle glob patterns |
| 188 | currentCommand.push(token.pattern); |
| 189 | } else if (typeof token === "string") { |
| 190 | currentCommand.push(token); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // Evaluate any remaining command |
| 195 | if (currentCommand.length > 0) { |
| 196 | const commandPolicy = evaluateSingleCommand( |
| 197 | currentCommand, |
| 198 | originalCommand, |
| 199 | ); |
| 200 | mostRestrictivePolicy = getMostRestrictive( |
| 201 | mostRestrictivePolicy, |
| 202 | commandPolicy, |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | // Also check for command substitution in the original command |
| 207 | // (shell-quote doesn't parse these as separate tokens) |
| 208 | if (hasCommandSubstitution(originalCommand)) { |
| 209 | const substitutedCommands = extractSubstitutedCommands(originalCommand); |
| 210 | for (const subCmd of substitutedCommands) { |
| 211 | const nestedPolicy = evaluateTerminalCommandSecurity(basePolicy, subCmd); |
| 212 | mostRestrictivePolicy = getMostRestrictive( |
| 213 | mostRestrictivePolicy, |
| 214 | nestedPolicy, |
| 215 | ); |
| 216 | if (mostRestrictivePolicy === "disabled") { |
| 217 | return "disabled"; |
| 218 | } |
| 219 | } |
| 220 | // Command substitution itself is risky |
| 221 | if (mostRestrictivePolicy === "allowedWithoutPermission") { |
| 222 | mostRestrictivePolicy = "allowedWithPermission"; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // Check for obfuscation patterns |
| 227 | if (hasObfuscationPatterns(originalCommand)) { |
| 228 | mostRestrictivePolicy = getMostRestrictive( |
| 229 | mostRestrictivePolicy, |
| 230 | "allowedWithPermission", |
| 231 | ); |
| 232 | } |
| 233 | |
| 234 | return mostRestrictivePolicy; |
| 235 | } |
| 236 | |
| 237 | /** |
| 238 | * Returns the most restrictive policy from multiple policies |
| 239 | */ |
| 240 | function getMostRestrictive(...policies: ToolPolicy[]): ToolPolicy { |
| 241 | if (policies.some((p) => p === "disabled")) { |
| 242 | return "disabled"; |
| 243 | } |
| 244 | if (policies.some((p) => p === "allowedWithPermission")) { |
| 245 | return "allowedWithPermission"; |
| 246 | } |
| 247 | return "allowedWithoutPermission"; |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Evaluates a pipe chain for dangerous patterns |
| 252 | */ |
| 253 | function evaluatePipeChain( |
| 254 | tokens: ParsedToken[], |
| 255 | startIdx: number, |
| 256 | ): ToolPolicy { |
| 257 | // Look at what comes after the pipe |
| 258 | let nextCommandStart = startIdx + 1; |
| 259 | |
| 260 | // Skip any additional operators |
| 261 | while ( |
| 262 | nextCommandStart < tokens.length && |
| 263 | isOperator(tokens[nextCommandStart]) |
| 264 | ) { |
| 265 | nextCommandStart++; |
| 266 | } |
| 267 | |
| 268 | if (nextCommandStart >= tokens.length) { |
| 269 | return "allowedWithoutPermission"; |
| 270 | } |
| 271 | |
| 272 | // Get the command after the pipe |
| 273 | const nextCommand: string[] = []; |
| 274 | for ( |
| 275 | let i = nextCommandStart; |
| 276 | i < tokens.length && !isOperator(tokens[i]); |
| 277 | i++ |
| 278 | ) { |
| 279 | const token = tokens[i]; |
| 280 | if (isComment(token)) { |
| 281 | continue; |
| 282 | } else if (isGlob(token)) { |
| 283 | nextCommand.push(token.pattern); |
| 284 | } else if (typeof token === "string") { |
| 285 | nextCommand.push(token); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | if (nextCommand.length > 0) { |
| 290 | const command = nextCommand[0].toLowerCase(); |
| 291 | |
| 292 | // Check for dangerous pipe destinations |
| 293 | const dangerousPipeCommands = [ |
| 294 | "sh", |
| 295 | "bash", |
| 296 | "zsh", |
| 297 | "python", |
| 298 | "perl", |
| 299 | "ruby", |
| 300 | "node", |
| 301 | ]; |
| 302 | if (dangerousPipeCommands.includes(command)) { |
| 303 | return "allowedWithPermission"; |
| 304 | } |
| 305 | |
| 306 | // Check for network exfiltration |
| 307 | if ( |
| 308 | command === "curl" || |
| 309 | command === "wget" || |
| 310 | command === "nc" || |
| 311 | command === "netcat" |
| 312 | ) { |
| 313 | return "allowedWithPermission"; |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | return "allowedWithoutPermission"; |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * Evaluates a single command (array of tokens) |
| 322 | */ |
| 323 | function evaluateSingleCommand( |
| 324 | commandTokens: string[], |
| 325 | originalCommand: string, |
| 326 | ): ToolPolicy { |
| 327 | if (commandTokens.length === 0) { |
| 328 | return "allowedWithoutPermission"; |
| 329 | } |
| 330 | |
| 331 | // The first token is the command |
| 332 | const baseCommand = commandTokens[0].toLowerCase(); |
| 333 | const args = commandTokens.slice(1); |
| 334 | |
| 335 | // Check for critical commands that should always be disabled |
| 336 | if (isCriticalCommand(baseCommand, args)) { |
| 337 | return "disabled"; |
| 338 | } |
| 339 | |
| 340 | // Handle variable expansion patterns |
| 341 | if (baseCommand.startsWith("$")) { |
| 342 | // Command is a variable - could be anything, so require permission |
| 343 | return "allowedWithPermission"; |
| 344 | } |
| 345 | |
| 346 | // Check for high-risk commands that require permission |
| 347 | if (isHighRiskCommand(baseCommand, args, originalCommand)) { |
| 348 | return "allowedWithPermission"; |
| 349 | } |
| 350 | |
| 351 | // Check for safe commands |
| 352 | if (isSafeCommand(baseCommand, args)) { |
| 353 | return "allowedWithoutPermission"; |
| 354 | } |
| 355 | |
| 356 | // Default: unknown commands require permission |
| 357 | return "allowedWithPermission"; |
| 358 | } |
| 359 | |
| 360 | /** |
| 361 | * Checks if a command is critical and should always be disabled |
| 362 | */ |
| 363 | function isCriticalCommand(baseCommand: string, args: string[]): boolean { |
| 364 | // System destruction commands - check if base command starts with mkfs |
| 365 | if (baseCommand.startsWith("mkfs")) { |
| 366 | return true; |
| 367 | } |
| 368 | |
| 369 | // Check for dangerous rm patterns - even if rm is hidden in a variable |
| 370 | // Combine all tokens to check for dangerous patterns |
| 371 | const allTokens = [baseCommand, ...args]; |
| 372 | const hasRf = |
| 373 | allTokens.some( |
| 374 | (arg) => |
| 375 | arg === "-rf" || |
| 376 | arg === "-fr" || |
| 377 | (arg.startsWith("-") && arg.includes("r") && arg.includes("f")), |
| 378 | ) || |
| 379 | (allTokens.includes("-r") && allTokens.includes("-f")) || |
| 380 | (allTokens.includes("--recursive") && allTokens.includes("--force")); |
| 381 | |
| 382 | const hasDangerousPath = allTokens.some( |
| 383 | (arg) => |
| 384 | arg === "/" || |
| 385 | arg === "/*" || |
| 386 | arg === "~" || |
| 387 | arg === "~/*" || |
| 388 | arg === "/usr" || |
| 389 | arg === "/etc" || |
| 390 | arg === "/bin" || |
| 391 | arg === "/sbin" || |
| 392 | arg.startsWith("/usr/") || |
| 393 | arg.startsWith("/etc/") || |
| 394 | arg.startsWith("/bin/") || |
| 395 | arg.startsWith("/sbin/"), |
| 396 | ); |
| 397 | |
| 398 | // If we have rm flags with dangerous paths, it's critical regardless of command |
| 399 | if (hasRf && hasDangerousPath) { |
| 400 | return true; |
| 401 | } |
| 402 | |
| 403 | // Check for explicit rm command with additional critical paths |
| 404 | if (baseCommand === "rm") { |
| 405 | // Check for deletion of critical system files (even without -rf) |
| 406 | const criticalPaths = [ |
| 407 | "/etc/passwd", |
| 408 | "/etc/shadow", |
| 409 | "/etc/sudoers", |
| 410 | "/etc/hosts", |
| 411 | "/boot/", |
| 412 | "/sys/", |
| 413 | "/proc/", |
| 414 | "/dev/", |
| 415 | "/bin/", |
| 416 | "/sbin/", |
| 417 | "/usr/bin/", |
| 418 | "/usr/sbin/", |
| 419 | "/lib/", |
| 420 | "/lib64/", |
| 421 | ]; |
| 422 | if (args.some((arg) => criticalPaths.some((path) => arg.includes(path)))) { |
| 423 | return true; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | // Windows destructive commands |
| 428 | if (baseCommand === "del") { |
| 429 | const hasRecursive = args.includes("/s") && args.includes("/q"); |
| 430 | const hasSystemDrive = args.some( |
| 431 | (arg) => arg.toLowerCase().includes("c:\\") || arg.includes("c:/"), |
| 432 | ); |
| 433 | if (hasRecursive || hasSystemDrive) { |
| 434 | return true; |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | if (baseCommand === "format" || baseCommand === "cipher") { |
| 439 | return true; |
| 440 | } |
| 441 | |
| 442 | // dd command (disk destroyer) |
| 443 | if (baseCommand === "dd") { |
| 444 | if ( |
| 445 | args.some( |
| 446 | (arg) => |
| 447 | arg.includes("of=/dev/") || |
| 448 | arg.includes("of=/dev/sda") || |
| 449 | arg.includes("of=/dev/disk"), |
| 450 | ) |
| 451 | ) { |
| 452 | return true; |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | // Privilege escalation |
| 457 | const privEscCommands = ["sudo", "su", "doas", "runas", "gsudo", "psexec"]; |
| 458 | if (privEscCommands.includes(baseCommand)) { |
| 459 | return true; |
| 460 | } |
| 461 | |
| 462 | // Permission modification with dangerous flags |
| 463 | if (baseCommand === "chmod") { |
| 464 | if ( |
| 465 | args.some( |
| 466 | (arg) => |
| 467 | arg === "777" || |
| 468 | arg === "776" || |
| 469 | arg === "775" || |
| 470 | arg === "+s" || |
| 471 | arg === "u+s" || |
| 472 | arg === "g+s", |
| 473 | ) |
| 474 | ) { |
| 475 | return true; |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | if (baseCommand === "chown") { |
| 480 | if (args.some((arg) => arg.includes("root"))) { |
| 481 | return true; |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | // Windows permission changes |
| 486 | if (baseCommand === "icacls") { |
| 487 | if ( |
| 488 | args.some( |
| 489 | (arg) => |
| 490 | arg.toLowerCase().includes("everyone:f") || |
| 491 | arg.includes("*s-1-1-0:(oi)(ci)f"), // Everyone SID |
| 492 | ) |
| 493 | ) { |
| 494 | return true; |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | if (baseCommand === "takeown") { |
| 499 | return true; |
| 500 | } |
| 501 | |
| 502 | // Kernel and system modification |
| 503 | const kernelCommands = [ |
| 504 | "insmod", |
| 505 | "modprobe", |
| 506 | "rmmod", |
| 507 | "iptables", |
| 508 | "ip6tables", |
| 509 | "nftables", |
| 510 | ]; |
| 511 | if (kernelCommands.includes(baseCommand)) { |
| 512 | return true; |
| 513 | } |
| 514 | |
| 515 | // Eval and exec commands |
| 516 | if (baseCommand === "eval" || baseCommand === "exec") { |
| 517 | return true; |
| 518 | } |
| 519 | |
| 520 | return false; |
| 521 | } |
| 522 | |
| 523 | /** |
| 524 | * Checks if command is a package manager install |
| 525 | */ |
| 526 | function isHighRiskPackageManager( |
| 527 | baseCommand: string, |
| 528 | args: string[], |
| 529 | ): boolean { |
| 530 | const packageManagers = [ |
| 531 | "npm", |
| 532 | "yarn", |
| 533 | "pnpm", |
| 534 | "pip", |
| 535 | "pip3", |
| 536 | "gem", |
| 537 | "cargo", |
| 538 | "go", |
| 539 | "apt", |
| 540 | "apt-get", |
| 541 | "yum", |
| 542 | "dnf", |
| 543 | "zypper", |
| 544 | "pacman", |
| 545 | "brew", |
| 546 | "choco", |
| 547 | "scoop", |
| 548 | "winget", |
| 549 | ]; |
| 550 | |
| 551 | if (packageManagers.includes(baseCommand)) { |
| 552 | // Check for install/add subcommands |
| 553 | const installCommands = ["install", "add", "i"]; |
| 554 | if (args.length > 0 && installCommands.includes(args[0])) { |
| 555 | return true; |
| 556 | } |
| 557 | } |
| 558 | return false; |
| 559 | } |
| 560 | |
| 561 | /** |
| 562 | * Checks if command is a network tool |
| 563 | */ |
| 564 | function isHighRiskNetworkTool(baseCommand: string): boolean { |
| 565 | const networkTools = [ |
| 566 | "curl", |
| 567 | "wget", |
| 568 | "nc", |
| 569 | "netcat", |
| 570 | "ncat", |
| 571 | "telnet", |
| 572 | "ssh", |
| 573 | "scp", |
| 574 | "rsync", |
| 575 | "ftp", |
| 576 | "sftp", |
| 577 | "tftp", |
| 578 | "socat", |
| 579 | ]; |
| 580 | return networkTools.includes(baseCommand); |
| 581 | } |
| 582 | |
| 583 | /** |
| 584 | * Checks if command is a script interpreter |
| 585 | */ |
| 586 | function isHighRiskScriptInterpreter( |
| 587 | baseCommand: string, |
| 588 | args: string[], |
| 589 | ): boolean { |
| 590 | const scriptInterpreters = [ |
| 591 | "sh", |
| 592 | "bash", |
| 593 | "zsh", |
| 594 | "fish", |
| 595 | "ksh", |
| 596 | "csh", |
| 597 | "tcsh", |
| 598 | "dash", |
| 599 | "python", |
| 600 | "python3", |
| 601 | "python2", |
| 602 | "ruby", |
| 603 | "perl", |
| 604 | "php", |
| 605 | "node", |
| 606 | "nodejs", |
| 607 | "deno", |
| 608 | "bun", |
| 609 | "lua", |
| 610 | "tcl", |
| 611 | "powershell", |
| 612 | "pwsh", |
| 613 | ]; |
| 614 | |
| 615 | if (scriptInterpreters.includes(baseCommand)) { |
| 616 | // Allow interpreter --help and --version |
| 617 | if ( |
| 618 | args.length === 1 && |
| 619 | (args[0] === "--help" || args[0] === "--version") |
| 620 | ) { |
| 621 | return false; |
| 622 | } |
| 623 | // Allow interpreter -c for inline commands (we'll check the command content) |
| 624 | if (args.includes("-c")) { |
| 625 | // For now, require permission for any -c usage |
| 626 | return true; |
| 627 | } |
| 628 | // If executing a file, require permission |
| 629 | if (args.length > 0) { |
| 630 | return true; |
| 631 | } |
| 632 | } |
| 633 | return false; |
| 634 | } |
| 635 | |
| 636 | /** |
| 637 | * Checks if command is direct script execution |
| 638 | */ |
| 639 | function isHighRiskDirectScript(baseCommand: string): boolean { |
| 640 | return ( |
| 641 | baseCommand.startsWith("./") || |
| 642 | baseCommand.endsWith(".sh") || |
| 643 | baseCommand.endsWith(".py") || |
| 644 | baseCommand.endsWith(".rb") || |
| 645 | baseCommand.endsWith(".pl") || |
| 646 | baseCommand.endsWith(".ps1") || |
| 647 | baseCommand.endsWith(".bat") || |
| 648 | baseCommand.endsWith(".cmd") |
| 649 | ); |
| 650 | } |
| 651 | |
| 652 | /** |
| 653 | * Checks if command modifies environment variables |
| 654 | */ |
| 655 | function isHighRiskEnvironmentModifier( |
| 656 | baseCommand: string, |
| 657 | args: string[], |
| 658 | ): boolean { |
| 659 | if ( |
| 660 | baseCommand === "export" || |
| 661 | baseCommand === "setx" || |
| 662 | baseCommand === "set" |
| 663 | ) { |
| 664 | // Check for dangerous environment variables |
| 665 | const dangerousVars = [ |
| 666 | "PATH", |
| 667 | "LD_PRELOAD", |
| 668 | "LD_LIBRARY_PATH", |
| 669 | "PYTHONPATH", |
| 670 | "NODE_PATH", |
| 671 | "PERL5LIB", |
| 672 | "RUBYLIB", |
| 673 | ]; |
| 674 | if (args.some((arg) => dangerousVars.some((v) => arg.includes(v)))) { |
| 675 | return true; |
| 676 | } |
| 677 | } |
| 678 | return false; |
| 679 | } |
| 680 | |
| 681 | /** |
| 682 | * Checks if command is process management |
| 683 | */ |
| 684 | function isHighRiskProcessCommand(baseCommand: string): boolean { |
| 685 | const processCommands = ["kill", "killall", "pkill", "taskkill", "pskill"]; |
| 686 | return processCommands.includes(baseCommand); |
| 687 | } |
| 688 | |
| 689 | /** |
| 690 | * Checks if command is system service management |
| 691 | */ |
| 692 | function isHighRiskSystemService(baseCommand: string): boolean { |
| 693 | return ( |
| 694 | baseCommand === "systemctl" || |
| 695 | baseCommand === "service" || |
| 696 | baseCommand === "launchctl" || |
| 697 | baseCommand === "sc" |
| 698 | ); |
| 699 | } |
| 700 | |
| 701 | /** |
| 702 | * Checks if command is file operation to sensitive location |
| 703 | */ |
| 704 | function isHighRiskFileOperation(baseCommand: string, args: string[]): boolean { |
| 705 | if (baseCommand === "mv" || baseCommand === "cp" || baseCommand === "copy") { |
| 706 | const sensitiveLocations = [ |
| 707 | "/etc/", |
| 708 | "/usr/", |
| 709 | "/bin/", |
| 710 | "/sbin/", |
| 711 | "c:\\windows", |
| 712 | "c:\\program", |
| 713 | ]; |
| 714 | if ( |
| 715 | args.some((arg) => |
| 716 | sensitiveLocations.some((loc) => arg.toLowerCase().includes(loc)), |
| 717 | ) |
| 718 | ) { |
| 719 | return true; |
| 720 | } |
| 721 | } |
| 722 | return false; |
| 723 | } |
| 724 | |
| 725 | /** |
| 726 | * Checks if rm command is high risk (but not critical) |
| 727 | */ |
| 728 | function isHighRiskRmCommand(baseCommand: string, args: string[]): boolean { |
| 729 | if (baseCommand === "rm") { |
| 730 | const hasRf = args.some((arg) => arg === "-rf" || arg === "-fr"); |
| 731 | const hasCriticalPath = args.some((arg) => |
| 732 | ["/etc/", "/usr/", "/bin/", "/sbin/"].some((path) => arg.includes(path)), |
| 733 | ); |
| 734 | if (!hasRf && !hasCriticalPath) { |
| 735 | return true; |
| 736 | } |
| 737 | } |
| 738 | return false; |
| 739 | } |
| 740 | |
| 741 | /** |
| 742 | * Checks if command is archive extraction to system directories |
| 743 | */ |
| 744 | function isHighRiskArchiveExtraction( |
| 745 | baseCommand: string, |
| 746 | args: string[], |
| 747 | ): boolean { |
| 748 | if ( |
| 749 | baseCommand === "tar" || |
| 750 | baseCommand === "unzip" || |
| 751 | baseCommand === "7z" |
| 752 | ) { |
| 753 | const hasSystemExtraction = args.some((arg, idx) => { |
| 754 | // Check for -C /path or -d /path patterns |
| 755 | if ( |
| 756 | (arg === "-C" || arg === "-d" || arg === "-o") && |
| 757 | idx < args.length - 1 |
| 758 | ) { |
| 759 | const nextArg = args[idx + 1]; |
| 760 | return nextArg.startsWith("/") || nextArg.startsWith("C:\\"); |
| 761 | } |
| 762 | // Check for -C/path patterns |
| 763 | return ( |
| 764 | arg.startsWith("-C/") || arg.startsWith("-d/") || arg.startsWith("-o/") |
| 765 | ); |
| 766 | }); |
| 767 | if (hasSystemExtraction) { |
| 768 | return true; |
| 769 | } |
| 770 | } |
| 771 | return false; |
| 772 | } |
| 773 | |
| 774 | /** |
| 775 | * Checks if command is container/orchestration tool |
| 776 | */ |
| 777 | function isHighRiskContainerCommand(baseCommand: string): boolean { |
| 778 | const containerCommands = [ |
| 779 | "docker", |
| 780 | "podman", |
| 781 | "kubectl", |
| 782 | "helm", |
| 783 | "terraform", |
| 784 | "vagrant", |
| 785 | ]; |
| 786 | return containerCommands.includes(baseCommand); |
| 787 | } |
| 788 | |
| 789 | /** |
| 790 | * Checks if command is cloud CLI |
| 791 | */ |
| 792 | function isHighRiskCloudCLI(baseCommand: string): boolean { |
| 793 | const cloudCommands = ["aws", "gcloud", "az", "oci", "ibmcloud"]; |
| 794 | return cloudCommands.includes(baseCommand); |
| 795 | } |
| 796 | |
| 797 | /** |
| 798 | * Checks if command is user/group management |
| 799 | */ |
| 800 | function isHighRiskUserCommand(baseCommand: string): boolean { |
| 801 | const userCommands = [ |
| 802 | "useradd", |
| 803 | "usermod", |
| 804 | "userdel", |
| 805 | "groupadd", |
| 806 | "passwd", |
| 807 | "chpasswd", |
| 808 | ]; |
| 809 | return userCommands.includes(baseCommand); |
| 810 | } |
| 811 | |
| 812 | /** |
| 813 | * Checks if command is scheduled task |
| 814 | */ |
| 815 | function isHighRiskScheduledTask(baseCommand: string): boolean { |
| 816 | return ( |
| 817 | baseCommand === "crontab" || |
| 818 | baseCommand === "at" || |
| 819 | baseCommand === "schtasks" |
| 820 | ); |
| 821 | } |
| 822 | |
| 823 | /** |
| 824 | * Checks if command is Windows registry/system configuration |
| 825 | */ |
| 826 | function isHighRiskWindowsRegistry(baseCommand: string): boolean { |
| 827 | return ( |
| 828 | baseCommand === "reg" || |
| 829 | baseCommand === "regedit" || |
| 830 | baseCommand === "regsvr32" |
| 831 | ); |
| 832 | } |
| 833 | |
| 834 | /** |
| 835 | * Checks if command is Windows management tool |
| 836 | */ |
| 837 | function isHighRiskWindowsManagement(baseCommand: string): boolean { |
| 838 | return ( |
| 839 | baseCommand === "wmic" || baseCommand === "net" || baseCommand === "netsh" |
| 840 | ); |
| 841 | } |
| 842 | |
| 843 | /** |
| 844 | * Checks if command is security/certificate tool |
| 845 | */ |
| 846 | function isHighRiskSecurityTool(baseCommand: string): boolean { |
| 847 | return baseCommand === "certutil" || baseCommand === "bitsadmin"; |
| 848 | } |
| 849 | |
| 850 | /** |
| 851 | * Checks if command is source/dot command |
| 852 | */ |
| 853 | function isHighRiskSourceCommand(baseCommand: string): boolean { |
| 854 | return baseCommand === "source" || baseCommand === "."; |
| 855 | } |
| 856 | |
| 857 | /** |
| 858 | * Checks if command manipulates history |
| 859 | */ |
| 860 | function isHighRiskHistoryManipulation( |
| 861 | baseCommand: string, |
| 862 | args: string[], |
| 863 | ): boolean { |
| 864 | if (baseCommand === "history" && args.includes("-c")) { |
| 865 | return true; |
| 866 | } |
| 867 | if (baseCommand === "unset" && args.some((arg) => arg.includes("HIST"))) { |
| 868 | return true; |
| 869 | } |
| 870 | return false; |
| 871 | } |
| 872 | |
| 873 | /** |
| 874 | * Checks if command is DNS tool (exfiltration risk) |
| 875 | */ |
| 876 | function isHighRiskDNSTool(baseCommand: string): boolean { |
| 877 | return ( |
| 878 | baseCommand === "dig" || |
| 879 | baseCommand === "nslookup" || |
| 880 | baseCommand === "host" |
| 881 | ); |
| 882 | } |
| 883 | |
| 884 | /** |
| 885 | * Checks if command is macOS specific high risk |
| 886 | */ |
| 887 | function isHighRiskMacOSCommand(baseCommand: string, args: string[]): boolean { |
| 888 | if ( |
| 889 | baseCommand === "defaults" && |
| 890 | args.some((arg) => arg.includes("/Library/")) |
| 891 | ) { |
| 892 | return true; |
| 893 | } |
| 894 | if (baseCommand === "pmset" || baseCommand === "csrutil") { |
| 895 | return true; |
| 896 | } |
| 897 | return false; |
| 898 | } |
| 899 | |
| 900 | /** |
| 901 | * Checks if a command is high risk and requires permission |
| 902 | */ |
| 903 | function isHighRiskCommand( |
| 904 | baseCommand: string, |
| 905 | args: string[], |
| 906 | originalCommand: string, |
| 907 | ): boolean { |
| 908 | // Check each category of high risk commands |
| 909 | if (isHighRiskPackageManager(baseCommand, args)) return true; |
| 910 | if (isHighRiskNetworkTool(baseCommand)) return true; |
| 911 | if (isHighRiskScriptInterpreter(baseCommand, args)) return true; |
| 912 | if (isHighRiskDirectScript(baseCommand)) return true; |
| 913 | if (isHighRiskEnvironmentModifier(baseCommand, args)) return true; |
| 914 | if (baseCommand === "alias") return true; |
| 915 | if (isFunctionDefinition([baseCommand, ...args], originalCommand)) |
| 916 | return true; |
| 917 | if (isHighRiskProcessCommand(baseCommand)) return true; |
| 918 | if (isHighRiskSystemService(baseCommand)) return true; |
| 919 | if (isHighRiskFileOperation(baseCommand, args)) return true; |
| 920 | if (isHighRiskRmCommand(baseCommand, args)) return true; |
| 921 | if (isHighRiskArchiveExtraction(baseCommand, args)) return true; |
| 922 | if (isHighRiskContainerCommand(baseCommand)) return true; |
| 923 | if (isHighRiskCloudCLI(baseCommand)) return true; |
| 924 | if (isHighRiskUserCommand(baseCommand)) return true; |
| 925 | if (isHighRiskScheduledTask(baseCommand)) return true; |
| 926 | if (isHighRiskWindowsRegistry(baseCommand)) return true; |
| 927 | if (isHighRiskWindowsManagement(baseCommand)) return true; |
| 928 | if (isHighRiskSecurityTool(baseCommand)) return true; |
| 929 | if (isHighRiskSourceCommand(baseCommand)) return true; |
| 930 | if (isHighRiskHistoryManipulation(baseCommand, args)) return true; |
| 931 | if (isHighRiskDNSTool(baseCommand)) return true; |
| 932 | if (isHighRiskMacOSCommand(baseCommand, args)) return true; |
| 933 | |
| 934 | return false; |
| 935 | } |
| 936 | |
| 937 | /** |
| 938 | * Checks if a command is safe and can be auto-approved |
| 939 | */ |
| 940 | function isSafeCommand(baseCommand: string, args: string[]): boolean { |
| 941 | // Information commands |
| 942 | const infoCommands = [ |
| 943 | "ls", |
| 944 | "dir", |
| 945 | "pwd", |
| 946 | "whoami", |
| 947 | "id", |
| 948 | "hostname", |
| 949 | "uname", |
| 950 | "date", |
| 951 | "uptime", |
| 952 | "df", |
| 953 | "du", |
| 954 | "free", |
| 955 | "top", |
| 956 | "htop", |
| 957 | "ps", |
| 958 | "jobs", |
| 959 | "which", |
| 960 | "whereis", |
| 961 | "type", |
| 962 | "file", |
| 963 | "stat", |
| 964 | "wc", |
| 965 | "head", |
| 966 | "tail", |
| 967 | ]; |
| 968 | |
| 969 | if (infoCommands.includes(baseCommand)) { |
| 970 | return true; |
| 971 | } |
| 972 | |
| 973 | // Read-only file operations |
| 974 | const readCommands = ["cat", "less", "more", "nl", "od", "strings"]; |
| 975 | if (readCommands.includes(baseCommand)) { |
| 976 | return true; |
| 977 | } |
| 978 | |
| 979 | // Safe text processing |
| 980 | if (baseCommand === "echo") { |
| 981 | return true; |
| 982 | } |
| 983 | |
| 984 | if (baseCommand === "grep" && !args.includes("--exec")) { |
| 985 | return true; |
| 986 | } |
| 987 | |
| 988 | // Safe find (without dangerous flags) |
| 989 | if (baseCommand === "find") { |
| 990 | const dangerousFlags = ["-exec", "-execdir", "-ok", "-okdir", "-delete"]; |
| 991 | if (!args.some((arg) => dangerousFlags.includes(arg))) { |
| 992 | return true; |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | // Safe git operations |
| 997 | if (baseCommand === "git") { |
| 998 | const safeGitOps = ["status", "log", "diff", "show", "branch", "remote"]; |
| 999 | if (args.length > 0 && safeGitOps.includes(args[0])) { |
| 1000 | return true; |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | // Safe npm/yarn commands |
| 1005 | if ( |
| 1006 | baseCommand === "npm" || |
| 1007 | baseCommand === "yarn" || |
| 1008 | baseCommand === "pnpm" |
| 1009 | ) { |
| 1010 | const safeOps = ["test", "build", "start", "run"]; |
| 1011 | if (args.length > 0 && safeOps.includes(args[0])) { |
| 1012 | // Check for suspicious script names |
| 1013 | const suspiciousScripts = [ |
| 1014 | "preinstall", |
| 1015 | "postinstall", |
| 1016 | "prepare", |
| 1017 | "prepublish", |
| 1018 | ]; |
| 1019 | if (args.length > 1 && !suspiciousScripts.includes(args[1])) { |
| 1020 | return true; |
| 1021 | } |
| 1022 | } |
| 1023 | } |
| 1024 | |
| 1025 | // Safe build commands |
| 1026 | const buildCommands = ["make", "gradle", "mvn", "cargo"]; |
| 1027 | if (buildCommands.includes(baseCommand)) { |
| 1028 | const safeBuildOps = ["build", "compile", "test", "check", "clean"]; |
| 1029 | if (args.some((arg) => safeBuildOps.includes(arg))) { |
| 1030 | return true; |
| 1031 | } |
| 1032 | } |
| 1033 | |
| 1034 | // Safe compression (creation only, not extraction to system paths) |
| 1035 | if (baseCommand === "tar") { |
| 1036 | // Check for create flag |
| 1037 | if ( |
| 1038 | args.some((arg) => arg.includes("c")) && |
| 1039 | !args.some( |
| 1040 | (arg, idx) => |
| 1041 | (arg === "-C" && |
| 1042 | idx < args.length - 1 && |
| 1043 | args[idx + 1].startsWith("/")) || |
| 1044 | arg.startsWith("-C/"), |
| 1045 | ) |
| 1046 | ) { |
| 1047 | return true; |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | if (baseCommand === "zip" && !args.some((arg) => arg.startsWith("-d/"))) { |
| 1052 | return true; |
| 1053 | } |
| 1054 | |
| 1055 | return false; |
| 1056 | } |
| 1057 | |
| 1058 | /** |
| 1059 | * Checks for command substitution patterns |
| 1060 | */ |
| 1061 | function hasCommandSubstitution(command: string): boolean { |
| 1062 | // Backticks |
| 1063 | if (command.includes("`")) { |
| 1064 | return true; |
| 1065 | } |
| 1066 | |
| 1067 | // $() substitution |
| 1068 | if (command.includes("$(")) { |
| 1069 | return true; |
| 1070 | } |
| 1071 | |
| 1072 | // Process substitution <() or >() |
| 1073 | if (command.match(/<\(|>\(/)) { |
| 1074 | return true; |
| 1075 | } |
| 1076 | |
| 1077 | return false; |
| 1078 | } |
| 1079 | |
| 1080 | /** |
| 1081 | * Extracts commands from substitution patterns |
| 1082 | */ |
| 1083 | function extractSubstitutedCommands(command: string): string[] { |
| 1084 | const commands: string[] = []; |
| 1085 | |
| 1086 | // Extract from backticks |
| 1087 | const backtickMatches = command.match(/`([^`]+)`/g); |
| 1088 | if (backtickMatches) { |
| 1089 | commands.push(...backtickMatches.map((m) => m.slice(1, -1))); |
| 1090 | } |
| 1091 | |
| 1092 | // Extract from $() - handle nested parentheses |
| 1093 | let idx = 0; |
| 1094 | while (idx < command.length) { |
| 1095 | const dollarParen = command.indexOf("$(", idx); |
| 1096 | if (dollarParen === -1) break; |
| 1097 | |
| 1098 | // Find matching closing parenthesis |
| 1099 | let depth = 1; |
| 1100 | let endIdx = dollarParen + 2; |
| 1101 | while (endIdx < command.length && depth > 0) { |
| 1102 | if (command[endIdx] === "(") depth++; |
| 1103 | else if (command[endIdx] === ")") depth--; |
| 1104 | endIdx++; |
| 1105 | } |
| 1106 | |
| 1107 | if (depth === 0) { |
| 1108 | // Extract the command inside $() |
| 1109 | const extracted = command.slice(dollarParen + 2, endIdx - 1); |
| 1110 | commands.push(extracted); |
| 1111 | // Also check for nested substitutions within this command |
| 1112 | if (extracted.includes("$(") || extracted.includes("`")) { |
| 1113 | commands.push(...extractSubstitutedCommands(extracted)); |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | idx = endIdx; |
| 1118 | } |
| 1119 | |
| 1120 | return commands; |
| 1121 | } |
| 1122 | |
| 1123 | /** |
| 1124 | * Checks if the original command contains a function definition |
| 1125 | */ |
| 1126 | function isFunctionDefinition( |
| 1127 | tokens: string[], |
| 1128 | originalCommand: string, |
| 1129 | ): boolean { |
| 1130 | // Check for 'function' keyword as first token |
| 1131 | if (tokens.length > 0 && tokens[0] === "function") { |
| 1132 | return true; |
| 1133 | } |
| 1134 | |
| 1135 | // Check original command for function definition patterns |
| 1136 | // Patterns: word() {, function word {, function word() { |
| 1137 | const functionPatterns = [ |
| 1138 | /^\s*\w+\s*\(\)\s*\{/, // name() { |
| 1139 | /^\s*function\s+\w+\s*\{/, // function name { |
| 1140 | /^\s*function\s+\w+\s*\(\)/, // function name() |
| 1141 | ]; |
| 1142 | |
| 1143 | if (functionPatterns.some((pattern) => pattern.test(originalCommand))) { |
| 1144 | return true; |
| 1145 | } |
| 1146 | |
| 1147 | return false; |
| 1148 | } |
| 1149 | |
| 1150 | /** |
| 1151 | * Checks for obfuscation patterns |
| 1152 | */ |
| 1153 | function hasObfuscationPatterns(command: string): boolean { |
| 1154 | // Base64 encoding |
| 1155 | if (command.match(/base64\s+-d|base64\s+--decode/)) { |
| 1156 | return true; |
| 1157 | } |
| 1158 | |
| 1159 | // Hex encoding |
| 1160 | if (command.match(/\\x[0-9a-f]{2}/i)) { |
| 1161 | return true; |
| 1162 | } |
| 1163 | |
| 1164 | // Unicode escapes |
| 1165 | if (command.match(/\\u[0-9a-f]{4}/i)) { |
| 1166 | return true; |
| 1167 | } |
| 1168 | |
| 1169 | // Octal escapes |
| 1170 | if (command.match(/\\[0-7]{3}/)) { |
| 1171 | return true; |
| 1172 | } |
| 1173 | |
| 1174 | // echo -e with escapes |
| 1175 | if ( |
| 1176 | command.includes("echo") && |
| 1177 | command.includes("-e") && |
| 1178 | command.match(/\\[xnu0-7]/) |
| 1179 | ) { |
| 1180 | return true; |
| 1181 | } |
| 1182 | |
| 1183 | // Suspicious use of printf |
| 1184 | if (command.includes("printf") && command.match(/\\[xnu0-7]/)) { |
| 1185 | return true; |
| 1186 | } |
| 1187 | |
| 1188 | // xxd for hex decoding |
| 1189 | if (command.includes("xxd") && command.includes("-r")) { |
| 1190 | return true; |
| 1191 | } |
| 1192 | |
| 1193 | // od for octal/hex decoding |
| 1194 | if ( |
| 1195 | command.includes("od") && |
| 1196 | (command.includes("-x") || command.includes("-o")) |
| 1197 | ) { |
| 1198 | return true; |
| 1199 | } |
| 1200 | |
| 1201 | return false; |
| 1202 | } |