Documentation
README
Remote Code Execution (RCE) Detection
You are performing a focused security assessment to find Remote Code Execution vulnerabilities in a codebase. This skill uses a three-phase approach with subagents: recon (find dangerous execution sinks), batched verify (trace whether user-supplied input reaches each sink in parallel batches of 3), and merge (consolidate batch results into the final report).
Prerequisites: sast/architecture.md must exist. Run the analysis skill first if it doesn't.
What is Remote Code Execution
Remote Code Execution (RCE) occurs when an attacker can cause the application to execute arbitrary OS commands or application-level code that they control. This is typically the highest-severity vulnerability class, often resulting in complete server compromise.
RCE arises from three primary root causes:
- OS Command Injection: User input is embedded unsafely into an OS command string, allowing shell metacharacters to inject additional commands.
- Code Injection (eval-like): User input is passed to functions that interpret it as executable code (
eval,exec,Function(), etc.). - Unsafe Deserialization: User-supplied serialized data is deserialized using a gadget-prone deserializer, triggering arbitrary code execution via crafted payloads.
What RCE IS
- Passing user input directly or indirectly into OS command execution functions with shell interpretation enabled
- Using
eval(),exec(),Function(), or equivalent constructs with user-controlled strings - Deserializing user-supplied bytes/strings with inherently unsafe deserializers (pickle, PHP unserialize, Java native serialization, Ruby Marshal, etc.)
- Using
yaml.load()without a safe loader on user-supplied content - Dynamic
require()/import()with user-controlled module paths - PHP file inclusion (
include/require) with user-controlled paths
What RCE is NOT
Do not flag these as RCE:
- SSRF: Making HTTP requests to attacker-controlled URLs β different vulnerability class (no code execution)
- Path Traversal: Reading/writing arbitrary files β separate class (unless the read file is then executed/deserialized)
- SSTI: Template injection via template engines β a separate though related class; flag as SSTI, not RCE
- XSS: JavaScript execution in a victim's browser β client-side only, not server-side RCE
- SQL Injection: Injecting into database queries β different class (even if
xp_cmdshellcan lead to OS commands, flag it as SQLi) - Safe subprocess list-form calls:
subprocess.run(["ls", user_arg])with a list and noshell=Trueβ arguments are passed directly to the OS without shell expansion; not vulnerable to command injection - Safe deserialization:
json.loads(),yaml.safe_load(),xml.etree.ElementTree.parse()β these formats have no code execution semantics
Patterns That Prevent RCE
When you see these patterns, the code is likely not vulnerable:
1. Subprocess list form without shell interpretation
# Python β list args, no shell=True
subprocess.run(["convert", "-resize", size, input_file, output_file])
subprocess.Popen(["git", "clone", repo_url])
# Node.js β spawn with separate args (no shell)
child_process.spawn("ffmpeg", ["-i", inputFile, outputFile])
# Java β ProcessBuilder with list
new ProcessBuilder("ls", "-la", dir).start()
# Ruby β system() with multiple args (not a single interpolated string)
system("ffmpeg", "-i", "input.mp4", "-f", format, "output")
2. Safe deserialization formats
# Python β JSON instead of pickle
import json
data = json.loads(user_input) # no code execution semantics
# Python β safe YAML loader
import yaml
data = yaml.safe_load(user_input) # restricts to basic types only
# Java β Jackson without enableDefaultTyping, with concrete target type
ObjectMapper mapper = new ObjectMapper();
MyClass obj = mapper.readValue(json, MyClass.class); # safe
3. Strict allowlist before command construction
# Python β allowlist for dynamic arguments
ALLOWED_FORMATS = {"png", "jpg", "webp"}
if fmt not in ALLOWED_FORMATS:
return abort(400)
subprocess.run(["convert", infile, f"output.{fmt}"])
# Node.js β allowlist for dynamic args
const ALLOWED_COMMANDS = ['ls', 'pwd'];
if (!ALLOWED_COMMANDS.includes(cmd)) return res.status(400).end();
spawn(cmd, []);
Vulnerable vs. Secure Examples
OS Command Injection β Python
# VULNERABLE: shell=True with f-string
@app.route('/ping')
def ping():
host = request.args.get('host')
result = subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True, text=True)
return result.stdout
# Payload: ?host=127.0.0.1;id β executes "id"
# VULNERABLE: os.system with string formatting
def convert_image(filename):
size = request.form.get('size')
os.system(f"convert {filename} -resize {size} output.jpg")
# SECURE: list-form subprocess, no shell
@app.route('/ping')
def ping():
host = request.args.get('host')
result = subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True, timeout=5)
return result.stdout
OS Command Injection β Node.js
// VULNERABLE: exec with template literal
app.get('/search', (req, res) => {
const query = req.query.q;
exec(`grep -r "${query}" /var/log/app/`, (err, stdout) => {
res.send(stdout);
});
});
// Payload: ?q=foo" /etc/passwd "
// VULNERABLE: execSync with concatenation
function runScript(userScript) {
return execSync('node scripts/' + userScript);
}
// SECURE: spawn with separate args
app.get('/search', (req, res) => {
const query = req.query.q;
const proc = spawn('grep', ['-r', query, '/var/log/app/']);
proc.stdout.on('data', (data) => res.write(data));
proc.on('close', () => res.end());
});
OS Command Injection β PHP
// VULNERABLE: shell_exec with user input
function generateThumbnail($file) {
$size = $_GET['size'];
shell_exec("convert {$file} -resize {$size} thumb.jpg");
}
// VULNERABLE: backtick operator
function checkHost() {
$host = $_POST['host'];
$result = `ping -c 1 $host`;
return $result;
}
// SECURE: escapeshellarg (reduces risk β but prefer removing shell entirely)
function generateThumbnail($file) {
$size = escapeshellarg($_GET['size']);
$file = escapeshellarg($file);
shell_exec("convert $file -resize $size thumb.jpg");
}
OS Command Injection β Ruby
# VULNERABLE: string interpolation in system()
get '/convert' do
format = params[:format]
system("ffmpeg -i input.mp4 -f #{format} output")
end
# VULNERABLE: backtick with user input
def check_dns
`nslookup #{params[:host]}`
end
# SECURE: system() with separate args (no shell expansion)
get '/convert' do
format = params[:format]
ALLOWED = %w[mp4 avi mkv]
return 400 unless ALLOWED.include?(format)
system("ffmpeg", "-i", "input.mp4", "-f", format, "output")
end
Code Injection β Python eval/exec
# VULNERABLE: eval with user input
@app.route('/calculate')
def calculate():
expr = request.args.get('expr')
result = eval(expr) # attacker can run __import__('os').system('id')
return str(result)
# VULNERABLE: exec with user code
@app.route('/run')
def run_code():
code = request.json.get('code')
exec(code) # full arbitrary code execution
return "ok"
# SECURE: ast.literal_eval for safe expression parsing (literals only)
from ast import literal_eval
@app.route('/parse')
def parse():
data = request.args.get('data')
result = literal_eval(data) # only parses strings/numbers/lists/dicts/bools
return str(result)
Code Injection β JavaScript eval / Function
// VULNERABLE: eval with user input
app.post('/formula', (req, res) => {
const formula = req.body.formula;
const result = eval(formula); // RCE: process.exit(), require('child_process')...
res.json({ result });
});
// VULNERABLE: new Function() constructor
function compute(userExpression) {
const fn = new Function('x', `return ${userExpression}`);
return fn(42);
}
// VULNERABLE: vm.runInNewContext (sandbox escape via __proto__ pollution)
const vm = require('vm');
app.post('/eval', (req, res) => {
const result = vm.runInNewContext(req.body.code);
res.json({ result });
});
// SECURE: use a math expression library (no arbitrary code)
const { evaluate } = require('mathjs');
app.post('/formula', (req, res) => {
const result = evaluate(req.body.formula); // sandboxed math expressions only
res.json({ result });
});
Unsafe Deserialization β Python pickle
# VULNERABLE: deserializing user-supplied pickle data
@app.route('/load', methods=['POST'])
def load_session():
data = request.get_data()
session = pickle.loads(data) # attacker controls __reduce__ β RCE
return jsonify(session)
# VULNERABLE: base64-encoded pickle from cookie
@app.route('/profile')
def profile():
session_cookie = request.cookies.get('session')
data = base64.b64decode(session_cookie)
user = pickle.loads(data) # crafted cookie β arbitrary code at deserialization
return render_template('profile.html', user=user)
# SECURE: use JSON (no code execution semantics)
@app.route('/profile')
def profile():
session_cookie = request.cookies.get('session')
user = json.loads(base64.b64decode(session_cookie))
return render_template('profile.html', user=user)
Unsafe Deserialization β Java
// VULNERABLE: ObjectInputStream.readObject() on user-supplied stream
@PostMapping("/deserialize")
public ResponseEntity<?> deserialize(@RequestBody byte[] data) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
Object obj = ois.readObject(); // gadget chains (Commons Collections, Spring, etc.) β RCE
return ResponseEntity.ok(obj);
}
// VULNERABLE: Jackson with enableDefaultTyping
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(); // attacker specifies arbitrary class type in JSON β RCE
MyData data = mapper.readValue(userJson, MyData.class);
// SECURE: Jackson with concrete type, no enableDefaultTyping
ObjectMapper mapper = new ObjectMapper();
MyData data = mapper.readValue(userJson, MyData.class); // safe with concrete target type
Unsafe Deserialization β PHP
// VULNERABLE: unserialize() with user input
function loadProfile() {
$data = base64_decode($_COOKIE['profile']);
$user = unserialize($data); // PHP object injection β POP chain β RCE
return $user;
}
// VULNERABLE: unserialize from POST body
$obj = unserialize($_POST['data']);
// SECURE: json_decode instead
function loadProfile() {
$data = base64_decode($_COOKIE['profile']);
$user = json_decode($data, true); // no code execution semantics
return $user;
}
Unsafe Deserialization β Ruby Marshal
# VULNERABLE: Marshal.load with user-supplied data
post '/restore' do
data = Base64.decode64(params[:state])
object = Marshal.load(data) # arbitrary Ruby object graph β RCE via gadgets
object.process
end
# SECURE: use JSON
post '/restore' do
data = JSON.parse(Base64.decode64(params[:state]))
# work with plain data structures only
end
Unsafe Deserialization β Node.js
// VULNERABLE: node-serialize (known RCE via IIFE in serialized string)
const serialize = require('node-serialize');
app.post('/restore', (req, res) => {
const obj = serialize.unserialize(req.body.data); // IIFE payload β RCE
res.json(obj);
});
// VULNERABLE: js-yaml v3 yaml.load (executes JS functions in YAML tags)
const yaml = require('js-yaml');
const data = yaml.load(userInput); // !!js/function payload β RCE
// SECURE: yaml.safeLoad (v3) or FAILSAFE_SCHEMA (v4)
const data = yaml.safeLoad(userInput); // only loads plain data types
Unsafe YAML β Python
# VULNERABLE: yaml.load without Loader
import yaml
data = yaml.load(user_input) # !!python/object/apply: payload β RCE
# SECURE: yaml.safe_load
data = yaml.safe_load(user_input) # only loads basic data types
Execution
This skill runs in three phases using subagents. Pass the contents of sast/architecture.md to all subagents as context.
Phase 1: Find Dangerous Execution Sinks
Launch a subagent with the following instructions:
Goal: Find every location in the codebase where OS commands are executed, code is dynamically evaluated, or data is deserialized using an unsafe deserializer. Flag ANY dynamic variable passed to these sinks, regardless of where it originates. Write results to
sast/rce-recon.md.Context: You will be given the project's architecture summary. Use it to understand the tech stack, language, frameworks, and any serialization patterns in use.
Category 1 β OS Command Execution Sinks
Look for functions that execute OS commands where the command string or arguments may be dynamically constructed. Flag when any non-constant variable appears in a dangerous position:
Python:
os.system(var)β always flag if any variableos.popen(var)β always flag if any variablesubprocess.run(var, shell=True),subprocess.call(var, shell=True),subprocess.Popen(var, shell=True),subprocess.check_output(var, shell=True)β flag ifshell=TrueAND a variable appears in the command string, OR if the command is a string (not a list) with any variablesubprocess.run(f"cmd {var}")withoutshell=Trueβ flag: passing a string (not list) to subprocess can still be unsafecommands.getoutput(var),commands.getstatusoutput(var)β always flagNode.js / JavaScript:
child_process.exec(var),child_process.execSync(var)β flag if any variable in command stringchild_process.execFile(var, ...)β flag if command or args contain variableschild_process.spawn(var, ...)orspawn(cmd, args)withshell: trueand variable in command β flagshelljs.exec(var),execa(var)β flag if variable in commandPHP:
exec(var),system(var),passthru(var),shell_exec(var),popen(var, ...),proc_open(var, ...)β flag if any variable in command string- Backtick operator:
`...{$var}...`or`$var`β always flagRuby:
system(var),exec(var),spawn(var),IO.popen(var),Open3.popen3(var)β flag if string form with interpolated variable- Backtick operator:
`...#{var}...`β always flag%x{...#{var}...}β always flagJava:
Runtime.getRuntime().exec(var)β flag if string argument contains variable concatenationnew ProcessBuilder(var)orProcessBuilderconstructed from variable-containing list β flagGo:
exec.Command(var, ...)β flag if command name or arguments are dynamically built from variables (especially from string splits of external input)C# / .NET:
Process.Start(var)β flag if FileName or Arguments are variableProcessStartInfo { FileName = var, Arguments = var }β flag
Category 2 β Code Evaluation Sinks
Look for functions that interpret strings as executable code:
Python:
eval(var)β flag if argument is a variableexec(var)β flag if argument is a variablecompile(var, ...)followed byexec()β flagimportlib.import_module(var),__import__(var)β flag if module name is a variableJavaScript / Node.js:
eval(var)β flag if argument is a variablenew Function(var),new Function('x', var)β flag if body is a variablesetTimeout(var, delay),setInterval(var, delay)β flag if first arg is a string variablevm.runInNewContext(var),vm.runInContext(var),vm.runInThisContext(var)β flag if variablerequire(var)β flag if module path is a variable (dynamic require with external input β path traversal + potential code execution)PHP:
eval(var)β always flag if variable in argumentpreg_replace(pattern, replacement, subject)with/emodifier in pattern β always flagassert(var)with string argument β flag if variablecreate_function('', var)β flag if body is variablecall_user_func(var),call_user_func_array(var, ...)β flag if function name is a variableRuby:
eval(var),instance_eval(var),class_eval(var),module_eval(var)β flag if variablebinding.eval(var)β flag if variable
Category 3 β Unsafe Deserialization Sinks
Look for deserialization of data that may originate externally. For deserialization sinks, flag every usage β the question of whether data is user-controlled is Phase 2's job:
Python:
pickle.loads(var),pickle.load(file_var)β flag always (pickle is inherently unsafe with untrusted data)marshal.loads(var),marshal.load(file_var)β flag alwaysyaml.load(var)without explicitLoader=yaml.SafeLoaderβ flag (any form without a safe loader)jsonpickle.decode(var)β flag alwaysshelveaccessed with externally-influenced keysJava:
ObjectInputStream.readObject(),ObjectInputStream.readUnshared()β flag alwaysXMLDecoder.readObject()β flag alwaysXStream.fromXML(var)β flag always (unless XStream security filters are explicitly configured)ObjectMapperwith.enableDefaultTyping()or.activateDefaultTyping(...)configured on it β flag the readValue callKryo.readObject(var, ...),Kryo.readClassAndObject(var)β flag if input stream comes from external sourcePHP:
unserialize(var)β flag always when argument is a variableRuby:
Marshal.load(var),Marshal.restore(var)β flag alwaysYAML.load(var)(Psych) withoutpermitted_classes: []β flagNode.js:
require('node-serialize').unserialize(var)β flag alwaysyaml.load(var)(js-yaml v3 default unsafe load) β flag.NET:
BinaryFormatter.Deserialize(var)β flag alwaysSoapFormatter.Deserialize(var)β flag alwaysNetDataContractSerializer.ReadObject(var)β flagJavaScriptSerializer.Deserialize(var)β flag if argument is variableLosFormatter.Deserialize(var)β flag always
What to skip (these are safe and should not be flagged):
subprocess.run(["cmd", arg1, arg2])with a list and noshell=Trueβ no shell expansionjson.loads(var),JSON.parse(var),json_decode(var)β safe format with no code executionyaml.safe_load(var)oryaml.load(var, Loader=yaml.SafeLoader)β safe loaderast.literal_eval(var)β only parses Python literals, not arbitrary code
Output format β write to
sast/rce-recon.md:# RCE Recon: [Project Name] ## Summary Found [N] potential RCE sinks: [X] OS command, [Y] code injection, [Z] unsafe deserialization. ## Sinks Found ### 1. [Descriptive name β e.g., "shell=True subprocess in image converter"] - **File**: `path/to/file.ext` (lines X-Y) - **Function / endpoint**: [function name or route] - **Category**: [OS Command Injection / Code Injection / Unsafe Deserialization] - **Sink**: [the dangerous function call β e.g., subprocess.run(..., shell=True)] - **Dynamic argument(s)**: `var_name` β [brief note on what it appears to represent] - **Code snippet**:[the relevant code around the sink]
[Repeat for each sink]
After Phase 1: Check for Candidates Before Proceeding
After Phase 1 completes, read sast/rce-recon.md. If the recon found zero sinks (the summary reports "Found 0" or the "Sinks Found" section is empty or absent), skip Phase 2 and Phase 3 entirely. Instead, write the following content to sast/rce-results.md, delete sast/rce-recon.md, and stop:
# RCE Analysis Results
No vulnerabilities found.
Only proceed to Phase 2 if Phase 1 found at least one potential sink.