DefectDojo Integration
DefectDojo Integration
The following files were used as context for generating this wiki page:
- .github/workflows/ghcr-publish.yml
- README.md
- RELEASE_3.0.0.md
- RELEASE_SUMMARY.md
- docs/V3_COMPLETE_GUIDE.md
- requirements.txt
- wshawk/advanced_cli.py
- wshawk/scanner_v2.py
Purpose and Scope
This document describes how WSHawk integrates with DefectDojo, an open-source vulnerability management platform. The integration enables automated pushing of security findings from WSHawk scans directly into DefectDojo engagements for centralized tracking and remediation workflows.
For information about other integration platforms, see Jira Integration and Webhook Notifications. For general configuration system details, see Configuration System.
Overview
WSHawk v3.0.0 includes native DefectDojo API v2 support through the DefectDojoIntegration class. When enabled, scan results are automatically pushed to DefectDojo as structured findings, complete with CVSS scores, severity classifications, and reproduction steps. This integration supports both manual scans and automated CI/CD pipelines.
Key Capabilities
| Capability | Description |
|------------|-------------|
| Automatic Engagement Creation | Creates DefectDojo engagements for each scan if they don't exist |
| Structured Finding Import | Maps WSHawk vulnerability data to DefectDojo's finding schema |
| CVSS Integration | Preserves CVSS v3.1 scores and severity classifications |
| Resilient Communication | Uses ResilientSession with circuit breakers and exponential backoff |
| Multi-Environment Support | Works in CLI, Web Dashboard, Docker, and Kubernetes deployments |
Sources: README.md:31, RELEASE_SUMMARY.md:30-34, docs/V3_COMPLETE_GUIDE.md:342-343
Configuration Methods
DefectDojo integration can be configured through three complementary methods, following WSHawk's hierarchical configuration system.
Configuration Hierarchy Diagram
graph TB
CLI["CLI Arguments<br/>--defectdojo URL<br/>--dd-product ID"]
Config["wshawk.yaml<br/>integrations.defectdojo"]
Env["Environment Variables<br/>DEFECTDOJO_API_KEY<br/>DEFECTDOJO_URL"]
Merged["Merged Configuration<br/>WSHawkConfig"]
Integration["DefectDojoIntegration<br/>Class Instance"]
CLI --> Merged
Config --> Merged
Env --> Merged
Merged --> Integration
Integration --> API["DefectDojo API v2<br/>Findings & Engagements"]
Sources: wshawk/advanced_cli.py:58-61, wshawk/advanced_cli.py:234-249
Method 1: Command-Line Arguments
The wshawk-advanced CLI provides direct flags for DefectDojo integration:
# Basic DefectDojo push
wshawk-advanced ws://target.com --defectdojo https://defectdojo.example.com
# With specific product ID
wshawk-advanced ws://target.com \
--defectdojo https://defectdojo.example.com \
--dd-product 42
# Full scan with DefectDojo integration
wshawk-advanced ws://target.com \
--full \
--defectdojo https://defectdojo.example.com \
--dd-product 42
| Flag | Type | Description |
|------|------|-------------|
| --defectdojo URL | string | DefectDojo instance base URL |
| --dd-product ID | integer | DefectDojo product ID (optional) |
Sources: wshawk/advanced_cli.py:58-61
Method 2: YAML Configuration File
For persistent configuration across multiple scans, define DefectDojo settings in wshawk.yaml:
integrations:
defectdojo:
enabled: true
url: "https://defectdojo.example.com"
api_key: "env:DEFECTDOJO_API_KEY" # Resolves from environment
product_id: 42
engagement_name: "WebSocket Security Scan"
auto_create_engagement: true
# Optional: Severity threshold for pushing findings
severity_threshold: "MEDIUM" # Only push MEDIUM and above
The configuration system supports secret resolution using the env: prefix, allowing sensitive API keys to be stored securely in environment variables rather than committed to version control.
Sources: README.md:137-150, wshawk/advanced_cli.py:86-97
Method 3: Environment Variables
Environment variables provide the most secure method for credentials in production environments:
# Required: API authentication
export DEFECTDOJO_API_KEY="your-api-token-here"
# Optional: Default DefectDojo URL
export DEFECTDOJO_URL="https://defectdojo.example.com"
# Optional: Default product ID
export DEFECTDOJO_PRODUCT_ID="42"
# Run scan (configuration from environment)
wshawk-advanced ws://target.com --defectdojo $DEFECTDOJO_URL
The DEFECTDOJO_API_KEY environment variable is mandatory for authentication. If not set, the integration will fail with a clear error message.
Sources: wshawk/advanced_cli.py:235-238
Integration Architecture
DefectDojo Integration Data Flow
graph TB
Scanner["WSHawkV2<br/>scanner_v2.py"]
Vulns["vulnerabilities[]<br/>List[Dict]"]
ScanInfo["scan_info<br/>Dict"]
DDInteg["DefectDojoIntegration<br/>integrations/defectdojo.py"]
Resilient["ResilientSession<br/>HTTP Wrapper"]
API1["POST /api/v2/engagements/<br/>Create Engagement"]
API2["POST /api/v2/import-scan/<br/>Import Findings"]
API3["GET /api/v2/products/<br/>Validate Product"]
Scanner --> Vulns
Scanner --> ScanInfo
Vulns --> DDInteg
ScanInfo --> DDInteg
DDInteg --> Resilient
Resilient -->|"Authorization: Token {key}"| API1
Resilient --> API2
Resilient --> API3
API2 --> Result["{'success': bool,<br/>'findings_imported': int,<br/>'engagement_id': int}"]
Sources: wshawk/scanner_v2.py:807-813, wshawk/advanced_cli.py:239-249
DefectDojoIntegration Class Structure
The DefectDojoIntegration class is located in wshawk/integrations/defectdojo.py and provides the following interface:
| Method | Purpose | Returns |
|--------|---------|---------|
| __init__(url, api_key, product_id) | Initialize integration with credentials | None |
| push_results(vulnerabilities, scan_info) | Push scan results to DefectDojo | Dict[str, Any] |
| create_engagement(product_id, scan_info) | Create new engagement if not exists | int (engagement_id) |
| import_findings(engagement_id, findings) | Import findings into engagement | Dict[str, int] |
| validate_connection() | Test API connectivity and credentials | bool |
Sources: wshawk/advanced_cli.py:239-249
Vulnerability Mapping
WSHawk vulnerability data is transformed into DefectDojo's finding schema during the push operation. The mapping ensures that all relevant security information is preserved.
Vulnerability Schema Transformation
graph LR
subgraph "WSHawk Vulnerability"
WType["type: str<br/>SQL Injection"]
WSev["severity: str<br/>HIGH"]
WConf["confidence: str<br/>HIGH"]
WDesc["description: str<br/>Full details"]
WPay["payload: str<br/>Attack vector"]
WResp["response_snippet: str<br/>Evidence"]
WRec["recommendation: str<br/>Remediation"]
WCVSS["cvss_score: float<br/>7.5"]
end
subgraph "DefectDojo Finding"
DTitle["title<br/>SQL Injection"]
DSev["severity<br/>High"]
DDesc["description<br/>Formatted report"]
DMit["mitigation<br/>Remediation steps"]
DImpact["impact<br/>Attack details"]
DRef["references<br/>Payload + Evidence"]
DCVSS["cvss<br/>AV:N/AC:L/..."]
end
WType --> DTitle
WSev --> DSev
WDesc --> DDesc
WRec --> DMit
WPay --> DImpact
WResp --> DRef
WCVSS --> DCVSS
Field Mapping Table
| WSHawk Field | DefectDojo Field | Transformation |
|--------------|------------------|----------------|
| type | title | Direct mapping |
| severity | severity | Uppercase to Title Case (HIGH → High) |
| confidence | verified | HIGH/CRITICAL → true, else false |
| description | description | Formatted with context |
| payload | impact | Wrapped with attack details |
| response_snippet | references | Included as evidence |
| recommendation | mitigation | Direct mapping |
| cvss_score | cvss | Converted to CVSS vector string |
Sources: wshawk/scanner_v2.py:684-692
Execution Flow
Scan-to-DefectDojo Pipeline
sequenceDiagram
participant CLI as CLI/Scanner
participant Scanner as WSHawkV2
participant DD as DefectDojoIntegration
participant RS as ResilientSession
participant API as DefectDojo API
CLI->>Scanner: run_heuristic_scan()
Scanner->>Scanner: Detect vulnerabilities
Scanner-->>Scanner: Store in self.vulnerabilities[]
Scanner->>DD: push_results(vulns, scan_info)
DD->>RS: GET /api/v2/products/{id}
RS->>API: Request with retry logic
API-->>RS: Product details
RS-->>DD: Product validated
DD->>RS: POST /api/v2/engagements/
RS->>API: Create engagement
API-->>RS: engagement_id
RS-->>DD: Engagement created
DD->>DD: Transform vulnerabilities
DD->>RS: POST /api/v2/import-scan/
RS->>API: JSON findings payload
API-->>RS: Import results
RS-->>DD: findings_imported: N
DD-->>Scanner: {'success': true, 'findings_imported': N}
Scanner-->>CLI: Logger.success("DefectDojo: N findings imported")
Sources: wshawk/advanced_cli.py:234-249
Error Handling States
The integration includes comprehensive error handling for common failure scenarios:
| Error Condition | Handling Strategy | User Feedback |
|----------------|-------------------|---------------|
| Missing API key | Immediate failure | Logger.error("Set DEFECTDOJO_API_KEY environment variable") |
| Invalid URL | Connection timeout | Retry with exponential backoff via ResilientSession |
| 401 Unauthorized | No retry (permanent) | Logger.error("DefectDojo: Authentication failed") |
| 429 Rate Limit | Exponential backoff | Automatic retry after delay |
| 500 Server Error | Circuit breaker | Fail-open after threshold |
| Network partition | Pause and resume | Wait for connectivity restoration |
Sources: wshawk/advanced_cli.py:235-249, RELEASE_SUMMARY.md:9-13
Resilient Communication
DefectDojo integration leverages WSHawk's ResilientSession wrapper to ensure reliable API communication even in unstable network conditions or when DefectDojo experiences load.
ResilientSession Integration
graph TB
DDInteg["DefectDojoIntegration"]
RS["ResilientSession<br/>Wrapper"]
CB["Circuit Breaker<br/>State Machine"]
EB["Exponential Backoff<br/>Retry Logic"]
RL["Rate Limiter<br/>Token Bucket"]
DDInteg --> RS
RS --> CB
RS --> EB
RS --> RL
CB -->|"CLOSED"| Success["Normal Operation"]
CB -->|"OPEN"| Wait["60s Cooldown"]
CB -->|"HALF_OPEN"| Test["Test Request"]
EB -->|"Attempt N"| Delay["Wait = min(Cap, Base * 2^N) + Jitter"]
RL -->|"Tokens Available"| Allow["Allow Request"]
RL -->|"No Tokens"| Throttle["Wait for Refill"]
Circuit Breaker Behavior
The circuit breaker protects both WSHawk and DefectDojo from cascading failures:
- CLOSED State: All DefectDojo API calls proceed normally
- Failure Threshold: After 5 consecutive failures, circuit opens
- OPEN State: All API calls are blocked for 60 seconds (cooldown)
- HALF_OPEN State: Single test request sent after cooldown
- Recovery: Success closes circuit; failure re-opens for another cooldown
This prevents WSHawk scans from hanging indefinitely if DefectDojo is temporarily unavailable.
Sources: RELEASE_SUMMARY.md:9-13, docs/V3_COMPLETE_GUIDE.md:136-169
Deployment Patterns
Pattern 1: Manual CLI Scans
For ad-hoc security assessments:
# Set credentials once
export DEFECTDOJO_API_KEY="dd_api_token_xxx"
# Run scan with DefectDojo integration
wshawk-advanced ws://staging-app.com/socket \
--defectdojo https://defectdojo.internal.company.com \
--dd-product 15 \
--full
Sources: wshawk/advanced_cli.py:234-249
Pattern 2: CI/CD Pipeline Integration
For automated security testing in GitHub Actions or GitLab CI:
name: WebSocket Security Scan
on: [push, pull_request]
jobs:
wshawk_scan:
runs-on: ubuntu-latest
steps:
- name: Run WSHawk with DefectDojo
run: |
docker run --rm \
-e DEFECTDOJO_API_KEY=${{ secrets.DEFECTDOJO_API_KEY }} \
rothackers/wshawk \
wshawk-advanced ws://test-env.internal/api \
--defectdojo https://defectdojo.company.com \
--dd-product 42 \
--rate 5
The containerized approach ensures consistent scanning across different CI environments.
Sources: docs/V3_COMPLETE_GUIDE.md:362-376
Pattern 3: Kubernetes CronJob for Continuous Monitoring
For production infrastructure with multiple services:
apiVersion: batch/v1
kind: CronJob
metadata:
name: wshawk-production-scan
spec:
schedule: "0 2 * * *" # Daily at 2 AM
jobTemplate:
spec:
template:
spec:
containers:
- name: wshawk
image: rothackers/wshawk:latest
env:
- name: DEFECTDOJO_API_KEY
valueFrom:
secretKeyRef:
name: defectdojo-credentials
key: api-key
args:
- "wshawk-advanced"
- "ws://prod-service.internal/websocket"
- "--defectdojo"
- "https://defectdojo.company.com"
- "--dd-product"
- "100"
- "--rate"
- "10"
restartPolicy: OnFailure
All findings automatically aggregate into a centralized DefectDojo instance for organization-wide visibility.
Sources: README.md:64-78, docs/V3_COMPLETE_GUIDE.md:359-361
Web Dashboard Integration
The WSHawk Web Management Dashboard (launched with wshawk --web) also supports DefectDojo integration through its REST API.
Dashboard API Integration Flow
graph TB
UI["Web Dashboard UI<br/>Browser"]
API["Flask REST API<br/>/api/scans"]
Scanner["WSHawkV2<br/>Scan Execution"]
DD["DefectDojoIntegration"]
UI -->|"POST /api/scans<br/>{target, options}"| API
API -->|"Start async scan"| Scanner
Scanner -->|"On completion"| DD
DD -->|"Push findings"| DDAPI["DefectDojo API"]
Scanner -->|"Store in DB"| DB[("scans.db<br/>SQLite")]
UI -->|"GET /api/scans/{id}"| API
API -->|"Query"| DB
DB -->|"Scan results + DD status"| API
API -->|"JSON response"| UI
When a scan is initiated through the Web Dashboard with DefectDojo enabled in wshawk.yaml, findings are automatically pushed upon scan completion. The scan record in scans.db includes DefectDojo push status.
Sources: README.md:106-136, RELEASE_SUMMARY.md:15-19
Testing and Validation
Connection Validation
Before pushing findings, verify DefectDojo connectivity:
# Test with dummy scan
wshawk-advanced ws://echo.websocket.org \
--defectdojo https://defectdojo.example.com \
--dd-product 1
Expected output on success:
[+] DefectDojo: 0 findings imported
Expected output on authentication failure:
[-] DefectDojo: Authentication failed - check DEFECTDOJO_API_KEY
Troubleshooting Common Issues
| Issue | Symptom | Solution |
|-------|---------|----------|
| Missing API key | Set DEFECTDOJO_API_KEY environment variable | Export DEFECTDOJO_API_KEY with valid token |
| Invalid product ID | Product not found | Verify product ID exists in DefectDojo |
| Network timeout | Connection failed after retries | Check DefectDojo URL and firewall rules |
| 403 Forbidden | Insufficient permissions | Ensure API key has Import-Scan permission |
| Duplicate findings | Warnings in DefectDojo logs | Normal behavior - DefectDojo deduplicates |
Sources: wshawk/advanced_cli.py:234-249
Security Considerations
API Key Management
DefectDojo API keys grant write access to vulnerability data. Follow these best practices:
- Never commit keys to version control: Use environment variables or secret managers
- Rotate keys regularly: DefectDojo supports key rotation without downtime
- Use read-only keys for validation: Test connectivity with restricted tokens
- Scope keys to specific products: Limit blast radius if compromised
TLS/SSL Requirements
WSHawk enforces HTTPS for all DefectDojo API communication when the URL starts with https://. Self-signed certificates require additional configuration in the underlying aiohttp session.
Data Privacy
Vulnerability findings pushed to DefectDojo include:
- Target URLs and endpoints
- Payload strings (may contain injected code)
- Response snippets (may contain sensitive data)
Ensure DefectDojo instance security matches the sensitivity of scanned targets.
Sources: README.md:137-150
Performance Characteristics
Throughput and Latency
| Metric | Typical Value | Notes | |--------|---------------|-------| | API call latency | 200-500ms | Network dependent | | Findings batch size | 100 per request | Configurable in DefectDojo | | Retry delay | 1s, 2s, 4s, 8s | Exponential backoff | | Circuit breaker cooldown | 60s | After 5 failures | | Maximum concurrent pushes | 1 | Sequential to avoid race conditions |
The integration is optimized for reliability over speed, prioritizing zero data loss.
Sources: RELEASE_SUMMARY.md:9-13, docs/V3_COMPLETE_GUIDE.md:136-173
Related Documentation
- Jira Integration - Alternative ticketing system integration
- Webhook Notifications - Real-time Slack/Discord/Teams alerts
- Configuration System - Hierarchical configuration with secret resolution
- Report Formats and Export - SARIF, JSON, CSV export options
- Kubernetes Deployment - Scaled DefectDojo integration in K8s
Sources: README.md:242-249, docs/V3_COMPLETE_GUIDE.md:332-349