
Building Vulnerability Aging And Sla Tracking
- 142 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with security tasks.
About
building-vulnerability-aging-and-sla-tracking is a Claude Code skill in the Security category.
- building-vulnerability-aging-and-sla-tracking
- Security
- AI-coding skill
Building Vulnerability Aging And Sla Tracking by the numbers
- 142 all-time installs (skills.sh)
- +5 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #909 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-aging-and-sla-trackingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 142 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with security tasks.
Files
Building Vulnerability Aging and SLA Tracking
Overview
With over 30,000 new vulnerabilities identified in 2024 (a 17% increase from the prior year), organizations must track how long vulnerabilities remain unpatched and whether remediation occurs within defined Service Level Agreements (SLAs). Vulnerability aging measures the time between discovery and remediation, while SLA tracking enforces severity-based deadlines. Industry benchmarks indicate standard SLAs of 14 days for critical, 30 days for high, 60 days for medium, and 90 days for low vulnerabilities, though more aggressive timelines (24-48 hours for actively exploited critical CVEs) are increasingly common. This skill covers designing SLA policies, building aging dashboards, implementing automated escalations, and generating compliance metrics.
When to Use
- When deploying or configuring building vulnerability aging and sla tracking 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
- Vulnerability management platform with historical scan data
- Asset inventory with criticality ratings
- ITSM/ticketing system for remediation tracking
- Reporting platform (Splunk, Elastic, Power BI, Grafana)
- Stakeholder agreement on SLA timelines and escalation procedures
Core Concepts
Standard Vulnerability SLA Framework
| Severity | CVSS Range | Standard SLA | Aggressive SLA | CISA KEV SLA |
|---|---|---|---|---|
| Critical | 9.0-10.0 | 14 days | 48 hours | BOD 22-01 due date |
| High | 7.0-8.9 | 30 days | 7 days | 14 days |
| Medium | 4.0-6.9 | 60 days | 30 days | N/A |
| Low | 0.1-3.9 | 90 days | 60 days | N/A |
| Informational | 0.0 | Best effort | Best effort | N/A |
Adaptive SLA Modifiers
| Factor | Modifier | Rationale |
|---|---|---|
| Internet-facing asset | -50% SLA | Higher exposure risk |
| CISA KEV listed | Override to 48h | Active exploitation confirmed |
| EPSS > 0.7 | -50% SLA | High exploitation probability |
| Tier 1 (crown jewel) asset | -25% SLA | Maximum business impact |
| Compensating control in place | +25% SLA | Risk partially mitigated |
| Vendor patch unavailable | Exception with review date | Cannot remediate yet |
Key Performance Indicators (KPIs)
| KPI | Formula | Target |
|---|---|---|
| Mean Time to Remediate (MTTR) | Avg(remediation_date - discovery_date) | < 30 days overall |
| SLA Compliance Rate | (Vulns remediated within SLA / Total vulns) * 100 | >= 90% |
| Overdue Vulnerability Count | Count where age > SLA | Trending downward |
| Vulnerability Aging Distribution | Count by age bucket (0-14d, 15-30d, 31-60d, 60+d) | Majority in 0-30d |
| Remediation Velocity | Vulns closed per week | Trending upward |
| Exception Rate | (Exceptions / Total vulns) * 100 | < 5% |
Workflow
Step 1: Define SLA Policy Document
Vulnerability Remediation SLA Policy v1.0
1. Scope: All information systems and applications
2. Severity Classification: Based on CVSS v4.0/v3.1 base score
3. SLA Timelines: See Standard SLA Framework table
4. Adaptive Modifiers: Applied based on asset context
5. Exception Process:
- Must be documented with business justification
- Requires compensating control description
- Maximum extension: 90 days (one renewal)
- CISO approval required for Critical/High exceptions
6. Escalation Path:
- 50% SLA elapsed: Automated reminder to asset owner
- 75% SLA elapsed: Escalation to manager
- 100% SLA elapsed (overdue): CISO notification
- 120% SLA elapsed: VP/CTO escalation
7. Metrics Reporting: Monthly to security committeeStep 2: Build the Aging Calculation Engine
import pandas as pd
from datetime import datetime, timedelta
class VulnerabilityAgingTracker:
"""Track vulnerability aging and SLA compliance."""
SLA_DAYS = {
"Critical": 14,
"High": 30,
"Medium": 60,
"Low": 90,
}
def __init__(self, sla_overrides=None):
if sla_overrides:
self.SLA_DAYS.update(sla_overrides)
def calculate_aging(self, vulns_df):
"""Calculate aging metrics for each vulnerability."""
today = datetime.now()
vulns_df["discovery_date"] = pd.to_datetime(vulns_df["discovery_date"])
vulns_df["remediation_date"] = pd.to_datetime(
vulns_df["remediation_date"], errors="coerce"
)
vulns_df["age_days"] = vulns_df.apply(
lambda row: (row["remediation_date"] - row["discovery_date"]).days
if pd.notna(row["remediation_date"])
else (today - row["discovery_date"]).days,
axis=1
)
vulns_df["sla_days"] = vulns_df["severity"].map(self.SLA_DAYS)
vulns_df["sla_deadline"] = vulns_df["discovery_date"] + \
pd.to_timedelta(vulns_df["sla_days"], unit="D")
vulns_df["is_overdue"] = vulns_df.apply(
lambda row: row["age_days"] > row["sla_days"]
if pd.isna(row["remediation_date"]) else False,
axis=1
)
vulns_df["sla_compliance"] = vulns_df.apply(
lambda row: row["age_days"] <= row["sla_days"]
if pd.notna(row["remediation_date"]) else None,
axis=1
)
vulns_df["days_overdue"] = vulns_df.apply(
lambda row: max(0, row["age_days"] - row["sla_days"])
if row["is_overdue"] else 0,
axis=1
)
vulns_df["sla_pct_elapsed"] = (
vulns_df["age_days"] / vulns_df["sla_days"] * 100
).round(1)
return vulns_df
def generate_kpis(self, vulns_df):
"""Generate KPI summary from aging data."""
open_vulns = vulns_df[vulns_df["remediation_date"].isna()]
closed_vulns = vulns_df[vulns_df["remediation_date"].notna()]
kpis = {
"total_vulnerabilities": len(vulns_df),
"open_vulnerabilities": len(open_vulns),
"closed_vulnerabilities": len(closed_vulns),
"overdue_count": open_vulns["is_overdue"].sum(),
"mttr_days": closed_vulns["age_days"].mean() if len(closed_vulns) > 0 else 0,
"sla_compliance_rate": (
closed_vulns["sla_compliance"].mean() * 100
if len(closed_vulns) > 0 else 0
),
}
kpis["overdue_by_severity"] = (
open_vulns[open_vulns["is_overdue"]]
.groupby("severity")
.size()
.to_dict()
)
return kpis
def get_escalation_list(self, vulns_df):
"""Get vulnerabilities requiring escalation."""
open_vulns = vulns_df[vulns_df["remediation_date"].isna()].copy()
escalations = []
for _, vuln in open_vulns.iterrows():
pct = vuln["sla_pct_elapsed"]
if pct >= 120:
level = "VP/CTO Escalation"
elif pct >= 100:
level = "CISO Notification"
elif pct >= 75:
level = "Manager Escalation"
elif pct >= 50:
level = "Owner Reminder"
else:
continue
escalations.append({
"cve_id": vuln.get("cve_id", ""),
"severity": vuln["severity"],
"age_days": vuln["age_days"],
"sla_days": vuln["sla_days"],
"days_overdue": vuln["days_overdue"],
"sla_pct": pct,
"escalation_level": level,
"asset": vuln.get("asset", ""),
"owner": vuln.get("owner", ""),
})
return pd.DataFrame(escalations)Step 3: Dashboard Visualization
# Grafana/Kibana query examples for vulnerability aging
# Age distribution histogram (Elasticsearch)
age_distribution_query = {
"aggs": {
"age_buckets": {
"range": {
"field": "age_days",
"ranges": [
{"key": "0-7 days", "to": 8},
{"key": "8-14 days", "from": 8, "to": 15},
{"key": "15-30 days", "from": 15, "to": 31},
{"key": "31-60 days", "from": 31, "to": 61},
{"key": "61-90 days", "from": 61, "to": 91},
{"key": "90+ days", "from": 91},
]
}
}
}
}
# SLA compliance trend (monthly)
sla_trend_query = {
"aggs": {
"monthly": {
"date_histogram": {"field": "remediation_date", "interval": "month"},
"aggs": {
"within_sla": {
"filter": {"script": {
"source": "doc['age_days'].value <= doc['sla_days'].value"
}}
}
}
}
}
}Best Practices
1. Start with achievable SLA targets and tighten them as processes mature 2. Adapt SLAs based on asset criticality and threat context, not just CVSS scores 3. Automate escalation notifications to reduce manual tracking overhead 4. Track MTTR trends month-over-month to demonstrate improvement 5. Build exception workflows that require documented compensating controls 6. Report SLA compliance to executive leadership monthly for accountability 7. Include aging metrics in security committee and board-level reporting 8. Integrate SLA tracking with ITSM ticketing for end-to-end remediation visibility
Common Pitfalls
- Setting unrealistic SLA targets that teams cannot meet, causing SLA fatigue
- Not adapting SLAs for asset criticality, treating all systems equally
- Lacking exception processes, forcing teams to either ignore SLAs or request blanket waivers
- Measuring only open vulnerability count without considering age and SLA compliance
- Not tracking the SLA clock from discovery date (using report date instead)
- Failing to re-baseline SLAs as team maturity improves
Related Skills
- implementing-vulnerability-remediation-sla
- building-executive-vulnerability-risk-report
- implementing-security-metrics-and-kpis
- performing-remediation-validation-scanning
Vulnerability Aging and SLA Compliance Report Template
KPI Summary
| Metric | Current Month | Prior Month | Target | Trend |
|---|---|---|---|---|
| Total Open Vulnerabilities | [N] | [N] | Decreasing | [Up/Down] |
| MTTR (all severities) | [N] days | [N] days | < 30 days | [Up/Down] |
| SLA Compliance Rate | [N]% | [N]% | >= 90% | [Up/Down] |
| Overdue Count | [N] | [N] | 0 | [Up/Down] |
| Exception Count | [N] | [N] | < 5% | [Up/Down] |
Aging Distribution
| Age Bucket | Critical | High | Medium | Low | Total |
|---|---|---|---|---|---|
| 0-7 days | [N] | [N] | [N] | [N] | [N] |
| 8-14 days | [N] | [N] | [N] | [N] | [N] |
| 15-30 days | [N] | [N] | [N] | [N] | [N] |
| 31-60 days | [N] | [N] | [N] | [N] | [N] |
| 61-90 days | [N] | [N] | [N] | [N] | [N] |
| 90+ days | [N] | [N] | [N] | [N] | [N] |
Escalation Summary
| Level | Count | Top Offending Team |
|---|---|---|
| Owner Reminder (50%) | [N] | [Team] |
| Manager Escalation (75%) | [N] | [Team] |
| CISO Notification (100%) | [N] | [Team] |
| VP/CTO Escalation (120%+) | [N] | [Team] |
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 Aging and SLA Tracking
SLA Definitions
| Severity | Remediation SLA | Patch SLA | Exception Max |
|---|---|---|---|
| Critical | 7 days | 15 days | 30 days |
| High | 30 days | 45 days | 90 days |
| Medium | 90 days | 120 days | 180 days |
| Low | 180 days | 365 days | 365 days |
Aging Buckets
| Bucket | Range |
|---|---|
| New | 0-7 days |
| Recent | 8-30 days |
| Aging | 31-60 days |
| Old | 61-90 days |
| Stale | 91-180 days |
| Ancient | 181-365 days |
| Critical Overdue | 365+ days |
Nessus API (Tenable.io)
# List vulnerabilities
curl -H "X-ApiKeys: accessKey=$ACCESS;secretKey=$SECRET" \
"https://cloud.tenable.com/workbenches/vulnerabilities"
# Export vulns
curl -X POST -H "X-ApiKeys: accessKey=$ACCESS;secretKey=$SECRET" \
"https://cloud.tenable.com/vulns/export" \
-d '{"filters":{"severity":["critical","high"]}}'Qualys API
# Vulnerability list
curl -u "user:pass" -X POST \
"https://qualysapi.qualys.com/api/2.0/fo/knowledge_base/vuln/" \
-d "action=list&details=All&published_after=2024-01-01"Key Metrics
| Metric | Description |
|---|---|
| MTTR | Mean Time to Remediate |
| SLA Compliance % | Vulns resolved within SLA / Total |
| Overdue Count | Vulns past SLA deadline |
| Risk Score | CVSS age_factor asset_criticality |
Standards and References - Vulnerability Aging and SLA Tracking
Industry Standards
- NIST SP 800-40 Rev 4: Guide to Enterprise Patch Management Planning
- CIS Controls v8.1 Control 7: Continuous Vulnerability Management
- PCI DSS v4.0 Req 6.3.3: Security patches installed within one month
- BOD 22-01: CISA remediation timelines for KEV vulnerabilities
- ISO 27001:2022 A.8.8: Management of technical vulnerabilities
SLA Benchmark References
- Tenable SLA Remediation: https://docs.tenable.com/cyber-exposure-studies/cyber-exposure-insurance/Content/SLARemediation.htm
- Nucleus Security SLA Guide: https://nucleussec.com/blog/how-to-define-vulnerability-remediation-slas-shortcuts-2/
- Phoenix Security SLA Framework: https://phoenix.security/vulnerability-timelines-sla-measurement-and-prioritization/
Industry SLA Benchmarks
| Source | Critical | High | Medium | Low |
|---|---|---|---|---|
| CISA BOD 22-01 | 2 weeks | N/A | N/A | N/A |
| PCI DSS | 30 days | 30 days | 90 days | 90 days |
| Industry Average | 14 days | 30 days | 60 days | 90 days |
| Aggressive Target | 48 hours | 7 days | 30 days | 60 days |
Vulnerability Statistics (2024)
- Total new CVEs published: 30,000+
- Year-over-year increase: 17%
- Average MTTR across industries: ~60 days
- Top-performing organizations MTTR: < 15 days for critical
Workflows - Vulnerability Aging and SLA Tracking
Workflow 1: SLA Lifecycle
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Vulnerability │────>│ Assign Severity │────>│ Calculate SLA │
│ Discovered │ │ + Asset Context │ │ Deadline │
└──────────────────┘ └──────────────────┘ └──────────────────┘
│ │
v v
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Create Ticket │────>│ Monitor Aging │────>│ Trigger │
│ (ITSM) │ │ (Daily) │ │ Escalations │
└──────────────────┘ └──────────────────┘ └──────────────────┘Workflow 2: Escalation Ladder
SLA % Elapsed:
50% ──> Email reminder to asset owner
75% ──> Escalation to owner's manager
100% ──> CISO notification, marked overdue
120% ──> VP/CTO escalation, exception requiredWorkflow 3: Monthly Reporting Cycle
Week 1: Collect scan data and aging metrics
Week 2: Generate KPI dashboard
Week 3: Present to security committee
Week 4: Action items assigned, SLA adjustments if needed#!/usr/bin/env python3
"""Vulnerability aging and SLA tracking agent.
Tracks vulnerability remediation timelines, calculates SLA compliance,
generates aging reports, and identifies overdue items by severity.
"""
import json
import datetime
import collections
SLA_DEFINITIONS = {
"critical": {"remediation_days": 7, "patch_days": 15, "exception_max_days": 30},
"high": {"remediation_days": 30, "patch_days": 45, "exception_max_days": 90},
"medium": {"remediation_days": 90, "patch_days": 120, "exception_max_days": 180},
"low": {"remediation_days": 180, "patch_days": 365, "exception_max_days": 365},
}
AGING_BUCKETS = [
(0, 7, "0-7 days"),
(8, 30, "8-30 days"),
(31, 60, "31-60 days"),
(61, 90, "61-90 days"),
(91, 180, "91-180 days"),
(181, 365, "181-365 days"),
(366, 99999, "365+ days"),
]
def calculate_age(discovery_date_str):
"""Calculate vulnerability age in days from discovery date."""
try:
disc = datetime.datetime.fromisoformat(discovery_date_str.replace("Z", "+00:00"))
now = datetime.datetime.now(datetime.timezone.utc)
return (now - disc).days
except (ValueError, AttributeError):
return 0
def check_sla_compliance(vuln):
"""Check if a vulnerability is within SLA."""
severity = vuln.get("severity", "medium").lower()
sla = SLA_DEFINITIONS.get(severity, SLA_DEFINITIONS["medium"])
age = calculate_age(vuln.get("discovery_date", ""))
status = vuln.get("status", "open")
result = {
"vuln_id": vuln.get("id", ""),
"severity": severity,
"age_days": age,
"sla_days": sla["remediation_days"],
"days_remaining": sla["remediation_days"] - age,
"sla_status": "within_sla",
}
if status in ("remediated", "closed"):
result["sla_status"] = "resolved"
elif status == "exception":
if age > sla["exception_max_days"]:
result["sla_status"] = "exception_expired"
else:
result["sla_status"] = "exception_active"
elif age > sla["remediation_days"]:
result["sla_status"] = "overdue"
elif age > sla["remediation_days"] * 0.8:
result["sla_status"] = "at_risk"
return result
def build_aging_report(vulns):
"""Build vulnerability aging distribution report."""
buckets = {label: {"total": 0, "critical": 0, "high": 0, "medium": 0, "low": 0}
for _, _, label in AGING_BUCKETS}
for vuln in vulns:
if vuln.get("status") in ("remediated", "closed"):
continue
age = calculate_age(vuln.get("discovery_date", ""))
severity = vuln.get("severity", "medium").lower()
for low, high, label in AGING_BUCKETS:
if low <= age <= high:
buckets[label]["total"] += 1
if severity in buckets[label]:
buckets[label][severity] += 1
break
return {"aging_distribution": buckets, "generated_at": datetime.datetime.utcnow().isoformat() + "Z"}
def calculate_mttr(vulns):
"""Calculate Mean Time to Remediate by severity."""
remediation_times = collections.defaultdict(list)
for vuln in vulns:
if vuln.get("status") in ("remediated", "closed") and vuln.get("remediation_date"):
try:
disc = datetime.datetime.fromisoformat(vuln["discovery_date"].replace("Z", "+00:00"))
rem = datetime.datetime.fromisoformat(vuln["remediation_date"].replace("Z", "+00:00"))
days = (rem - disc).days
severity = vuln.get("severity", "medium").lower()
remediation_times[severity].append(days)
except (ValueError, KeyError):
pass
mttr = {}
for sev, times in remediation_times.items():
mttr[sev] = {
"mean_days": round(sum(times) / len(times), 1),
"median_days": sorted(times)[len(times) // 2],
"count": len(times),
}
return mttr
def generate_sla_dashboard(vulns):
"""Generate SLA compliance dashboard data."""
total = 0
compliant = 0
overdue = 0
at_risk = 0
by_severity = collections.defaultdict(lambda: {"total": 0, "compliant": 0, "overdue": 0})
for vuln in vulns:
sla_result = check_sla_compliance(vuln)
if sla_result["sla_status"] == "resolved":
continue
total += 1
severity = sla_result["severity"]
by_severity[severity]["total"] += 1
if sla_result["sla_status"] == "within_sla":
compliant += 1
by_severity[severity]["compliant"] += 1
elif sla_result["sla_status"] == "overdue":
overdue += 1
by_severity[severity]["overdue"] += 1
elif sla_result["sla_status"] == "at_risk":
at_risk += 1
return {
"total_open": total,
"compliant": compliant,
"overdue": overdue,
"at_risk": at_risk,
"compliance_rate": round(compliant / max(total, 1) * 100, 1),
"by_severity": dict(by_severity),
}
if __name__ == "__main__":
print("=" * 60)
print("Vulnerability Aging & SLA Tracking")
print("SLA compliance, aging distribution, MTTR calculation")
print("=" * 60)
now = datetime.datetime.utcnow()
demo_vulns = [
{"id": "CVE-2024-1234", "severity": "critical", "status": "open",
"discovery_date": (now - datetime.timedelta(days=10)).isoformat() + "Z"},
{"id": "CVE-2024-2345", "severity": "high", "status": "open",
"discovery_date": (now - datetime.timedelta(days=45)).isoformat() + "Z"},
{"id": "CVE-2024-3456", "severity": "medium", "status": "open",
"discovery_date": (now - datetime.timedelta(days=120)).isoformat() + "Z"},
{"id": "CVE-2024-4567", "severity": "critical", "status": "remediated",
"discovery_date": (now - datetime.timedelta(days=5)).isoformat() + "Z",
"remediation_date": (now - datetime.timedelta(days=2)).isoformat() + "Z"},
{"id": "CVE-2024-5678", "severity": "low", "status": "exception",
"discovery_date": (now - datetime.timedelta(days=200)).isoformat() + "Z"},
]
print("\n--- SLA Compliance ---")
for vuln in demo_vulns:
result = check_sla_compliance(vuln)
print(" {} [{}] age={}d sla={}d -> {}".format(
result["vuln_id"], result["severity"], result["age_days"],
result["sla_days"], result["sla_status"]))
dashboard = generate_sla_dashboard(demo_vulns)
print("\n--- Dashboard ---")
print(" Compliance rate: {}%".format(dashboard["compliance_rate"]))
print(" Open: {} | Compliant: {} | Overdue: {} | At-risk: {}".format(
dashboard["total_open"], dashboard["compliant"], dashboard["overdue"], dashboard["at_risk"]))
mttr = calculate_mttr(demo_vulns)
if mttr:
print("\n--- MTTR ---")
for sev, data in mttr.items():
print(" {}: mean={}d median={}d (n={})".format(sev, data["mean_days"], data["median_days"], data["count"]))
print("\n" + json.dumps({"vulns_tracked": len(demo_vulns)}, indent=2))
#!/usr/bin/env python3
"""
Vulnerability Aging and SLA Tracking Engine
Calculates vulnerability aging, SLA compliance, and generates
escalation reports and KPI dashboards.
Requirements:
pip install pandas
Usage:
python process.py analyze --csv vulns.csv --output aging_report.csv
python process.py kpis --csv vulns.csv
python process.py escalations --csv vulns.csv --output escalations.csv
"""
import argparse
import sys
from datetime import datetime, timedelta
import pandas as pd
SLA_DAYS = {
"Critical": 14,
"High": 30,
"Medium": 60,
"Low": 90,
}
def calculate_aging(df, sla_config=None):
"""Add aging and SLA columns to vulnerability dataframe."""
sla = sla_config or SLA_DAYS
today = pd.Timestamp.now()
df["discovery_date"] = pd.to_datetime(df["discovery_date"])
df["remediation_date"] = pd.to_datetime(df["remediation_date"], errors="coerce")
df["age_days"] = df.apply(
lambda r: (r["remediation_date"] - r["discovery_date"]).days
if pd.notna(r["remediation_date"])
else (today - r["discovery_date"]).days,
axis=1
)
df["sla_days"] = df["severity"].map(sla).fillna(90).astype(int)
df["sla_deadline"] = df["discovery_date"] + pd.to_timedelta(df["sla_days"], unit="D")
df["is_open"] = df["remediation_date"].isna()
df["is_overdue"] = df["is_open"] & (df["age_days"] > df["sla_days"])
df["days_overdue"] = df.apply(
lambda r: max(0, r["age_days"] - r["sla_days"]) if r["is_overdue"] else 0,
axis=1
)
df["sla_pct_elapsed"] = (df["age_days"] / df["sla_days"] * 100).round(1)
df["within_sla"] = df.apply(
lambda r: r["age_days"] <= r["sla_days"]
if pd.notna(r["remediation_date"]) else None,
axis=1
)
return df
def generate_kpis(df):
"""Generate KPI summary."""
open_df = df[df["is_open"]]
closed_df = df[~df["is_open"]]
print(f"\n{'=' * 60}")
print("VULNERABILITY AGING KPI REPORT")
print(f"{'=' * 60}")
print(f"Report Date: {datetime.now().strftime('%Y-%m-%d')}")
print(f"Total Vulnerabilities: {len(df)}")
print(f"Open: {len(open_df)}")
print(f"Closed: {len(closed_df)}")
print(f"Overdue: {open_df['is_overdue'].sum()}")
if len(closed_df) > 0:
mttr = closed_df["age_days"].mean()
sla_rate = closed_df["within_sla"].mean() * 100
print(f"\nMTTR (all): {mttr:.1f} days")
print(f"SLA Compliance Rate: {sla_rate:.1f}%")
for sev in ["Critical", "High", "Medium", "Low"]:
sev_df = closed_df[closed_df["severity"] == sev]
if len(sev_df) > 0:
print(f" {sev} MTTR: {sev_df['age_days'].mean():.1f}d "
f"| SLA: {sev_df['within_sla'].mean() * 100:.1f}%")
print(f"\nOpen Vulnerabilities by Age:")
bins = [0, 7, 14, 30, 60, 90, float("inf")]
labels = ["0-7d", "8-14d", "15-30d", "31-60d", "61-90d", "90+d"]
if len(open_df) > 0:
open_df = open_df.copy()
open_df["age_bucket"] = pd.cut(open_df["age_days"], bins=bins, labels=labels)
print(open_df["age_bucket"].value_counts().sort_index().to_string())
print(f"\nOverdue by Severity:")
overdue = open_df[open_df["is_overdue"]]
if len(overdue) > 0:
print(overdue.groupby("severity")["days_overdue"].agg(["count", "mean", "max"]).to_string())
def generate_escalations(df):
"""Generate escalation list."""
open_df = df[df["is_open"]].copy()
escalations = []
for _, row in open_df.iterrows():
pct = row["sla_pct_elapsed"]
if pct >= 120:
level = "VP/CTO Escalation"
elif pct >= 100:
level = "CISO Notification"
elif pct >= 75:
level = "Manager Escalation"
elif pct >= 50:
level = "Owner Reminder"
else:
continue
escalations.append({
"cve_id": row.get("cve_id", ""),
"severity": row["severity"],
"asset": row.get("asset", ""),
"owner": row.get("owner", ""),
"age_days": row["age_days"],
"sla_days": row["sla_days"],
"days_overdue": row["days_overdue"],
"sla_pct": pct,
"escalation_level": level,
})
return pd.DataFrame(escalations).sort_values("sla_pct", ascending=False)
def main():
parser = argparse.ArgumentParser(description="Vulnerability Aging and SLA Tracker")
subparsers = parser.add_subparsers(dest="command")
analyze_p = subparsers.add_parser("analyze", help="Calculate aging metrics")
analyze_p.add_argument("--csv", required=True)
analyze_p.add_argument("--output", default="aging_report.csv")
subparsers.add_parser("kpis", help="Generate KPI summary").add_argument("--csv", required=True)
esc_p = subparsers.add_parser("escalations", help="Generate escalation list")
esc_p.add_argument("--csv", required=True)
esc_p.add_argument("--output", default="escalations.csv")
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(1)
df = pd.read_csv(args.csv)
df = calculate_aging(df)
if args.command == "analyze":
df.to_csv(args.output, index=False)
print(f"[+] Aging report saved to {args.output}")
generate_kpis(df)
elif args.command == "kpis":
generate_kpis(df)
elif args.command == "escalations":
esc_df = generate_escalations(df)
esc_df.to_csv(args.output, index=False)
print(f"[+] {len(esc_df)} escalations saved to {args.output}")
if len(esc_df) > 0:
print(esc_df["escalation_level"].value_counts().to_string())
if __name__ == "__main__":
main()