Exploit database

GH-9b0f86f20f987faf13d8eab8040be7a0

zemarkhos/cve-2025-55182-exploit-poc-scanner

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-55182

257 sources

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

Repository files3
zemarkhos/cve-2025-55182-exploit-poc-scannerRevision c89e3d841d9d

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

rsc-crawler.py

Python · 27,377 bytes
#!/usr/bin/env python3
"""
CVE-2025-55182 - RSC Crawler & Endpoint Discovery Tool
=======================================================
React Server Components (RSC) / Flight protokolü keşif aracı.
Domain'leri tarayarak potansiyel savunmasız endpoint'leri tespit eder.

Usage:
    python3 rsc-crawler.py -d https://target.com
    python3 rsc-crawler.py -l domains.txt -p http://192.168.50.253:8080
    python3 rsc-crawler.py -l domains.txt --export-endpoints endpoints.txt
"""

import argparse
import requests
import json
import re
import sys
import time
import concurrent.futures
from datetime import datetime
from urllib.parse import urlparse, urljoin, urldefrag
from collections import deque

try:
    from bs4 import BeautifulSoup
    BS4_AVAILABLE = True
except ImportError:
    BS4_AVAILABLE = False
    print("[!] beautifulsoup4 yüklü değil. Yükleme: pip install beautifulsoup4 lxml")


# Renk kodları
class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    RESET = '\033[0m'
    BOLD = '\033[1m'


# RSC/Flight protokol pattern'leri
RSC_PATTERNS = {
    'action_ref': re.compile(r'\$ACTION_REF_\d+', re.IGNORECASE),
    'action_id': re.compile(r'\$ACTION_ID_[a-f0-9]+', re.IGNORECASE),
    'action_bound': re.compile(r'\$ACTION_\d+:\d+'),
    'server_reference': re.compile(r'["\'][a-f0-9]{32,}["\']'),  # Server Action hash
    'flight_protocol': re.compile(r'text/x-component'),
    'rsc_param': re.compile(r'[?&]_rsc='),
    'webpack_require': re.compile(r'__webpack_require__'),
    'decode_action': re.compile(r'decodeAction|loadServerReference|decodeReply'),
    'server_manifest': re.compile(r'serverManifest|serverModuleMap'),
    'react_server_dom': re.compile(r'react-server-dom-webpack|react-server-dom-turbopack'),
    'dangerous_modules': re.compile(r'(child_process|vm|fs)#\w+'),
    'next_api': re.compile(r'["\']\/api\/[a-zA-Z0-9_\/-]+["\']'),
    'form_action': re.compile(r'formaction\s*=\s*["\']([^"\']+)["\']', re.IGNORECASE),
    'action_attr': re.compile(r'action\s*=\s*["\']([^"\']+)["\']', re.IGNORECASE),
    'fetch_post': re.compile(r'fetch\s*\(\s*["\']([^"\']+)["\'].*?method\s*:\s*["\']POST["\']', re.IGNORECASE | re.DOTALL),
    'use_server': re.compile(r'["\']use server["\']'),
    'server_actions': re.compile(r'createServerReference|registerServerReference'),
}

# Next.js ve React tespiti için pattern'ler
NEXTJS_PATTERNS = {
    'next_data': re.compile(r'__NEXT_DATA__'),
    'next_script': re.compile(r'/_next/static'),
    'next_image': re.compile(r'/_next/image'),
    'next_version': re.compile(r'Next\.js\s*([\d.]+)'),
    'react_version': re.compile(r'react@([\d.]+)'),
    'app_router': re.compile(r'/_next/static/chunks/app/'),
}


def banner():
    print(f"""{Colors.CYAN}
    ╔═══════════════════════════════════════════════════════════╗
    ║  {Colors.BOLD}CVE-2025-55182 - RSC Crawler & Endpoint Discovery{Colors.CYAN}       ║
    ║  React Server Components Vulnerability Scanner            ║
    ╠═══════════════════════════════════════════════════════════╣
    ║  {Colors.YELLOW}Finds: Server Actions, Flight Protocol, API Endpoints{Colors.CYAN}   ║
    ║  {Colors.GREEN}Output: JSON report + endpoints.txt for exploit{Colors.CYAN}         ║
    ╚═══════════════════════════════════════════════════════════╝
    {Colors.RESET}""")


class JSAnalyzer:
    """JavaScript dosyalarını analiz eder ve RSC işaretlerini bulur"""

    def __init__(self, verbose=False):
        self.verbose = verbose
        self.findings = {
            'rsc_indicators': [],
            'server_actions': [],
            'api_endpoints': [],
            'dangerous_modules': [],
            'versions': {}
        }

    def analyze(self, js_content, source_url=""):
        """JS içeriğini analiz et"""
        results = {
            'source': source_url,
            'rsc_indicators': [],
            'endpoints': [],
            'dangerous_modules': [],
            'is_rsc': False
        }

        # RSC pattern'lerini ara
        for name, pattern in RSC_PATTERNS.items():
            matches = pattern.findall(js_content)
            if matches:
                results['rsc_indicators'].append({
                    'type': name,
                    'count': len(matches),
                    'samples': matches[:5]  # İlk 5 örnek
                })
                if name in ['action_ref', 'action_id', 'decode_action', 'react_server_dom', 'use_server']:
                    results['is_rsc'] = True

        # API endpoint'lerini bul
        api_matches = RSC_PATTERNS['next_api'].findall(js_content)
        for match in api_matches:
            endpoint = match.strip('"\'')
            if endpoint not in results['endpoints']:
                results['endpoints'].append(endpoint)

        # fetch POST endpoint'lerini bul
        fetch_matches = RSC_PATTERNS['fetch_post'].findall(js_content)
        for match in fetch_matches:
            if match not in results['endpoints']:
                results['endpoints'].append(match)

        # Tehlikeli modülleri bul
        dangerous = RSC_PATTERNS['dangerous_modules'].findall(js_content)
        results['dangerous_modules'] = list(set(dangerous))

        return results

    def analyze_html_for_js(self, html_content, base_url):
        """HTML içindeki inline JS'leri analiz et"""
        if not BS4_AVAILABLE:
            return []

        soup = BeautifulSoup(html_content, 'lxml')
        results = []

        # Inline script'leri analiz et
        for script in soup.find_all('script'):
            if script.string:
                result = self.analyze(script.string, f"{base_url} (inline)")
                if result['rsc_indicators'] or result['endpoints']:
                    results.append(result)

        return results


class EndpointDiscovery:
    """HTML ve JS'lerden endpoint'leri keşfeder"""

    def __init__(self):
        self.endpoints = set()
        self.forms = []

    def discover_from_html(self, html_content, base_url):
        """HTML'den endpoint'leri bul"""
        if not BS4_AVAILABLE:
            return []

        soup = BeautifulSoup(html_content, 'lxml')
        discovered = []

        # Form action'ları
        for form in soup.find_all('form'):
            action = form.get('action', '')
            method = form.get('method', 'GET').upper()
            if action:
                full_url = urljoin(base_url, action)
                discovered.append({
                    'url': full_url,
                    'type': 'form_action',
                    'method': method
                })

        # formaction attribute'ları
        for elem in soup.find_all(attrs={'formaction': True}):
            action = elem.get('formaction')
            if action:
                full_url = urljoin(base_url, action)
                discovered.append({
                    'url': full_url,
                    'type': 'formaction',
                    'method': 'POST'
                })

        # data-action attribute'ları (bazı framework'ler kullanır)
        for elem in soup.find_all(attrs={'data-action': True}):
            action = elem.get('data-action')
            if action and action.startswith('/'):
                full_url = urljoin(base_url, action)
                discovered.append({
                    'url': full_url,
                    'type': 'data_action',
                    'method': 'POST'
                })

        return discovered

    def discover_from_js(self, js_content, base_url):
        """JS'den endpoint'leri bul"""
        discovered = []

        # API route pattern'leri
        api_pattern = re.compile(r'["\'](\/?api\/[a-zA-Z0-9_\/-]+)["\']')
        for match in api_pattern.findall(js_content):
            endpoint = match if match.startswith('/') else '/' + match
            full_url = urljoin(base_url, endpoint)
            discovered.append({
                'url': full_url,
                'type': 'api_route',
                'method': 'POST'  # Assume POST for Server Actions
            })

        # fetch/axios URL'leri
        fetch_pattern = re.compile(r'(?:fetch|axios)\s*[.(]\s*["\']([^"\']+)["\']')
        for match in fetch_pattern.findall(js_content):
            if match.startswith('/') or match.startswith('http'):
                full_url = urljoin(base_url, match) if match.startswith('/') else match
                discovered.append({
                    'url': full_url,
                    'type': 'fetch_call',
                    'method': 'UNKNOWN'
                })

        return discovered


class RSCCrawler:
    """Ana crawler sınıfı"""

    def __init__(self, proxy=None, cookies=None, headers=None, timeout=10,
                 delay=0.5, max_pages=200, depth=5, include_external=True,
                 verbose=False, threads=5):
        self.proxy = proxy
        self.cookies = cookies
        self.headers = headers or {}
        self.timeout = timeout
        self.delay = delay
        self.max_pages = max_pages
        self.depth = depth
        self.include_external = include_external
        self.verbose = verbose
        self.threads = threads

        self.session = requests.Session()
        self.session.verify = False

        # Proxy ayarla
        if proxy:
            self.session.proxies = {'http': proxy, 'https': proxy}

        # Cookie'leri ayarla
        if cookies:
            for cookie in cookies.split(';'):
                if '=' in cookie:
                    key, value = cookie.strip().split('=', 1)
                    self.session.cookies.set(key.strip(), value.strip())

        # Header'ları ayarla
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
        })
        if headers:
            for header in headers:
                if ':' in header:
                    key, value = header.split(':', 1)
                    self.session.headers[key.strip()] = value.strip()

        # Analiz araçları
        self.js_analyzer = JSAnalyzer(verbose)
        self.endpoint_discovery = EndpointDiscovery()

        # Sonuçlar
        self.visited = set()
        self.js_files = set()
        self.results = {
            'domain': '',
            'scan_time': '',
            'is_nextjs': False,
            'is_rsc': False,
            'pages_crawled': 0,
            'js_files_analyzed': 0,
            'findings': {
                'rsc_indicators': [],
                'endpoints': [],
                'dangerous_modules': [],
                'forms': []
            },
            'potential_targets': []
        }

    def fetch(self, url):
        """URL'yi fetch et"""
        try:
            response = self.session.get(url, timeout=self.timeout)
            return response
        except Exception as e:
            if self.verbose:
                print(f"{Colors.RED}[!] Fetch hatası: {url} - {e}{Colors.RESET}")
            return None

    def fetch_js(self, url):
        """JS dosyasını indir"""
        try:
            response = self.session.get(url, timeout=self.timeout)
            if response.status_code == 200:
                return response.text
        except Exception as e:
            if self.verbose:
                print(f"{Colors.RED}[!] JS fetch hatası: {url} - {e}{Colors.RESET}")
        return None

    def extract_links(self, html, base_url):
        """HTML'den linkleri çıkar"""
        if not BS4_AVAILABLE:
            return []

        links = []
        soup = BeautifulSoup(html, 'lxml')

        # href linkleri
        for a in soup.find_all('a', href=True):
            href = a['href']
            full_url = urljoin(base_url, href)
            full_url = urldefrag(full_url)[0]  # Fragment'ı kaldır
            links.append(full_url)

        return links

    def extract_js_urls(self, html, base_url):
        """HTML'den JS URL'lerini çıkar"""
        if not BS4_AVAILABLE:
            return []

        js_urls = []
        soup = BeautifulSoup(html, 'lxml')

        for script in soup.find_all('script', src=True):
            src = script['src']
            full_url = urljoin(base_url, src)

            # Harici JS kontrolü
            parsed_base = urlparse(base_url)
            parsed_src = urlparse(full_url)

            if self.include_external or parsed_base.netloc == parsed_src.netloc:
                js_urls.append(full_url)

        return js_urls

    def check_nextjs(self, html, headers):
        """Next.js kullanımını kontrol et"""
        # Header kontrolü
        if 'x-powered-by' in headers:
            if 'next.js' in headers['x-powered-by'].lower():
                return True

        # HTML içerik kontrolü
        if NEXTJS_PATTERNS['next_data'].search(html):
            return True
        if NEXTJS_PATTERNS['next_script'].search(html):
            return True
        if NEXTJS_PATTERNS['app_router'].search(html):
            return True

        return False

    def crawl_domain(self, domain):
        """Tek domain'i tara"""
        # URL formatını düzelt
        if not domain.startswith(('http://', 'https://')):
            domain = 'https://' + domain

        parsed = urlparse(domain)
        base_domain = f"{parsed.scheme}://{parsed.netloc}"

        self.results['domain'] = parsed.netloc
        self.results['scan_time'] = datetime.now().isoformat()

        print(f"\n{Colors.CYAN}[*] Taranıyor: {base_domain}{Colors.RESET}")

        # BFS ile crawling
        queue = deque([(domain, 0)])  # (url, depth)
        self.visited.add(domain)

        while queue and len(self.visited) < self.max_pages:
            current_url, current_depth = queue.popleft()

            if current_depth > self.depth:
                continue

            if self.verbose:
                print(f"{Colors.BLUE}[.] Sayfa: {current_url} (derinlik: {current_depth}){Colors.RESET}")

            response = self.fetch(current_url)
            if not response:
                continue

            self.results['pages_crawled'] += 1
            html = response.text
            headers = {k.lower(): v for k, v in response.headers.items()}

            # Next.js kontrolü
            if not self.results['is_nextjs']:
                self.results['is_nextjs'] = self.check_nextjs(html, headers)
                if self.results['is_nextjs']:
                    print(f"{Colors.GREEN}[+] Next.js tespit edildi!{Colors.RESET}")

            # Inline JS analizi
            inline_results = self.js_analyzer.analyze_html_for_js(html, current_url)
            for result in inline_results:
                if result['is_rsc']:
                    self.results['is_rsc'] = True
                    print(f"{Colors.GREEN}[+] RSC işareti bulundu: {current_url}{Colors.RESET}")
                self.results['findings']['rsc_indicators'].extend(result['rsc_indicators'])
                for ep in result['endpoints']:
                    full_ep = urljoin(base_domain, ep)
                    if full_ep not in self.results['findings']['endpoints']:
                        self.results['findings']['endpoints'].append(full_ep)

            # HTML'den endpoint keşfi
            html_endpoints = self.endpoint_discovery.discover_from_html(html, current_url)
            for ep in html_endpoints:
                if ep['url'] not in [e['url'] for e in self.results['findings']['forms']]:
                    self.results['findings']['forms'].append(ep)

            # JS URL'lerini topla
            js_urls = self.extract_js_urls(html, current_url)
            for js_url in js_urls:
                if js_url not in self.js_files:
                    self.js_files.add(js_url)

            # Linkleri queue'ya ekle
            if current_depth < self.depth:
                links = self.extract_links(html, current_url)
                for link in links:
                    parsed_link = urlparse(link)
                    # Aynı domain'de kal
                    if parsed_link.netloc == parsed.netloc and link not in self.visited:
                        self.visited.add(link)
                        queue.append((link, current_depth + 1))

            time.sleep(self.delay)

        # JS dosyalarını analiz et
        print(f"\n{Colors.CYAN}[*] JS dosyaları analiz ediliyor ({len(self.js_files)} dosya)...{Colors.RESET}")
        self.analyze_js_files(base_domain)

        # Potansiyel hedefleri derle
        self.compile_targets(base_domain)

        return self.results

    def analyze_js_files(self, base_domain):
        """Toplanan JS dosyalarını analiz et"""
        for js_url in self.js_files:
            if self.verbose:
                print(f"{Colors.BLUE}[.] JS: {js_url}{Colors.RESET}")

            js_content = self.fetch_js(js_url)
            if not js_content:
                continue

            self.results['js_files_analyzed'] += 1

            # JS analizi
            result = self.js_analyzer.analyze(js_content, js_url)

            if result['is_rsc']:
                self.results['is_rsc'] = True
                print(f"{Colors.GREEN}[+] RSC JS bulundu: {js_url}{Colors.RESET}")

            # Sonuçları ekle
            self.results['findings']['rsc_indicators'].extend(result['rsc_indicators'])
            self.results['findings']['dangerous_modules'].extend(result['dangerous_modules'])

            for ep in result['endpoints']:
                full_ep = urljoin(base_domain, ep)
                if full_ep not in self.results['findings']['endpoints']:
                    self.results['findings']['endpoints'].append(full_ep)

            # JS'den endpoint keşfi
            js_endpoints = self.endpoint_discovery.discover_from_js(js_content, base_domain)
            for ep in js_endpoints:
                if ep['url'] not in self.results['findings']['endpoints']:
                    self.results['findings']['endpoints'].append(ep['url'])

            time.sleep(self.delay / 2)

    def compile_targets(self, base_domain):
        """Potansiyel exploit hedeflerini derle"""
        targets = set()

        # Form action'ları
        for form in self.results['findings']['forms']:
            if form['method'] == 'POST':
                targets.add(form['url'])

        # API endpoint'leri
        for ep in self.results['findings']['endpoints']:
            if '/api/' in ep:
                targets.add(ep)

        # RSC bulunduysa, ana domain'i de ekle
        if self.results['is_rsc']:
            targets.add(base_domain)
            targets.add(f"{base_domain}/")

        self.results['potential_targets'] = sorted(list(targets))


class ReportGenerator:
    """Rapor oluşturma sınıfı"""

    @staticmethod
    def generate_json(results, output_file):
        """JSON rapor oluştur"""
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=2, ensure_ascii=False)
        print(f"{Colors.GREEN}[+] JSON rapor kaydedildi: {output_file}{Colors.RESET}")

    @staticmethod
    def generate_endpoints(results_list, output_file):
        """Exploit için endpoint listesi oluştur"""
        all_targets = set()

        for results in results_list:
            for target in results.get('potential_targets', []):
                all_targets.add(target)

        with open(output_file, 'w') as f:
            for target in sorted(all_targets):
                f.write(target + '\n')

        print(f"{Colors.GREEN}[+] Endpoint listesi kaydedildi: {output_file} ({len(all_targets)} endpoint){Colors.RESET}")

    @staticmethod
    def print_summary(results):
        """Özet yazdır"""
        print(f"\n{Colors.CYAN}{'='*60}{Colors.RESET}")
        print(f"{Colors.BOLD}{Colors.YELLOW}[*] Tarama Özeti: {results['domain']}{Colors.RESET}")
        print(f"{Colors.CYAN}{'='*60}{Colors.RESET}")

        print(f"{Colors.BLUE}[*] Taranan sayfa: {results['pages_crawled']}{Colors.RESET}")
        print(f"{Colors.BLUE}[*] Analiz edilen JS: {results['js_files_analyzed']}{Colors.RESET}")

        if results['is_nextjs']:
            print(f"{Colors.GREEN}[+] Next.js: EVET{Colors.RESET}")
        else:
            print(f"{Colors.YELLOW}[-] Next.js: HAYIR{Colors.RESET}")

        if results['is_rsc']:
            print(f"{Colors.GREEN}[+] RSC/Server Actions: EVET - POTANSIYEL HEDEF!{Colors.RESET}")
        else:
            print(f"{Colors.YELLOW}[-] RSC/Server Actions: Bulunamadı{Colors.RESET}")

        print(f"\n{Colors.BLUE}[*] Bulunan endpoint sayısı: {len(results['findings']['endpoints'])}{Colors.RESET}")
        print(f"{Colors.BLUE}[*] Bulunan form sayısı: {len(results['findings']['forms'])}{Colors.RESET}")

        if results['findings']['dangerous_modules']:
            print(f"{Colors.RED}[!] Tehlikeli modüller: {', '.join(set(results['findings']['dangerous_modules']))}{Colors.RESET}")

        if results['potential_targets']:
            print(f"\n{Colors.GREEN}[+] Potansiyel hedefler:{Colors.RESET}")
            for target in results['potential_targets'][:10]:
                print(f"    {target}")
            if len(results['potential_targets']) > 10:
                print(f"    ... ve {len(results['potential_targets']) - 10} daha")


def load_domains(filepath):
    """Dosyadan domain listesi yükle"""
    domains = []
    try:
        with open(filepath, 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    domains.append(line)
    except FileNotFoundError:
        print(f"{Colors.RED}[!] Dosya bulunamadı: {filepath}{Colors.RESET}")
        sys.exit(1)
    return domains


def main():
    parser = argparse.ArgumentParser(
        description='CVE-2025-55182 - RSC Crawler & Endpoint Discovery',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Örnekler:
  %(prog)s -d https://target.com
  %(prog)s -l domains.txt -p http://192.168.50.253:8080
  %(prog)s -d https://target.com -o results.json --export-endpoints endpoints.txt
        """
    )

    # Hedef
    target_group = parser.add_mutually_exclusive_group(required=True)
    target_group.add_argument('-d', '--domain', help='Tek domain tara')
    target_group.add_argument('-l', '--list', dest='domain_list', help='Domain listesi dosyası')

    # Crawling
    parser.add_argument('--depth', type=int, default=5, help='Crawl derinliği (varsayılan: 5)')
    parser.add_argument('--max-pages', type=int, default=200, help='Maksimum sayfa (varsayılan: 200)')
    parser.add_argument('--timeout', type=int, default=10, help='İstek timeout (varsayılan: 10)')
    parser.add_argument('--delay', type=float, default=0.5, help='İstekler arası bekleme (varsayılan: 0.5)')

    # Bağlantı
    parser.add_argument('-p', '--proxy', help='Proxy URL')
    parser.add_argument('-c', '--cookies', help='Cookie string')
    parser.add_argument('-H', '--header', action='append', help='Ekstra header')
    parser.add_argument('-t', '--threads', type=int, default=5, help='Thread sayısı (varsayılan: 5)')

    # Analiz
    parser.add_argument('--no-external', action='store_true', help='Harici JS analiz etme')

    # Çıktı
    parser.add_argument('-o', '--output', help='JSON sonuç dosyası')
    parser.add_argument('--export-endpoints', help='Endpoint listesi dosyası')
    parser.add_argument('-v', '--verbose', action='store_true', help='Detaylı çıktı')
    parser.add_argument('-q', '--quiet', action='store_true', help='Sessiz mod')

    args = parser.parse_args()

    if not BS4_AVAILABLE:
        print(f"{Colors.RED}[!] beautifulsoup4 gerekli. Yükleyin: pip install beautifulsoup4 lxml{Colors.RESET}")
        sys.exit(1)

    # SSL uyarılarını kapat
    requests.packages.urllib3.disable_warnings()

    if not args.quiet:
        banner()

    # Domain listesini hazırla
    if args.domain_list:
        domains = load_domains(args.domain_list)
        print(f"{Colors.BLUE}[*] {len(domains)} domain yüklenecek{Colors.RESET}")
    else:
        domains = [args.domain]

    # Crawler oluştur
    crawler = RSCCrawler(
        proxy=args.proxy,
        cookies=args.cookies,
        headers=args.header,
        timeout=args.timeout,
        delay=args.delay,
        max_pages=args.max_pages,
        depth=args.depth,
        include_external=not args.no_external,
        verbose=args.verbose,
        threads=args.threads
    )

    # Tüm sonuçlar
    all_results = []

    # Domain'leri tara
    for domain in domains:
        try:
            results = crawler.crawl_domain(domain)
            all_results.append(results)

            if not args.quiet:
                ReportGenerator.print_summary(results)

            # Her domain için crawler'ı sıfırla
            crawler.visited.clear()
            crawler.js_files.clear()
            crawler.results = {
                'domain': '',
                'scan_time': '',
                'is_nextjs': False,
                'is_rsc': False,
                'pages_crawled': 0,
                'js_files_analyzed': 0,
                'findings': {
                    'rsc_indicators': [],
                    'endpoints': [],
                    'dangerous_modules': [],
                    'forms': []
                },
                'potential_targets': []
            }

        except KeyboardInterrupt:
            print(f"\n{Colors.YELLOW}[*] Tarama durduruldu.{Colors.RESET}")
            break
        except Exception as e:
            print(f"{Colors.RED}[!] Hata ({domain}): {e}{Colors.RESET}")
            continue

    # Sonuçları kaydet
    if args.output:
        if len(all_results) == 1:
            ReportGenerator.generate_json(all_results[0], args.output)
        else:
            ReportGenerator.generate_json(all_results, args.output)

    if args.export_endpoints:
        ReportGenerator.generate_endpoints(all_results, args.export_endpoints)

    # Özet
    total_targets = sum(len(r.get('potential_targets', [])) for r in all_results)
    rsc_count = sum(1 for r in all_results if r.get('is_rsc'))

    print(f"\n{Colors.CYAN}{'='*60}{Colors.RESET}")
    print(f"{Colors.BOLD}{Colors.YELLOW}[*] Genel Özet{Colors.RESET}")
    print(f"{Colors.CYAN}{'='*60}{Colors.RESET}")
    print(f"{Colors.BLUE}[*] Taranan domain: {len(all_results)}{Colors.RESET}")
    print(f"{Colors.GREEN}[+] RSC bulunan: {rsc_count}{Colors.RESET}")
    print(f"{Colors.GREEN}[+] Toplam potansiyel hedef: {total_targets}{Colors.RESET}")

    if args.export_endpoints:
        print(f"\n{Colors.YELLOW}[*] Exploit için:{Colors.RESET}")
        print(f"    python3 exploit-custom.py -l {args.export_endpoints} --check")


if __name__ == '__main__':
    main()