Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ public ValidationResult validate(String command, Set<String> 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)) {
Expand Down Expand Up @@ -212,4 +222,49 @@ public boolean containsMultipleCommands(String command) {

return false;
}

/**
* 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ public ValidationResult validate(String command, Set<String> allowedCommands) {
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(
Expand Down Expand Up @@ -244,4 +254,23 @@ public boolean containsMultipleCommands(String command) {

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;
}
}
Original file line number Diff line number Diff line change
@@ -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<String> 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());
}
}
Loading