devsecops

Integrating DAST with OWASP ZAP in Pipeline

This skill covers integrating OWASP ZAP (Zed Attack Proxy) for Dynamic Application Security Testing in CI/CD pipelines. It addresses configuring baseline, full, and API scans against running applications, interpreting ZAP findings, tuning scan policies, and establishing DAST quality gates in GitHub Actions and GitLab CI.

cicddastdevsecopsdynamic-testingowasp-zapsecure-sdlc
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When testing running web applications for vulnerabilities like XSS, SQLi, CSRF, and misconfigurations
  • When SAST alone is insufficient and runtime behavior testing is required
  • When compliance mandates dynamic security testing of web applications before production
  • When testing APIs (REST/GraphQL) for authentication, authorization, and injection flaws
  • When establishing continuous DAST scanning in staging environments before production deployment

Do not use for scanning source code (use SAST), for scanning dependencies (use SCA), or for infrastructure configuration scanning (use IaC scanning tools).

Prerequisites

  • OWASP ZAP Docker image or installed locally (zaproxy/zap-stable or zaproxy/action-*)
  • Running target application accessible from the CI/CD runner (staging URL or Docker service)
  • ZAP scan rules configuration (optional, for tuning)
  • OpenAPI/Swagger specification for API scanning (optional)

Workflow

Step 1: Configure ZAP Baseline Scan in GitHub Actions

# .github/workflows/dast-scan.yml
name: DAST Security Scan
 
on:
  deployment_status:
  workflow_dispatch:
    inputs:
      target_url:
        description: 'Target URL to scan'
        required: true
 
jobs:
  zap-baseline:
    name: ZAP Baseline Scan
    runs-on: ubuntu-latest
    services:
      webapp:
        image: ${{ github.repository }}:${{ github.sha }}
        ports:
          - 8080:8080
        options: --health-cmd="curl -f http://localhost:8080/health" --health-interval=10s --health-timeout=5s --health-retries=5
 
    steps:
      - uses: actions/checkout@v4
 
      - name: ZAP Baseline Scan
        uses: zaproxy/action-baseline@v0.12.0
        with:
          target: 'http://webapp:8080'
          rules_file_name: '.zap/rules.tsv'
          cmd_options: '-a -j'
          allow_issue_writing: false
 
      - name: Upload ZAP Report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: zap-baseline-report
          path: report_html.html

Step 2: Configure ZAP Full Scan for Comprehensive Testing

  zap-full-scan:
    name: ZAP Full Scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
 
      - name: ZAP Full Scan
        uses: zaproxy/action-full-scan@v0.12.0
        with:
          target: ${{ github.event.inputs.target_url || 'https://staging.example.com' }}
          rules_file_name: '.zap/rules.tsv'
          cmd_options: '-a -j -T 60'
 
      - name: Upload Reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: zap-full-report
          path: |
            report_html.html
            report_json.json

Step 3: Configure API Scan with OpenAPI Specification

  zap-api-scan:
    name: ZAP API Scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
 
      - name: ZAP API Scan
        uses: zaproxy/action-api-scan@v0.12.0
        with:
          target: 'https://staging.example.com/api/openapi.json'
          format: openapi
          rules_file_name: '.zap/api-rules.tsv'
          cmd_options: '-a -j'

Step 4: Configure ZAP Scan Rules

# .zap/rules.tsv
# Rule ID	Action (IGNORE/WARN/FAIL)	Description
10003	IGNORE	# Vulnerable JS Library (handled by SCA)
10015	WARN	# Incomplete or No Cache-control Header
10021	FAIL	# X-Content-Type-Options Missing
10035	FAIL	# Strict-Transport-Security Missing
10038	FAIL	# Content Security Policy Missing
10098	IGNORE	# Cross-Domain Misconfiguration (CDN)
40012	FAIL	# Cross Site Scripting (Reflected)
40014	FAIL	# Cross Site Scripting (Persistent)
40018	FAIL	# SQL Injection
40019	FAIL	# SQL Injection (MySQL)
40032	FAIL	# .htaccess Information Leak
90033	FAIL	# Loosely Scoped Cookie

Step 5: Run ZAP with Docker Compose for Local Testing

# docker-compose.zap.yml
version: '3.8'
services:
  webapp:
    build: .
    ports:
      - "8080:8080"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 10s
      retries: 5
 
  zap:
    image: zaproxy/zap-stable:latest
    depends_on:
      webapp:
        condition: service_healthy
    command: >
      zap-baseline.py
        -t http://webapp:8080
        -r /zap/wrk/report.html
        -J /zap/wrk/report.json
        -c /zap/wrk/rules.tsv
        -I
    volumes:
      - ./zap-reports:/zap/wrk
      - ./.zap/rules.tsv:/zap/wrk/rules.tsv

Key Concepts

Term Definition
DAST Dynamic Application Security Testing — tests running applications by sending requests and analyzing responses
Baseline Scan Quick passive scan that spiders the application without active attacks, suitable for CI/CD
Full Scan Active scan including attack payloads for XSS, SQLi, and other injection vulnerabilities
API Scan Targeted scan using OpenAPI/Swagger specs to test all documented API endpoints
Spider ZAP's crawler that discovers application pages and endpoints by following links
Active Scan Phase where ZAP sends attack payloads to discovered endpoints to find exploitable vulnerabilities
Passive Scan Analysis of HTTP responses for security headers, cookies, and information disclosure without sending attacks
Scan Policy Configuration defining which attack types to enable and their intensity levels

Tools & Systems

  • OWASP ZAP: Open-source web application security scanner for DAST testing
  • zaproxy/action-baseline: GitHub Action for ZAP passive baseline scanning
  • zaproxy/action-full-scan: GitHub Action for ZAP active full scanning
  • zaproxy/action-api-scan: GitHub Action for API-focused scanning with OpenAPI support
  • Nuclei: Alternative vulnerability scanner with template-based detection for CI/CD integration

Common Scenarios

Scenario: Integrating DAST into a Staging Deployment Pipeline

Context: A team deploys to staging before production and needs automated DAST scanning between stages to catch runtime vulnerabilities.

Approach:

  1. Add a DAST job in the pipeline that triggers after successful staging deployment
  2. Run ZAP baseline scan first for quick passive feedback (2-5 minutes)
  3. Follow with a targeted API scan using the application's OpenAPI specification
  4. Configure rules.tsv to FAIL on critical findings (XSS, SQLi) and WARN on headers/cookies
  5. Upload ZAP reports as pipeline artifacts for review
  6. Block production deployment if any FAIL-level findings are detected
  7. Schedule weekly full scans against staging for deeper coverage

Pitfalls: ZAP full scans can take 30+ minutes and may overwhelm staging servers with attack traffic. Use baseline scans in CI and full scans on schedule. Running DAST against production without coordination can trigger WAF blocks and incident alerts.

Output Format

ZAP DAST Scan Report
======================
Target: https://staging.example.com
Scan Type: Baseline + API
Date: 2026-02-23
Duration: 4m 32s
 
FINDINGS:
  FAIL: 3
  WARN: 7
  INFO: 12
  PASS: 45
 
FAILING ALERTS:
  [HIGH] 40012 - Cross Site Scripting (Reflected)
    URL: https://staging.example.com/search?q=<script>
    Method: GET
    Evidence: <script>alert(1)</script>
 
  [MEDIUM] 10021 - X-Content-Type-Options Missing
    URL: https://staging.example.com/api/v1/*
    Evidence: Response header missing
 
  [MEDIUM] 10035 - Strict-Transport-Security Missing
    URL: https://staging.example.com/
    Evidence: HSTS header not present
 
QUALITY GATE: FAILED (1 HIGH, 2 MEDIUM findings)
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.5 KB

API Reference: OWASP ZAP DAST Pipeline Integration

ZAP Docker Scan Scripts

Baseline Scan (Passive Only)

docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-baseline.py -t https://target.com -J report.json -I

Full Scan (Active + Passive)

docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-full-scan.py -t https://target.com -J report.json -m 5 -I

API Scan (OpenAPI/Swagger)

docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-api-scan.py -t https://target.com/openapi.json -f openapi -J report.json

Return Codes

Code Meaning
0 No alerts above threshold
1 Warnings found
2 Failures found

Common Flags

Flag Description
-t Target URL
-J JSON report filename
-m Max scan duration in minutes
-I Do not return failure on warnings
-f API spec format (openapi, soap)
-r HTML report filename
-c Config file for rule tuning

ZAP JSON Report Structure

{"site": [{"alerts": [{"name": "...", "riskdesc": "High (Medium)",
  "cweid": "79", "count": 3, "solution": "..."}]}]}

Risk Levels

Level Action
High Block deployment
Medium Require review
Low Track as tech debt
Informational Log only

References

standards.md1.4 KB

Standards Reference: DAST with OWASP ZAP

OWASP Top 10 - DAST Coverage

OWASP Category ZAP Detection Alert IDs
A01: Broken Access Control Partial 10020, 10035, 40012
A02: Cryptographic Failures Yes 10003, 10041
A03: Injection Yes 40012, 40014, 40018, 40019
A05: Security Misconfiguration Yes 10015, 10020, 10021, 10035
A07: Auth Failures Partial 10010, 10054
A09: Logging Failures Yes 10035
A10: SSRF Partial Custom scan

OWASP SAMM - Verification: Security Testing

Level 2: DAST Integration

  • Automated DAST scanning in CI/CD pipelines
  • Baseline scans on every deployment, full scans weekly
  • Findings tracked and triaged with defined SLAs

Level 3: Advanced DAST

  • Authenticated scanning with session management
  • API-specific scanning with OpenAPI specifications
  • Custom scan policies tuned for application-specific risks

NIST SSDF (SP 800-218)

PW.8: Test Executable Code

  • PW.8.1: Test executable code using dynamic analysis
  • DAST validates running application behavior against security requirements
  • Integration into CI/CD automates regular testing

PCI DSS v4.0

  • 6.2.4: Use automated methods to prevent common attacks (XSS, SQLi)
  • 6.4.1: Web applications are protected against known attacks
  • 11.3.1: Internal vulnerability scans performed at least quarterly
workflows.md2.4 KB

Workflow Reference: DAST with OWASP ZAP

DAST Pipeline Integration

Build & Deploy to Staging


┌──────────────────┐
│ Health Check      │
│ (wait for ready)  │
└──────┬───────────┘

       ├──────────────┐
       ▼              ▼
┌───────────┐  ┌───────────┐
│ ZAP       │  │ ZAP API   │
│ Baseline  │  │ Scan      │
│ Scan      │  │ (OpenAPI) │
└─────┬─────┘  └─────┬─────┘
      │               │
      └───────┬───────┘

       ┌──────────────┐
       │ Report Gen   │
       │ + Upload     │
       └──────┬───────┘

       ┌──────┴──────┐
       ▼             ▼
     PASS          FAIL
     Deploy to     Block +
     Production    Alert

ZAP Scan Types Comparison

Scan Type Duration Coverage CI/CD Suitable Active Attacks
Baseline 2-5 min Passive only Yes No
Full Scan 30-120 min Comprehensive Scheduled Yes
API Scan 5-15 min API endpoints Yes Yes

ZAP Docker Commands

# Baseline scan (passive)
docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-baseline.py -t http://target:8080 \
  -r report.html -J report.json -c rules.tsv
 
# Full scan (active)
docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-full-scan.py -t http://target:8080 \
  -r report.html -J report.json -c rules.tsv -T 60
 
# API scan (OpenAPI)
docker run --rm -v $(pwd):/zap/wrk zaproxy/zap-stable \
  zap-api-scan.py -t http://target:8080/openapi.json \
  -f openapi -r report.html -J report.json

Authenticated Scanning Configuration

# zap-auth-config.yaml
authentication:
  method: form
  loginUrl: http://target:8080/login
  parameters:
    username: testuser
    password: testpass123
  loggedInIndicator: "\\QWelcome\\E"
  loggedOutIndicator: "\\QSign In\\E"
 
context:
  name: "auth-context"
  include:
    - "http://target:8080/.*"
  exclude:
    - "http://target:8080/logout"
    - "http://target:8080/static/.*"

Scripts 2

agent.py6.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for running OWASP ZAP DAST scans and parsing results for CI/CD integration."""

import subprocess
import json
import argparse
import sys
import os


def run_baseline_scan(target_url, output_dir):
    """Run ZAP baseline scan (passive only, fast)."""
    print(f"[*] Running ZAP baseline scan on {target_url}...")
    report_path = os.path.join(output_dir, "zap_baseline.json")
    cmd = ["docker", "run", "--rm", "-v", f"{os.path.abspath(output_dir)}:/zap/wrk",
           "zaproxy/zap-stable", "zap-baseline.py", "-t", target_url,
           "-J", "zap_baseline.json", "-I"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
    print(f"  Return code: {result.returncode} (0=pass, 1=warn, 2=fail)")
    return report_path, result.returncode


def run_full_scan(target_url, output_dir, mins=5):
    """Run ZAP full scan (active + passive, slower)."""
    print(f"[*] Running ZAP full scan on {target_url} ({mins} min)...")
    report_path = os.path.join(output_dir, "zap_full.json")
    cmd = ["docker", "run", "--rm", "-v", f"{os.path.abspath(output_dir)}:/zap/wrk",
           "zaproxy/zap-stable", "zap-full-scan.py", "-t", target_url,
           "-J", "zap_full.json", "-m", str(mins), "-I"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=mins * 120)
    print(f"  Return code: {result.returncode}")
    return report_path, result.returncode


def run_api_scan(target_spec, output_dir, spec_format="openapi"):
    """Run ZAP API scan against an OpenAPI/Swagger spec."""
    print(f"[*] Running ZAP API scan with {spec_format} spec...")
    report_path = os.path.join(output_dir, "zap_api.json")
    cmd = ["docker", "run", "--rm", "-v", f"{os.path.abspath(output_dir)}:/zap/wrk",
           "zaproxy/zap-stable", "zap-api-scan.py", "-t", target_spec,
           "-f", spec_format, "-J", "zap_api.json", "-I"]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
    print(f"  Return code: {result.returncode}")
    return report_path, result.returncode


def parse_zap_report(report_path):
    """Parse ZAP JSON report and extract findings by risk level."""
    if not os.path.exists(report_path):
        print(f"  [-] Report not found: {report_path}")
        return []
    with open(report_path) as f:
        data = json.load(f)
    alerts = []
    for site in data.get("site", []):
        for alert in site.get("alerts", []):
            alerts.append({
                "name": alert.get("name"), "risk": alert.get("riskdesc", "").split()[0],
                "confidence": alert.get("confidence"), "count": alert.get("count", 0),
                "cweid": alert.get("cweid"), "wascid": alert.get("wascid"),
                "solution": alert.get("solution", "")[:200],
            })
    risk_counts = {}
    for a in alerts:
        risk_counts[a["risk"]] = risk_counts.get(a["risk"], 0) + 1
    print(f"\n[*] Findings: {len(alerts)} unique alerts")
    for risk, count in sorted(risk_counts.items()):
        print(f"  {risk}: {count}")
    return alerts


def apply_quality_gate(alerts, fail_on="High"):
    """Apply quality gate: fail if findings at or above threshold."""
    severity_order = {"Informational": 0, "Low": 1, "Medium": 2, "High": 3}
    threshold = severity_order.get(fail_on, 3)
    blocking = [a for a in alerts if severity_order.get(a.get("risk", ""), 0) >= threshold]
    if blocking:
        print(f"\n[!] QUALITY GATE FAILED: {len(blocking)} findings at {fail_on}+ severity")
        for b in blocking[:5]:
            print(f"  - {b['risk']}: {b['name']}")
        return False
    print(f"\n[+] Quality gate passed (threshold: {fail_on})")
    return True


def generate_sarif(alerts, output_path):
    """Convert ZAP findings to SARIF format for GitHub Advanced Security."""
    rules, results = [], []
    for i, a in enumerate(alerts):
        rule_id = f"ZAP-{a.get('cweid', i)}"
        rules.append({"id": rule_id, "shortDescription": {"text": a["name"]},
                       "defaultConfiguration": {"level": "warning"}})
        results.append({"ruleId": rule_id, "message": {"text": a["name"]},
                         "level": "warning" if a["risk"] != "High" else "error"})
    sarif = {"$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
             "runs": [{"tool": {"driver": {"name": "OWASP ZAP", "rules": rules}},
                        "results": results}]}
    with open(output_path, "w") as f:
        json.dump(sarif, f, indent=2)
    print(f"[*] SARIF report: {output_path}")


def main():
    parser = argparse.ArgumentParser(description="OWASP ZAP DAST Pipeline Agent")
    parser.add_argument("action", choices=["baseline", "full", "api", "parse", "gate"])
    parser.add_argument("--target", help="Target URL or API spec URL")
    parser.add_argument("--report", help="Path to existing ZAP JSON report")
    parser.add_argument("--fail-on", default="High", choices=["Low", "Medium", "High"])
    parser.add_argument("--scan-mins", type=int, default=5)
    parser.add_argument("-o", "--output", default=".")
    args = parser.parse_args()

    os.makedirs(args.output, exist_ok=True)
    if args.action == "baseline":
        rpt, _ = run_baseline_scan(args.target, args.output)
        alerts = parse_zap_report(rpt)
        apply_quality_gate(alerts, args.fail_on)
    elif args.action == "full":
        rpt, _ = run_full_scan(args.target, args.output, args.scan_mins)
        alerts = parse_zap_report(rpt)
        apply_quality_gate(alerts, args.fail_on)
    elif args.action == "api":
        rpt, _ = run_api_scan(args.target, args.output)
        alerts = parse_zap_report(rpt)
        apply_quality_gate(alerts, args.fail_on)
    elif args.action == "parse":
        alerts = parse_zap_report(args.report)
        generate_sarif(alerts, os.path.join(args.output, "zap.sarif"))
    elif args.action == "gate":
        alerts = parse_zap_report(args.report)
        passed = apply_quality_gate(alerts, args.fail_on)
        sys.exit(0 if passed else 1)


if __name__ == "__main__":
    main()
process.py7.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
OWASP ZAP DAST Pipeline Script

Orchestrates ZAP scans, parses results, evaluates quality gates,
and generates consolidated DAST reports.

Usage:
    python process.py --target http://localhost:8080 --scan-type baseline
    python process.py --target http://staging.example.com --scan-type api --openapi-url /openapi.json
"""

import argparse
import json
import os
import subprocess
import sys
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional


RISK_LEVELS = {"High": 0, "Medium": 1, "Low": 2, "Informational": 3}


@dataclass
class ZapAlert:
    alert_id: int
    name: str
    risk: str
    confidence: str
    description: str
    url: str
    method: str
    evidence: str
    solution: str
    cwe_id: int = 0
    wasc_id: int = 0
    instances_count: int = 1


def run_zap_scan(target: str, scan_type: str = "baseline",
                 rules_file: Optional[str] = None,
                 openapi_url: Optional[str] = None,
                 report_dir: str = "/tmp/zap") -> dict:
    """Run ZAP scan via Docker and return results."""
    os.makedirs(report_dir, exist_ok=True)

    scan_scripts = {
        "baseline": "zap-baseline.py",
        "full": "zap-full-scan.py",
        "api": "zap-api-scan.py"
    }

    script = scan_scripts.get(scan_type, "zap-baseline.py")

    cmd = [
        "docker", "run", "--rm",
        "-v", f"{report_dir}:/zap/wrk",
        "--network", "host",
        "zaproxy/zap-stable",
        script,
        "-t", target,
        "-J", "report.json",
        "-r", "report.html",
        "-w", "report.md"
    ]

    if rules_file and os.path.exists(rules_file):
        cmd.extend(["-c", f"/zap/wrk/{os.path.basename(rules_file)}"])

    if scan_type == "api" and openapi_url:
        cmd.extend(["-f", "openapi"])

    cmd.extend(["-I"])  # Don't return error on warnings

    try:
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)

        json_report = os.path.join(report_dir, "report.json")
        if os.path.exists(json_report):
            with open(json_report, "r") as f:
                return json.load(f)

        return {"error": f"No report generated. stderr: {proc.stderr[:300]}"}

    except subprocess.TimeoutExpired:
        return {"error": "ZAP scan timed out after 3600 seconds"}
    except FileNotFoundError:
        return {"error": "Docker not found. Install Docker to run ZAP scans."}


def parse_zap_results(zap_json: dict) -> list:
    """Parse ZAP JSON report into ZapAlert objects."""
    alerts = []

    for site in zap_json.get("site", []):
        for alert in site.get("alerts", []):
            instances = alert.get("instances", [])
            first_instance = instances[0] if instances else {}

            alerts.append(ZapAlert(
                alert_id=int(alert.get("pluginid", 0)),
                name=alert.get("name", ""),
                risk=alert.get("riskdesc", "").split(" ")[0] if alert.get("riskdesc") else "Informational",
                confidence=alert.get("confidence", ""),
                description=alert.get("desc", "")[:300],
                url=first_instance.get("uri", ""),
                method=first_instance.get("method", ""),
                evidence=first_instance.get("evidence", "")[:200],
                solution=alert.get("solution", "")[:300],
                cwe_id=int(alert.get("cweid", 0)),
                wasc_id=int(alert.get("wascid", 0)),
                instances_count=len(instances)
            ))

    return alerts


def apply_rules(alerts: list, rules_file: Optional[str]) -> list:
    """Apply rules.tsv to override alert actions."""
    if not rules_file or not os.path.exists(rules_file):
        return alerts

    rules = {}
    with open(rules_file, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = line.split("\t")
            if len(parts) >= 2:
                rules[int(parts[0])] = parts[1].upper()

    filtered = []
    for alert in alerts:
        action = rules.get(alert.alert_id, "WARN")
        if action != "IGNORE":
            alert.confidence = action  # Reuse field for action tracking
            filtered.append(alert)

    return filtered


def evaluate_quality_gate(alerts: list, threshold: str,
                          rules_file: Optional[str] = None) -> dict:
    """Evaluate quality gate based on alert risk levels."""
    threshold_level = RISK_LEVELS.get(threshold, 1)

    rules = {}
    if rules_file and os.path.exists(rules_file):
        with open(rules_file, "r") as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                parts = line.split("\t")
                if len(parts) >= 2:
                    rules[int(parts[0])] = parts[1].upper()

    blocking = []
    for a in alerts:
        action = rules.get(a.alert_id, "WARN")
        if action == "FAIL" and RISK_LEVELS.get(a.risk, 3) <= threshold_level:
            blocking.append(a)

    risk_counts = {}
    for a in alerts:
        risk_counts[a.risk] = risk_counts.get(a.risk, 0) + 1

    return {
        "passed": len(blocking) == 0,
        "threshold": threshold,
        "total_alerts": len(alerts),
        "blocking_count": len(blocking),
        "risk_counts": risk_counts,
        "blocking_details": [
            {"id": a.alert_id, "name": a.name, "risk": a.risk,
             "url": a.url, "cwe": a.cwe_id}
            for a in blocking[:15]
        ]
    }


def main():
    parser = argparse.ArgumentParser(description="OWASP ZAP DAST Pipeline")
    parser.add_argument("--target", required=True, help="Target URL to scan")
    parser.add_argument("--scan-type", default="baseline", choices=["baseline", "full", "api"])
    parser.add_argument("--rules-file", default=None, help="Path to rules.tsv")
    parser.add_argument("--openapi-url", default=None, help="OpenAPI spec URL for API scan")
    parser.add_argument("--output", default="dast-report.json")
    parser.add_argument("--report-dir", default="/tmp/zap")
    parser.add_argument("--risk-threshold", default="Medium", choices=["High", "Medium", "Low"])
    parser.add_argument("--fail-on-findings", action="store_true")
    args = parser.parse_args()

    print(f"[*] Running ZAP {args.scan_type} scan against {args.target}")

    zap_json = run_zap_scan(
        args.target, args.scan_type,
        rules_file=args.rules_file,
        openapi_url=args.openapi_url,
        report_dir=args.report_dir
    )

    if "error" in zap_json:
        print(f"[ERROR] {zap_json['error']}")
        sys.exit(2)

    alerts = parse_zap_results(zap_json)
    quality_gate = evaluate_quality_gate(alerts, args.risk_threshold, args.rules_file)

    report = {
        "metadata": {
            "target": args.target,
            "scan_type": args.scan_type,
            "scan_date": datetime.now(timezone.utc).isoformat()
        },
        "quality_gate": quality_gate,
        "alerts": [
            {"id": a.alert_id, "name": a.name, "risk": a.risk,
             "url": a.url, "method": a.method, "cwe": a.cwe_id,
             "solution": a.solution, "instances": a.instances_count}
            for a in sorted(alerts, key=lambda x: RISK_LEVELS.get(x.risk, 3))
        ]
    }

    output_path = os.path.abspath(args.output)
    with open(output_path, "w") as f:
        json.dump(report, f, indent=2)
    print(f"[*] Report: {output_path}")

    if quality_gate["passed"]:
        print(f"\n[PASS] Quality gate passed. {quality_gate['total_alerts']} alerts, none blocking.")
    else:
        print(f"\n[FAIL] {quality_gate['blocking_count']} blocking alerts:")
        for d in quality_gate["blocking_details"]:
            print(f"  [{d['risk']}] {d['id']} - {d['name']} ({d['url'][:80]})")

    if args.fail_on_findings and not quality_gate["passed"]:
        sys.exit(1)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 2.4 KB
Keep exploring