Buckets:

download
raw
19.4 kB
"""OWASP ZAP Integration Examples
This file demonstrates how to use the complete ZAP integration:
- Basic scanning
- Authenticated scanning
- API scanning
- Automation workflows
- Compliance checking
- CI/CD integration
Author: Zen-AI-Pentest Team
License: MIT
"""
import asyncio
# =============================================================================
# Example 1: Basic ZAP Scan
# =============================================================================
async def example_basic_scan():
"""
Example: Run a basic ZAP scan against a target.
This demonstrates the simplest way to scan a target.
"""
from tools.zap_integration_enhanced import ZAPClient
print("=" * 60)
print("Example 1: Basic ZAP Scan")
print("=" * 60)
# Create ZAP client
async with ZAPClient(
zap_url="http://localhost:8080",
api_key=None, # Set your API key if required
) as client:
# Check connection
if not await client.check_connection():
print("❌ Cannot connect to ZAP. Make sure ZAP is running.")
return
print(f"✅ Connected to ZAP version {client._version}")
# Run spider scan
print("\n🕷️ Starting spider scan...")
scan_id = await client.spider_scan(
target="http://testphp.vulnweb.com",
max_depth=3,
progress_callback=lambda p: print(f" Spider progress: {p}%"),
)
print(f"✅ Spider scan completed: {scan_id}")
# Run active scan
print("\n🎯 Starting active scan...")
active_id = await client.active_scan(
target="http://testphp.vulnweb.com",
scan_policy="Default",
progress_callback=lambda p: print(f" Active scan progress: {p}%"),
)
print(f"✅ Active scan completed: {active_id}")
# Get alerts
print("\n📊 Getting alerts...")
alerts = await client.get_alerts()
print(f"Found {len(alerts)} alerts:")
for alert in alerts[:5]: # Show first 5
print(f" [{alert.risk}] {alert.name}")
print(f" URL: {alert.url}")
print(f" Description: {alert.description[:100]}...")
print()
# =============================================================================
# Example 2: Authenticated Scan
# =============================================================================
async def example_authenticated_scan():
"""
Example: Run an authenticated ZAP scan.
Demonstrates different authentication methods:
- Form-based authentication
- JWT Bearer token
- API Key
- Basic Auth
- OAuth2
"""
from tools.zap_integration_enhanced import ZAPAutomation
print("=" * 60)
print("Example 2: Authenticated ZAP Scan")
print("=" * 60)
async with ZAPAutomation(
zap_url="http://localhost:8080",
api_key=None,
) as automation:
# Example 2a: Form-based authentication
print("\n🔐 Form-based Authentication")
form_auth = {
"type": "form",
"login_url": "http://testphp.vulnweb.com/login.php",
"username_field": "username",
"password_field": "password",
"username": "test",
"password": "test",
}
result = await automation.full_scan(
target="http://testphp.vulnweb.com",
auth=form_auth,
policy="Default",
progress_callback=lambda u: print(f" Phase: {u.get('phase')}, Progress: {u.get('progress')}%"),
)
if result.success:
print(f"✅ Scan completed with {len(result.alerts)} findings")
else:
print(f"❌ Scan failed: {result.error}")
# Example 2b: JWT Authentication
print("\n🔑 JWT Bearer Token Authentication")
# Example 2c: API Key Authentication
print("\n🔑 API Key Authentication")
# Example 2d: Basic Authentication
print("\n🔑 Basic HTTP Authentication")
# Example 2e: OAuth2 Authentication
print("\n🔑 OAuth2 Authentication")
# =============================================================================
# Example 3: API Scanning with OpenAPI
# =============================================================================
async def example_api_scan():
"""
Example: Scan a REST API using ZAP.
Demonstrates API-specific scanning with OpenAPI import.
"""
from modules.zap_automation import create_automation_manager
print("=" * 60)
print("Example 3: API Scanning")
print("=" * 60)
manager = create_automation_manager(
zap_url="http://localhost:8080",
)
# Run API scan with OpenAPI spec
print("\n🌐 Scanning API with OpenAPI spec...")
result = await manager.run_api_scan(
target="https://api.example.com",
openapi_url="https://api.example.com/openapi.json",
auth={
"type": "api_key",
"api_key": "your-api-key",
},
)
if result["status"] == "completed":
print("✅ API scan completed")
findings = result.get("findings", {})
print(f" Total findings: {findings.get('total', 0)}")
print(f" Risk counts: {findings.get('risk_counts', {})}")
else:
print(f"❌ API scan failed: {result.get('error')}")
# =============================================================================
# Example 4: Full Automation with Compliance
# =============================================================================
async def example_automation_with_compliance():
"""
Example: Run automated scan with compliance checking.
Demonstrates full automation with OWASP Top 10 and PCI DSS compliance.
"""
from modules.zap_automation import (
ComplianceStandard,
create_automation_manager,
)
print("=" * 60)
print("Example 4: Automation with Compliance")
print("=" * 60)
manager = create_automation_manager(
zap_url="http://localhost:8080",
)
print("\n🔍 Running automated security scan with compliance checks...")
result = await manager.run_automated_scan(
target="http://testphp.vulnweb.com",
policy="Full Policy",
compliance_standards=[
ComplianceStandard.OWASP_TOP_10,
ComplianceStandard.PCI_DSS,
],
notify_callback=lambda n: print(f" 📢 Notification: {n.get('type')}"),
progress_callback=lambda u: print(f" ⏳ {u.get('phase')}: {u.get('progress')}%"),
)
print("\n📊 Results:")
print(f" Status: {result['status']}")
print(f" Scan ID: {result['scan_id']}")
if result["status"] == "completed":
findings = result.get("findings", {})
print(f" Total findings: {findings.get('total', 0)}")
# Compliance results
if result.get("compliance"):
print("\n✅ Compliance Results:")
for std, comp_result in result["compliance"].items():
status = "✅ PASS" if comp_result["passed"] else "❌ FAIL"
print(f" {std}: {status} ({comp_result['score']:.1f}%)")
print(f" Requirements met: {len(comp_result['requirements_met'])}")
print(f" Requirements failed: {len(comp_result['requirements_failed'])}")
# Trend analysis
if result.get("trend"):
trend = result["trend"]
print("\n📈 Trend Analysis:")
print(f" Total: {trend['total']}")
print(f" High: {trend['high']}")
print(f" New findings: {trend['new_findings']}")
print(f" Resolved: {trend['resolved_findings']}")
# =============================================================================
# Example 5: Scheduled Scanning
# =============================================================================
async def example_scheduled_scanning():
"""
Example: Schedule recurring security scans.
Demonstrates how to set up weekly automated scans.
"""
from modules.zap_automation import (
ScanSchedule,
create_automation_manager,
)
print("=" * 60)
print("Example 5: Scheduled Scanning")
print("=" * 60)
manager = create_automation_manager(
zap_url="http://localhost:8080",
)
# Schedule weekly scan
print("\n📅 Scheduling weekly scan...")
schedule_id = manager.schedule_scan(
target="http://testphp.vulnweb.com",
frequency=ScanSchedule.WEEKLY,
policy="Default",
auth={
"type": "form",
"login_url": "http://testphp.vulnweb.com/login.php",
"username": "test",
"password": "test",
},
)
print(f"✅ Scan scheduled with ID: {schedule_id}")
print(f" Next run: {manager._schedules[schedule_id].next_run}")
# Run any due scheduled scans
print("\n🔄 Running scheduled scans...")
results = await manager.run_scheduled_scans()
print(f" Ran {len(results)} scheduled scans")
# =============================================================================
# Example 6: Trend Analysis
# =============================================================================
async def example_trend_analysis():
"""
Example: Analyze vulnerability trends over time.
Demonstrates tracking vulnerability trends for a target.
"""
from modules.zap_automation import create_automation_manager
print("=" * 60)
print("Example 6: Trend Analysis")
print("=" * 60)
manager = create_automation_manager(
zap_url="http://localhost:8080",
)
# Run multiple scans to build trend data
target = "http://testphp.vulnweb.com"
print("\n🔍 Running scans to build trend data...")
for i in range(3):
print(f" Scan {i + 1}...")
await manager.run_automated_scan(
target=target,
policy="Default",
)
# Get trend report
print("\n📊 Trend Report (Last 30 days):")
trend_report = manager.get_trend_report(target, days=30)
if "error" not in trend_report:
print(f" Data points: {trend_report['data_points']}")
print(f" Current findings: {trend_report['current']['total']}")
print(f" Average findings: {trend_report['average']['total']:.1f}")
print("\n Trend data:")
for point in trend_report["trend"][-3:]: # Show last 3
print(f" {point['timestamp']}: {point['total']} total, {point['high']} high")
else:
print(f" Error: {trend_report['error']}")
# =============================================================================
# Example 7: CI/CD Integration
# =============================================================================
def example_cicd_integration():
"""
Example: Generate CI/CD configuration for ZAP scanning.
Demonstrates generating configurations for GitHub Actions, GitLab CI, and Jenkins.
"""
from modules.zap_automation import create_automation_manager
print("=" * 60)
print("Example 7: CI/CD Integration")
print("=" * 60)
manager = create_automation_manager()
target = "http://testphp.vulnweb.com"
# Generate GitHub Actions workflow
print("\n🐙 GitHub Actions Configuration:")
github_config = manager.generate_cicd_config(
target=target,
format="github_actions",
fail_on_high=True,
fail_threshold=0,
)
print(github_config[:1000] + "...")
# Generate GitLab CI configuration
print("\n🦊 GitLab CI Configuration:")
gitlab_config = manager.generate_cicd_config(
target=target,
format="gitlab_ci",
fail_on_high=True,
)
print(gitlab_config[:1000] + "...")
# Generate Jenkinsfile
print("\n🔧 Jenkins Configuration:")
jenkins_config = manager.generate_cicd_config(
target=target,
format="jenkins",
fail_on_high=True,
)
print(jenkins_config[:1000] + "...")
# =============================================================================
# Example 8: Using the API Endpoints
# =============================================================================
def example_api_endpoints():
"""
Example: Using the REST API endpoints.
Demonstrates how to interact with the ZAP API endpoints.
"""
print("=" * 60)
print("Example 8: API Endpoints Usage")
print("=" * 60)
examples = """
# Check ZAP Status
GET /api/v1/tools/zap/status
# Start a Full Scan
POST /api/v1/tools/zap/scan
{
"target": "http://testphp.vulnweb.com",
"policy": "Default",
"spider": true,
"activeScan": true,
"auth": {
"type": "form",
"loginUrl": "http://testphp.vulnweb.com/login.php",
"usernameField": "username",
"passwordField": "password",
"username": "test",
"password": "test"
}
}
# Get Scan Status
GET /api/v1/tools/zap/scan/{scan_id}
# Get All Alerts
GET /api/v1/tools/zap/alerts?minRisk=Medium
# Get Scan Alerts
GET /api/v1/tools/zap/scan/{scan_id}/alerts
# Generate Report
POST /api/v1/tools/zap/report
{
"format": "json",
"title": "My Security Report"
}
# Start Spider Only
POST /api/v1/tools/zap/spider
{
"target": "http://testphp.vulnweb.com",
"maxDepth": 5
}
# List All Scans
GET /api/v1/tools/zap/scans
# Stop a Scan
POST /api/v1/tools/zap/scan/{scan_id}/stop
# Delete a Scan
DELETE /api/v1/tools/zap/scan/{scan_id}
"""
print(examples)
# =============================================================================
# Example 9: ReAct Agent Integration
# =============================================================================
def example_react_agent_integration():
"""
Example: Using ZAP with ReAct Agents.
Demonstrates how agents can use ZAP tools directly.
"""
print("=" * 60)
print("Example 9: ReAct Agent Integration")
print("=" * 60)
code_example = """
# Agent can use these tools directly:
# 1. Full security scan
result = await agent.tools["zap_full_scan"](
target="https://example.com",
auth_type="jwt",
auth_token="eyJhbGciOiJIUzI1NiIs...",
policy="API"
)
# 2. Spider crawl
result = await agent.tools["zap_spider"](
target="https://example.com",
max_depth=5
)
# 3. Get findings
result = await agent.tools["zap_get_findings"](
target="https://example.com",
min_risk="High"
)
# 4. Automated security test
result = await agent.tools["zap_automated_security_test"](
target="https://example.com",
compliance="owasp_top_10,pci_dss"
)
# 5. Schedule recurring scans
result = await agent.tools["zap_schedule_security_scan"](
target="https://example.com",
frequency="weekly",
policy="Full Policy"
)
# 6. Generate CI/CD config
result = await agent.tools["zap_generate_cicd_config"](
target="https://example.com",
format="github_actions",
fail_on_high=True
)
"""
print(code_example)
# =============================================================================
# Example 10: Complete Workflow
# =============================================================================
async def example_complete_workflow():
"""
Example: Complete security testing workflow.
Demonstrates a full workflow from scan to report.
"""
from modules.zap_automation import (
ComplianceStandard,
ScanSchedule,
create_automation_manager,
)
print("=" * 60)
print("Example 10: Complete Security Testing Workflow")
print("=" * 60)
target = "http://testphp.vulnweb.com"
manager = create_automation_manager(zap_url="http://localhost:8080")
# Step 1: Run initial comprehensive scan
print("\n1️⃣ Running initial comprehensive scan...")
result = await manager.run_automated_scan(
target=target,
policy="Full Policy",
compliance_standards=[
ComplianceStandard.OWASP_TOP_10,
ComplianceStandard.PCI_DSS,
],
progress_callback=lambda u: print(f" {u.get('phase')}: {u.get('progress')}%"),
)
if result["status"] != "completed":
print(f"❌ Initial scan failed: {result.get('error')}")
return
baseline_id = result["scan_id"]
print(f"✅ Initial scan complete: {baseline_id}")
# Step 2: Schedule weekly scans
print("\n2️⃣ Scheduling weekly scans...")
schedule_id = manager.schedule_scan(
target=target,
frequency=ScanSchedule.WEEKLY,
policy="Default",
)
print(f"✅ Scheduled: {schedule_id}")
# Step 3: Run follow-up scan with baseline comparison
print("\n3️⃣ Running follow-up scan with baseline comparison...")
follow_up = await manager.run_automated_scan(
target=target,
policy="Default",
baseline_scan_id=baseline_id,
)
if follow_up.get("baseline_comparison"):
comp = follow_up["baseline_comparison"]
print(f" New findings: {comp['new_findings_count']}")
print(f" Resolved: {comp['resolved_findings_count']}")
print(f" Unchanged: {comp['unchanged_count']}")
# Step 4: Get trend analysis
print("\n4️⃣ Trend analysis...")
trend = manager.get_trend_report(target, days=30)
if "error" not in trend:
print(f" Data points: {trend['data_points']}")
print(f" Current total: {trend['current']['total']}")
# Step 5: Generate CI/CD configuration
print("\n5️⃣ Generating CI/CD configuration...")
cicd_config = manager.generate_cicd_config(
target=target,
format="github_actions",
fail_on_high=True,
)
print(f" Generated {len(cicd_config)} characters of configuration")
print("\n✅ Complete workflow finished successfully!")
# =============================================================================
# Main
# =============================================================================
async def main():
"""Run all examples"""
print("\n" + "=" * 60)
print("OWASP ZAP Integration Examples")
print("=" * 60 + "\n")
# Run selected examples
examples = [
("Basic Scan", example_basic_scan),
("Authenticated Scan", example_authenticated_scan),
("API Scan", example_api_scan),
("Compliance Scan", example_automation_with_compliance),
("Scheduled Scanning", example_scheduled_scanning),
("Trend Analysis", example_trend_analysis),
]
for name, example_func in examples:
try:
print(f"\n{'=' * 60}")
print(f"Running: {name}")
print("=" * 60)
await example_func()
except Exception as e:
print(f"⚠️ Example '{name}' failed: {e}")
# Run non-async examples
try:
example_cicd_integration()
except Exception as e:
print(f"⚠️ CI/CD example failed: {e}")
try:
example_api_endpoints()
except Exception as e:
print(f"⚠️ API endpoints example failed: {e}")
try:
example_react_agent_integration()
except Exception as e:
print(f"⚠️ ReAct agent example failed: {e}")
print("\n" + "=" * 60)
print("All examples completed!")
print("=" * 60)
if __name__ == "__main__":
asyncio.run(main())

Xet Storage Details

Size:
19.4 kB
¡
Xet hash:
914c61810b39117a8e9444fadd3b8d5e6e1d4025a58e61037c8874855c4ccad2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.