
Building Vulnerability Dashboard With Defectdojo
- 163 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with security tasks.
About
building-vulnerability-dashboard-with-defectdojo is a Claude Code skill in the Security category.
- building-vulnerability-dashboard-with-defectdojo
- Security
- AI-coding skill
Building Vulnerability Dashboard With Defectdojo by the numbers
- 163 all-time installs (skills.sh)
- +6 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #858 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-vulnerability-dashboard-with-defectdojoAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 163 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with security tasks.
Files
Building Vulnerability Dashboard with DefectDojo
Overview
DefectDojo is an open-source application vulnerability management platform that aggregates findings from 200+ security tools, deduplicates results, tracks remediation progress, and provides executive dashboards. It serves as a central hub for vulnerability management, integrating with CI/CD pipelines, Jira for ticketing, and Slack for notifications. DefectDojo supports OWASP-based categorization and provides REST API for automation.
When to Use
- When deploying or configuring building vulnerability dashboard with defectdojo capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Docker and Docker Compose
- 4GB+ RAM, 2+ CPU cores, 20GB+ disk
- PostgreSQL 12+ (included in Docker deployment)
- Python 3.9+ for API integration scripts
- Jira instance (optional, for ticket integration)
Deployment
Docker Compose Deployment
# Clone DefectDojo repository
git clone https://github.com/DefectDojo/django-DefectDojo.git
cd django-DefectDojo
# Start with Docker Compose (production mode)
./dc-up-d.sh
# Alternative: manual Docker Compose
docker compose up -d
# Check service status
docker compose ps
# View initial admin credentials
docker compose logs initializer 2>&1 | grep "Admin password"
# Access DefectDojo at http://localhost:8080Environment Configuration
# Key environment variables in docker-compose.yml
DD_DATABASE_ENGINE=django.db.backends.postgresql
DD_DATABASE_HOST=postgres
DD_DATABASE_PORT=5432
DD_DATABASE_NAME=defectdojo
DD_DATABASE_USER=defectdojo
DD_DATABASE_PASSWORD=<secure_password>
DD_ALLOWED_HOSTS=*
DD_SECRET_KEY=<random_64_char_key>
DD_CREDENTIAL_AES_256_KEY=<random_128_bit_key>
DD_SOCIAL_AUTH_GOOGLE_OAUTH2_ENABLED=TrueOrganizational Structure
Hierarchy
Product Type (Business Unit)
└── Product (Application/Service)
└── Engagement (Assessment/Sprint)
└── Test (Scanner Run)
└── Finding (Individual Vulnerability)Setup via API
import requests
DD_URL = "http://localhost:8080/api/v2"
API_KEY = "your_api_key_here"
HEADERS = {"Authorization": f"Token {API_KEY}", "Content-Type": "application/json"}
# Create Product Type
resp = requests.post(f"{DD_URL}/product_types/", headers=HEADERS, json={
"name": "Web Applications",
"description": "Customer-facing web application portfolio"
})
product_type_id = resp.json()["id"]
# Create Product
resp = requests.post(f"{DD_URL}/products/", headers=HEADERS, json={
"name": "Customer Portal",
"description": "Main customer-facing web application",
"prod_type": product_type_id,
"sla_configuration": 1,
})
product_id = resp.json()["id"]
# Create Engagement
resp = requests.post(f"{DD_URL}/engagements/", headers=HEADERS, json={
"name": "Q1 2024 Security Assessment",
"product": product_id,
"target_start": "2024-01-01",
"target_end": "2024-03-31",
"engagement_type": "CI/CD",
"status": "In Progress",
})
engagement_id = resp.json()["id"]Scanner Integration
Import Scan Results via API
# Upload Nessus scan results
curl -X POST "${DD_URL}/reimport-scan/" \
-H "Authorization: Token ${API_KEY}" \
-F "scan_type=Nessus Scan" \
-F "file=@nessus_report.csv" \
-F "product_name=Customer Portal" \
-F "engagement_name=Q1 2024 Security Assessment" \
-F "auto_create_context=true" \
-F "deduplication_on_engagement=true"
# Upload OWASP ZAP results
curl -X POST "${DD_URL}/reimport-scan/" \
-H "Authorization: Token ${API_KEY}" \
-F "scan_type=ZAP Scan" \
-F "file=@zap_report.xml" \
-F "product_name=Customer Portal" \
-F "engagement_name=Q1 2024 Security Assessment" \
-F "auto_create_context=true"
# Upload Trivy container scan
curl -X POST "${DD_URL}/reimport-scan/" \
-H "Authorization: Token ${API_KEY}" \
-F "scan_type=Trivy Scan" \
-F "file=@trivy_results.json" \
-F "product_name=Customer Portal" \
-F "engagement_name=Q1 2024 Security Assessment" \
-F "auto_create_context=true"Supported Scanner Types (Partial List)
| Scanner | Type String | Format |
|---|---|---|
| Nessus | Nessus Scan | CSV/XML |
| OpenVAS | OpenVAS CSV | CSV |
| Qualys | Qualys Scan | XML |
| OWASP ZAP | ZAP Scan | XML/JSON |
| Burp Suite | Burp XML | XML |
| Trivy | Trivy Scan | JSON |
| Semgrep | Semgrep JSON Report | JSON |
| Snyk | Snyk Scan | JSON |
| SonarQube | SonarQube Scan | JSON |
| Checkov | Checkov Scan | JSON |
CI/CD Integration (GitHub Actions)
# .github/workflows/security-scan.yml
name: Security Scan
on: [push]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Semgrep
run: |
pip install semgrep
semgrep --config auto --json -o semgrep_results.json .
- name: Upload to DefectDojo
run: |
curl -X POST "${{ secrets.DD_URL }}/api/v2/reimport-scan/" \
-H "Authorization: Token ${{ secrets.DD_API_KEY }}" \
-F "scan_type=Semgrep JSON Report" \
-F "file=@semgrep_results.json" \
-F "product_name=${{ github.event.repository.name }}" \
-F "engagement_name=CI/CD" \
-F "auto_create_context=true"Jira Integration
# Configure Jira integration in DefectDojo settings
jira_config = {
"url": "https://company.atlassian.net",
"username": "jira-bot@company.com",
"password": "jira_api_token",
"default_issue_type": "Bug",
"critical_mapping_severity": "Blocker",
"high_mapping_severity": "Critical",
"medium_mapping_severity": "Major",
"low_mapping_severity": "Minor",
"finding_text": "**Vulnerability**: {{ finding.title }}\n**Severity**: {{ finding.severity }}\n**CVE**: {{ finding.cve }}\n**Description**: {{ finding.description }}",
"accepted_mapping_resolution": "Done",
"close_status_key": 6,
}Metrics and Dashboards
Key Metrics API Queries
# Get finding counts by severity
resp = requests.get(f"{DD_URL}/findings/?limit=0&active=true",
headers=HEADERS)
findings = resp.json()
# Get SLA breach counts
resp = requests.get(f"{DD_URL}/findings/?limit=0&active=true&sla_breached=true",
headers=HEADERS)
# Get product-level metrics
resp = requests.get(f"{DD_URL}/products/{product_id}/",
headers=HEADERS)
product_data = resp.json()References
DefectDojo Configuration Template
Product Hierarchy Setup
Product Types (Business Units)
| Product Type | Description |
|---|---|
| Web Applications | Customer-facing web applications |
| Mobile Applications | iOS and Android apps |
| Internal Tools | Employee-facing internal applications |
| Infrastructure | Network and cloud infrastructure |
| APIs | REST and GraphQL API services |
Scanner Type Mappings
| Scanner | DefectDojo Scan Type | File Format |
|---|---|---|
| Nessus | Nessus Scan | .csv or .nessus |
| OWASP ZAP | ZAP Scan | .xml or .json |
| Burp Suite | Burp XML | .xml |
| Trivy | Trivy Scan | .json |
| Semgrep | Semgrep JSON Report | .json |
| Snyk | Snyk Scan | .json |
| SonarQube | SonarQube Scan | .json |
| Checkov | Checkov Scan | .json |
| Bandit | Bandit Scan | .json |
| OpenVAS | OpenVAS CSV | .csv |
| Qualys | Qualys Scan | .xml |
SLA Configuration
| Severity | Days to Remediate |
|---|---|
| Critical | 7 |
| High | 30 |
| Medium | 90 |
| Low | 120 |
| Info | No SLA |
Jira Integration Settings
Jira URL: https://company.atlassian.net
Project Key: SEC
Issue Type: Bug
Priority Mapping:
Critical -> Blocker
High -> Critical
Medium -> Major
Low -> Minor
Auto-close: Yes (when finding is closed in DefectDojo)CI/CD Integration Snippet
# Generic CI/CD step for DefectDojo upload
- name: Upload scan results to DefectDojo
env:
DD_URL: ${{ secrets.DEFECTDOJO_URL }}
DD_API_KEY: ${{ secrets.DEFECTDOJO_API_KEY }}
run: |
curl -X POST "${DD_URL}/api/v2/reimport-scan/" \
-H "Authorization: Token ${DD_API_KEY}" \
-F "scan_type=${SCAN_TYPE}" \
-F "file=@${SCAN_FILE}" \
-F "product_name=${PRODUCT_NAME}" \
-F "auto_create_context=true" \
-F "close_old_findings=true"
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Vulnerability Dashboard with DefectDojo
Authentication
# Token-based auth
curl -H "Authorization: Token $DEFECTDOJO_TOKEN" \
"http://localhost:8080/api/v2/findings/"Core Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v2/findings/ | List vulnerability findings |
| GET | /api/v2/products/ | List products |
| GET | /api/v2/engagements/ | List engagements |
| GET | /api/v2/tests/ | List tests |
| POST | /api/v2/import-scan/ | Import scanner results |
| POST | /api/v2/reimport-scan/ | Re-import/update results |
Finding Query Parameters
| Parameter | Type | Description |
|---|---|---|
| severity | string | Critical, High, Medium, Low, Info |
| active | boolean | Only active findings |
| verified | boolean | Only verified findings |
| duplicate | boolean | Include duplicates |
| product | integer | Filter by product ID |
| limit | integer | Results per page |
| offset | integer | Pagination offset |
Import Scan
curl -X POST "http://localhost:8080/api/v2/import-scan/" \
-H "Authorization: Token $TOKEN" \
-F "product=1" \
-F "engagement=1" \
-F "scan_type=Nessus Scan" \
-F "file=@nessus_export.csv" \
-F "active=true" \
-F "verified=false"Supported Scan Types (partial)
| Scanner | scan_type Value |
|---|---|
| Nessus | Nessus Scan |
| Qualys | Qualys Scan |
| Burp Suite | Burp REST API |
| OWASP ZAP | ZAP Scan |
| Trivy | Trivy Scan |
| Snyk | Snyk Scan |
| Semgrep | Semgrep JSON Report |
| Nuclei | Nuclei Scan |
| Checkov | Checkov Scan |
| SARIF | SARIF |
Python Client
import requests
class DefectDojoClient:
def __init__(self, url, token):
self.url = url.rstrip("/")
self.headers = {"Authorization": "Token " + token}
def get_findings(self, **params):
return requests.get(
f"{self.url}/api/v2/findings/",
headers=self.headers, params=params
).json()Standards and References - DefectDojo Vulnerability Dashboard
Primary References
DefectDojo Project
- GitHub: https://github.com/DefectDojo/django-DefectDojo
- Documentation: https://defectdojo.github.io/django-DefectDojo/
- API v2 Docs: https://defectdojo.github.io/django-DefectDojo/integrations/api-v2-docs/
- OWASP Project Page: https://owasp.org/www-project-defectdojo/
- License: BSD-3-Clause
Supported Scanner Integrations
- Full List: https://defectdojo.com/integrations
- 200+ parsers including Nessus, Qualys, Burp Suite, ZAP, Trivy, Semgrep, SonarQube, Snyk, Checkov, and more
OWASP Application Security Verification Standard (ASVS)
- URL: https://owasp.org/www-project-application-security-verification-standard/
- Relevance: DefectDojo categorizes findings using OWASP taxonomy
NIST SP 800-53 Rev 5 - RA-5
- Title: Vulnerability Monitoring and Scanning
- Relevance: DefectDojo supports centralized vulnerability tracking as required by RA-5
PCI DSS v4.0 - Requirement 6
- Relevance: DefectDojo tracks application security findings for PCI compliance
Deployment Requirements
| Component | Minimum | Recommended |
|---|---|---|
| CPU | 2 cores | 4 cores |
| RAM | 4 GB | 8 GB |
| Disk | 20 GB | 50 GB+ |
| PostgreSQL | 12+ | 15+ |
| Docker | 20.10+ | Latest stable |
| Docker Compose | 2.0+ | Latest stable |
Workflows - DefectDojo Vulnerability Dashboard
Workflow 1: Initial Setup and Configuration
Steps
1. Clone DefectDojo repository and deploy with Docker Compose 2. Configure admin account and change default password 3. Create Product Types aligned with business units 4. Create Products for each application/service 5. Configure Jira integration for ticket management 6. Configure Slack/Teams webhook for notifications 7. Set up SLA policies for each severity level 8. Create API keys for scanner integration
Workflow 2: CI/CD Scanner Integration
Steps
1. Add scan step to CI/CD pipeline (GitHub Actions, GitLab CI, Jenkins) 2. Run security scanner (Semgrep, Trivy, ZAP, etc.) 3. Upload scan results to DefectDojo via reimport-scan API 4. DefectDojo deduplicates findings against existing data 5. New findings trigger Jira ticket creation 6. Closed findings auto-close associated Jira tickets 7. Pipeline receives pass/fail status based on finding severity
Workflow 3: Vulnerability Triage
Steps
1. Security analyst reviews new findings in DefectDojo dashboard 2. For each finding: verify, assign severity, set risk acceptance status 3. Valid findings: push to Jira for remediation tracking 4. False positives: mark as false positive with justification 5. Risk accepted: document compensating controls and set expiration 6. Track remediation progress through DefectDojo metrics
Workflow 4: Executive Reporting
Steps
1. Pull metrics via DefectDojo API for reporting period 2. Calculate: total findings, new vs closed, SLA compliance rate 3. Generate product-level and business-unit-level summaries 4. Track mean time to remediate by severity 5. Export dashboard data for executive presentation
#!/usr/bin/env python3
"""Vulnerability dashboard builder using DefectDojo API.
Queries DefectDojo REST API v2 for findings, products, and engagements
to build vulnerability management dashboards and metrics.
"""
import json
import datetime
import os
import collections
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
class DefectDojoClient:
"""Client for DefectDojo REST API v2."""
def __init__(self, url=None, api_key=None):
self.url = (url or os.environ.get("DEFECTDOJO_URL", "http://localhost:8080")).rstrip("/")
self.api_key = api_key or os.environ.get("DEFECTDOJO_API_KEY", "")
self.headers = {
"Authorization": "Token " + self.api_key,
"Content-Type": "application/json",
}
def _get(self, endpoint, params=None):
if not HAS_REQUESTS or not self.api_key:
return {"error": "requests not available or no API key"}
try:
resp = requests.get(
self.url + "/api/v2/" + endpoint,
headers=self.headers, params=params, timeout=15
)
if resp.status_code == 200:
return resp.json()
return {"error": "HTTP {}".format(resp.status_code)}
except Exception as e:
return {"error": str(e)}
def get_findings(self, severity=None, active=True, limit=100):
params = {"active": active, "limit": limit}
if severity:
params["severity"] = severity
return self._get("findings/", params)
def get_products(self, limit=100):
return self._get("products/", {"limit": limit})
def get_engagements(self, product_id=None, limit=100):
params = {"limit": limit}
if product_id:
params["product"] = product_id
return self._get("engagements/", params)
def get_finding_count_by_severity(self):
result = {}
for sev in ["Critical", "High", "Medium", "Low", "Info"]:
data = self._get("findings/", {"severity": sev, "active": True, "limit": 1})
if isinstance(data, dict) and "count" in data:
result[sev] = data["count"]
return result
def import_scan(self, product_id, engagement_id, scan_type, file_path):
if not HAS_REQUESTS or not self.api_key:
return {"error": "requests not available or no API key"}
try:
with open(file_path, "rb") as f:
resp = requests.post(
self.url + "/api/v2/import-scan/",
headers={"Authorization": "Token " + self.api_key},
data={
"product": product_id,
"engagement": engagement_id,
"scan_type": scan_type,
"active": True,
"verified": False,
},
files={"file": f},
timeout=60,
)
if resp.status_code in (200, 201):
return resp.json()
return {"error": "HTTP {}".format(resp.status_code)}
except Exception as e:
return {"error": str(e)}
def build_dashboard_data(findings):
"""Build dashboard metrics from findings list."""
if not isinstance(findings, dict) or "results" not in findings:
return {"error": "Invalid findings data"}
results = findings["results"]
severity_counts = collections.Counter()
product_counts = collections.Counter()
age_sum = 0
overdue_count = 0
now = datetime.datetime.now(datetime.timezone.utc)
for f in results:
severity_counts[f.get("severity", "Unknown")] += 1
product_counts[f.get("test", {}).get("engagement", {}).get("product", {}).get("name", "Unknown")] += 1
if f.get("date"):
try:
created = datetime.datetime.fromisoformat(f["date"])
if created.tzinfo is None:
created = created.replace(tzinfo=datetime.timezone.utc)
age = (now - created).days
age_sum += age
sla = {"Critical": 7, "High": 30, "Medium": 90, "Low": 180}.get(f.get("severity", ""), 999)
if age > sla:
overdue_count += 1
except ValueError:
pass
total = len(results)
return {
"total_active_findings": total,
"by_severity": dict(severity_counts),
"by_product": dict(product_counts.most_common(10)),
"avg_age_days": round(age_sum / max(total, 1), 1),
"overdue_count": overdue_count,
"sla_compliance_pct": round((total - overdue_count) / max(total, 1) * 100, 1),
}
SUPPORTED_SCAN_TYPES = [
"Nessus Scan", "Qualys Scan", "Burp REST API",
"ZAP Scan", "Trivy Scan", "Snyk Scan",
"Semgrep JSON Report", "SARIF", "Generic Findings Import",
"Anchore Grype", "Nuclei Scan", "Checkov Scan",
]
if __name__ == "__main__":
print("=" * 60)
print("Vulnerability Dashboard with DefectDojo")
print("REST API v2 queries, severity metrics, SLA tracking")
print("=" * 60)
print(" requests available: {}".format(HAS_REQUESTS))
client = DefectDojoClient()
print("\n--- Supported Scan Types ---")
for st in SUPPORTED_SCAN_TYPES:
print(" - {}".format(st))
print("\n--- API Endpoints ---")
endpoints = [
("GET", "/api/v2/findings/", "List findings"),
("GET", "/api/v2/products/", "List products"),
("GET", "/api/v2/engagements/", "List engagements"),
("POST", "/api/v2/import-scan/", "Import scan results"),
("POST", "/api/v2/reimport-scan/", "Re-import scan results"),
]
for method, path, desc in endpoints:
print(" {} {:30s} {}".format(method, path, desc))
demo_findings = {
"count": 5,
"results": [
{"severity": "Critical", "title": "SQL Injection", "date": "2025-01-10", "test": {"engagement": {"product": {"name": "WebApp"}}}},
{"severity": "High", "title": "XSS", "date": "2025-01-15", "test": {"engagement": {"product": {"name": "WebApp"}}}},
{"severity": "Medium", "title": "Missing Headers", "date": "2024-12-01", "test": {"engagement": {"product": {"name": "API"}}}},
{"severity": "Low", "title": "Cookie flag", "date": "2025-02-01", "test": {"engagement": {"product": {"name": "API"}}}},
{"severity": "Critical", "title": "RCE", "date": "2025-02-20", "test": {"engagement": {"product": {"name": "WebApp"}}}},
],
}
dashboard = build_dashboard_data(demo_findings)
print("\n--- Dashboard ---")
for k, v in dashboard.items():
print(" {}: {}".format(k, v))
print("\n" + json.dumps({"findings_analyzed": demo_findings["count"]}, indent=2))
#!/usr/bin/env python3
"""DefectDojo Vulnerability Dashboard Automation.
Manages products, engagements, scan imports, and metrics via the
DefectDojo REST API v2.
"""
import argparse
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
import requests
DD_URL = os.environ.get("DD_URL", "http://localhost:8080/api/v2")
DD_API_KEY = os.environ.get("DD_API_KEY", "")
def get_headers():
return {
"Authorization": f"Token {DD_API_KEY}",
"Content-Type": "application/json",
}
def create_product_type(name, description=""):
resp = requests.post(
f"{DD_URL}/product_types/",
headers=get_headers(),
json={"name": name, "description": description},
timeout=30,
)
resp.raise_for_status()
pt = resp.json()
print(f"[+] Created product type: {name} (ID: {pt['id']})")
return pt["id"]
def create_product(name, product_type_id, description=""):
resp = requests.post(
f"{DD_URL}/products/",
headers=get_headers(),
json={
"name": name,
"description": description,
"prod_type": product_type_id,
},
timeout=30,
)
resp.raise_for_status()
product = resp.json()
print(f"[+] Created product: {name} (ID: {product['id']})")
return product["id"]
def create_engagement(name, product_id, start_date=None, end_date=None):
if not start_date:
start_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")
if not end_date:
end_date = "2025-12-31"
resp = requests.post(
f"{DD_URL}/engagements/",
headers=get_headers(),
json={
"name": name,
"product": product_id,
"target_start": start_date,
"target_end": end_date,
"engagement_type": "CI/CD",
"status": "In Progress",
},
timeout=30,
)
resp.raise_for_status()
eng = resp.json()
print(f"[+] Created engagement: {name} (ID: {eng['id']})")
return eng["id"]
def import_scan(scan_file, scan_type, product_name, engagement_name=None):
"""Import or reimport scan results into DefectDojo."""
data = {
"scan_type": scan_type,
"product_name": product_name,
"auto_create_context": "true",
"deduplication_on_engagement": "true",
"close_old_findings": "true",
}
if engagement_name:
data["engagement_name"] = engagement_name
with open(scan_file, "rb") as f:
resp = requests.post(
f"{DD_URL}/reimport-scan/",
headers={"Authorization": f"Token {DD_API_KEY}"},
data=data,
files={"file": f},
timeout=120,
)
if resp.status_code in (200, 201):
result = resp.json()
test_id = result.get("test", 0)
print(f"[+] Scan imported successfully (Test ID: {test_id})")
print(f" New findings: {result.get('statistics', {}).get('created', 0)}")
print(f" Closed findings: {result.get('statistics', {}).get('closed', 0)}")
print(f" Reactivated: {result.get('statistics', {}).get('reactivated', 0)}")
return result
else:
print(f"[-] Import failed: {resp.status_code} {resp.text}")
return None
def get_findings(product_id=None, severity=None, active=True, limit=100):
"""Query findings with filters."""
params = {"limit": limit, "active": str(active).lower()}
if product_id:
params["test__engagement__product"] = product_id
if severity:
params["severity"] = severity
resp = requests.get(f"{DD_URL}/findings/", headers=get_headers(), params=params, timeout=30)
resp.raise_for_status()
return resp.json()
def get_metrics(product_id=None):
"""Get vulnerability metrics for dashboard."""
params = {"limit": 0}
if product_id:
params["test__engagement__product"] = product_id
metrics = {}
for severity in ["Critical", "High", "Medium", "Low", "Info"]:
resp = requests.get(
f"{DD_URL}/findings/",
headers=get_headers(),
params={**params, "severity": severity, "active": "true"},
timeout=30,
)
if resp.status_code == 200:
metrics[severity] = resp.json().get("count", 0)
# SLA breached findings
resp = requests.get(
f"{DD_URL}/findings/",
headers=get_headers(),
params={**params, "active": "true", "is_mitigated": "false"},
timeout=30,
)
if resp.status_code == 200:
metrics["total_active"] = resp.json().get("count", 0)
return metrics
def generate_dashboard_report(output_path, product_id=None):
"""Generate dashboard metrics report."""
metrics = get_metrics(product_id)
report = {
"generated_at": datetime.now(timezone.utc).isoformat(),
"active_findings": metrics,
"total_active": metrics.get("total_active", 0),
}
with open(output_path, "w", encoding="utf-8") as f:
json.dump(report, f, indent=2)
print(f"\n[+] Dashboard Report: {output_path}")
print(f" Critical: {metrics.get('Critical', 0)}")
print(f" High: {metrics.get('High', 0)}")
print(f" Medium: {metrics.get('Medium', 0)}")
print(f" Low: {metrics.get('Low', 0)}")
print(f" Total Active: {metrics.get('total_active', 0)}")
return report
def main():
parser = argparse.ArgumentParser(description="DefectDojo Dashboard Automation")
parser.add_argument("--url", default=DD_URL, help="DefectDojo API URL")
parser.add_argument("--api-key", default=DD_API_KEY, help="API key")
sub = parser.add_subparsers(dest="command")
setup = sub.add_parser("setup", help="Create product type, product, engagement")
setup.add_argument("--product-type", required=True)
setup.add_argument("--product", required=True)
setup.add_argument("--engagement", default="CI/CD")
imp = sub.add_parser("import", help="Import scan results")
imp.add_argument("--file", required=True)
imp.add_argument("--scan-type", required=True)
imp.add_argument("--product", required=True)
imp.add_argument("--engagement")
dash = sub.add_parser("dashboard", help="Generate dashboard report")
dash.add_argument("--product-id", type=int)
dash.add_argument("--output", default="defectdojo_dashboard.json")
findings = sub.add_parser("findings", help="List findings")
findings.add_argument("--product-id", type=int)
findings.add_argument("--severity")
findings.add_argument("--limit", type=int, default=20)
args = parser.parse_args()
global DD_URL, DD_API_KEY
DD_URL = args.url
if args.api_key:
DD_API_KEY = args.api_key
if args.command == "setup":
pt_id = create_product_type(args.product_type)
prod_id = create_product(args.product, pt_id)
create_engagement(args.engagement, prod_id)
elif args.command == "import":
import_scan(args.file, args.scan_type, args.product, args.engagement)
elif args.command == "dashboard":
generate_dashboard_report(args.output, args.product_id)
elif args.command == "findings":
result = get_findings(args.product_id, args.severity, limit=args.limit)
for f in result.get("results", []):
print(f" [{f['severity']}] {f['title']} (ID: {f['id']})")
else:
parser.print_help()
if __name__ == "__main__":
main()