compliance governance

Implementing ISO 27001 Information Security Management

ISO/IEC 27001:2022 is the international standard for establishing, implementing, maintaining, and continually improving an Information Security Management System (ISMS). This skill covers the complete lifecycle from scoping through certification, including Annex A control selection, risk assessment methodology, Statement of Applicability (SoA) creation, and continuous improvement processes.

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

Overview

ISO/IEC 27001:2022 is the international standard for establishing, implementing, maintaining, and continually improving an Information Security Management System (ISMS). This skill covers the complete lifecycle from scoping through certification, including Annex A control selection, risk assessment methodology, Statement of Applicability (SoA) creation, and continuous improvement processes.

When to Use

  • When deploying or configuring implementing iso 27001 information security management 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

  • Understanding of information security principles and risk management concepts
  • Familiarity with organizational governance structures and business processes
  • Knowledge of IT infrastructure, network architecture, and data flows
  • Access to ISO/IEC 27001:2022 and ISO/IEC 27002:2022 standards documents

Core Concepts

ISMS Clauses (4-10)

The management system requirements define what must be done:

  • Clause 4 - Context of the Organization: Define scope, interested parties, and internal/external issues
  • Clause 5 - Leadership: Top management commitment, information security policy, roles and responsibilities
  • Clause 6 - Planning: Risk assessment process, risk treatment plan, information security objectives
  • Clause 7 - Support: Resources, competence, awareness, communication, documented information
  • Clause 8 - Operation: Operational planning, risk assessment execution, risk treatment implementation
  • Clause 9 - Performance Evaluation: Monitoring, measurement, internal audit, management review
  • Clause 10 - Improvement: Nonconformities, corrective actions, continual improvement

Annex A Controls (2022 Edition)

The 2022 revision restructured 93 controls into four categories:

Category Controls Examples
Organizational (A.5) 37 controls Policies, roles, threat intelligence, cloud security
People (A.6) 8 controls Screening, awareness, remote working, reporting
Physical (A.7) 14 controls Perimeters, entry controls, equipment security
Technological (A.8) 34 controls Access control, cryptography, logging, secure development

New Controls in 2022 Edition

11 new controls were added:

  1. A.5.7 - Threat Intelligence
  2. A.5.23 - Information Security for Cloud Services
  3. A.5.30 - ICT Readiness for Business Continuity
  4. A.7.4 - Physical Security Monitoring
  5. A.8.9 - Configuration Management
  6. A.8.10 - Information Deletion
  7. A.8.11 - Data Masking
  8. A.8.12 - Data Leakage Prevention
  9. A.8.16 - Monitoring Activities
  10. A.8.23 - Web Filtering
  11. A.8.28 - Secure Coding

Workflow

Phase 1: Gap Analysis and Scoping (Weeks 1-4)

  1. Define ISMS scope boundaries (locations, business units, systems)
  2. Identify interested parties and their requirements
  3. Perform gap analysis against ISO 27001:2022 requirements
  4. Document internal and external context (PESTLE, SWOT)
  5. Obtain top management commitment and allocate budget

Phase 2: Risk Assessment (Weeks 5-10)

  1. Define risk assessment methodology (asset-based, scenario-based, or hybrid)
  2. Create asset inventory covering information, people, processes, technology
  3. Identify threats and vulnerabilities for each asset
  4. Assess risk likelihood and impact using defined criteria
  5. Calculate risk levels and determine risk treatment options (mitigate, accept, transfer, avoid)
  6. Develop Risk Treatment Plan (RTP)

Phase 3: Control Selection and SoA (Weeks 11-14)

  1. Map risk treatments to Annex A controls
  2. Create Statement of Applicability (SoA) documenting:
    • Which controls are applicable and justification
    • Which controls are excluded and justification
    • Implementation status of each control
  3. Design control implementation plans with owners and timelines

Phase 4: Implementation (Weeks 15-30)

  1. Develop and approve information security policy
  2. Implement selected Annex A controls
  3. Create mandatory documented procedures:
    • Information Security Policy (A.5.1)
    • Risk Assessment Process (Clause 6.1.2)
    • Risk Treatment Process (Clause 6.1.3)
    • Internal Audit Programme (Clause 9.2)
    • Management Review Process (Clause 9.3)
    • Corrective Action Procedure (Clause 10.1)
  4. Deploy technical controls and security tooling
  5. Conduct security awareness training for all personnel

Phase 5: Internal Audit and Management Review (Weeks 31-36)

  1. Plan and execute internal audit programme covering all clauses and applicable controls
  2. Document audit findings and nonconformities
  3. Implement corrective actions with root cause analysis
  4. Conduct management review covering:
    • Status of previous actions
    • Changes in internal/external issues
    • Information security performance metrics
    • Audit results and risk assessment outcomes
    • Opportunities for improvement

Phase 6: Certification Audit (Weeks 37-42)

  1. Stage 1 Audit: Documentation review, readiness assessment
  2. Address Stage 1 findings
  3. Stage 2 Audit: On-site assessment of ISMS effectiveness
  4. Resolve any nonconformities (major NCRs require re-audit)
  5. Receive ISO 27001 certification (valid for 3 years)

Phase 7: Continual Improvement (Ongoing)

  1. Annual surveillance audits (Years 1 and 2)
  2. Recertification audit (Year 3)
  3. Regular risk reassessment and control effectiveness reviews
  4. Incident-driven improvements and lessons learned integration

Key Artifacts

  • ISMS Scope Document
  • Information Security Policy
  • Risk Assessment Methodology
  • Risk Register and Risk Treatment Plan
  • Statement of Applicability (SoA)
  • Internal Audit Reports
  • Management Review Minutes
  • Corrective Action Register
  • Metrics and KPI Dashboard

Common Pitfalls

  • Scope too broad or too narrow, leading to audit complications
  • Treating ISO 27001 as a checkbox exercise rather than embedding into business processes
  • Insufficient top management involvement and commitment
  • Failing to maintain documented evidence of control operation
  • Not performing regular risk reassessments as the threat landscape changes
  • Ignoring the 11 new controls in the 2022 edition during transition

Integration Points

  • ISO 27002:2022: Detailed implementation guidance for Annex A controls
  • ISO 27005: Information security risk management methodology
  • ISO 27017: Cloud security controls
  • ISO 27018: Protection of PII in cloud services
  • ISO 27701: Privacy Information Management System (PIMS) extension
  • NIST CSF 2.0: Cross-mapping for dual compliance
  • SOC 2: Overlapping trust service criteria

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.5 KB

API Reference: Implementing ISO 27001 Information Security Management

ISO 27001:2022 Clause Structure

Clause Title Key Deliverable
4 Context of the Organization ISMS Scope Document
5 Leadership Information Security Policy
6 Planning SoA, Risk Treatment Plan
7 Support Competence records, Awareness
8 Operation Risk assessment/treatment results
9 Performance Evaluation Audit reports, Management review
10 Improvement Corrective action records

Annex A Control Categories (2022)

Category Name Controls
A.5 Organizational 37 controls
A.6 People 8 controls
A.7 Physical 14 controls
A.8 Technological 34 controls

Required Documented Information

Document Clause
ISMS Scope 4.3
Information Security Policy 5.2
Risk Assessment Methodology 6.1.2
Statement of Applicability 6.1.3d
Risk Treatment Plan 6.1.3
Security Objectives 6.2
Internal Audit Program 9.2
Management Review Minutes 9.3

Risk Assessment Formula

Risk Level = Likelihood x Impact
- Likelihood: 1 (Rare) to 5 (Almost Certain)
- Impact: 1 (Negligible) to 5 (Catastrophic)
- Risk Rating: Low (1-6), Medium (7-12), High (13-19), Critical (20-25)

References

standards.md7.3 KB

ISO 27001 Standards Reference

Primary Standards

ISO/IEC 27001:2022

  • Title: Information Security, Cybersecurity and Privacy Protection - Information Security Management Systems - Requirements
  • Published: October 2022
  • Scope: Specifies requirements for establishing, implementing, maintaining, and continually improving an ISMS
  • Certification: Organizations can be certified against this standard by accredited certification bodies
  • Key Changes from 2013:
    • Annex A restructured from 14 domains to 4 themes (Organizational, People, Physical, Technological)
    • 93 controls (down from 114)
    • 11 new controls added
    • Title expanded to include "Cybersecurity and Privacy Protection"
    • Clause 6.3 added for planning changes to the ISMS

ISO/IEC 27002:2022

  • Title: Information Security, Cybersecurity and Privacy Protection - Information Security Controls
  • Role: Implementation guidance for Annex A controls
  • Key Addition: Each control now includes attribute taxonomy:
    • Control type: Preventive, Detective, Corrective
    • Information security properties: Confidentiality, Integrity, Availability
    • Cybersecurity concepts: Identify, Protect, Detect, Respond, Recover
    • Operational capabilities: 15 categories (Governance, Asset Management, etc.)
    • Security domains: Governance and Ecosystem, Protection, Defence, Resilience

Supporting Standards in the ISO 27000 Family

ISO/IEC 27000:2018

  • Overview and vocabulary for ISMS

ISO/IEC 27003:2017

  • Guidance on ISMS implementation

ISO/IEC 27004:2016

  • Information security management monitoring, measurement, analysis, and evaluation

ISO/IEC 27005:2022

  • Guidance on managing information security risks
  • Aligns with ISO 31000 risk management framework
  • Provides asset-based and event-based risk assessment approaches

ISO/IEC 27006-1:2024

  • Requirements for bodies providing audit and certification of ISMS

ISO/IEC 27007:2020

  • Guidelines for ISMS auditing

ISO/IEC 27017:2015

  • Code of practice for cloud services information security controls

ISO/IEC 27018:2019

  • Code of practice for protection of PII in public clouds

ISO/IEC 27701:2019

  • Extension to ISO 27001 for Privacy Information Management System (PIMS)
  • Supports GDPR compliance

Annex A Control Categories Detail

A.5 Organizational Controls (37 controls)

Control Title
A.5.1 Policies for information security
A.5.2 Information security roles and responsibilities
A.5.3 Segregation of duties
A.5.4 Management responsibilities
A.5.5 Contact with authorities
A.5.6 Contact with special interest groups
A.5.7 Threat intelligence (NEW)
A.5.8 Information security in project management
A.5.9 Inventory of information and other associated assets
A.5.10 Acceptable use of information and other associated assets
A.5.11 Return of assets
A.5.12 Classification of information
A.5.13 Labelling of information
A.5.14 Information transfer
A.5.15 Access control
A.5.16 Identity management
A.5.17 Authentication information
A.5.18 Access rights
A.5.19 Information security in supplier relationships
A.5.20 Addressing information security within supplier agreements
A.5.21 Managing information security in the ICT supply chain
A.5.22 Monitoring, review and change management of supplier services
A.5.23 Information security for use of cloud services (NEW)
A.5.24 Information security incident management planning and preparation
A.5.25 Assessment and decision on information security events
A.5.26 Response to information security incidents
A.5.27 Learning from information security incidents
A.5.28 Collection of evidence
A.5.29 Information security during disruption
A.5.30 ICT readiness for business continuity (NEW)
A.5.31 Legal, statutory, regulatory and contractual requirements
A.5.32 Intellectual property rights
A.5.33 Protection of records
A.5.34 Privacy and protection of PII
A.5.35 Independent review of information security
A.5.36 Compliance with policies, rules and standards for information security
A.5.37 Documented operating procedures

A.6 People Controls (8 controls)

Control Title
A.6.1 Screening
A.6.2 Terms and conditions of employment
A.6.3 Information security awareness, education and training
A.6.4 Disciplinary process
A.6.5 Responsibilities after termination or change of employment
A.6.6 Confidentiality or non-disclosure agreements
A.6.7 Remote working
A.6.8 Information security event reporting

A.7 Physical Controls (14 controls)

Control Title
A.7.1 Physical security perimeters
A.7.2 Physical entry
A.7.3 Securing offices, rooms and facilities
A.7.4 Physical security monitoring (NEW)
A.7.5 Protecting against physical and environmental threats
A.7.6 Working in secure areas
A.7.7 Clear desk and clear screen
A.7.8 Equipment siting and protection
A.7.9 Security of assets off-premises
A.7.10 Storage media
A.7.11 Supporting utilities
A.7.12 Cabling security
A.7.13 Equipment maintenance
A.7.14 Secure disposal or re-use of equipment

A.8 Technological Controls (34 controls)

Control Title
A.8.1 User endpoint devices
A.8.2 Privileged access rights
A.8.3 Information access restriction
A.8.4 Access to source code
A.8.5 Secure authentication
A.8.6 Capacity management
A.8.7 Protection against malware
A.8.8 Management of technical vulnerabilities
A.8.9 Configuration management (NEW)
A.8.10 Information deletion (NEW)
A.8.11 Data masking (NEW)
A.8.12 Data leakage prevention (NEW)
A.8.13 Information backup
A.8.14 Redundancy of information processing facilities
A.8.15 Logging
A.8.16 Monitoring activities (NEW)
A.8.17 Clock synchronization
A.8.18 Use of privileged utility programs
A.8.19 Installation of software on operational systems
A.8.20 Networks security
A.8.21 Security of network services
A.8.22 Segregation of networks
A.8.23 Web filtering (NEW)
A.8.24 Use of cryptography
A.8.25 Secure development life cycle
A.8.26 Application security requirements
A.8.27 Secure system architecture and engineering principles
A.8.28 Secure coding (NEW)
A.8.29 Security testing in development and acceptance
A.8.30 Outsourced development
A.8.31 Separation of development, test and production environments
A.8.32 Change management
A.8.33 Test information
A.8.34 Protection of information systems during audit testing

Certification Process

  1. Stage 1 Audit (Document Review): Auditor reviews ISMS documentation, scope, SoA, risk assessment methodology
  2. Stage 2 Audit (Certification Audit): On-site assessment of ISMS implementation and effectiveness
  3. Surveillance Audits: Annual audits in Years 1 and 2 to verify continued compliance
  4. Recertification Audit: Full re-assessment in Year 3 before certificate expiry

Accreditation Bodies

  • UKAS (United Kingdom)
  • ANAB (United States)
  • DAkkS (Germany)
  • JAS-ANZ (Australia/New Zealand)
  • COFRAC (France)
workflows.md6.5 KB

ISO 27001 Implementation Workflows

Workflow 1: ISMS Scoping and Context Analysis

Start
  |
  v
[Identify Internal Context]
  - Organization structure
  - Existing policies and processes
  - IT infrastructure and systems
  - Culture and capabilities
  |
  v
[Identify External Context]
  - Legal and regulatory requirements
  - Industry standards and obligations
  - Customer and partner requirements
  - Threat landscape and geopolitical factors
  |
  v
[Identify Interested Parties]
  - Customers and clients
  - Regulators and authorities
  - Employees and contractors
  - Shareholders and board members
  - Suppliers and partners
  |
  v
[Define ISMS Scope]
  - Business units in scope
  - Physical locations
  - Information systems and networks
  - Third-party services
  - Exclusions with justification
  |
  v
[Document ISMS Scope Statement]
  |
  v
[Obtain Top Management Approval]
  |
  v
End

Workflow 2: Risk Assessment Process

Start
  |
  v
[Define Risk Criteria]
  - Risk acceptance criteria
  - Likelihood scale (1-5)
  - Impact scale (1-5)
  - Risk matrix thresholds
  |
  v
[Create Asset Inventory]
  - Information assets
  - Software assets
  - Hardware assets
  - People (roles)
  - Services (cloud, third-party)
  - Physical locations
  |
  v
[Identify Threats]
  - Natural threats (fire, flood)
  - Human threats (insider, external attacker)
  - Technical threats (malware, system failure)
  - Supply chain threats
  |
  v
[Identify Vulnerabilities]
  - Technical vulnerabilities
  - Process weaknesses
  - People-related gaps
  - Physical security gaps
  |
  v
[Assess Existing Controls]
  - Document current controls
  - Evaluate control effectiveness
  |
  v
[Calculate Risk Level]
  Risk = Likelihood x Impact
  - Consider existing controls
  - Use defined risk criteria
  |
  v
[Compare Against Risk Acceptance]
  |
  +--> [Risk Acceptable] --> Document and Monitor
  |
  +--> [Risk Not Acceptable]
        |
        v
      [Select Risk Treatment]
        - Mitigate (apply controls)
        - Transfer (insurance, outsource)
        - Avoid (stop activity)
        - Accept (with justification)
        |
        v
      [Map to Annex A Controls]
        |
        v
      [Document in Risk Treatment Plan]
        |
        v
      [Update Statement of Applicability]
        |
        v
      End

Workflow 3: Statement of Applicability (SoA) Creation

Start
  |
  v
[List All 93 Annex A Controls]
  |
  v
[For Each Control]
  |
  v
[Is Control Required by Risk Treatment?]
  |
  +--> Yes --> Mark as Applicable
  |             - Link to risk(s)
  |             - Document implementation status
  |             - Assign control owner
  |
  +--> No --> [Is Control Required by Law/Contract?]
               |
               +--> Yes --> Mark as Applicable
               |             - Document legal/contractual basis
               |
               +--> No --> [Is Control Best Practice?]
                            |
                            +--> Yes --> Mark as Applicable
                            |             - Document business justification
                            |
                            +--> No --> Mark as Not Applicable
                                        - Document exclusion justification
  |
  v
[Review SoA Completeness]
  - All 93 controls addressed
  - Every exclusion justified
  - Implementation status documented
  |
  v
[Approve SoA]
  |
  v
End

Workflow 4: Internal Audit Programme

Start
  |
  v
[Plan Audit Programme]
  - Define audit scope (clauses and controls)
  - Schedule audits across the year
  - Assign qualified auditors (independent of audited area)
  - Prepare audit criteria and checklists
  |
  v
[Conduct Audit]
  - Opening meeting with auditees
  - Review documented information
  - Interview key personnel
  - Observe processes in action
  - Collect objective evidence
  - Closing meeting with preliminary findings
  |
  v
[Document Findings]
  - Major Nonconformities (systemic failure, absence of control)
  - Minor Nonconformities (isolated failure, partial implementation)
  - Observations (potential for improvement)
  - Opportunities for Improvement (OFIs)
  |
  v
[Issue Audit Report]
  |
  v
[Corrective Action Process]
  - Containment: immediate action to limit impact
  - Root Cause Analysis: identify underlying cause
  - Corrective Action: implement fix to prevent recurrence
  - Verification: confirm effectiveness of correction
  |
  v
[Track to Closure]
  |
  v
[Feed into Management Review]
  |
  v
End

Workflow 5: Management Review

Start
  |
  v
[Prepare Review Inputs]
  - Status of actions from previous reviews
  - Changes in external/internal issues
  - Changes in interested party needs
  - Information security performance:
    * Nonconformities and corrective actions
    * Monitoring and measurement results
    * Audit results
    * Fulfilment of objectives
  - Feedback from interested parties
  - Results of risk assessment and treatment plan
  - Opportunities for continual improvement
  |
  v
[Conduct Management Review Meeting]
  - Present ISMS performance data
  - Discuss risk landscape changes
  - Review incident trends
  - Evaluate resource adequacy
  |
  v
[Document Review Outputs]
  - Decisions on continual improvement opportunities
  - Changes needed to the ISMS
  - Resource allocation decisions
  - Updated risk acceptance criteria (if needed)
  |
  v
[Assign Actions with Owners and Deadlines]
  |
  v
[Track Implementation]
  |
  v
End

Workflow 6: Certification Audit Preparation

Start
  |
  v
[Pre-Audit Readiness Check]
  - All mandatory documents in place
  - SoA current and approved
  - Risk assessment completed
  - Internal audit completed
  - Management review conducted
  - Corrective actions closed
  |
  v
[Select Certification Body]
  - Verify UKAS/ANAB accreditation
  - Compare audit team experience
  - Review commercial terms
  |
  v
[Stage 1 Audit (Documentation Review)]
  - Auditor reviews ISMS documentation
  - Assesses readiness for Stage 2
  - Identifies any significant gaps
  |
  v
[Address Stage 1 Findings]
  - Resolve documentation gaps
  - Complete any missing processes
  |
  v
[Stage 2 Audit (Certification Audit)]
  - On-site assessment (typically 3-5 days)
  - Evidence-based verification
  - Interviews across the organization
  - Technical control testing
  |
  v
[Audit Outcome]
  |
  +--> [No Major NCRs] --> Certificate Issued
  |
  +--> [Major NCRs Found]
        |
        v
      [Resolve NCRs within 90 days]
        |
        v
      [Follow-up Audit]
        |
        v
      [Certificate Issued]
  |
  v
End

Scripts 2

agent.py8.2 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for assessing ISO 27001:2022 ISMS compliance."""

import json
import argparse
from datetime import datetime
from collections import Counter

ANNEX_A_CATEGORIES = {
    "A.5": {"name": "Organizational controls", "count": 37},
    "A.6": {"name": "People controls", "count": 8},
    "A.7": {"name": "Physical controls", "count": 14},
    "A.8": {"name": "Technological controls", "count": 34},
}

REQUIRED_DOCUMENTS = [
    "ISMS Scope (4.3)", "Information Security Policy (5.2)",
    "Risk Assessment Methodology (6.1.2)", "Risk Treatment Plan (6.1.3)",
    "Statement of Applicability (6.1.3d)", "Information Security Objectives (6.2)",
    "Evidence of Competence (7.2)", "Documented Operating Procedures (8.1)",
    "Risk Assessment Results (8.2)", "Risk Treatment Results (8.3)",
    "Monitoring and Measurement Results (9.1)", "Internal Audit Program (9.2)",
    "Management Review Results (9.3)", "Nonconformities and Corrective Actions (10.1)",
]


def assess_soa_completeness(soa_path):
    """Assess Statement of Applicability completeness."""
    with open(soa_path) as f:
        soa = json.load(f)
    controls = soa if isinstance(soa, list) else soa.get("controls", [])
    total = len(controls)
    implemented = sum(1 for c in controls if c.get("status", "").lower() == "implemented")
    partially = sum(1 for c in controls if c.get("status", "").lower() == "partial")
    not_implemented = sum(1 for c in controls if c.get("status", "").lower() == "not_implemented")
    excluded = sum(1 for c in controls if c.get("status", "").lower() == "excluded")

    missing_justification = [c for c in controls
                             if c.get("status", "").lower() == "excluded"
                             and not c.get("justification")]
    findings = []
    if missing_justification:
        findings.append({
            "issue": f"{len(missing_justification)} excluded controls without justification",
            "severity": "HIGH",
            "controls": [c.get("id", "") for c in missing_justification],
        })

    no_evidence = [c for c in controls
                   if c.get("status", "").lower() == "implemented"
                   and not c.get("evidence")]
    if no_evidence:
        findings.append({
            "issue": f"{len(no_evidence)} implemented controls without evidence",
            "severity": "MEDIUM",
        })

    return {
        "total_controls": total,
        "implemented": implemented,
        "partial": partially,
        "not_implemented": not_implemented,
        "excluded": excluded,
        "implementation_rate": round(implemented / total * 100, 1) if total else 0,
        "findings": findings,
    }


def assess_documentation(docs_inventory_path):
    """Check required ISMS documentation against inventory."""
    with open(docs_inventory_path) as f:
        inventory = json.load(f)
    docs = inventory if isinstance(inventory, list) else inventory.get("documents", [])
    doc_names = [d.get("name", d.get("title", "")).lower() for d in docs]

    missing = []
    for req in REQUIRED_DOCUMENTS:
        found = any(req.lower().split("(")[0].strip() in name for name in doc_names)
        if not found:
            missing.append(req)

    outdated = [d for d in docs
                if d.get("last_review") and
                (datetime.utcnow() - datetime.fromisoformat(
                    d["last_review"].replace("Z", ""))).days > 365]

    return {
        "required": len(REQUIRED_DOCUMENTS),
        "present": len(REQUIRED_DOCUMENTS) - len(missing),
        "missing": missing,
        "outdated_documents": len(outdated),
        "compliance_rate": round(
            (len(REQUIRED_DOCUMENTS) - len(missing)) / len(REQUIRED_DOCUMENTS) * 100, 1),
    }


def assess_risk_register(risk_register_path):
    """Assess risk register for completeness and currency."""
    with open(risk_register_path) as f:
        register = json.load(f)
    risks = register if isinstance(register, list) else register.get("risks", [])
    findings = []
    by_level = Counter()

    for risk in risks:
        level = risk.get("risk_level", risk.get("rating", "unknown")).lower()
        by_level[level] += 1
        if not risk.get("treatment", risk.get("mitigation")):
            findings.append({
                "risk": risk.get("id", risk.get("name", "")),
                "issue": "No treatment plan defined",
                "severity": "HIGH",
            })
        if not risk.get("owner"):
            findings.append({
                "risk": risk.get("id", ""),
                "issue": "No risk owner assigned",
                "severity": "MEDIUM",
            })
        if risk.get("treatment", "").lower() == "accept" and not risk.get("acceptance_authority"):
            findings.append({
                "risk": risk.get("id", ""),
                "issue": "Risk accepted without management approval",
                "severity": "HIGH",
            })

    return {
        "total_risks": len(risks),
        "by_level": dict(by_level),
        "findings": findings,
        "untreated": sum(1 for r in risks if not r.get("treatment")),
    }


def generate_gap_analysis(current_state):
    """Generate ISO 27001 gap analysis from current state assessment."""
    clauses = {
        "4_context": ["scope_defined", "interested_parties", "isms_scope_document"],
        "5_leadership": ["security_policy", "roles_responsibilities", "management_commitment"],
        "6_planning": ["risk_methodology", "risk_assessment", "soa", "security_objectives"],
        "7_support": ["resources", "competence", "awareness", "communication", "documented_info"],
        "8_operation": ["operational_planning", "risk_assessment_results", "risk_treatment"],
        "9_evaluation": ["monitoring", "internal_audit", "management_review"],
        "10_improvement": ["nonconformity_handling", "corrective_actions", "continual_improvement"],
    }
    gaps = {}
    for clause, requirements in clauses.items():
        clause_state = current_state.get(clause, {})
        met = sum(1 for r in requirements if clause_state.get(r, False))
        gaps[clause] = {
            "total": len(requirements),
            "met": met,
            "gaps": [r for r in requirements if not clause_state.get(r, False)],
            "compliance": round(met / len(requirements) * 100, 1),
        }
    return gaps


def main():
    parser = argparse.ArgumentParser(description="ISO 27001 ISMS Compliance Agent")
    parser.add_argument("--soa", help="Statement of Applicability JSON")
    parser.add_argument("--docs", help="Documentation inventory JSON")
    parser.add_argument("--risks", help="Risk register JSON")
    parser.add_argument("--state", help="Current state assessment JSON for gap analysis")
    parser.add_argument("--action", choices=["soa", "docs", "risks", "gaps", "full"],
                        default="full")
    parser.add_argument("--output", default="iso27001_report.json")
    args = parser.parse_args()

    report = {"generated_at": datetime.utcnow().isoformat(), "results": {}}

    if args.action in ("soa", "full") and args.soa:
        result = assess_soa_completeness(args.soa)
        report["results"]["soa"] = result
        print(f"[+] SoA: {result['implementation_rate']}% implemented")

    if args.action in ("docs", "full") and args.docs:
        result = assess_documentation(args.docs)
        report["results"]["documentation"] = result
        print(f"[+] Documentation: {result['compliance_rate']}%, {len(result['missing'])} missing")

    if args.action in ("risks", "full") and args.risks:
        result = assess_risk_register(args.risks)
        report["results"]["risks"] = result
        print(f"[+] Risk register: {result['total_risks']} risks, {result['untreated']} untreated")

    if args.action in ("gaps", "full") and args.state:
        with open(args.state) as f:
            state = json.load(f)
        gaps = generate_gap_analysis(state)
        report["results"]["gap_analysis"] = gaps
        avg = sum(g["compliance"] for g in gaps.values()) / len(gaps)
        print(f"[+] Gap analysis: {avg:.1f}% average compliance")

    with open(args.output, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py31.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
ISO 27001 ISMS Compliance Check Automation

Automates gap analysis, risk assessment tracking, Statement of Applicability
management, and audit readiness checks for ISO/IEC 27001:2022 implementation.
"""

import json
import csv
import os
import sys
from datetime import datetime, timedelta
from typing import Optional
from pathlib import Path
from dataclasses import dataclass, field, asdict
from enum import Enum


class ControlCategory(Enum):
    ORGANIZATIONAL = "A.5"
    PEOPLE = "A.6"
    PHYSICAL = "A.7"
    TECHNOLOGICAL = "A.8"


class ControlStatus(Enum):
    NOT_IMPLEMENTED = "Not Implemented"
    PARTIALLY_IMPLEMENTED = "Partially Implemented"
    FULLY_IMPLEMENTED = "Fully Implemented"
    NOT_APPLICABLE = "Not Applicable"


class RiskLevel(Enum):
    CRITICAL = "Critical"
    HIGH = "High"
    MEDIUM = "Medium"
    LOW = "Low"
    NEGLIGIBLE = "Negligible"


class RiskTreatment(Enum):
    MITIGATE = "Mitigate"
    TRANSFER = "Transfer"
    AVOID = "Avoid"
    ACCEPT = "Accept"


# Full Annex A control catalog for ISO 27001:2022
ANNEX_A_CONTROLS = {
    "A.5.1": {"title": "Policies for information security", "category": "Organizational"},
    "A.5.2": {"title": "Information security roles and responsibilities", "category": "Organizational"},
    "A.5.3": {"title": "Segregation of duties", "category": "Organizational"},
    "A.5.4": {"title": "Management responsibilities", "category": "Organizational"},
    "A.5.5": {"title": "Contact with authorities", "category": "Organizational"},
    "A.5.6": {"title": "Contact with special interest groups", "category": "Organizational"},
    "A.5.7": {"title": "Threat intelligence", "category": "Organizational", "new": True},
    "A.5.8": {"title": "Information security in project management", "category": "Organizational"},
    "A.5.9": {"title": "Inventory of information and other associated assets", "category": "Organizational"},
    "A.5.10": {"title": "Acceptable use of information and other associated assets", "category": "Organizational"},
    "A.5.11": {"title": "Return of assets", "category": "Organizational"},
    "A.5.12": {"title": "Classification of information", "category": "Organizational"},
    "A.5.13": {"title": "Labelling of information", "category": "Organizational"},
    "A.5.14": {"title": "Information transfer", "category": "Organizational"},
    "A.5.15": {"title": "Access control", "category": "Organizational"},
    "A.5.16": {"title": "Identity management", "category": "Organizational"},
    "A.5.17": {"title": "Authentication information", "category": "Organizational"},
    "A.5.18": {"title": "Access rights", "category": "Organizational"},
    "A.5.19": {"title": "Information security in supplier relationships", "category": "Organizational"},
    "A.5.20": {"title": "Addressing information security within supplier agreements", "category": "Organizational"},
    "A.5.21": {"title": "Managing information security in the ICT supply chain", "category": "Organizational"},
    "A.5.22": {"title": "Monitoring, review and change management of supplier services", "category": "Organizational"},
    "A.5.23": {"title": "Information security for use of cloud services", "category": "Organizational", "new": True},
    "A.5.24": {"title": "Information security incident management planning and preparation", "category": "Organizational"},
    "A.5.25": {"title": "Assessment and decision on information security events", "category": "Organizational"},
    "A.5.26": {"title": "Response to information security incidents", "category": "Organizational"},
    "A.5.27": {"title": "Learning from information security incidents", "category": "Organizational"},
    "A.5.28": {"title": "Collection of evidence", "category": "Organizational"},
    "A.5.29": {"title": "Information security during disruption", "category": "Organizational"},
    "A.5.30": {"title": "ICT readiness for business continuity", "category": "Organizational", "new": True},
    "A.5.31": {"title": "Legal, statutory, regulatory and contractual requirements", "category": "Organizational"},
    "A.5.32": {"title": "Intellectual property rights", "category": "Organizational"},
    "A.5.33": {"title": "Protection of records", "category": "Organizational"},
    "A.5.34": {"title": "Privacy and protection of PII", "category": "Organizational"},
    "A.5.35": {"title": "Independent review of information security", "category": "Organizational"},
    "A.5.36": {"title": "Compliance with policies, rules and standards", "category": "Organizational"},
    "A.5.37": {"title": "Documented operating procedures", "category": "Organizational"},
    "A.6.1": {"title": "Screening", "category": "People"},
    "A.6.2": {"title": "Terms and conditions of employment", "category": "People"},
    "A.6.3": {"title": "Information security awareness, education and training", "category": "People"},
    "A.6.4": {"title": "Disciplinary process", "category": "People"},
    "A.6.5": {"title": "Responsibilities after termination or change of employment", "category": "People"},
    "A.6.6": {"title": "Confidentiality or non-disclosure agreements", "category": "People"},
    "A.6.7": {"title": "Remote working", "category": "People"},
    "A.6.8": {"title": "Information security event reporting", "category": "People"},
    "A.7.1": {"title": "Physical security perimeters", "category": "Physical"},
    "A.7.2": {"title": "Physical entry", "category": "Physical"},
    "A.7.3": {"title": "Securing offices, rooms and facilities", "category": "Physical"},
    "A.7.4": {"title": "Physical security monitoring", "category": "Physical", "new": True},
    "A.7.5": {"title": "Protecting against physical and environmental threats", "category": "Physical"},
    "A.7.6": {"title": "Working in secure areas", "category": "Physical"},
    "A.7.7": {"title": "Clear desk and clear screen", "category": "Physical"},
    "A.7.8": {"title": "Equipment siting and protection", "category": "Physical"},
    "A.7.9": {"title": "Security of assets off-premises", "category": "Physical"},
    "A.7.10": {"title": "Storage media", "category": "Physical"},
    "A.7.11": {"title": "Supporting utilities", "category": "Physical"},
    "A.7.12": {"title": "Cabling security", "category": "Physical"},
    "A.7.13": {"title": "Equipment maintenance", "category": "Physical"},
    "A.7.14": {"title": "Secure disposal or re-use of equipment", "category": "Physical"},
    "A.8.1": {"title": "User endpoint devices", "category": "Technological"},
    "A.8.2": {"title": "Privileged access rights", "category": "Technological"},
    "A.8.3": {"title": "Information access restriction", "category": "Technological"},
    "A.8.4": {"title": "Access to source code", "category": "Technological"},
    "A.8.5": {"title": "Secure authentication", "category": "Technological"},
    "A.8.6": {"title": "Capacity management", "category": "Technological"},
    "A.8.7": {"title": "Protection against malware", "category": "Technological"},
    "A.8.8": {"title": "Management of technical vulnerabilities", "category": "Technological"},
    "A.8.9": {"title": "Configuration management", "category": "Technological", "new": True},
    "A.8.10": {"title": "Information deletion", "category": "Technological", "new": True},
    "A.8.11": {"title": "Data masking", "category": "Technological", "new": True},
    "A.8.12": {"title": "Data leakage prevention", "category": "Technological", "new": True},
    "A.8.13": {"title": "Information backup", "category": "Technological"},
    "A.8.14": {"title": "Redundancy of information processing facilities", "category": "Technological"},
    "A.8.15": {"title": "Logging", "category": "Technological"},
    "A.8.16": {"title": "Monitoring activities", "category": "Technological", "new": True},
    "A.8.17": {"title": "Clock synchronization", "category": "Technological"},
    "A.8.18": {"title": "Use of privileged utility programs", "category": "Technological"},
    "A.8.19": {"title": "Installation of software on operational systems", "category": "Technological"},
    "A.8.20": {"title": "Networks security", "category": "Technological"},
    "A.8.21": {"title": "Security of network services", "category": "Technological"},
    "A.8.22": {"title": "Segregation of networks", "category": "Technological"},
    "A.8.23": {"title": "Web filtering", "category": "Technological", "new": True},
    "A.8.24": {"title": "Use of cryptography", "category": "Technological"},
    "A.8.25": {"title": "Secure development life cycle", "category": "Technological"},
    "A.8.26": {"title": "Application security requirements", "category": "Technological"},
    "A.8.27": {"title": "Secure system architecture and engineering principles", "category": "Technological"},
    "A.8.28": {"title": "Secure coding", "category": "Technological", "new": True},
    "A.8.29": {"title": "Security testing in development and acceptance", "category": "Technological"},
    "A.8.30": {"title": "Outsourced development", "category": "Technological"},
    "A.8.31": {"title": "Separation of development, test and production environments", "category": "Technological"},
    "A.8.32": {"title": "Change management", "category": "Technological"},
    "A.8.33": {"title": "Test information", "category": "Technological"},
    "A.8.34": {"title": "Protection of information systems during audit testing", "category": "Technological"},
}


@dataclass
class RiskEntry:
    risk_id: str
    asset: str
    threat: str
    vulnerability: str
    likelihood: int  # 1-5
    impact: int      # 1-5
    existing_controls: list = field(default_factory=list)
    risk_level: str = ""
    treatment: str = ""
    treatment_controls: list = field(default_factory=list)
    owner: str = ""
    status: str = "Open"
    due_date: str = ""

    def __post_init__(self):
        score = self.likelihood * self.impact
        if score >= 20:
            self.risk_level = RiskLevel.CRITICAL.value
        elif score >= 15:
            self.risk_level = RiskLevel.HIGH.value
        elif score >= 8:
            self.risk_level = RiskLevel.MEDIUM.value
        elif score >= 4:
            self.risk_level = RiskLevel.LOW.value
        else:
            self.risk_level = RiskLevel.NEGLIGIBLE.value


@dataclass
class SoAEntry:
    control_id: str
    control_title: str
    applicable: bool
    justification: str
    implementation_status: str
    control_owner: str = ""
    linked_risks: list = field(default_factory=list)
    evidence_reference: str = ""


@dataclass
class AuditFinding:
    finding_id: str
    clause_or_control: str
    finding_type: str  # Major NCR, Minor NCR, Observation, OFI
    description: str
    evidence: str
    root_cause: str = ""
    corrective_action: str = ""
    responsible_person: str = ""
    due_date: str = ""
    status: str = "Open"
    closure_date: str = ""


class ISO27001ComplianceManager:
    """Manages ISO 27001 ISMS compliance checks and tracking."""

    def __init__(self, output_dir: str = "./iso27001_output"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.risk_register: list[RiskEntry] = []
        self.soa_entries: list[SoAEntry] = []
        self.audit_findings: list[AuditFinding] = []

    def perform_gap_analysis(self) -> dict:
        """Perform gap analysis against all 93 Annex A controls."""
        print("\n" + "=" * 70)
        print("ISO 27001:2022 GAP ANALYSIS")
        print("=" * 70)

        results = {
            "date": datetime.now().isoformat(),
            "total_controls": len(ANNEX_A_CONTROLS),
            "categories": {},
            "controls": {},
            "summary": {}
        }

        status_counts = {s.value: 0 for s in ControlStatus}

        for control_id, control_info in ANNEX_A_CONTROLS.items():
            category = control_info["category"]
            if category not in results["categories"]:
                results["categories"][category] = {
                    "total": 0,
                    "implemented": 0,
                    "partial": 0,
                    "not_implemented": 0,
                    "not_applicable": 0,
                }

            # Default assessment - mark all as not implemented for gap analysis
            status = ControlStatus.NOT_IMPLEMENTED.value
            results["controls"][control_id] = {
                "title": control_info["title"],
                "category": category,
                "is_new_2022": control_info.get("new", False),
                "status": status,
                "gap_notes": "",
                "priority": "High" if control_info.get("new", False) else "Medium",
            }

            results["categories"][category]["total"] += 1
            results["categories"][category]["not_implemented"] += 1
            status_counts[status] += 1

        results["summary"] = {
            "compliance_percentage": 0.0,
            "controls_needing_implementation": status_counts[ControlStatus.NOT_IMPLEMENTED.value],
            "new_2022_controls": sum(
                1 for c in ANNEX_A_CONTROLS.values() if c.get("new", False)
            ),
            "status_breakdown": status_counts,
        }

        # Save gap analysis report
        report_path = self.output_dir / "gap_analysis_report.json"
        with open(report_path, "w") as f:
            json.dump(results, f, indent=2)

        print(f"\nTotal Controls Assessed: {results['total_controls']}")
        print(f"\nCategory Breakdown:")
        for cat, data in results["categories"].items():
            print(f"  {cat}: {data['total']} controls")
        print(f"\nNew 2022 Controls: {results['summary']['new_2022_controls']}")
        print(f"Gap Analysis Report saved to: {report_path}")

        return results

    def create_risk_register(self, risks: list[dict]) -> list[RiskEntry]:
        """Create and populate risk register with assessed risks."""
        print("\n" + "=" * 70)
        print("RISK REGISTER CREATION")
        print("=" * 70)

        for risk_data in risks:
            entry = RiskEntry(**risk_data)
            self.risk_register.append(entry)
            print(f"\n  [{entry.risk_id}] {entry.asset}")
            print(f"    Threat: {entry.threat}")
            print(f"    Vulnerability: {entry.vulnerability}")
            print(f"    Score: {entry.likelihood} x {entry.impact} = {entry.likelihood * entry.impact}")
            print(f"    Risk Level: {entry.risk_level}")
            print(f"    Treatment: {entry.treatment}")

        # Save risk register
        register_path = self.output_dir / "risk_register.json"
        with open(register_path, "w") as f:
            json.dump([asdict(r) for r in self.risk_register], f, indent=2)

        # Generate risk summary
        risk_summary = {}
        for entry in self.risk_register:
            risk_summary.setdefault(entry.risk_level, 0)
            risk_summary[entry.risk_level] += 1

        print(f"\n  Risk Summary:")
        for level, count in sorted(risk_summary.items()):
            print(f"    {level}: {count}")
        print(f"\n  Risk Register saved to: {register_path}")

        return self.risk_register

    def generate_soa(self, control_assessments: Optional[dict] = None) -> list[SoAEntry]:
        """Generate Statement of Applicability for all 93 controls."""
        print("\n" + "=" * 70)
        print("STATEMENT OF APPLICABILITY (SoA)")
        print("=" * 70)

        if control_assessments is None:
            control_assessments = {}

        for control_id, control_info in ANNEX_A_CONTROLS.items():
            assessment = control_assessments.get(control_id, {})
            entry = SoAEntry(
                control_id=control_id,
                control_title=control_info["title"],
                applicable=assessment.get("applicable", True),
                justification=assessment.get("justification", "Required by risk assessment"),
                implementation_status=assessment.get("status", ControlStatus.NOT_IMPLEMENTED.value),
                control_owner=assessment.get("owner", ""),
                linked_risks=assessment.get("linked_risks", []),
                evidence_reference=assessment.get("evidence", ""),
            )
            self.soa_entries.append(entry)

        # Calculate SoA statistics
        applicable_count = sum(1 for e in self.soa_entries if e.applicable)
        implemented_count = sum(
            1 for e in self.soa_entries
            if e.applicable and e.implementation_status == ControlStatus.FULLY_IMPLEMENTED.value
        )
        partial_count = sum(
            1 for e in self.soa_entries
            if e.applicable and e.implementation_status == ControlStatus.PARTIALLY_IMPLEMENTED.value
        )
        not_applicable_count = sum(1 for e in self.soa_entries if not e.applicable)

        compliance_pct = (
            (implemented_count / applicable_count * 100) if applicable_count > 0 else 0
        )

        print(f"\n  Total Controls: {len(self.soa_entries)}")
        print(f"  Applicable: {applicable_count}")
        print(f"  Not Applicable: {not_applicable_count}")
        print(f"  Fully Implemented: {implemented_count}")
        print(f"  Partially Implemented: {partial_count}")
        print(f"  Compliance Rate: {compliance_pct:.1f}%")

        # Save SoA
        soa_path = self.output_dir / "statement_of_applicability.json"
        with open(soa_path, "w") as f:
            json.dump([asdict(e) for e in self.soa_entries], f, indent=2)

        # Generate CSV version for auditors
        csv_path = self.output_dir / "soa_report.csv"
        with open(csv_path, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([
                "Control ID", "Title", "Category", "Applicable",
                "Justification", "Implementation Status", "Owner",
                "Linked Risks", "Evidence Reference", "New in 2022"
            ])
            for entry in self.soa_entries:
                control_info = ANNEX_A_CONTROLS.get(entry.control_id, {})
                writer.writerow([
                    entry.control_id,
                    entry.control_title,
                    control_info.get("category", ""),
                    "Yes" if entry.applicable else "No",
                    entry.justification,
                    entry.implementation_status,
                    entry.control_owner,
                    "; ".join(entry.linked_risks),
                    entry.evidence_reference,
                    "Yes" if control_info.get("new", False) else "No",
                ])

        print(f"  SoA saved to: {soa_path}")
        print(f"  SoA CSV saved to: {csv_path}")

        return self.soa_entries

    def check_audit_readiness(self) -> dict:
        """Check readiness for Stage 1 and Stage 2 certification audits."""
        print("\n" + "=" * 70)
        print("CERTIFICATION AUDIT READINESS CHECK")
        print("=" * 70)

        checks = {
            "mandatory_documents": {
                "Information Security Policy (A.5.1)": False,
                "ISMS Scope Document (Clause 4.3)": False,
                "Risk Assessment Methodology (Clause 6.1.2)": False,
                "Risk Assessment Report (Clause 8.2)": False,
                "Risk Treatment Plan (Clause 6.1.3)": False,
                "Statement of Applicability (Clause 6.1.3)": False,
                "Information Security Objectives (Clause 6.2)": False,
                "Competence Evidence (Clause 7.2)": False,
                "Operational Planning Documents (Clause 8.1)": False,
                "Internal Audit Programme and Reports (Clause 9.2)": False,
                "Management Review Minutes (Clause 9.3)": False,
                "Corrective Action Records (Clause 10.1)": False,
            },
            "process_checks": {
                "Risk assessment completed within last 12 months": False,
                "Internal audit covers all clauses and applicable controls": False,
                "Management review conducted": False,
                "All major nonconformities closed": False,
                "Security awareness training delivered": False,
                "Incident response process tested": False,
                "Business continuity plans tested": False,
                "Supplier security reviews conducted": False,
            },
            "control_implementation": {
                "All applicable Annex A controls implemented": False,
                "Evidence of control operation available": False,
                "Control effectiveness measured": False,
                "New 2022 controls addressed": False,
            },
        }

        # Auto-check based on existing data
        if self.soa_entries:
            checks["mandatory_documents"]["Statement of Applicability (Clause 6.1.3)"] = True

        if self.risk_register:
            checks["mandatory_documents"]["Risk Assessment Report (Clause 8.2)"] = True
            checks["process_checks"]["Risk assessment completed within last 12 months"] = True

        total_checks = sum(len(v) for v in checks.values())
        passed_checks = sum(
            sum(1 for passed in v.values() if passed) for v in checks.values()
        )
        readiness_pct = (passed_checks / total_checks * 100) if total_checks > 0 else 0

        print(f"\n  Readiness Score: {passed_checks}/{total_checks} ({readiness_pct:.1f}%)")

        for section, items in checks.items():
            print(f"\n  {section.replace('_', ' ').title()}:")
            for item, status in items.items():
                icon = "[PASS]" if status else "[FAIL]"
                print(f"    {icon} {item}")

        if readiness_pct < 80:
            print(f"\n  WARNING: Readiness below 80%. Address gaps before scheduling Stage 1 audit.")
        elif readiness_pct < 100:
            print(f"\n  NOTICE: Some items pending. Complete before Stage 2 audit.")
        else:
            print(f"\n  READY: All checks passed. Proceed with certification audit.")

        # Save readiness report
        report = {
            "date": datetime.now().isoformat(),
            "readiness_percentage": readiness_pct,
            "passed": passed_checks,
            "total": total_checks,
            "checks": checks,
        }
        report_path = self.output_dir / "audit_readiness_report.json"
        with open(report_path, "w") as f:
            json.dump(report, f, indent=2)

        print(f"\n  Readiness Report saved to: {report_path}")
        return report

    def track_audit_findings(self, findings: list[dict]) -> list[AuditFinding]:
        """Track internal or external audit findings and corrective actions."""
        print("\n" + "=" * 70)
        print("AUDIT FINDINGS TRACKER")
        print("=" * 70)

        for finding_data in findings:
            finding = AuditFinding(**finding_data)
            self.audit_findings.append(finding)
            print(f"\n  [{finding.finding_id}] {finding.finding_type}")
            print(f"    Clause/Control: {finding.clause_or_control}")
            print(f"    Description: {finding.description}")
            print(f"    Status: {finding.status}")

        # Summary
        type_counts = {}
        for f in self.audit_findings:
            type_counts.setdefault(f.finding_type, 0)
            type_counts[f.finding_type] += 1

        print(f"\n  Finding Summary:")
        for ftype, count in type_counts.items():
            print(f"    {ftype}: {count}")

        open_count = sum(1 for f in self.audit_findings if f.status == "Open")
        print(f"    Open Findings: {open_count}")

        # Save findings
        findings_path = self.output_dir / "audit_findings.json"
        with open(findings_path, "w") as f:
            json.dump([asdict(af) for af in self.audit_findings], f, indent=2)

        print(f"\n  Findings saved to: {findings_path}")
        return self.audit_findings

    def generate_compliance_dashboard(self) -> dict:
        """Generate overall ISMS compliance dashboard metrics."""
        print("\n" + "=" * 70)
        print("ISMS COMPLIANCE DASHBOARD")
        print("=" * 70)

        dashboard = {
            "generated": datetime.now().isoformat(),
            "risk_register": {
                "total_risks": len(self.risk_register),
                "by_level": {},
                "by_treatment": {},
                "open_risks": sum(1 for r in self.risk_register if r.status == "Open"),
            },
            "soa": {
                "total_controls": len(ANNEX_A_CONTROLS),
                "applicable": sum(1 for e in self.soa_entries if e.applicable),
                "fully_implemented": sum(
                    1 for e in self.soa_entries
                    if e.applicable and e.implementation_status == ControlStatus.FULLY_IMPLEMENTED.value
                ),
                "partially_implemented": sum(
                    1 for e in self.soa_entries
                    if e.applicable and e.implementation_status == ControlStatus.PARTIALLY_IMPLEMENTED.value
                ),
                "not_implemented": sum(
                    1 for e in self.soa_entries
                    if e.applicable and e.implementation_status == ControlStatus.NOT_IMPLEMENTED.value
                ),
            },
            "audit_findings": {
                "total": len(self.audit_findings),
                "open": sum(1 for f in self.audit_findings if f.status == "Open"),
                "major_ncrs": sum(1 for f in self.audit_findings if f.finding_type == "Major NCR"),
                "minor_ncrs": sum(1 for f in self.audit_findings if f.finding_type == "Minor NCR"),
            },
        }

        # Risk breakdown
        for r in self.risk_register:
            dashboard["risk_register"]["by_level"].setdefault(r.risk_level, 0)
            dashboard["risk_register"]["by_level"][r.risk_level] += 1
            if r.treatment:
                dashboard["risk_register"]["by_treatment"].setdefault(r.treatment, 0)
                dashboard["risk_register"]["by_treatment"][r.treatment] += 1

        # Compliance rate
        applicable = dashboard["soa"]["applicable"]
        implemented = dashboard["soa"]["fully_implemented"]
        dashboard["soa"]["compliance_rate"] = (
            f"{(implemented / applicable * 100):.1f}%" if applicable > 0 else "N/A"
        )

        print(f"\n  Risk Register:")
        print(f"    Total Risks: {dashboard['risk_register']['total_risks']}")
        print(f"    Open Risks: {dashboard['risk_register']['open_risks']}")
        for level, count in dashboard["risk_register"]["by_level"].items():
            print(f"    {level}: {count}")

        print(f"\n  Statement of Applicability:")
        print(f"    Total Controls: {dashboard['soa']['total_controls']}")
        print(f"    Applicable: {dashboard['soa']['applicable']}")
        print(f"    Fully Implemented: {dashboard['soa']['fully_implemented']}")
        print(f"    Compliance Rate: {dashboard['soa']['compliance_rate']}")

        print(f"\n  Audit Findings:")
        print(f"    Total: {dashboard['audit_findings']['total']}")
        print(f"    Open: {dashboard['audit_findings']['open']}")
        print(f"    Major NCRs: {dashboard['audit_findings']['major_ncrs']}")

        # Save dashboard
        dashboard_path = self.output_dir / "compliance_dashboard.json"
        with open(dashboard_path, "w") as f:
            json.dump(dashboard, f, indent=2)

        print(f"\n  Dashboard saved to: {dashboard_path}")
        return dashboard


def main():
    """Run ISO 27001 compliance assessment."""
    manager = ISO27001ComplianceManager()

    # Phase 1: Gap Analysis
    gap_results = manager.perform_gap_analysis()

    # Phase 2: Risk Register with sample risks
    sample_risks = [
        {
            "risk_id": "RISK-001",
            "asset": "Customer Database",
            "threat": "SQL Injection Attack",
            "vulnerability": "Unparameterized database queries",
            "likelihood": 4,
            "impact": 5,
            "existing_controls": ["WAF", "Input validation"],
            "treatment": RiskTreatment.MITIGATE.value,
            "treatment_controls": ["A.8.26", "A.8.28", "A.8.29"],
            "owner": "CTO",
            "due_date": (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),
        },
        {
            "risk_id": "RISK-002",
            "asset": "Employee Laptops",
            "threat": "Ransomware Infection",
            "vulnerability": "Outdated endpoint protection",
            "likelihood": 4,
            "impact": 4,
            "existing_controls": ["Antivirus"],
            "treatment": RiskTreatment.MITIGATE.value,
            "treatment_controls": ["A.8.1", "A.8.7", "A.8.8"],
            "owner": "IT Manager",
            "due_date": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
        },
        {
            "risk_id": "RISK-003",
            "asset": "Cloud Infrastructure (AWS)",
            "threat": "Unauthorized Access via Misconfigured IAM",
            "vulnerability": "Overly permissive IAM policies",
            "likelihood": 3,
            "impact": 5,
            "existing_controls": ["MFA for root account"],
            "treatment": RiskTreatment.MITIGATE.value,
            "treatment_controls": ["A.5.15", "A.5.23", "A.8.2", "A.8.3"],
            "owner": "Cloud Architect",
            "due_date": (datetime.now() + timedelta(days=21)).strftime("%Y-%m-%d"),
        },
        {
            "risk_id": "RISK-004",
            "asset": "Physical Server Room",
            "threat": "Unauthorized Physical Access",
            "vulnerability": "No CCTV monitoring, single-factor entry",
            "likelihood": 2,
            "impact": 4,
            "existing_controls": ["Key card access"],
            "treatment": RiskTreatment.MITIGATE.value,
            "treatment_controls": ["A.7.1", "A.7.2", "A.7.4"],
            "owner": "Facilities Manager",
            "due_date": (datetime.now() + timedelta(days=45)).strftime("%Y-%m-%d"),
        },
        {
            "risk_id": "RISK-005",
            "asset": "Business Operations",
            "threat": "Key Person Dependency",
            "vulnerability": "Single administrator with no backup",
            "likelihood": 3,
            "impact": 3,
            "existing_controls": [],
            "treatment": RiskTreatment.MITIGATE.value,
            "treatment_controls": ["A.5.2", "A.5.3", "A.6.2"],
            "owner": "HR Director",
            "due_date": (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),
        },
    ]

    risk_register = manager.create_risk_register(sample_risks)

    # Phase 3: Statement of Applicability
    soa = manager.generate_soa()

    # Phase 4: Audit Readiness Check
    readiness = manager.check_audit_readiness()

    # Phase 5: Sample Audit Findings
    sample_findings = [
        {
            "finding_id": "FIND-001",
            "clause_or_control": "A.5.7",
            "finding_type": "Minor NCR",
            "description": "Threat intelligence process not formally documented",
            "evidence": "No threat intelligence procedure or subscription found",
            "root_cause": "New 2022 control not yet addressed",
            "corrective_action": "Establish threat intelligence feeds and document process",
            "responsible_person": "Security Analyst",
            "due_date": (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d"),
        },
        {
            "finding_id": "FIND-002",
            "clause_or_control": "Clause 9.2",
            "finding_type": "Minor NCR",
            "description": "Internal audit programme does not cover all Annex A controls",
            "evidence": "Audit plan only covers 60 of 93 applicable controls",
            "root_cause": "Audit programme not updated for 2022 edition",
            "corrective_action": "Revise audit programme to cover all applicable controls",
            "responsible_person": "Internal Auditor",
            "due_date": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
        },
    ]

    findings = manager.track_audit_findings(sample_findings)

    # Phase 6: Compliance Dashboard
    dashboard = manager.generate_compliance_dashboard()

    print("\n" + "=" * 70)
    print("ISO 27001 COMPLIANCE ASSESSMENT COMPLETE")
    print("=" * 70)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 11.4 KB
Keep exploring