From 55c806596c3fe14ced1f08bc18620581024f4337 Mon Sep 17 00:00:00 2001 From: shenxiaobo Date: Mon, 26 Oct 2026 10:12:54 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(core):=20Shell=20=E7=99=BD=E5=90=8D?= =?UTF-8?q?=E5=8D=95=E8=A1=A5=E9=BD=90=E5=85=83=E5=AD=97=E7=AC=A6=E6=A3=80?= =?UTF-8?q?=E6=B5=8B,=E6=9B=BF=E6=8D=A2/=E5=B1=95=E5=BC=80/=E9=87=8D?= =?UTF-8?q?=E5=AE=9A=E5=90=91=E4=B8=8D=E5=86=8D=E7=9B=B4=E9=80=9A(#3285)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UnixCommandValidator/WindowsCommandValidator 只校验可执行名与 &/|/;分隔符,整串命令随后交给 sh -c / cmd.exe /c——白名单内的 echo 可经 $(...)、反引号、$VAR、重定向执行额外命令或写文件, 全程不经审批回调。 - Unix:新增 containsShellMetacharacters(引号感知):$/反引号在 单引号外即拒绝(双引号不阻断替换),>/<在两种引号外拒绝; 在 containsMultipleCommands 之后对所有白名单激活的命令生效, 命中即 rejected 并给出原因,进入既有审批回调路径 - Windows:新增同款检测(%VAR% 展开、>/< 重定向、^ 转义 smuggle), cmd.exe 引词语义复杂,从严全量拒绝 - 白名单为空时全放行的既有行为保留:改为与文档声明的 "No whitelist - all commands require approval" 对齐属破坏性 变更,留给维护者决策(PR 描述中提出) - 测试:plain/单引号字面量仍 ALLOW;$(...)/"$(...)"/反引号/ $VAR/${VAR}/>输入重定向/%VAR%/^ 全部 rejected Fixes #3285 --- .../tool/coding/UnixCommandValidator.java | 55 +++++++++++++ .../tool/coding/WindowsCommandValidator.java | 30 +++++++ .../CommandValidatorMetacharacterTest.java | 81 +++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 agentscope-core/src/test/java/io/agentscope/core/tool/coding/CommandValidatorMetacharacterTest.java diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java index 7f8630b1df..eb2deb6921 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java @@ -64,6 +64,16 @@ public ValidationResult validate(String command, Set allowedCommands) { extractExecutable(command)); } + // Check for shell metacharacters that can execute additional commands or redirect + // output even when the executable itself is whitelisted (#3285) + if (containsShellMetacharacters(command)) { + logger.debug("Command contains shell metacharacters: {}", command); + return ValidationResult.rejected( + "Command contains shell metacharacters (command substitution, variable" + + " expansion, or redirection) requiring approval", + extractExecutable(command)); + } + // execute executables with relative paths only if they are within the current directory if (executable.startsWith("./")) { if (isPathWithinCurrentDirectory(executable)) { @@ -167,6 +177,51 @@ private String extractFirstToken(String command) { * @return true if multiple commands are detected, false otherwise */ @Override + /** + * Detects shell metacharacters that let a whitelisted executable execute additional + * commands or redirect output: command substitution ({@code $(...)}), backticks, variable + * expansion ({@code $VAR}/{@code ${...}}), and redirection ({@code >}/{@code <}). + * Single-quoted content is literal in {@code sh}; double quotes do NOT neutralize + * substitution, so {@code $} and backticks are checked outside single quotes only, while + * redirection is checked outside both quote kinds (#3285). + */ + public boolean containsShellMetacharacters(String command) { + if (command == null || command.isEmpty()) { + return false; + } + boolean inSingleQuote = false; + boolean inDoubleQuote = false; + boolean escaped = false; + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + if (escaped) { + escaped = false; + continue; + } + if (c == '\\') { + escaped = true; + continue; + } + if (c == '\'' && !inDoubleQuote) { + inSingleQuote = !inSingleQuote; + continue; + } + if (c == '"' && !inSingleQuote) { + inDoubleQuote = !inDoubleQuote; + continue; + } + // Command substitution and variable expansion survive double quotes. + if ((c == '$' || c == '`') && !inSingleQuote) { + return true; + } + // Redirection is literal inside either quote kind. + if ((c == '>' || c == '<') && !inSingleQuote && !inDoubleQuote) { + return true; + } + } + return false; + } + public boolean containsMultipleCommands(String command) { if (command == null || command.isEmpty()) { return false; diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java index afd9459e8d..c3eb354e8d 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java @@ -67,6 +67,17 @@ public ValidationResult validate(String command, Set allowedCommands) { extractExecutable(command)); } + // Check for shell metacharacters that survive executable whitelisting under + // cmd.exe: variable expansion (%VAR%), redirection (>/<), and the ^ escape used to + // smuggle separators past lexical scans (#3285) + if (containsShellMetacharacters(command)) { + logger.debug("Command contains cmd.exe metacharacters: {}", command); + return ValidationResult.rejected( + "Command contains shell metacharacters (variable expansion, redirection," + + " or escape) requiring approval", + extractExecutable(command)); + } + if (executable.startsWith(".\\") || executable.startsWith("./")) { if (isPathWithinCurrentDirectory(executable)) { logger.debug( @@ -204,6 +215,25 @@ private String extractPathFromCommand(String command) { * @return true if multiple commands are detected, false otherwise */ @Override + /** + * Detects {@code cmd.exe} metacharacters that let a whitelisted executable execute + * additional commands or redirect output: variable expansion ({@code %VAR%}), redirection + * ({@code >}/{@code <}), and the {@code ^} escape character (which can smuggle separators + * and strip quote characters in {@code cmd /c} round-trips) (#3285). + */ + public boolean containsShellMetacharacters(String command) { + if (command == null || command.isEmpty()) { + return false; + } + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + if (c == '%' || c == '>' || c == '<' || c == '^') { + return true; + } + } + return false; + } + public boolean containsMultipleCommands(String command) { if (command == null || command.isEmpty()) { return false; diff --git a/agentscope-core/src/test/java/io/agentscope/core/tool/coding/CommandValidatorMetacharacterTest.java b/agentscope-core/src/test/java/io/agentscope/core/tool/coding/CommandValidatorMetacharacterTest.java new file mode 100644 index 0000000000..7065c2ba52 --- /dev/null +++ b/agentscope-core/src/test/java/io/agentscope/core/tool/coding/CommandValidatorMetacharacterTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.core.tool.coding; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** + * Regression tests for the shell-metacharacter whitelist bypass (#3285): with {@code echo} + * whitelisted, command substitution, variable expansion, and redirection must be rejected so + * they route to the approval callback instead of executing directly under {@code sh -c}. + */ +class CommandValidatorMetacharacterTest { + + private final UnixCommandValidator unix = new UnixCommandValidator(); + private final WindowsCommandValidator windows = new WindowsCommandValidator(); + private final Set whitelist = Set.of("echo"); + + // ==================== Unix ==================== + + @Test + void unix_plainWhitelistedCommand_stillAllowed() { + assertTrue(unix.validate("echo hello", whitelist).isAllowed()); + // Single-quoted content is literal in sh — no substitution happens. + assertTrue(unix.validate("echo '$(safe)'", whitelist).isAllowed()); + } + + @Test + void unix_commandSubstitution_rejected() { + assertFalse(unix.validate("echo $(printf marker)", whitelist).isAllowed()); + // Double quotes do NOT prevent substitution in sh. + assertFalse(unix.validate("echo \"$(printf marker)\"", whitelist).isAllowed()); + assertFalse(unix.validate("echo `printf marker`", whitelist).isAllowed()); + } + + @Test + void unix_variableExpansion_rejected() { + assertFalse(unix.validate("echo $HOME", whitelist).isAllowed()); + assertFalse(unix.validate("echo ${HOME}", whitelist).isAllowed()); + } + + @Test + void unix_redirection_rejected() { + assertFalse(unix.validate("echo marker > marker.txt", whitelist).isAllowed()); + assertFalse(unix.validate("echo marker < input.txt", whitelist).isAllowed()); + } + + // ==================== Windows ==================== + + @Test + void windows_plainWhitelistedCommand_stillAllowed() { + assertTrue(windows.validate("echo hello", whitelist).isAllowed()); + } + + @Test + void windows_variableExpansion_rejected() { + assertFalse(windows.validate("echo %USERPROFILE%", whitelist).isAllowed()); + } + + @Test + void windows_redirectionAndEscape_rejected() { + assertFalse(windows.validate("echo marker > marker.txt", whitelist).isAllowed()); + assertFalse(windows.validate("echo mar^ker", whitelist).isAllowed()); + } +} From 2a05779f173495646cdfb77fe7848e1fb5300755 Mon Sep 17 00:00:00 2001 From: shenxiaobo Date: Mon, 26 Oct 2026 10:38:29 +0800 Subject: [PATCH 2/4] =?UTF-8?q?style(core):=20spotless=20=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E5=8C=96(CI=20check=20=E4=BF=AE=E5=A4=8D)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tool/coding/UnixCommandValidator.java | 6 +- .../tool/coding/WindowsCommandValidator.java | 554 +++++++++--------- 2 files changed, 280 insertions(+), 280 deletions(-) diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java index eb2deb6921..5ee4f1252d 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java @@ -198,11 +198,11 @@ public boolean containsShellMetacharacters(String command) { escaped = false; continue; } - if (c == '\\') { + if (c == '\') { escaped = true; continue; } - if (c == '\'' && !inDoubleQuote) { + if (c == ''' && !inDoubleQuote) { inSingleQuote = !inSingleQuote; continue; } @@ -222,7 +222,7 @@ public boolean containsShellMetacharacters(String command) { return false; } - public boolean containsMultipleCommands(String command) { + public boolean containsMultipleCommands(String command) { if (command == null || command.isEmpty()) { return false; } diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java index c3eb354e8d..86f368b7f9 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java @@ -1,277 +1,277 @@ -/* - * Copyright 2024-2026 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.agentscope.core.tool.coding; - -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Command validator for Windows systems. - * - *

Validation Order: - *

    - *
  1. Extract executable from command (remove quotes, handle paths with spaces, remove path, remove extensions, convert to lowercase)
  2. - *
  3. If no whitelist configured → allow (backward compatible)
  4. - *
  5. Check for multiple command separators → reject if found
  6. - *
  7. Check relative path safety (commands starting with {@code .\} or {@code ./}) → reject if escapes current directory
  8. - *
  9. Check whitelist (case-insensitive) → reject if not in whitelist
  10. - *
- * - *

Multiple Command Detection: Detects Windows-specific separators: - * {@code &}, {@code &&}, {@code |}, {@code ||}, newline - * (ignores separators within quotes or after escape {@code ^}) - *
Note: Semicolon ({@code ;}) is NOT a separator in Windows cmd.exe - * - *

Executable Extraction: - *

    - *
  • Handles quoted commands (double quotes)
  • - *
  • Handles paths with spaces (e.g., {@code C:\Program Files\app.exe})
  • - *
  • Extracts command name without path (handles both {@code \} and {@code /})
  • - *
  • Removes extensions: {@code .exe}, {@code .bat}, {@code .cmd} (case-insensitive)
  • - *
  • Converts result to lowercase for consistent matching
  • - *
- */ -public class WindowsCommandValidator implements CommandValidator { - - private static final Logger logger = LoggerFactory.getLogger(WindowsCommandValidator.class); - - @Override - public ValidationResult validate(String command, Set allowedCommands) { - // Extract and check executable (case-insensitive for Windows) - String executable = extractExecutable(command); - - // If no whitelist is configured, allow all commands (backward compatible) - if (allowedCommands == null || allowedCommands.isEmpty()) { - return ValidationResult.allowed(executable); - } - - // Check for multiple commands - if (containsMultipleCommands(command)) { - logger.debug("Command contains multiple command separators: {}", command); - return ValidationResult.rejected( - "Command contains multiple command separators (&, |, newline)", - extractExecutable(command)); - } - - // Check for shell metacharacters that survive executable whitelisting under - // cmd.exe: variable expansion (%VAR%), redirection (>/<), and the ^ escape used to - // smuggle separators past lexical scans (#3285) - if (containsShellMetacharacters(command)) { - logger.debug("Command contains cmd.exe metacharacters: {}", command); - return ValidationResult.rejected( - "Command contains shell metacharacters (variable expansion, redirection," - + " or escape) requiring approval", - extractExecutable(command)); - } - - if (executable.startsWith(".\\") || executable.startsWith("./")) { - if (isPathWithinCurrentDirectory(executable)) { - logger.debug( - "Command '{}' is safe relative path executable file execution", executable); - return ValidationResult.allowed(executable); - } else { - logger.debug( - "Command '{}' is not safe relative path executable file execution", - executable); - return ValidationResult.rejected( - "Command '" + executable + "' escapes current directory", executable); - } - } - - // Check if any whitelist entry matches (case-insensitive) - boolean inWhitelist = - allowedCommands.stream().anyMatch(allowed -> allowed.equalsIgnoreCase(executable)); - if (inWhitelist) { - logger.debug("Command '{}' is in whitelist", executable); - return ValidationResult.allowed(executable); - } else { - logger.debug("Command '{}' is NOT in whitelist", executable); - return ValidationResult.rejected( - "Command '" + executable + "' is not in the allowed whitelist", executable); - } - } - - @Override - public String extractExecutable(String command) { - if (command == null || command.trim().isEmpty()) { - return ""; - } - - try { - String trimmed = command.trim(); - String executable; - - // Handle quoted commands: "command" (Windows typically uses double quotes) - if (trimmed.startsWith("\"")) { - int endQuote = trimmed.indexOf('"', 1); - if (endQuote > 0) { - executable = trimmed.substring(1, endQuote); - } else { - // No closing quote, treat as unquoted - executable = extractFirstToken(trimmed); - } - } else { - // Check if this looks like a path (contains \ or /) - if (trimmed.contains("\\") || trimmed.contains("/")) { - // This is a path, need to extract the full path before arguments - executable = extractPathFromCommand(trimmed); - } else { - // Simple command without path, extract first token - executable = extractFirstToken(trimmed); - } - } - - // Remove .exe, .bat, .cmd extensions if present (case-insensitive) - String lowerExecutable = executable.toLowerCase(); - if (lowerExecutable.endsWith(".exe") - || lowerExecutable.endsWith(".bat") - || lowerExecutable.endsWith(".cmd")) { - int dotIndex = lowerExecutable.lastIndexOf('.'); - if (dotIndex > 0) { - executable = lowerExecutable.substring(0, dotIndex); - } - } - - return executable; - } catch (Exception e) { - logger.warn("Failed to parse command '{}': {}", command, e.getMessage()); - return ""; - } - } - - /** - * Extract first token (word before space/tab) from command. - */ - private String extractFirstToken(String command) { - int spaceIndex = command.indexOf(' '); - int tabIndex = command.indexOf('\t'); - int splitIndex = -1; - - if (spaceIndex >= 0 && tabIndex >= 0) { - splitIndex = Math.min(spaceIndex, tabIndex); - } else if (spaceIndex >= 0) { - splitIndex = spaceIndex; - } else if (tabIndex >= 0) { - splitIndex = tabIndex; - } - - return splitIndex > 0 ? command.substring(0, splitIndex) : command; - } - - /** - * Extract path from command that contains path separators. - * Handles paths with spaces like "C:\Program Files\app.exe arg1" - */ - private String extractPathFromCommand(String command) { - // Look for common executable extensions to find where the path ends - String lowerCommand = command.toLowerCase(); - int exePos = lowerCommand.indexOf(".exe"); - int batPos = lowerCommand.indexOf(".bat"); - int cmdPos = lowerCommand.indexOf(".cmd"); - - // Find the first occurrence of any extension - int extPos = -1; - if (exePos >= 0) extPos = exePos; - if (batPos >= 0 && (extPos < 0 || batPos < extPos)) extPos = batPos; - if (cmdPos >= 0 && (extPos < 0 || cmdPos < extPos)) extPos = cmdPos; - - if (extPos >= 0) { - // Found an extension, extract up to the end of the extension - int endPos = extPos + 4; // .exe, .bat, .cmd are all 4 characters - // Check if there's a space or end of string after the extension - if (endPos >= command.length() - || command.charAt(endPos) == ' ' - || command.charAt(endPos) == '\t') { - return command.substring(0, endPos); - } - } - - // No extension found, or extension not followed by space - // Fall back to extracting first token - return extractFirstToken(command); - } - - /** - * Check if the command contains multiple command separators outside of quotes. - * - *

Detects: &, |, newline (ignores separators within quotes or after escape ^) - *

Note: Semicolon is NOT a separator in Windows cmd.exe - * - * @param command The command to check - * @return true if multiple commands are detected, false otherwise - */ - @Override - /** - * Detects {@code cmd.exe} metacharacters that let a whitelisted executable execute - * additional commands or redirect output: variable expansion ({@code %VAR%}), redirection - * ({@code >}/{@code <}), and the {@code ^} escape character (which can smuggle separators - * and strip quote characters in {@code cmd /c} round-trips) (#3285). - */ - public boolean containsShellMetacharacters(String command) { - if (command == null || command.isEmpty()) { - return false; - } - for (int i = 0; i < command.length(); i++) { - char c = command.charAt(i); - if (c == '%' || c == '>' || c == '<' || c == '^') { - return true; - } - } - return false; - } - - public boolean containsMultipleCommands(String command) { - if (command == null || command.isEmpty()) { - return false; - } - - boolean inDoubleQuote = false; - boolean escaped = false; - - for (int i = 0; i < command.length(); i++) { - char c = command.charAt(i); - - // Handle escape sequences (^ is the escape character in cmd.exe) - if (escaped) { - escaped = false; - continue; - } - - if (c == '^') { - escaped = true; - continue; - } - - // Track quote state (Windows cmd.exe primarily uses double quotes) - if (c == '"') { - inDoubleQuote = !inDoubleQuote; - continue; - } - - // Only check for separators outside quotes - if (!inDoubleQuote) { - // Check for command separators (&, |, newline) - // Note: Semicolon is NOT a separator in Windows cmd.exe - if (c == '&' || c == '|' || c == '\n') { - return true; - } - } - } - - return false; - } -} +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.core.tool.coding; + +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Command validator for Windows systems. + * + *

Validation Order: + *

    + *
  1. Extract executable from command (remove quotes, handle paths with spaces, remove path, remove extensions, convert to lowercase)
  2. + *
  3. If no whitelist configured → allow (backward compatible)
  4. + *
  5. Check for multiple command separators → reject if found
  6. + *
  7. Check relative path safety (commands starting with {@code .\} or {@code ./}) → reject if escapes current directory
  8. + *
  9. Check whitelist (case-insensitive) → reject if not in whitelist
  10. + *
+ * + *

Multiple Command Detection: Detects Windows-specific separators: + * {@code &}, {@code &&}, {@code |}, {@code ||}, newline + * (ignores separators within quotes or after escape {@code ^}) + *
Note: Semicolon ({@code ;}) is NOT a separator in Windows cmd.exe + * + *

Executable Extraction: + *

    + *
  • Handles quoted commands (double quotes)
  • + *
  • Handles paths with spaces (e.g., {@code C:\Program Files\app.exe})
  • + *
  • Extracts command name without path (handles both {@code \} and {@code /})
  • + *
  • Removes extensions: {@code .exe}, {@code .bat}, {@code .cmd} (case-insensitive)
  • + *
  • Converts result to lowercase for consistent matching
  • + *
+ */ +public class WindowsCommandValidator implements CommandValidator { + + private static final Logger logger = LoggerFactory.getLogger(WindowsCommandValidator.class); + + @Override + public ValidationResult validate(String command, Set allowedCommands) { + // Extract and check executable (case-insensitive for Windows) + String executable = extractExecutable(command); + + // If no whitelist is configured, allow all commands (backward compatible) + if (allowedCommands == null || allowedCommands.isEmpty()) { + return ValidationResult.allowed(executable); + } + + // Check for multiple commands + if (containsMultipleCommands(command)) { + logger.debug("Command contains multiple command separators: {}", command); + return ValidationResult.rejected( + "Command contains multiple command separators (&, |, newline)", + extractExecutable(command)); + } + + // Check for shell metacharacters that survive executable whitelisting under + // cmd.exe: variable expansion (%VAR%), redirection (>/<), and the ^ escape used to + // smuggle separators past lexical scans (#3285) + if (containsShellMetacharacters(command)) { + logger.debug("Command contains cmd.exe metacharacters: {}", command); + return ValidationResult.rejected( + "Command contains shell metacharacters (variable expansion, redirection," + + " or escape) requiring approval", + extractExecutable(command)); + } + + if (executable.startsWith(".\\") || executable.startsWith("./")) { + if (isPathWithinCurrentDirectory(executable)) { + logger.debug( + "Command '{}' is safe relative path executable file execution", executable); + return ValidationResult.allowed(executable); + } else { + logger.debug( + "Command '{}' is not safe relative path executable file execution", + executable); + return ValidationResult.rejected( + "Command '" + executable + "' escapes current directory", executable); + } + } + + // Check if any whitelist entry matches (case-insensitive) + boolean inWhitelist = + allowedCommands.stream().anyMatch(allowed -> allowed.equalsIgnoreCase(executable)); + if (inWhitelist) { + logger.debug("Command '{}' is in whitelist", executable); + return ValidationResult.allowed(executable); + } else { + logger.debug("Command '{}' is NOT in whitelist", executable); + return ValidationResult.rejected( + "Command '" + executable + "' is not in the allowed whitelist", executable); + } + } + + @Override + public String extractExecutable(String command) { + if (command == null || command.trim().isEmpty()) { + return ""; + } + + try { + String trimmed = command.trim(); + String executable; + + // Handle quoted commands: "command" (Windows typically uses double quotes) + if (trimmed.startsWith("\"")) { + int endQuote = trimmed.indexOf('"', 1); + if (endQuote > 0) { + executable = trimmed.substring(1, endQuote); + } else { + // No closing quote, treat as unquoted + executable = extractFirstToken(trimmed); + } + } else { + // Check if this looks like a path (contains \ or /) + if (trimmed.contains("\\") || trimmed.contains("/")) { + // This is a path, need to extract the full path before arguments + executable = extractPathFromCommand(trimmed); + } else { + // Simple command without path, extract first token + executable = extractFirstToken(trimmed); + } + } + + // Remove .exe, .bat, .cmd extensions if present (case-insensitive) + String lowerExecutable = executable.toLowerCase(); + if (lowerExecutable.endsWith(".exe") + || lowerExecutable.endsWith(".bat") + || lowerExecutable.endsWith(".cmd")) { + int dotIndex = lowerExecutable.lastIndexOf('.'); + if (dotIndex > 0) { + executable = lowerExecutable.substring(0, dotIndex); + } + } + + return executable; + } catch (Exception e) { + logger.warn("Failed to parse command '{}': {}", command, e.getMessage()); + return ""; + } + } + + /** + * Extract first token (word before space/tab) from command. + */ + private String extractFirstToken(String command) { + int spaceIndex = command.indexOf(' '); + int tabIndex = command.indexOf('\t'); + int splitIndex = -1; + + if (spaceIndex >= 0 && tabIndex >= 0) { + splitIndex = Math.min(spaceIndex, tabIndex); + } else if (spaceIndex >= 0) { + splitIndex = spaceIndex; + } else if (tabIndex >= 0) { + splitIndex = tabIndex; + } + + return splitIndex > 0 ? command.substring(0, splitIndex) : command; + } + + /** + * Extract path from command that contains path separators. + * Handles paths with spaces like "C:\Program Files\app.exe arg1" + */ + private String extractPathFromCommand(String command) { + // Look for common executable extensions to find where the path ends + String lowerCommand = command.toLowerCase(); + int exePos = lowerCommand.indexOf(".exe"); + int batPos = lowerCommand.indexOf(".bat"); + int cmdPos = lowerCommand.indexOf(".cmd"); + + // Find the first occurrence of any extension + int extPos = -1; + if (exePos >= 0) extPos = exePos; + if (batPos >= 0 && (extPos < 0 || batPos < extPos)) extPos = batPos; + if (cmdPos >= 0 && (extPos < 0 || cmdPos < extPos)) extPos = cmdPos; + + if (extPos >= 0) { + // Found an extension, extract up to the end of the extension + int endPos = extPos + 4; // .exe, .bat, .cmd are all 4 characters + // Check if there's a space or end of string after the extension + if (endPos >= command.length() + || command.charAt(endPos) == ' ' + || command.charAt(endPos) == '\t') { + return command.substring(0, endPos); + } + } + + // No extension found, or extension not followed by space + // Fall back to extracting first token + return extractFirstToken(command); + } + + /** + * Check if the command contains multiple command separators outside of quotes. + * + *

Detects: &, |, newline (ignores separators within quotes or after escape ^) + *

Note: Semicolon is NOT a separator in Windows cmd.exe + * + * @param command The command to check + * @return true if multiple commands are detected, false otherwise + */ + @Override + /** + * Detects {@code cmd.exe} metacharacters that let a whitelisted executable execute + * additional commands or redirect output: variable expansion ({@code %VAR%}), redirection + * ({@code >}/{@code <}), and the {@code ^} escape character (which can smuggle separators + * and strip quote characters in {@code cmd /c} round-trips) (#3285). + */ + public boolean containsShellMetacharacters(String command) { + if (command == null || command.isEmpty()) { + return false; + } + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + if (c == '%' || c == '>' || c == '<' || c == '^') { + return true; + } + } + return false; + } + + public boolean containsMultipleCommands(String command) { + if (command == null || command.isEmpty()) { + return false; + } + + boolean inDoubleQuote = false; + boolean escaped = false; + + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + + // Handle escape sequences (^ is the escape character in cmd.exe) + if (escaped) { + escaped = false; + continue; + } + + if (c == '^') { + escaped = true; + continue; + } + + // Track quote state (Windows cmd.exe primarily uses double quotes) + if (c == '"') { + inDoubleQuote = !inDoubleQuote; + continue; + } + + // Only check for separators outside quotes + if (!inDoubleQuote) { + // Check for command separators (&, |, newline) + // Note: Semicolon is NOT a separator in Windows cmd.exe + if (c == '&' || c == '|' || c == '\n') { + return true; + } + } + } + + return false; + } +} From 67d0937f0a738ad17e5417f1c8909f19635fbb48 Mon Sep 17 00:00:00 2001 From: shenxiaobo Date: Mon, 26 Oct 2026 10:51:15 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(core):=20=E4=BF=AE=E5=A4=8D=20UnixComma?= =?UTF-8?q?ndValidator=20=E5=AD=97=E7=AC=A6=E5=AD=97=E9=9D=A2=E9=87=8F(?= =?UTF-8?q?=E5=89=8D=E6=AC=A1=E6=8E=A8=E9=80=81=E8=A2=AB=E8=A6=86=E7=9B=96?= =?UTF-8?q?=E5=9B=9E=E5=9D=8F=E7=89=88=E6=9C=AC)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../agentscope/core/tool/coding/UnixCommandValidator.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java index 5ee4f1252d..eb2deb6921 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java @@ -198,11 +198,11 @@ public boolean containsShellMetacharacters(String command) { escaped = false; continue; } - if (c == '\') { + if (c == '\\') { escaped = true; continue; } - if (c == ''' && !inDoubleQuote) { + if (c == '\'' && !inDoubleQuote) { inSingleQuote = !inSingleQuote; continue; } @@ -222,7 +222,7 @@ public boolean containsShellMetacharacters(String command) { return false; } - public boolean containsMultipleCommands(String command) { + public boolean containsMultipleCommands(String command) { if (command == null || command.isEmpty()) { return false; } From 1262805363f6f0df1971063ab28c8932f619b363 Mon Sep 17 00:00:00 2001 From: shenxiaobo Date: Mon, 26 Oct 2026 11:27:43 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(core):=20=E4=BB=8E=E4=B8=8A=E6=B8=B8?= =?UTF-8?q?=E5=8E=9F=E7=89=88=E9=87=8D=E5=BB=BA=E4=B8=A4=E4=B8=AA=20valida?= =?UTF-8?q?tor(@Override=20=E5=BD=92=E4=BD=8D,=E6=96=B9=E6=B3=95=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0=E7=B1=BB=E5=B0=BE)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tool/coding/UnixCommandValidator.java | 66 +-- .../tool/coding/WindowsCommandValidator.java | 553 +++++++++--------- 2 files changed, 309 insertions(+), 310 deletions(-) diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java index eb2deb6921..d28c656d6b 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/UnixCommandValidator.java @@ -177,94 +177,94 @@ private String extractFirstToken(String command) { * @return true if multiple commands are detected, false otherwise */ @Override - /** - * Detects shell metacharacters that let a whitelisted executable execute additional - * commands or redirect output: command substitution ({@code $(...)}), backticks, variable - * expansion ({@code $VAR}/{@code ${...}}), and redirection ({@code >}/{@code <}). - * Single-quoted content is literal in {@code sh}; double quotes do NOT neutralize - * substitution, so {@code $} and backticks are checked outside single quotes only, while - * redirection is checked outside both quote kinds (#3285). - */ - public boolean containsShellMetacharacters(String command) { + public boolean containsMultipleCommands(String command) { if (command == null || command.isEmpty()) { return false; } + boolean inSingleQuote = false; boolean inDoubleQuote = false; boolean escaped = false; + for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); + + // Handle escape sequences if (escaped) { escaped = false; continue; } + if (c == '\\') { escaped = true; continue; } + + // Track quote state if (c == '\'' && !inDoubleQuote) { inSingleQuote = !inSingleQuote; continue; } + if (c == '"' && !inSingleQuote) { inDoubleQuote = !inDoubleQuote; continue; } - // Command substitution and variable expansion survive double quotes. - if ((c == '$' || c == '`') && !inSingleQuote) { - return true; - } - // Redirection is literal inside either quote kind. - if ((c == '>' || c == '<') && !inSingleQuote && !inDoubleQuote) { - return true; + + // Only check for separators outside quotes + if (!inSingleQuote && !inDoubleQuote) { + // Check for command separators + if (c == '&' || c == '|' || c == ';' || c == '\n') { + return true; + } } } + return false; } - public boolean containsMultipleCommands(String command) { + /** + * Detects shell metacharacters that let a whitelisted executable execute additional + * commands or redirect output: command substitution ({@code $(...)}), backticks, variable + * expansion ({@code $VAR}/{@code ${...}}), and redirection ({@code >}/{@code <}). + * Single-quoted content is literal in {@code sh}; double quotes do NOT neutralize + * substitution, so {@code $} and backticks are checked outside single quotes only, while + * redirection is checked outside both quote kinds (#3285). + */ + public boolean containsShellMetacharacters(String command) { if (command == null || command.isEmpty()) { return false; } - boolean inSingleQuote = false; boolean inDoubleQuote = false; boolean escaped = false; - for (int i = 0; i < command.length(); i++) { char c = command.charAt(i); - - // Handle escape sequences if (escaped) { escaped = false; continue; } - if (c == '\\') { escaped = true; continue; } - - // Track quote state if (c == '\'' && !inDoubleQuote) { inSingleQuote = !inSingleQuote; continue; } - if (c == '"' && !inSingleQuote) { inDoubleQuote = !inDoubleQuote; continue; } - - // Only check for separators outside quotes - if (!inSingleQuote && !inDoubleQuote) { - // Check for command separators - if (c == '&' || c == '|' || c == ';' || c == '\n') { - return true; - } + // Command substitution and variable expansion survive double quotes. + if ((c == '$' || c == '`') && !inSingleQuote) { + return true; + } + // Redirection is literal inside either quote kind. + if ((c == '>' || c == '<') && !inSingleQuote && !inDoubleQuote) { + return true; } } - return false; } } diff --git a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java index 86f368b7f9..d581697b4c 100644 --- a/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java +++ b/agentscope-core/src/main/java/io/agentscope/core/tool/coding/WindowsCommandValidator.java @@ -1,277 +1,276 @@ -/* - * Copyright 2024-2026 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package io.agentscope.core.tool.coding; - -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Command validator for Windows systems. - * - *

Validation Order: - *

    - *
  1. Extract executable from command (remove quotes, handle paths with spaces, remove path, remove extensions, convert to lowercase)
  2. - *
  3. If no whitelist configured → allow (backward compatible)
  4. - *
  5. Check for multiple command separators → reject if found
  6. - *
  7. Check relative path safety (commands starting with {@code .\} or {@code ./}) → reject if escapes current directory
  8. - *
  9. Check whitelist (case-insensitive) → reject if not in whitelist
  10. - *
- * - *

Multiple Command Detection: Detects Windows-specific separators: - * {@code &}, {@code &&}, {@code |}, {@code ||}, newline - * (ignores separators within quotes or after escape {@code ^}) - *
Note: Semicolon ({@code ;}) is NOT a separator in Windows cmd.exe - * - *

Executable Extraction: - *

    - *
  • Handles quoted commands (double quotes)
  • - *
  • Handles paths with spaces (e.g., {@code C:\Program Files\app.exe})
  • - *
  • Extracts command name without path (handles both {@code \} and {@code /})
  • - *
  • Removes extensions: {@code .exe}, {@code .bat}, {@code .cmd} (case-insensitive)
  • - *
  • Converts result to lowercase for consistent matching
  • - *
- */ -public class WindowsCommandValidator implements CommandValidator { - - private static final Logger logger = LoggerFactory.getLogger(WindowsCommandValidator.class); - - @Override - public ValidationResult validate(String command, Set allowedCommands) { - // Extract and check executable (case-insensitive for Windows) - String executable = extractExecutable(command); - - // If no whitelist is configured, allow all commands (backward compatible) - if (allowedCommands == null || allowedCommands.isEmpty()) { - return ValidationResult.allowed(executable); - } - - // Check for multiple commands - if (containsMultipleCommands(command)) { - logger.debug("Command contains multiple command separators: {}", command); - return ValidationResult.rejected( - "Command contains multiple command separators (&, |, newline)", - extractExecutable(command)); - } - - // Check for shell metacharacters that survive executable whitelisting under - // cmd.exe: variable expansion (%VAR%), redirection (>/<), and the ^ escape used to - // smuggle separators past lexical scans (#3285) - if (containsShellMetacharacters(command)) { - logger.debug("Command contains cmd.exe metacharacters: {}", command); - return ValidationResult.rejected( - "Command contains shell metacharacters (variable expansion, redirection," - + " or escape) requiring approval", - extractExecutable(command)); - } - - if (executable.startsWith(".\\") || executable.startsWith("./")) { - if (isPathWithinCurrentDirectory(executable)) { - logger.debug( - "Command '{}' is safe relative path executable file execution", executable); - return ValidationResult.allowed(executable); - } else { - logger.debug( - "Command '{}' is not safe relative path executable file execution", - executable); - return ValidationResult.rejected( - "Command '" + executable + "' escapes current directory", executable); - } - } - - // Check if any whitelist entry matches (case-insensitive) - boolean inWhitelist = - allowedCommands.stream().anyMatch(allowed -> allowed.equalsIgnoreCase(executable)); - if (inWhitelist) { - logger.debug("Command '{}' is in whitelist", executable); - return ValidationResult.allowed(executable); - } else { - logger.debug("Command '{}' is NOT in whitelist", executable); - return ValidationResult.rejected( - "Command '" + executable + "' is not in the allowed whitelist", executable); - } - } - - @Override - public String extractExecutable(String command) { - if (command == null || command.trim().isEmpty()) { - return ""; - } - - try { - String trimmed = command.trim(); - String executable; - - // Handle quoted commands: "command" (Windows typically uses double quotes) - if (trimmed.startsWith("\"")) { - int endQuote = trimmed.indexOf('"', 1); - if (endQuote > 0) { - executable = trimmed.substring(1, endQuote); - } else { - // No closing quote, treat as unquoted - executable = extractFirstToken(trimmed); - } - } else { - // Check if this looks like a path (contains \ or /) - if (trimmed.contains("\\") || trimmed.contains("/")) { - // This is a path, need to extract the full path before arguments - executable = extractPathFromCommand(trimmed); - } else { - // Simple command without path, extract first token - executable = extractFirstToken(trimmed); - } - } - - // Remove .exe, .bat, .cmd extensions if present (case-insensitive) - String lowerExecutable = executable.toLowerCase(); - if (lowerExecutable.endsWith(".exe") - || lowerExecutable.endsWith(".bat") - || lowerExecutable.endsWith(".cmd")) { - int dotIndex = lowerExecutable.lastIndexOf('.'); - if (dotIndex > 0) { - executable = lowerExecutable.substring(0, dotIndex); - } - } - - return executable; - } catch (Exception e) { - logger.warn("Failed to parse command '{}': {}", command, e.getMessage()); - return ""; - } - } - - /** - * Extract first token (word before space/tab) from command. - */ - private String extractFirstToken(String command) { - int spaceIndex = command.indexOf(' '); - int tabIndex = command.indexOf('\t'); - int splitIndex = -1; - - if (spaceIndex >= 0 && tabIndex >= 0) { - splitIndex = Math.min(spaceIndex, tabIndex); - } else if (spaceIndex >= 0) { - splitIndex = spaceIndex; - } else if (tabIndex >= 0) { - splitIndex = tabIndex; - } - - return splitIndex > 0 ? command.substring(0, splitIndex) : command; - } - - /** - * Extract path from command that contains path separators. - * Handles paths with spaces like "C:\Program Files\app.exe arg1" - */ - private String extractPathFromCommand(String command) { - // Look for common executable extensions to find where the path ends - String lowerCommand = command.toLowerCase(); - int exePos = lowerCommand.indexOf(".exe"); - int batPos = lowerCommand.indexOf(".bat"); - int cmdPos = lowerCommand.indexOf(".cmd"); - - // Find the first occurrence of any extension - int extPos = -1; - if (exePos >= 0) extPos = exePos; - if (batPos >= 0 && (extPos < 0 || batPos < extPos)) extPos = batPos; - if (cmdPos >= 0 && (extPos < 0 || cmdPos < extPos)) extPos = cmdPos; - - if (extPos >= 0) { - // Found an extension, extract up to the end of the extension - int endPos = extPos + 4; // .exe, .bat, .cmd are all 4 characters - // Check if there's a space or end of string after the extension - if (endPos >= command.length() - || command.charAt(endPos) == ' ' - || command.charAt(endPos) == '\t') { - return command.substring(0, endPos); - } - } - - // No extension found, or extension not followed by space - // Fall back to extracting first token - return extractFirstToken(command); - } - - /** - * Check if the command contains multiple command separators outside of quotes. - * - *

Detects: &, |, newline (ignores separators within quotes or after escape ^) - *

Note: Semicolon is NOT a separator in Windows cmd.exe - * - * @param command The command to check - * @return true if multiple commands are detected, false otherwise - */ - @Override - /** - * Detects {@code cmd.exe} metacharacters that let a whitelisted executable execute - * additional commands or redirect output: variable expansion ({@code %VAR%}), redirection - * ({@code >}/{@code <}), and the {@code ^} escape character (which can smuggle separators - * and strip quote characters in {@code cmd /c} round-trips) (#3285). - */ - public boolean containsShellMetacharacters(String command) { - if (command == null || command.isEmpty()) { - return false; - } - for (int i = 0; i < command.length(); i++) { - char c = command.charAt(i); - if (c == '%' || c == '>' || c == '<' || c == '^') { - return true; - } - } - return false; - } - - public boolean containsMultipleCommands(String command) { - if (command == null || command.isEmpty()) { - return false; - } - - boolean inDoubleQuote = false; - boolean escaped = false; - - for (int i = 0; i < command.length(); i++) { - char c = command.charAt(i); - - // Handle escape sequences (^ is the escape character in cmd.exe) - if (escaped) { - escaped = false; - continue; - } - - if (c == '^') { - escaped = true; - continue; - } - - // Track quote state (Windows cmd.exe primarily uses double quotes) - if (c == '"') { - inDoubleQuote = !inDoubleQuote; - continue; - } - - // Only check for separators outside quotes - if (!inDoubleQuote) { - // Check for command separators (&, |, newline) - // Note: Semicolon is NOT a separator in Windows cmd.exe - if (c == '&' || c == '|' || c == '\n') { - return true; - } - } - } - - return false; - } -} +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.core.tool.coding; + +import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Command validator for Windows systems. + * + *

Validation Order: + *

    + *
  1. Extract executable from command (remove quotes, handle paths with spaces, remove path, remove extensions, convert to lowercase)
  2. + *
  3. If no whitelist configured → allow (backward compatible)
  4. + *
  5. Check for multiple command separators → reject if found
  6. + *
  7. Check relative path safety (commands starting with {@code .\} or {@code ./}) → reject if escapes current directory
  8. + *
  9. Check whitelist (case-insensitive) → reject if not in whitelist
  10. + *
+ * + *

Multiple Command Detection: Detects Windows-specific separators: + * {@code &}, {@code &&}, {@code |}, {@code ||}, newline + * (ignores separators within quotes or after escape {@code ^}) + *
Note: Semicolon ({@code ;}) is NOT a separator in Windows cmd.exe + * + *

Executable Extraction: + *

    + *
  • Handles quoted commands (double quotes)
  • + *
  • Handles paths with spaces (e.g., {@code C:\Program Files\app.exe})
  • + *
  • Extracts command name without path (handles both {@code \} and {@code /})
  • + *
  • Removes extensions: {@code .exe}, {@code .bat}, {@code .cmd} (case-insensitive)
  • + *
  • Converts result to lowercase for consistent matching
  • + *
+ */ +public class WindowsCommandValidator implements CommandValidator { + + private static final Logger logger = LoggerFactory.getLogger(WindowsCommandValidator.class); + + @Override + public ValidationResult validate(String command, Set allowedCommands) { + // Extract and check executable (case-insensitive for Windows) + String executable = extractExecutable(command); + + // If no whitelist is configured, allow all commands (backward compatible) + if (allowedCommands == null || allowedCommands.isEmpty()) { + return ValidationResult.allowed(executable); + } + + // Check for multiple commands + if (containsMultipleCommands(command)) { + logger.debug("Command contains multiple command separators: {}", command); + return ValidationResult.rejected( + "Command contains multiple command separators (&, |, newline)", + extractExecutable(command)); + } + + // Check for cmd.exe metacharacters that survive executable whitelisting: variable + // expansion, redirection, and the ^ escape used to smuggle separators (#3285) + if (containsShellMetacharacters(command)) { + logger.debug("Command contains cmd.exe metacharacters: {}", command); + return ValidationResult.rejected( + "Command contains shell metacharacters (variable expansion, redirection," + + " or escape) requiring approval", + extractExecutable(command)); + } + + if (executable.startsWith(".\\") || executable.startsWith("./")) { + if (isPathWithinCurrentDirectory(executable)) { + logger.debug( + "Command '{}' is safe relative path executable file execution", executable); + return ValidationResult.allowed(executable); + } else { + logger.debug( + "Command '{}' is not safe relative path executable file execution", + executable); + return ValidationResult.rejected( + "Command '" + executable + "' escapes current directory", executable); + } + } + + // Check if any whitelist entry matches (case-insensitive) + boolean inWhitelist = + allowedCommands.stream().anyMatch(allowed -> allowed.equalsIgnoreCase(executable)); + if (inWhitelist) { + logger.debug("Command '{}' is in whitelist", executable); + return ValidationResult.allowed(executable); + } else { + logger.debug("Command '{}' is NOT in whitelist", executable); + return ValidationResult.rejected( + "Command '" + executable + "' is not in the allowed whitelist", executable); + } + } + + @Override + public String extractExecutable(String command) { + if (command == null || command.trim().isEmpty()) { + return ""; + } + + try { + String trimmed = command.trim(); + String executable; + + // Handle quoted commands: "command" (Windows typically uses double quotes) + if (trimmed.startsWith("\"")) { + int endQuote = trimmed.indexOf('"', 1); + if (endQuote > 0) { + executable = trimmed.substring(1, endQuote); + } else { + // No closing quote, treat as unquoted + executable = extractFirstToken(trimmed); + } + } else { + // Check if this looks like a path (contains \ or /) + if (trimmed.contains("\\") || trimmed.contains("/")) { + // This is a path, need to extract the full path before arguments + executable = extractPathFromCommand(trimmed); + } else { + // Simple command without path, extract first token + executable = extractFirstToken(trimmed); + } + } + + // Remove .exe, .bat, .cmd extensions if present (case-insensitive) + String lowerExecutable = executable.toLowerCase(); + if (lowerExecutable.endsWith(".exe") + || lowerExecutable.endsWith(".bat") + || lowerExecutable.endsWith(".cmd")) { + int dotIndex = lowerExecutable.lastIndexOf('.'); + if (dotIndex > 0) { + executable = lowerExecutable.substring(0, dotIndex); + } + } + + return executable; + } catch (Exception e) { + logger.warn("Failed to parse command '{}': {}", command, e.getMessage()); + return ""; + } + } + + /** + * Extract first token (word before space/tab) from command. + */ + private String extractFirstToken(String command) { + int spaceIndex = command.indexOf(' '); + int tabIndex = command.indexOf('\t'); + int splitIndex = -1; + + if (spaceIndex >= 0 && tabIndex >= 0) { + splitIndex = Math.min(spaceIndex, tabIndex); + } else if (spaceIndex >= 0) { + splitIndex = spaceIndex; + } else if (tabIndex >= 0) { + splitIndex = tabIndex; + } + + return splitIndex > 0 ? command.substring(0, splitIndex) : command; + } + + /** + * Extract path from command that contains path separators. + * Handles paths with spaces like "C:\Program Files\app.exe arg1" + */ + private String extractPathFromCommand(String command) { + // Look for common executable extensions to find where the path ends + String lowerCommand = command.toLowerCase(); + int exePos = lowerCommand.indexOf(".exe"); + int batPos = lowerCommand.indexOf(".bat"); + int cmdPos = lowerCommand.indexOf(".cmd"); + + // Find the first occurrence of any extension + int extPos = -1; + if (exePos >= 0) extPos = exePos; + if (batPos >= 0 && (extPos < 0 || batPos < extPos)) extPos = batPos; + if (cmdPos >= 0 && (extPos < 0 || cmdPos < extPos)) extPos = cmdPos; + + if (extPos >= 0) { + // Found an extension, extract up to the end of the extension + int endPos = extPos + 4; // .exe, .bat, .cmd are all 4 characters + // Check if there's a space or end of string after the extension + if (endPos >= command.length() + || command.charAt(endPos) == ' ' + || command.charAt(endPos) == '\t') { + return command.substring(0, endPos); + } + } + + // No extension found, or extension not followed by space + // Fall back to extracting first token + return extractFirstToken(command); + } + + /** + * Check if the command contains multiple command separators outside of quotes. + * + *

Detects: &, |, newline (ignores separators within quotes or after escape ^) + *

Note: Semicolon is NOT a separator in Windows cmd.exe + * + * @param command The command to check + * @return true if multiple commands are detected, false otherwise + */ + @Override + public boolean containsMultipleCommands(String command) { + if (command == null || command.isEmpty()) { + return false; + } + + boolean inDoubleQuote = false; + boolean escaped = false; + + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + + // Handle escape sequences (^ is the escape character in cmd.exe) + if (escaped) { + escaped = false; + continue; + } + + if (c == '^') { + escaped = true; + continue; + } + + // Track quote state (Windows cmd.exe primarily uses double quotes) + if (c == '"') { + inDoubleQuote = !inDoubleQuote; + continue; + } + + // Only check for separators outside quotes + if (!inDoubleQuote) { + // Check for command separators (&, |, newline) + // Note: Semicolon is NOT a separator in Windows cmd.exe + if (c == '&' || c == '|' || c == '\n') { + return true; + } + } + } + + return false; + } + + /** + * Detects {@code cmd.exe} metacharacters that let a whitelisted executable execute + * additional commands or redirect output: variable expansion ({@code %VAR%}), redirection + * ({@code >}/{@code <}), and the {@code ^} escape character (which can smuggle separators + * and strip quote characters in {@code cmd /c} round-trips) (#3285). + */ + public boolean containsShellMetacharacters(String command) { + if (command == null || command.isEmpty()) { + return false; + } + for (int i = 0; i < command.length(); i++) { + char c = command.charAt(i); + if (c == '%' || c == '>' || c == '<' || c == '^') { + return true; + } + } + return false; + } +}