AGENT SKILL

vulnerability-csv-reporting

Generate structured CSV security audit reports from vulnerability data with proper schema control and a mandatory write-and-verify artifact gate before termination.

License 许可
Apache-2.0
最近更新
2026-11-14
Stars
★ 0
Forks
1

01 前言 Front Matter

name
vulnerability-csv-reporting
description
Generate structured CSV security audit reports from vulnerability data with proper schema control and a mandatory write-and-verify artifact gate before termination.

03 SKILL.md 正文

Vulnerability CSV Report Generation

This skill provides guidance on generating structured CSV reports from vulnerability scan data—a common format for security audits and compliance reporting.

Complete-the-deliverable workflow (do this before terminating)

  1. Identify the required deliverable(s) and the exact required path(s) early; treat paths as part of the spec.
  2. Always write the CSV even when there are zero findings (typically header-only with zero data rows).
  3. Immediately after writing, run a hard artifact gate: file exists at the exact required path, header matches the expected schema, and row count matches expectations.
  4. Only terminate after the artifact gate passes.
import csv
import os

def write_and_verify_csv(rows, out_path, headers):
    # Write
    os.makedirs(os.path.dirname(out_path) or '.', exist_ok=True)
    with open(out_path, 'w', newline='', encoding='utf-8') as f:
        w = csv.DictWriter(f, fieldnames=headers)
        w.writeheader()
        w.writerows(rows)

    # Hard artifact gate
    assert os.path.exists(out_path), "CSV missing at required path"
    with open(out_path, 'r', encoding='utf-8') as f:
        first = f.readline().strip()
    assert first.split(',') == headers, "CSV header mismatch"

    line_count = sum(1 for _ in open(out_path, 'r', encoding='utf-8'))
    assert line_count - 1 == len(rows), "CSV row count mismatch"

Decision rule: if the grader checks a file artifact, treat “write + artifact gate” as the last mandatory operation, and re-check the required output path from the task spec before stopping.

Overview

CSV (Comma-Separated Values) is a widely-used format for security reports because it's:

  • Human-readable: Can be opened in Excel, Google Sheets
  • Machine-parseable: Easy to process programmatically
  • Universal: Supported by all data analysis tools
  • Lightweight: Smaller than JSON/XML formats

When to Use CSV Reports

Ideal Use Cases

  • Compliance audits requiring tabular data
  • Executive summaries for non-technical stakeholders
  • Integration with ticketing systems (Jira, ServiceNow)
  • Automated vulnerability tracking pipelines
  • Data analysis in spreadsheet tools

Limitations

  • No hierarchical data (flat structure only)
  • Limited support for nested information
  • No standard for binary data

Alternative formats: JSON (for APIs), PDF (for formal reports), HTML (for dashboards)

CSV Schema Design for Security Reports

Essential Fields

A well-designed vulnerability report CSV should include:

Field Type Description Example
Package String Vulnerable package name express
Version String Installed version 4.17.1
CVE_ID String Vulnerability identifier CVE-2022-24999
Severity Enum Risk level CRITICAL, HIGH
CVSS_Score Float/String Numeric severity score 9.8 or N/A
Fixed_Version String Patched version 4.18.0 or N/A
Title String Brief description XSS in Express.js
Url String Reference link https://nvd.nist.gov/...

Design Principles

  1. Use descriptive column names: Package not pkg, CVE_ID not id
  2. Handle missing data: Use N/A for unavailable fields, not empty strings
  3. Consistent data types: Ensure all rows have same format
  4. Include metadata: Consider adding scan date, target, tool version

Python CSV Generation with DictWriter

Why DictWriter?

Python's csv.DictWriter is ideal for structured reports:

  • Type-safe: Column names defined upfront
  • Readable: Use dictionary keys instead of indices
  • Maintainable: Easy to add/remove columns
  • Automatic header generation: No manual header writing

Basic Usage

import csv

# Define schema
headers = ["Package", "Version", "CVE_ID", "Severity", "CVSS_Score", 
           "Fixed_Version", "Title", "Url"]

# Prepare data
vulnerabilities = [
    {
        "Package": "minimist",
        "Version": "1.2.5",
        "CVE_ID": "CVE-2021-44906",
        "Severity": "CRITICAL",
        "CVSS_Score": 9.8,
        "Fixed_Version": "1.2.6",
        "Title": "Prototype Pollution",
        "Url": "https://avd.aquasec.com/nvd/cve-2021-44906"
    }
]

# Write CSV
with open('security_audit.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=headers)
    writer.writeheader()  # Write column names
    writer.writerows(vulnerabilities)  # Write all rows

Important parameters:

  • newline='': Prevents extra blank lines on Windows
  • encoding='utf-8': Handles special characters in descriptions

Severity-Based Filtering

Why Filter by Severity?

Security teams prioritize based on risk. Filtering ensures reports focus on critical issues:

Severity Action Required Typical SLA
CRITICAL Immediate patch 24 hours
HIGH Urgent patch 7 days
MEDIUM Scheduled patch 30 days
LOW Optional patch 90 days

Implementation

def filter_high_severity(vulnerabilities, min_severity=['HIGH', 'CRITICAL']):
    """Filter vulnerabilities by severity level."""
    return [v for v in vulnerabilities if v.get('Severity') in min_severity]

Field Mapping from JSON to CSV

Extracting Fields from Scanner Output

import json

def parse_trivy_json_to_csv_records(json_file):
    """Parse Trivy JSON output and extract CSV-ready records."""
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    records = []
    for result in data.get('Results', []):
        for vuln in result.get('Vulnerabilities', []):
            records.append({
                "Package": vuln.get('PkgName'),
                "Version": vuln.get('InstalledVersion'),
                "CVE_ID": vuln.get('VulnerabilityID'),
                "Severity": vuln.get('Severity', 'UNKNOWN'),
                "CVSS_Score": extract_cvss_score(vuln),
                "Fixed_Version": vuln.get('FixedVersion', 'N/A'),
                "Title": vuln.get('Title', 'No description'),
                "Url": vuln.get('PrimaryURL', '')
            })
    return records

def extract_cvss_score(vuln):
    """Extract CVSS score (from cvss-score-extraction skill)."""
    cvss = vuln.get('CVSS', {})
    for source in ['nvd', 'ghsa', 'redhat']:
        score = (cvss.get(source) or {}).get('V3Score')
        if score is not None:
            return score
    return 'N/A'

Complete Vulnerability CSV Report Generator

import json
import csv


def generate_vulnerability_csv_report(json_input, csv_output, severity_filter=('HIGH', 'CRITICAL')):
    with open(json_input, 'r', encoding='utf-8') as f:
        data = json.load(f)

    headers = ["Package", "Version", "CVE_ID", "Severity", "CVSS_Score",
               "Fixed_Version", "Title", "Url"]

    rows = []
    for result in data.get('Results', []):
        for vuln in result.get('Vulnerabilities', []):
            if vuln.get('Severity') not in severity_filter:
                continue
            rows.append({
                "Package": vuln.get('PkgName'),
                "Version": vuln.get('InstalledVersion'),
                "CVE_ID": vuln.get('VulnerabilityID'),
                "Severity": vuln.get('Severity', 'UNKNOWN'),
                "CVSS_Score": extract_cvss_score(vuln),
                "Fixed_Version": vuln.get('FixedVersion', 'N/A'),
                "Title": vuln.get('Title', 'No description'),
                "Url": vuln.get('PrimaryURL', '')
            })

    with open(csv_output, 'w', newline='', encoding='utf-8') as f:
        w = csv.DictWriter(f, fieldnames=headers)
        w.writeheader()
        w.writerows(rows)

Common Pitfalls

  • Writing the report but not to the exact required path (relative paths or alternate filenames often fail grading).
  • Terminating after analysis without running a hard artifact gate (existence + header/schema + row count).
  • Omitting the CSV entirely when there are zero findings (write header-only instead).

Dependencies

  • csv (standard library)
  • json (standard library)

04 同仓库更多 Skills