compliance governance

Performing NIST CSF Maturity Assessment

The NIST Cybersecurity Framework (CSF) 2.0, released in February 2024, provides a comprehensive taxonomy for managing cybersecurity risk through six core Functions - Govern, Identify, Protect, Detect, Respond, and Recover. This skill covers conducting a maturity assessment against the CSF using Implementation Tiers to measure organizational cybersecurity posture and create improvement roadmaps.

compliancecsfgovernancematurity-assessmentnistrisk-management
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

The NIST Cybersecurity Framework (CSF) 2.0, released in February 2024, provides a comprehensive taxonomy for managing cybersecurity risk through six core Functions: Govern, Identify, Protect, Detect, Respond, and Recover. This skill covers conducting a maturity assessment against the CSF, using the four Implementation Tiers (Partial, Risk-Informed, Repeatable, Adaptive) to measure organizational cybersecurity posture and create improvement roadmaps.

When to Use

  • When conducting security assessments that involve performing nist csf maturity assessment
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Understanding of cybersecurity risk management principles
  • Access to NIST CSF 2.0 documentation and reference tool
  • Knowledge of organizational IT/OT environment and security controls
  • Stakeholder access across business units for assessment interviews

Core Concepts

CSF 2.0 Functions (6 Functions, 22 Categories)

Function Code Categories Purpose
Govern GV 6 Establish and monitor cybersecurity risk management strategy
Identify ID 3 Determine current cybersecurity risk to the organization
Protect PR 5 Implement safeguards to prevent or reduce risk
Detect DE 2 Find and analyze possible cybersecurity attacks
Respond RS 4 Take action regarding detected cybersecurity incidents
Recover RC 2 Restore capabilities impaired by cybersecurity incidents

Govern Function (New in CSF 2.0)

  • GV.OC: Organizational Context
  • GV.RM: Risk Management Strategy
  • GV.RR: Roles, Responsibilities, and Authorities
  • GV.PO: Policy
  • GV.OV: Oversight
  • GV.SC: Cybersecurity Supply Chain Risk Management

Implementation Tiers

Tier Name Description
Tier 1 Partial Ad hoc, reactive; limited awareness of cybersecurity risk
Tier 2 Risk-Informed Risk-aware but not organization-wide; approved but may not be policy
Tier 3 Repeatable Formal policies; consistently implemented; regularly updated
Tier 4 Adaptive Continuous improvement; real-time risk response; lessons learned integrated

Workflow

Phase 1: Scoping and Preparation (Weeks 1-2)

  1. Define assessment scope (enterprise-wide vs. business unit)
  2. Identify stakeholders and schedule interviews
  3. Gather existing documentation (policies, procedures, architecture diagrams)
  4. Customize CSF Profile for organizational context
  5. Select assessment methodology (self-assessment, facilitated, third-party)

Phase 2: Current State Assessment (Weeks 3-6)

  1. Assess each CSF Category and Subcategory against Implementation Tiers
  2. For each subcategory, evaluate:
    • Policy/documentation maturity
    • Implementation completeness
    • Automation level
    • Measurement and metrics
    • Continuous improvement evidence
  3. Score using tier criteria (1-4 scale)
  4. Document evidence supporting each tier rating
  5. Identify strengths, gaps, and improvement areas

Phase 3: Target State Definition (Weeks 7-8)

  1. Define target tier for each Function based on:
    • Risk appetite and tolerance
    • Industry requirements and benchmarks
    • Regulatory obligations
    • Available resources and budget
  2. Create Target Profile documenting desired maturity state
  3. Validate target state with executive leadership

Phase 4: Gap Analysis and Roadmap (Weeks 9-12)

  1. Compare Current Profile to Target Profile
  2. Prioritize gaps based on risk reduction potential
  3. Develop improvement roadmap with:
    • Short-term quick wins (0-3 months)
    • Medium-term improvements (3-12 months)
    • Long-term strategic initiatives (12-24 months)
  4. Estimate resource requirements for each initiative
  5. Assign ownership and timelines

Phase 5: Implementation and Reassessment (Ongoing)

  1. Execute improvement roadmap initiatives
  2. Track progress against milestones
  3. Conduct periodic reassessments (annually recommended)
  4. Report maturity progress to leadership
  5. Adjust roadmap based on evolving threats and business changes

Key Artifacts

  • CSF Current Profile (by Function/Category/Subcategory)
  • CSF Target Profile
  • Gap Analysis Report
  • Maturity Assessment Scorecard
  • Improvement Roadmap with Priorities
  • Executive Summary and Dashboard

Common Pitfalls

  • Assessing technology only without evaluating governance and people
  • Setting unrealistic target tiers without resource commitment
  • Treating assessment as one-time rather than continuous process
  • Ignoring the new Govern function in CSF 2.0
  • Not aligning CSF assessment with existing compliance requirements (ISO 27001, SOC 2)

References

Source materials

References and resources

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

References 3

api-reference.md1.6 KB

API Reference — Performing NIST CSF Maturity Assessment

Libraries Used

  • csv: Parse and generate assessment CSV files
  • pathlib: File operations

CLI Interface

python agent.py assess --csv assessment_responses.csv
python agent.py gaps --csv assessment_responses.csv
python agent.py template [--output template.csv]
python agent.py executive --csv assessment_responses.csv

Core Functions

assess_from_csv(assessment_file) — Calculate maturity scores

Scores each NIST CSF function (Identify, Protect, Detect, Respond, Recover). Calculates overall maturity level (1-4 scale) and gap-to-target.

generate_gap_analysis(assessment_file) — Prioritized gap report

Classifies gaps: HIGH (>=2 gap), MEDIUM (>=1), LOW (<1).

create_assessment_template(output_file) — Generate blank assessment CSV

Produces CSV with all 23 CSF categories, score/target/evidence columns.

generate_executive_summary(assessment_file) — Board-level report

NIST CSF Functions & Categories (23 total)

Function Categories
IDENTIFY ID.AM, ID.BE, ID.GV, ID.RA, ID.RM, ID.SC
PROTECT PR.AC, PR.AT, PR.DS, PR.IP, PR.MA, PR.PT
DETECT DE.AE, DE.CM, DE.DP
RESPOND RS.RP, RS.CO, RS.AN, RS.MI, RS.IM
RECOVER RC.RP, RC.IM, RC.CO

Maturity Levels

Level Name Description
1 Partial Not formalized
2 Risk Informed Approved but not org-wide
3 Repeatable Formally expressed as policy
4 Adaptive Continuous improvement

Dependencies

No external packages — Python standard library only.

standards.md3.5 KB

NIST CSF 2.0 Standards Reference

Primary Standard

NIST Cybersecurity Framework (CSF) Version 2.0

  • Published: February 26, 2024
  • Publisher: National Institute of Standards and Technology (NIST)
  • Document: NIST CSWP 29
  • Scope: Applicable to all organizations regardless of size, sector, or maturity
  • Key Change: Added Govern function as central pillar; expanded from 5 to 6 functions

CSF 2.0 Core Structure

GV - Govern

  • GV.OC-01 to GV.OC-05: Organizational context understood
  • GV.RM-01 to GV.RM-07: Risk management strategy established
  • GV.RR-01 to GV.RR-04: Roles, responsibilities, and authorities
  • GV.PO-01 to GV.PO-02: Cybersecurity policy established
  • GV.OV-01 to GV.OV-03: Cybersecurity strategy oversight
  • GV.SC-01 to GV.SC-10: Supply chain risk management

ID - Identify

  • ID.AM-01 to ID.AM-08: Asset management
  • ID.RA-01 to ID.RA-10: Risk assessment
  • ID.IM-01 to ID.IM-04: Improvement
  • ID.BE (removed in 2.0, moved to GV)

PR - Protect

  • PR.AA-01 to PR.AA-06: Identity management, authentication, access control
  • PR.AT-01 to PR.AT-02: Awareness and training
  • PR.DS-01 to PR.DS-10: Data security
  • PR.PS-01 to PR.PS-06: Platform security
  • PR.IR-01 to PR.IR-02: Technology infrastructure resilience

DE - Detect

  • DE.CM-01 to DE.CM-09: Continuous monitoring
  • DE.AE-01 to DE.AE-08: Adverse event analysis

RS - Respond

  • RS.MA-01 to RS.MA-05: Incident management
  • RS.AN-01 to RS.AN-08: Incident analysis
  • RS.CO-01 to RS.CO-03: Incident response reporting and communication
  • RS.MI-01 to RS.MI-02: Incident mitigation

RC - Recover

  • RC.RP-01 to RC.RP-06: Incident recovery plan execution

Implementation Tiers Detail

Tier 1: Partial

  • Risk Management Process: Ad hoc; not formalized
  • Integrated Risk Management: Limited awareness; irregular risk practices
  • External Participation: No formal collaboration with external entities
  • Governance: Cybersecurity not integrated into enterprise risk management

Tier 2: Risk-Informed

  • Risk Management Process: Approved by management but may not be policy
  • Integrated Risk Management: Awareness at organizational level; some sharing
  • External Participation: Aware of ecosystem role; limited collaboration
  • Governance: Some integration of cybersecurity into enterprise risk

Tier 3: Repeatable

  • Risk Management Process: Formally approved policies; regularly updated
  • Integrated Risk Management: Organization-wide approach; consistent implementation
  • External Participation: Regular collaboration with partners and ecosystem
  • Governance: Cybersecurity fully integrated into enterprise risk management

Tier 4: Adaptive

  • Risk Management Process: Continuous improvement using advanced techniques
  • Integrated Risk Management: Real-time shared awareness; dynamic risk response
  • External Participation: Active leadership in ecosystem risk management
  • Governance: Agile cybersecurity governance adapting to changes

Related NIST Publications

  • SP 800-53 Rev 5: Security and Privacy Controls (detailed control catalog)
  • SP 800-37 Rev 2: Risk Management Framework (RMF)
  • SP 800-30 Rev 1: Guide for Conducting Risk Assessments
  • SP 800-171 Rev 3: Protecting CUI in Nonfederal Systems
  • SP 800-207: Zero Trust Architecture
  • SP 800-218: Secure Software Development Framework (SSDF)

CSF 2.0 Informative References

The CSF references specific controls from:

  • NIST SP 800-53 Rev 5
  • ISO/IEC 27001:2022
  • CIS Controls v8
  • COBIT 2019
  • ISA/IEC 62443 (Industrial Control Systems)
workflows.md3.5 KB

NIST CSF Maturity Assessment Workflows

Workflow 1: Assessment Planning

Start
  |
  v
[Define Assessment Scope]
  - Enterprise-wide or business unit
  - Include/exclude OT systems
  - Include/exclude third parties
  |
  v
[Identify Stakeholders]
  - CISO and security team
  - IT leadership
  - Business unit leaders
  - Risk management
  - Legal/compliance
  - Executive sponsors
  |
  v
[Select Assessment Approach]
  +--> Self-Assessment (internal team)
  +--> Facilitated (consultant-guided)
  +--> Third-Party (independent assessment)
  |
  v
[Gather Documentation]
  - Security policies and procedures
  - Risk assessments and registers
  - Architecture diagrams
  - Previous audit results
  - Incident reports
  - Training records
  |
  v
[Schedule Assessment Activities]
  |
  v
End

Workflow 2: Current State Scoring

Start
  |
  v
[For Each CSF Function (GV, ID, PR, DE, RS, RC)]
  |
  v
  [For Each Category in Function]
    |
    v
    [For Each Subcategory]
      |
      v
      [Evaluate Against Tier Criteria]
        |
        +--> Tier 1 (Partial)?
        |     - No formal process
        |     - Ad hoc practices
        |     - Limited documentation
        |
        +--> Tier 2 (Risk-Informed)?
        |     - Approved by management
        |     - Inconsistent application
        |     - Some documentation
        |
        +--> Tier 3 (Repeatable)?
        |     - Formal policies
        |     - Consistent implementation
        |     - Regular updates
        |     - Metrics captured
        |
        +--> Tier 4 (Adaptive)?
              - Continuous improvement
              - Real-time adaptation
              - Advanced automation
              - Lessons learned integrated
      |
      v
      [Document Score and Evidence]
      |
      v
      [Record Strengths and Gaps]
    |
    v
  [Calculate Category Average Score]
  |
  v
[Calculate Function Average Score]
  |
  v
[Generate Current Profile Heatmap]
  |
  v
End

Workflow 3: Gap Analysis

Start
  |
  v
[Define Target Profile]
  - Executive input on risk appetite
  - Industry benchmark comparison
  - Regulatory requirements
  - Available resources
  |
  v
[Compare Current vs Target for Each Subcategory]
  Gap = Target Tier - Current Tier
  |
  v
[Classify Gaps]
  |
  +--> Critical (Gap >= 2 tiers, high-risk area)
  +--> Significant (Gap = 1 tier, high-risk area)
  +--> Moderate (Gap = 1 tier, medium-risk area)
  +--> Minor (Gap = 1 tier, low-risk area)
  +--> None (current meets or exceeds target)
  |
  v
[Prioritize Based On]
  - Risk reduction impact
  - Regulatory requirements
  - Implementation effort
  - Cost and resource availability
  - Dependencies on other improvements
  |
  v
[Generate Prioritized Gap Report]
  |
  v
End

Workflow 4: Improvement Roadmap

Start
  |
  v
[Quick Wins (0-3 months)]
  - Low effort, high impact
  - Policy updates and documentation
  - Enable existing but unused capabilities
  - Awareness training refresh
  |
  v
[Medium-Term (3-12 months)]
  - Tool deployment and configuration
  - Process formalization
  - Staff training and certification
  - Vendor security programme establishment
  |
  v
[Long-Term (12-24 months)]
  - Architecture redesign
  - Advanced automation (SOAR, AI-driven)
  - Cultural transformation
  - Advanced threat detection capabilities
  |
  v
[Assign Ownership and Budget]
  - Initiative owner for each item
  - Resource allocation
  - Budget approval
  - Success metrics
  |
  v
[Track Progress Quarterly]
  - Milestone reviews
  - Reassess maturity scores
  - Adjust roadmap as needed
  |
  v
End

Scripts 2

agent.py7.5 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for performing NIST Cybersecurity Framework (CSF) maturity assessment."""

import json
import argparse
import csv
from datetime import datetime


NIST_CSF_FUNCTIONS = {
    "IDENTIFY": {
        "categories": ["ID.AM", "ID.BE", "ID.GV", "ID.RA", "ID.RM", "ID.SC"],
        "descriptions": {
            "ID.AM": "Asset Management",
            "ID.BE": "Business Environment",
            "ID.GV": "Governance",
            "ID.RA": "Risk Assessment",
            "ID.RM": "Risk Management Strategy",
            "ID.SC": "Supply Chain Risk Management",
        },
    },
    "PROTECT": {
        "categories": ["PR.AC", "PR.AT", "PR.DS", "PR.IP", "PR.MA", "PR.PT"],
        "descriptions": {
            "PR.AC": "Identity Management & Access Control",
            "PR.AT": "Awareness and Training",
            "PR.DS": "Data Security",
            "PR.IP": "Information Protection Processes",
            "PR.MA": "Maintenance",
            "PR.PT": "Protective Technology",
        },
    },
    "DETECT": {
        "categories": ["DE.AE", "DE.CM", "DE.DP"],
        "descriptions": {
            "DE.AE": "Anomalies and Events",
            "DE.CM": "Security Continuous Monitoring",
            "DE.DP": "Detection Processes",
        },
    },
    "RESPOND": {
        "categories": ["RS.RP", "RS.CO", "RS.AN", "RS.MI", "RS.IM"],
        "descriptions": {
            "RS.RP": "Response Planning",
            "RS.CO": "Communications",
            "RS.AN": "Analysis",
            "RS.MI": "Mitigation",
            "RS.IM": "Improvements",
        },
    },
    "RECOVER": {
        "categories": ["RC.RP", "RC.IM", "RC.CO"],
        "descriptions": {
            "RC.RP": "Recovery Planning",
            "RC.IM": "Improvements",
            "RC.CO": "Communications",
        },
    },
}

MATURITY_LEVELS = {
    1: "Partial — Risk management practices not formalized",
    2: "Risk Informed — Risk management approved but not org-wide",
    3: "Repeatable — Policies and practices formally approved and expressed as policy",
    4: "Adaptive — Organization adapts based on lessons learned and predictive indicators",
}


def assess_from_csv(assessment_file):
    """Load assessment responses from CSV and calculate maturity scores."""
    with open(assessment_file, "r", encoding="utf-8", errors="replace") as f:
        reader = csv.DictReader(f)
        rows = list(reader)
    scores = {}
    for row in rows:
        category = row.get("category", row.get("Category", row.get("subcategory", "")))
        score = int(row.get("score", row.get("maturity_level", row.get("Score", 0))))
        target = int(row.get("target", row.get("Target", 3)))
        function_name = ""
        for fn, data in NIST_CSF_FUNCTIONS.items():
            if any(category.startswith(c) for c in data["categories"]):
                function_name = fn
                break
        scores.setdefault(function_name or "UNKNOWN", []).append({
            "category": category, "score": score, "target": target, "gap": target - score,
        })
    function_scores = {}
    for fn, items in scores.items():
        avg = sum(i["score"] for i in items) / len(items) if items else 0
        avg_target = sum(i["target"] for i in items) / len(items) if items else 0
        function_scores[fn] = {
            "average_maturity": round(avg, 1),
            "target_maturity": round(avg_target, 1),
            "gap": round(avg_target - avg, 1),
            "categories_assessed": len(items),
            "below_target": sum(1 for i in items if i["gap"] > 0),
        }
    overall = sum(fs["average_maturity"] for fs in function_scores.values()) / max(len(function_scores), 1)
    return {
        "assessment_file": assessment_file,
        "overall_maturity": round(overall, 1),
        "overall_level": MATURITY_LEVELS.get(round(overall), "Unknown"),
        "function_scores": function_scores,
        "total_categories": sum(fs["categories_assessed"] for fs in function_scores.values()),
        "categories_below_target": sum(fs["below_target"] for fs in function_scores.values()),
    }


def generate_gap_analysis(assessment_file):
    """Generate detailed gap analysis with prioritized recommendations."""
    assessment = assess_from_csv(assessment_file)
    gaps = []
    for fn, data in assessment["function_scores"].items():
        if data["gap"] > 0:
            gaps.append({
                "function": fn, "current": data["average_maturity"],
                "target": data["target_maturity"], "gap": data["gap"],
                "priority": "HIGH" if data["gap"] >= 2 else "MEDIUM" if data["gap"] >= 1 else "LOW",
            })
    gaps.sort(key=lambda x: x["gap"], reverse=True)
    return {
        "generated": datetime.utcnow().isoformat(),
        "overall_maturity": assessment["overall_maturity"],
        "gaps": gaps,
        "high_priority_gaps": [g for g in gaps if g["priority"] == "HIGH"],
    }


def create_assessment_template(output_file=None):
    """Create a blank NIST CSF assessment CSV template."""
    rows = [["category", "description", "score", "target", "evidence", "notes"]]
    for fn, data in NIST_CSF_FUNCTIONS.items():
        for cat in data["categories"]:
            rows.append([cat, data["descriptions"].get(cat, ""), "", "3", "", ""])
    if output_file:
        with open(output_file, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerows(rows)
    return {"template_rows": len(rows) - 1, "functions": list(NIST_CSF_FUNCTIONS.keys()),
            "output": output_file, "categories": [r[0] for r in rows[1:]]}


def generate_executive_summary(assessment_file):
    """Generate executive-level maturity summary."""
    assessment = assess_from_csv(assessment_file)
    gap = generate_gap_analysis(assessment_file)
    return {
        "generated": datetime.utcnow().isoformat(),
        "framework": "NIST CSF 2.0",
        "overall_maturity_score": assessment["overall_maturity"],
        "maturity_level": assessment["overall_level"],
        "total_categories_assessed": assessment["total_categories"],
        "categories_meeting_target": assessment["total_categories"] - assessment["categories_below_target"],
        "categories_below_target": assessment["categories_below_target"],
        "function_summary": {fn: {"score": d["average_maturity"], "target": d["target_maturity"]}
                            for fn, d in assessment["function_scores"].items()},
        "top_gaps": gap["high_priority_gaps"][:5],
    }


def main():
    parser = argparse.ArgumentParser(description="NIST CSF Maturity Assessment Agent")
    sub = parser.add_subparsers(dest="command")
    a = sub.add_parser("assess", help="Run maturity assessment from CSV")
    a.add_argument("--csv", required=True)
    g = sub.add_parser("gaps", help="Generate gap analysis")
    g.add_argument("--csv", required=True)
    t = sub.add_parser("template", help="Create assessment template")
    t.add_argument("--output", help="Output CSV file path")
    e = sub.add_parser("executive", help="Executive summary")
    e.add_argument("--csv", required=True)
    args = parser.parse_args()
    if args.command == "assess":
        result = assess_from_csv(args.csv)
    elif args.command == "gaps":
        result = generate_gap_analysis(args.csv)
    elif args.command == "template":
        result = create_assessment_template(args.output)
    elif args.command == "executive":
        result = generate_executive_summary(args.csv)
    else:
        parser.print_help()
        return
    print(json.dumps(result, indent=2, default=str))


if __name__ == "__main__":
    main()
process.py16.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
NIST CSF 2.0 Maturity Assessment Automation

Automates maturity scoring across all 6 CSF functions, gap analysis
between current and target profiles, and improvement roadmap generation.
"""

import json
import csv
from datetime import datetime
from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Optional

# CSF 2.0 Category structure
CSF_CATEGORIES = {
    "GV": {
        "name": "Govern",
        "categories": {
            "GV.OC": "Organizational Context",
            "GV.RM": "Risk Management Strategy",
            "GV.RR": "Roles, Responsibilities, and Authorities",
            "GV.PO": "Policy",
            "GV.OV": "Oversight",
            "GV.SC": "Cybersecurity Supply Chain Risk Management",
        }
    },
    "ID": {
        "name": "Identify",
        "categories": {
            "ID.AM": "Asset Management",
            "ID.RA": "Risk Assessment",
            "ID.IM": "Improvement",
        }
    },
    "PR": {
        "name": "Protect",
        "categories": {
            "PR.AA": "Identity Management, Authentication, and Access Control",
            "PR.AT": "Awareness and Training",
            "PR.DS": "Data Security",
            "PR.PS": "Platform Security",
            "PR.IR": "Technology Infrastructure Resilience",
        }
    },
    "DE": {
        "name": "Detect",
        "categories": {
            "DE.CM": "Continuous Monitoring",
            "DE.AE": "Adverse Event Analysis",
        }
    },
    "RS": {
        "name": "Respond",
        "categories": {
            "RS.MA": "Incident Management",
            "RS.AN": "Incident Analysis",
            "RS.CO": "Incident Response Reporting and Communication",
            "RS.MI": "Incident Mitigation",
        }
    },
    "RC": {
        "name": "Recover",
        "categories": {
            "RC.RP": "Incident Recovery Plan Execution",
        }
    },
}

TIER_DESCRIPTIONS = {
    1: "Partial - Ad hoc, reactive, limited awareness",
    2: "Risk-Informed - Approved practices, inconsistent application",
    3: "Repeatable - Formal policies, consistent implementation",
    4: "Adaptive - Continuous improvement, real-time adaptation",
}


@dataclass
class CategoryAssessment:
    category_id: str
    category_name: str
    function_id: str
    current_tier: int
    target_tier: int
    evidence: str = ""
    strengths: list = field(default_factory=list)
    gaps: list = field(default_factory=list)
    recommendations: list = field(default_factory=list)

    @property
    def gap_size(self) -> int:
        return max(0, self.target_tier - self.current_tier)

    @property
    def gap_priority(self) -> str:
        gap = self.gap_size
        if gap >= 2:
            return "Critical"
        elif gap == 1 and self.target_tier >= 3:
            return "High"
        elif gap == 1:
            return "Medium"
        else:
            return "On Target"


@dataclass
class ImprovementInitiative:
    initiative_id: str
    category_id: str
    title: str
    description: str
    current_tier: int
    target_tier: int
    timeframe: str  # Quick Win, Medium-Term, Long-Term
    effort: str     # Low, Medium, High
    impact: str     # Low, Medium, High
    owner: str = ""
    estimated_cost: str = ""
    status: str = "Planned"


class NISTCSFAssessment:
    """Conducts NIST CSF 2.0 maturity assessment."""

    def __init__(self, output_dir: str = "./nist_csf_output",
                 organization: str = "Organization"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.organization = organization
        self.assessments: list[CategoryAssessment] = []
        self.initiatives: list[ImprovementInitiative] = []

    def assess_maturity(self, scores: list[dict]) -> list[CategoryAssessment]:
        """Score each CSF category against implementation tiers."""
        print("\n" + "=" * 70)
        print(f"NIST CSF 2.0 MATURITY ASSESSMENT - {self.organization}")
        print("=" * 70)

        for score_data in scores:
            assessment = CategoryAssessment(**score_data)
            self.assessments.append(assessment)

        # Display by function
        for func_id, func_info in CSF_CATEGORIES.items():
            func_assessments = [a for a in self.assessments if a.function_id == func_id]
            if not func_assessments:
                continue

            avg_current = sum(a.current_tier for a in func_assessments) / len(func_assessments)
            avg_target = sum(a.target_tier for a in func_assessments) / len(func_assessments)

            print(f"\n  {func_info['name']} ({func_id}) - Avg Current: {avg_current:.1f} | Avg Target: {avg_target:.1f}")
            print(f"  {'Category':<50} {'Current':>8} {'Target':>8} {'Gap':>5} {'Priority':>10}")
            print(f"  {'-'*85}")

            for a in func_assessments:
                gap_indicator = f"+{a.gap_size}" if a.gap_size > 0 else "0"
                print(f"  {a.category_name:<50} {a.current_tier:>5}/4  {a.target_tier:>5}/4  {gap_indicator:>5} {a.gap_priority:>10}")

        # Overall summary
        total_avg_current = sum(a.current_tier for a in self.assessments) / len(self.assessments)
        total_avg_target = sum(a.target_tier for a in self.assessments) / len(self.assessments)

        print(f"\n  {'='*85}")
        print(f"  Overall Average Current Tier: {total_avg_current:.2f}")
        print(f"  Overall Average Target Tier:  {total_avg_target:.2f}")
        print(f"  Overall Gap:                  {total_avg_target - total_avg_current:.2f}")

        # Tier distribution
        tier_dist = {1: 0, 2: 0, 3: 0, 4: 0}
        for a in self.assessments:
            tier_dist[a.current_tier] += 1

        print(f"\n  Current Tier Distribution:")
        for tier, count in tier_dist.items():
            bar = "#" * (count * 3)
            print(f"    Tier {tier}: {count:>3} categories {bar}")

        # Save assessment
        report_path = self.output_dir / "maturity_assessment.json"
        with open(report_path, "w") as f:
            json.dump({
                "organization": self.organization,
                "date": datetime.now().isoformat(),
                "overall_current": total_avg_current,
                "overall_target": total_avg_target,
                "assessments": [asdict(a) for a in self.assessments],
            }, f, indent=2)

        print(f"\n  Assessment saved to: {report_path}")
        return self.assessments

    def generate_gap_analysis(self) -> dict:
        """Generate gap analysis between current and target profiles."""
        print("\n" + "=" * 70)
        print("GAP ANALYSIS")
        print("=" * 70)

        gaps = {
            "Critical": [],
            "High": [],
            "Medium": [],
            "On Target": [],
        }

        for a in self.assessments:
            gaps[a.gap_priority].append({
                "category": a.category_id,
                "name": a.category_name,
                "current": a.current_tier,
                "target": a.target_tier,
                "gap": a.gap_size,
                "gaps_detail": a.gaps,
                "recommendations": a.recommendations,
            })

        for priority in ["Critical", "High", "Medium", "On Target"]:
            items = gaps[priority]
            print(f"\n  {priority} ({len(items)} categories):")
            for item in items:
                if priority != "On Target":
                    print(f"    {item['category']}: {item['name']} (Tier {item['current']} -> {item['target']})")
                    for gap in item.get("gaps_detail", []):
                        print(f"      - {gap}")

        gap_path = self.output_dir / "gap_analysis.json"
        with open(gap_path, "w") as f:
            json.dump(gaps, f, indent=2)

        print(f"\n  Gap Analysis saved to: {gap_path}")
        return gaps

    def create_roadmap(self, initiatives: list[dict]) -> list[ImprovementInitiative]:
        """Create improvement roadmap with prioritized initiatives."""
        print("\n" + "=" * 70)
        print("IMPROVEMENT ROADMAP")
        print("=" * 70)

        for init_data in initiatives:
            initiative = ImprovementInitiative(**init_data)
            self.initiatives.append(initiative)

        timeframes = {"Quick Win (0-3 months)": [], "Medium-Term (3-12 months)": [], "Long-Term (12-24 months)": []}
        for init in self.initiatives:
            timeframes.setdefault(init.timeframe, [])
            timeframes[init.timeframe].append(init)

        for tf, items in timeframes.items():
            print(f"\n  {tf}:")
            for item in items:
                print(f"    [{item.initiative_id}] {item.title}")
                print(f"      Category: {item.category_id} | Effort: {item.effort} | Impact: {item.impact}")
                if item.owner:
                    print(f"      Owner: {item.owner}")

        roadmap_path = self.output_dir / "improvement_roadmap.json"
        with open(roadmap_path, "w") as f:
            json.dump([asdict(i) for i in self.initiatives], f, indent=2)

        print(f"\n  Roadmap saved to: {roadmap_path}")
        return self.initiatives

    def generate_executive_summary(self) -> dict:
        """Generate executive-level maturity summary."""
        print("\n" + "=" * 70)
        print("EXECUTIVE SUMMARY")
        print("=" * 70)

        func_scores = {}
        for func_id, func_info in CSF_CATEGORIES.items():
            func_assessments = [a for a in self.assessments if a.function_id == func_id]
            if func_assessments:
                avg = sum(a.current_tier for a in func_assessments) / len(func_assessments)
                target_avg = sum(a.target_tier for a in func_assessments) / len(func_assessments)
                func_scores[func_info["name"]] = {"current": round(avg, 2), "target": round(target_avg, 2)}

        summary = {
            "organization": self.organization,
            "date": datetime.now().isoformat(),
            "function_scores": func_scores,
            "total_categories": len(self.assessments),
            "critical_gaps": sum(1 for a in self.assessments if a.gap_priority == "Critical"),
            "high_gaps": sum(1 for a in self.assessments if a.gap_priority == "High"),
            "improvement_initiatives": len(self.initiatives),
        }

        print(f"\n  Organization: {self.organization}")
        print(f"\n  Function Maturity Scores:")
        for func, scores in func_scores.items():
            bar_current = "|" * int(scores["current"] * 5)
            bar_target = "." * int((scores["target"] - scores["current"]) * 5)
            print(f"    {func:<15} Current: {scores['current']:.1f}/4  Target: {scores['target']:.1f}/4  {bar_current}{bar_target}")

        print(f"\n  Critical Gaps: {summary['critical_gaps']}")
        print(f"  High Gaps: {summary['high_gaps']}")
        print(f"  Planned Initiatives: {summary['improvement_initiatives']}")

        summary_path = self.output_dir / "executive_summary.json"
        with open(summary_path, "w") as f:
            json.dump(summary, f, indent=2)

        print(f"\n  Executive Summary saved to: {summary_path}")
        return summary


def main():
    """Run NIST CSF 2.0 maturity assessment."""
    assessment = NISTCSFAssessment(organization="Example Corporation")

    sample_scores = [
        {"category_id": "GV.OC", "category_name": "Organizational Context", "function_id": "GV", "current_tier": 2, "target_tier": 3, "gaps": ["Risk appetite not formally documented"], "recommendations": ["Document and approve risk appetite statement"]},
        {"category_id": "GV.RM", "category_name": "Risk Management Strategy", "function_id": "GV", "current_tier": 2, "target_tier": 3, "gaps": ["Strategy not updated annually"], "recommendations": ["Establish annual review cycle"]},
        {"category_id": "GV.RR", "category_name": "Roles and Responsibilities", "function_id": "GV", "current_tier": 3, "target_tier": 3},
        {"category_id": "GV.PO", "category_name": "Policy", "function_id": "GV", "current_tier": 2, "target_tier": 3, "gaps": ["Policies not reviewed in 18+ months"], "recommendations": ["Implement annual policy review cycle"]},
        {"category_id": "GV.OV", "category_name": "Oversight", "function_id": "GV", "current_tier": 1, "target_tier": 3, "gaps": ["No board-level security reporting", "No metrics dashboard"], "recommendations": ["Establish quarterly board reporting", "Deploy security metrics dashboard"]},
        {"category_id": "GV.SC", "category_name": "Supply Chain Risk Management", "function_id": "GV", "current_tier": 1, "target_tier": 3, "gaps": ["No supply chain risk programme", "Vendor assessments ad hoc"], "recommendations": ["Establish vendor risk management programme"]},
        {"category_id": "ID.AM", "category_name": "Asset Management", "function_id": "ID", "current_tier": 2, "target_tier": 3, "gaps": ["Asset inventory incomplete for cloud"], "recommendations": ["Extend CMDB to cloud assets"]},
        {"category_id": "ID.RA", "category_name": "Risk Assessment", "function_id": "ID", "current_tier": 2, "target_tier": 3, "gaps": ["Risk assessments not quantitative"], "recommendations": ["Adopt FAIR methodology for quantification"]},
        {"category_id": "ID.IM", "category_name": "Improvement", "function_id": "ID", "current_tier": 2, "target_tier": 3},
        {"category_id": "PR.AA", "category_name": "Identity and Access Control", "function_id": "PR", "current_tier": 3, "target_tier": 3},
        {"category_id": "PR.AT", "category_name": "Awareness and Training", "function_id": "PR", "current_tier": 2, "target_tier": 3, "gaps": ["No role-based training"], "recommendations": ["Implement role-based security training"]},
        {"category_id": "PR.DS", "category_name": "Data Security", "function_id": "PR", "current_tier": 2, "target_tier": 3, "gaps": ["DLP not fully deployed"], "recommendations": ["Complete DLP deployment"]},
        {"category_id": "PR.PS", "category_name": "Platform Security", "function_id": "PR", "current_tier": 3, "target_tier": 3},
        {"category_id": "PR.IR", "category_name": "Infrastructure Resilience", "function_id": "PR", "current_tier": 2, "target_tier": 3},
        {"category_id": "DE.CM", "category_name": "Continuous Monitoring", "function_id": "DE", "current_tier": 2, "target_tier": 3, "gaps": ["Limited cloud monitoring", "No OT monitoring"], "recommendations": ["Extend SIEM to cloud and OT"]},
        {"category_id": "DE.AE", "category_name": "Adverse Event Analysis", "function_id": "DE", "current_tier": 2, "target_tier": 3, "gaps": ["Manual correlation only"], "recommendations": ["Implement automated correlation"]},
        {"category_id": "RS.MA", "category_name": "Incident Management", "function_id": "RS", "current_tier": 3, "target_tier": 3},
        {"category_id": "RS.AN", "category_name": "Incident Analysis", "function_id": "RS", "current_tier": 2, "target_tier": 3},
        {"category_id": "RS.CO", "category_name": "Response Communication", "function_id": "RS", "current_tier": 2, "target_tier": 3},
        {"category_id": "RS.MI", "category_name": "Incident Mitigation", "function_id": "RS", "current_tier": 2, "target_tier": 3},
        {"category_id": "RC.RP", "category_name": "Recovery Plan Execution", "function_id": "RC", "current_tier": 2, "target_tier": 3, "gaps": ["DR plan not tested in 2+ years"], "recommendations": ["Conduct DR tabletop and technical test"]},
    ]

    assessment.assess_maturity(sample_scores)
    assessment.generate_gap_analysis()

    sample_initiatives = [
        {"initiative_id": "INIT-001", "category_id": "GV.OV", "title": "Establish Board Security Reporting", "description": "Create quarterly security report template and present to board", "current_tier": 1, "target_tier": 3, "timeframe": "Quick Win (0-3 months)", "effort": "Low", "impact": "High", "owner": "CISO"},
        {"initiative_id": "INIT-002", "category_id": "GV.SC", "title": "Vendor Risk Management Programme", "description": "Establish formal vendor assessment and monitoring programme", "current_tier": 1, "target_tier": 3, "timeframe": "Medium-Term (3-12 months)", "effort": "Medium", "impact": "High", "owner": "Security Manager"},
        {"initiative_id": "INIT-003", "category_id": "DE.CM", "title": "Cloud Security Monitoring", "description": "Extend SIEM to cover AWS/Azure/GCP workloads", "current_tier": 2, "target_tier": 3, "timeframe": "Medium-Term (3-12 months)", "effort": "High", "impact": "High", "owner": "SOC Manager"},
        {"initiative_id": "INIT-004", "category_id": "RC.RP", "title": "DR Testing Programme", "description": "Annual DR tabletop and semi-annual technical recovery tests", "current_tier": 2, "target_tier": 3, "timeframe": "Quick Win (0-3 months)", "effort": "Medium", "impact": "High", "owner": "IT Director"},
    ]

    assessment.create_roadmap(sample_initiatives)
    assessment.generate_executive_summary()

    print("\n" + "=" * 70)
    print("NIST CSF 2.0 MATURITY ASSESSMENT COMPLETE")
    print("=" * 70)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 3.0 KB
Keep exploring