

Disclaimer: This guide is for educational and defensive purposes. The "Ruby2Shell" vulnerability refers to patterns where unsanitized user input is passed to system shells via Ruby methods like system(), exec(), or backticks (`). This guide demonstrates how to implement secure, programmatic alternatives to shell execution to prevent RCE.
Before implementing secure execution patterns, ensure your development environment is prepared:
ruby -v).eslint for JS or flake8 for Python) to detect dangerous functions.Set up your workspace for testing the secure implementations.
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install necessary libraries for testing
pip install subprocess pydantic
# Initialize project
mkdir secure-exec-demo && cd secure-exec-demo
npm init -y
# Install TypeScript and types
npm install typescript ts-node @types/node --save-dev
# Initialize TypeScript config
npx tsc --init
The core of the vulnerability is Shell Injection. To fix it, we must move from "Shell Execution" (where a string is parsed by /bin/sh) to "Process Execution" (where arguments are passed as a discrete array).
subprocess)This example demonstrates the difference between the vulnerable way and the secure, production-ready way.
import subprocess
import shlex
from typing import List
def secure_execute_command(cmd_base: str, user_args: List[str]) -> str:
"""
Executes a command securely by avoiding shell=True.
Args:
cmd_base: The base executable (e.g., 'ls', 'git')
user_args: A list of arguments provided by the user
Returns:
The stdout of the command.
"""
try:
# SECURE PATTERN:
# We pass the command and arguments as a LIST.
# shell=False (default) ensures the OS treats user_args
# as literal strings, not shell commands.
# Example: If user_args is ["; rm -rf /"],
# the system looks for a file named "; rm -rf /"
# instead of executing the command.
result = subprocess.run(
[cmd_base] + user_args,
capture_output=True,
text=True,
check=True, # Raises CalledProcessError if exit code != 0
shell=False # CRITICAL: Must be False to prevent RCE
)
return result.stdout
except subprocess.CalledProcessError as e:
return f"Error: Command failed with exit code {e.returncode}. Output: {e.stderr}"
except FileNotFoundError:
return f"Error: The executable '{cmd_base}' was not found."
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
# --- TEST CASES ---
if __name__ == "__main__":
print("--- Scenario 1: Valid Command ---")
print(secure_execute_command("echo", ["Hello", "World"]))
print("\n--- Scenario 2: Attempted RCE (Injection) ---")
# In a vulnerable system, this would print files or delete data.
# In this secure system, it will simply try to print the literal string.
print(secure_execute_command("echo", ["; ls -la /"]))
child_process)Using spawn instead of exec is the industry standard for preventing RCE in Node.js.
import { spawn } from 'child_process';
/**
* Interface for command execution results
*/
interface ExecutionResult {
stdout: string;
stderr: string;
error?: string;
}
/**
* Executes a system command securely using spawn.
* Unlike exec(), spawn() does not spawn a shell by default,
* making it immune to shell metacharacter injection.
*
* @param command The base binary to run
* @param args Array of arguments to pass to the binary
*/
async function safeSpawn(command: string, args: string[]): Promise<ExecutionResult> {
return new Promise((resolve) => {
// SECURE PATTERN:
// 'spawn' takes arguments as an array.
// It does not interpret characters like ';', '&', or '|'.
const child = spawn(command, args, {
shell: false, // Ensure shell is disabled
env: { PATH: process.env.PATH } // Limit environment scope if needed
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (data) => {
stdout += data.toString();
});
child.stderr.on('data', (data) => {
stderr += data.toString();
});
child.on('error', (err) => {
resolve({ stdout, stderr, error: err.message });
});
child.on('close', (code) => {
if (code !== 0) {
resolve({ stdout, stderr, error: `Process exited with code ${code}` });
} else {
resolve({ stdout, stderr });
}
});
});
}
// --- TEST CASES ---
async function runTests() {
console.log("--- Scenario 1: Valid Command ---");
const res1 = await safeSpawn('echo', ['Secure', 'Execution']);
console.log(res1.stdout);
console.log("\n--- Scenario 2: Attempted RCE (Injection) ---");
// This attempt to inject a second command via ';' will fail safely.
const res2 = await safeSpawn('echo', ['hello', ';', 'whoami']);
console.log(res2.stdout);
// Expected output: "hello ; whoami" (The ';' is treated as text)
}
runTests();
When building production systems, do not hardcode paths or command names. Use environment variables to define allowed binaries.
Example .env file:
# Define allowed binaries to prevent attackers from calling unauthorized tools
ALLOWED_BINARY_PATH=/usr/bin/git
LOG_LEVEL=info
MAX_EXECUTION_TIMEOUT=5000
Implementation Pattern:
import os
from dotenv import load_dotenv
load_dotenv()
# Fetching from env with a fallback
GIT_PATH = os.getenv("ALLOWED_BINARY_PATH", "/usr/bin/git")
Never allow arbitrary commands. Use an allow-list to map user intent to specific, hardcoded commands.
# VULNERABLE
# cmd = user_input <-- NEVER DO THIS
# SECURE
ALLOWED_ACTIONS = {
"list_files": ["ls", "-la"],
"check_status": ["systemctl", "status", "myapp"]
}
def run_action(action_key: str):
if action_key in ALLOWED_ACTIONS:
cmd_parts = ALLOWED_ACTIONS[action_key]
# execute cmd_parts safely...
| Error | Cause | Fix |
|---|---|---|
FileNotFoundError (Python) | The binary path provided is incorrect or not in $PATH. | Use absolute paths (e.g., /usr/bin/ls instead of ls). |
ENOENT (Node.js) | The command or the binary itself cannot be found. | Verify the binary exists in the container/server environment. |
| Command runs but returns empty | The command executed successfully but produced no output. | Check stderr to see if the command failed silently. |
| Permission Denied | The user running the script lacks execution rights. | Use chmod +x or run with appropriate service user permissions. |
Before deploying code that interacts with the system shell:
shell=False (Python) or shell: false (Node.js) is explicitly set.../)?Source: Security Week AI
Follow ICARAX for more AI insights and tutorials.
