Instructions references/incident-response.md references/iso27001-controls.md references/risk-assessment-guide.md scripts/compliance_checker.py scripts/risk_assessment.py
Implement and manage Information Security Management Systems (ISMS) aligned with ISO 27001:2022 and healthcare regulatory requirements.
Table of Contents
Trigger Phrases
Use this skill when you hear:
“implement ISO 27001”
“ISMS implementation”
“security risk assessment”
“information security policy”
“ISO 27001 certification”
“security controls implementation”
“incident response plan”
“healthcare data security”
“medical device cybersecurity”
“security compliance audit”
Quick Start
Run Security Risk Assessment
python scripts/risk_assessment.py --scope "patient-data-system" --output risk_register.json
Check Compliance Status
python scripts/compliance_checker.py --standard iso27001 --controls-file controls.csv
Generate Gap Analysis Report
python scripts/compliance_checker.py --standard iso27001 --gap-analysis --output gaps.md
risk_assessment.py
Automated security risk assessment following ISO 27001 Clause 6.1.2 methodology.
Usage:
# Full risk assessment
python scripts/risk_assessment.py --scope "cloud-infrastructure" --output risks.json
# Healthcare-specific assessment
python scripts/risk_assessment.py --scope "ehr-system" --template healthcare --output risks.json
# Quick asset-based assessment
python scripts/risk_assessment.py --assets assets.csv --output risks.json
Parameters:
Parameter Required Description --scopeYes System or area to assess --templateNo Assessment template: general, healthcare, cloud --assetsNo CSV file with asset inventory --outputNo Output file (default: stdout) --formatNo Output format: json, csv, markdown
Output:
Asset inventory with classification
Threat and vulnerability mapping
Risk scores (likelihood × impact)
Treatment recommendations
Residual risk calculations
compliance_checker.py
Verify ISO 27001/27002 control implementation status.
Usage:
# Check all ISO 27001 controls
python scripts/compliance_checker.py --standard iso27001
# Gap analysis with recommendations
python scripts/compliance_checker.py --standard iso27001 --gap-analysis
# Check specific control domains
python scripts/compliance_checker.py --standard iso27001 --domains "access-control,cryptography"
# Export compliance report
python scripts/compliance_checker.py --standard iso27001 --output compliance_report.md
Parameters:
Parameter Required Description --standardYes Standard to check: iso27001, iso27002, hipaa --controls-fileNo CSV with current control status --gap-analysisNo Include remediation recommendations --domainsNo Specific control domains to check --outputNo Output file path
Output:
Control implementation status
Compliance percentage by domain
Gap analysis with priorities
Remediation recommendations
Workflows
Workflow 1: ISMS Implementation
Step 1: Define Scope and Context
Document organizational context and ISMS boundaries:
Identify interested parties and requirements
Define ISMS scope and boundaries
Document internal/external issues
Validation: Scope statement reviewed and approved by management.
Step 2: Conduct Risk Assessment
python scripts/risk_assessment.py --scope "full-organization" --template general --output initial_risks.json
Identify information assets
Assess threats and vulnerabilities
Calculate risk levels
Determine risk treatment options
Validation: Risk register contains all critical assets with assigned owners.
Step 3: Select and Implement Controls
Map risks to ISO 27002 controls:
python scripts/compliance_checker.py --standard iso27002 --gap-analysis --output control_gaps.md
Control categories:
Organizational (policies, roles, responsibilities)
People (screening, awareness, training)
Physical (perimeters, equipment, media)
Technological (access, crypto, network, application)
Validation: Statement of Applicability (SoA) documents all controls with justification.
Step 4: Establish Monitoring
Define security metrics:
Incident count and severity trends
Control effectiveness scores
Training completion rates
Audit findings closure rate
Validation: Dashboard shows real-time compliance status.
Workflow 2: Security Risk Assessment
Step 1: Asset Identification
Create asset inventory:
Asset Type Examples Classification Information Patient records, source code Confidential Software EHR system, APIs Critical Hardware Servers, medical devices High Services Cloud hosting, backup High People Admin accounts, developers Varies
Validation: All assets have assigned owners and classifications.
Step 2: Threat Analysis
Identify threats per asset category:
Asset Threats Likelihood Patient data Unauthorized access, breach High Medical devices Malware, tampering Medium Cloud services Misconfiguration, outage Medium Credentials Phishing, brute force High
Validation: Threat model covers top-10 industry threats.
Step 3: Vulnerability Assessment
python scripts/risk_assessment.py --scope "network-infrastructure" --output vuln_risks.json
Document vulnerabilities:
Technical (unpatched systems, weak configs)
Process (missing procedures, gaps)
People (lack of training, insider risk)
Validation: Vulnerability scan results mapped to risk register.
Step 4: Risk Evaluation and Treatment
Calculate risk: Risk = Likelihood × Impact
Risk Level Score Treatment Critical 20-25 Immediate action required High 15-19 Treatment plan within 30 days Medium 10-14 Treatment plan within 90 days Low 5-9 Accept or monitor Minimal 1-4 Accept
Validation: All high/critical risks have approved treatment plans.
Workflow 3: Incident Response
Step 1: Detection and Reporting
Incident categories:
Security breach (unauthorized access)
Malware infection
Data leakage
System compromise
Policy violation
Validation: Incident logged within 15 minutes of detection.
Step 2: Triage and Classification
Severity Criteria Response Time Critical Data breach, system down Immediate High Active threat, significant risk 1 hour Medium Contained threat, limited impact 4 hours Low Minor violation, no impact 24 hours
Validation: Severity assigned and escalation triggered if needed.
Step 3: Containment and Eradication
Immediate actions:
Isolate affected systems
Preserve evidence
Block threat vectors
Remove malicious artifacts
Validation: Containment confirmed, no ongoing compromise.
Step 4: Recovery and Lessons Learned
Post-incident activities:
Restore systems from clean backups
Verify integrity before reconnection
Document timeline and actions
Conduct post-incident review
Update controls and procedures
Validation: Post-incident report completed within 5 business days.
Reference Guides
When to Use Each Reference
references/iso27001-controls.md
Control selection for SoA
Implementation guidance
Evidence requirements
Audit preparation
references/risk-assessment-guide.md
Risk methodology selection
Asset classification criteria
Threat modeling approaches
Risk calculation methods
references/incident-response.md
Response procedures
Escalation matrices
Communication templates
Recovery checklists
Validation Checkpoints
ISMS Implementation Validation
Phase Checkpoint Evidence Required Scope Scope approved Signed scope document Risk Register complete Risk register with owners Controls SoA approved Statement of Applicability Operation Metrics active Dashboard screenshots Audit Internal audit done Audit report
Certification Readiness
Before Stage 1 audit:
Before Stage 2 audit:
Compliance Verification
Run periodic checks:
# Monthly compliance check
python scripts/compliance_checker.py --standard iso27001 --output monthly_ $( date +%Y%m ) .md
# Quarterly gap analysis
python scripts/compliance_checker.py --standard iso27001 --gap-analysis --output quarterly_gaps.md
Worked Example: Healthcare Risk Assessment
Scenario: Assess security risks for a patient data management system.
Step 1: Define Assets
python scripts/risk_assessment.py --scope "patient-data-system" --template healthcare
Asset inventory output:
Asset ID Asset Type Owner Classification A001 Patient database Information DBA Team Confidential A002 EHR application Software App Team Critical A003 Database server Hardware Infra Team High A004 Admin credentials Access Security Critical
Step 2: Identify Risks
Risk register output:
Risk ID Asset Threat Vulnerability L I Score R001 A001 Data breach Weak encryption 3 5 15 R002 A002 SQL injection Input validation 4 4 16 R003 A004 Credential theft No MFA 4 5 20
Step 3: Determine Treatment
Risk Treatment Control Timeline R001 Mitigate Implement AES-256 encryption 30 days R002 Mitigate Add input validation, WAF 14 days R003 Mitigate Enforce MFA for all admins 7 days
Step 4: Verify Implementation
python scripts/compliance_checker.py --controls-file implemented_controls.csv
Verification output:
Control Implementation Status
=============================
Cryptography (A.8.24): IMPLEMENTED
- AES-256 at rest: YES
- TLS 1.3 in transit: YES
Access Control (A.8.5): IMPLEMENTED
- MFA enabled: YES
- Admin accounts: 100% coverage
Application Security (A.8.26): PARTIAL
- Input validation: YES
- WAF deployed: PENDING
Overall Compliance: 87% Incident Response Procedures
Security incident detection, response, and recovery procedures per ISO 27001 requirements.
Table of Contents
Incident Classification
Incident Categories
Category
Description
Examples
Security Breach
Unauthorized access to systems/data
Account compromise, data exfiltration
Malware
Malicious software infection
Ransomware, virus, trojan
Data Leakage
Unauthorized data disclosure
Accidental email, misconfigured storage
Denial of Service
Service availability impact
DDoS attack, resource exhaustion
Policy Violation
Security policy breach
Unauthorized software, data handling
Physical
Physical security incident
Theft, unauthorized entry
Severity Levels
Level
Criteria
Response Time
Examples
Critical (P1)
Active breach, data loss, system down
Immediate (15 min)
Ransomware, confirmed breach
High (P2)
Active threat, potential data exposure
1 hour
Malware detected, suspicious access
Medium (P3)
Contained threat, limited impact
4 hours
Failed attacks, policy violations
Low (P4)
Minor issue, no immediate risk
24 hours
Suspicious emails, minor violations
Severity Decision Tree
Is there active data loss or system compromise?
├── Yes → CRITICAL (P1)
└── No → Is there an active uncontained threat?
├── Yes → HIGH (P2)
└── No → Is there potential for data exposure?
├── Yes → MEDIUM (P3)
└── No → LOW (P4)
Response Procedures
Phase 1: Detection and Reporting
Objective: Identify and report security incidents promptly.
Steps:
Identify potential incident through monitoring, alerts, or reports
Document initial observations (time, systems, symptoms)
Report to Security Team via designated channel
Assign incident ID and log in tracking system
Validation: Incident logged within 15 minutes of detection.
Documentation Required:
Date/time of detection
Detection source (monitoring, user report, automated alert)
Affected systems/users (initial assessment)
Reporter information
Phase 2: Triage and Assessment
Objective: Determine incident scope and severity.
Steps:
Gather additional information (logs, system state)
Determine incident category and severity
Identify affected assets and potential impact
Assign incident owner and response team
Validation: Severity assigned and escalation triggered if needed.
Assessment Checklist:
Phase 3: Containment
Objective: Limit damage and prevent spread.
Immediate Containment (Short-term):
Isolate affected systems from network
Disable compromised accounts
Block malicious IPs/domains
Preserve evidence before changes
Long-term Containment:
Apply temporary fixes
Implement additional monitoring
Strengthen access controls
Prepare for eradication
Validation: Containment confirmed, no ongoing spread.
Containment Actions by Incident Type:
Incident Type
Containment Actions
Account Compromise
Disable account, revoke sessions, reset credentials
Malware
Isolate host, block C2 domains, scan related systems
Data Breach
Block exfiltration path, revoke access, enable DLP
DDoS
Enable DDoS protection, rate limiting, traffic scrubbing
Phase 4: Eradication
Objective: Remove threat from environment.
Steps:
Identify root cause
Remove malware/backdoors
Close vulnerabilities exploited
Reset compromised credentials
Verify threat elimination
Validation: No indicators of compromise remain.
Eradication Checklist:
Phase 5: Recovery
Objective: Restore systems to normal operation.
Steps:
Restore from clean backups if needed
Rebuild compromised systems
Verify system integrity
Monitor for re-infection
Return to production gradually
Validation: Systems operational with enhanced monitoring.
Recovery Checklist:
Phase 6: Lessons Learned
Objective: Improve security posture and response capability.
Steps:
Conduct post-incident review (within 5 business days)
Document timeline and actions taken
Identify what worked and what didn't
Update procedures and controls
Share relevant findings (internally, externally if required)
Validation: Post-incident report completed and actions tracked.
Escalation Matrix
Escalation Paths
Severity
Initial Response
1 Hour
4 Hours
24 Hours
Critical
Security Team
CISO + Management
Executive Team
Board notification
High
Security Team
CISO
Management
-
Medium
Security Team
Security Manager
CISO if unresolved
-
Low
Security Analyst
Security Team Lead
-
-
Contact Information (Template)
Role
Primary
Backup
Contact Method
Security On-Call
[Name]
[Name]
Phone, Slack
CISO
[Name]
[Name]
Phone, Email
IT Director
[Name]
[Name]
Phone, Email
Legal Counsel
[Name]
[Firm]
Phone
PR/Communications
[Name]
[Name]
Phone
Executive Sponsor
[Name]
[Name]
Phone
External Notifications
Condition
Notify
Timeline
Patient data breach
HHS (HIPAA)
60 days
EU personal data breach
Supervisory Authority (GDPR)
72 hours
Significant breach
Law enforcement
As appropriate
Third-party involved
Affected vendor
Immediately
Communication Templates
Internal Notification (Initial)
Subject: [SEVERITY] Security Incident - [Brief Description]
INCIDENT SUMMARY
----------------
Incident ID: INC-[YYYY]-[###]
Detected: [Date/Time]
Severity: [Critical/High/Medium/Low]
Status: [Investigating/Contained/Resolved]
WHAT HAPPENED
[Brief description of the incident]
CURRENT IMPACT
[Systems affected, business impact]
ACTIONS BEING TAKEN
[Current response activities]
WHAT YOU NEED TO DO
[Any required user actions]
NEXT UPDATE
Expected by: [Time]
Contact: Security Team - [contact info] External Notification (Breach)
Subject: Important Security Notice from [Organization]
Dear [Affected Party],
We are writing to inform you of a security incident that may have
involved your personal information.
WHAT HAPPENED
On [date], we discovered [brief description].
WHAT INFORMATION WAS INVOLVED
[Types of data potentially affected]
WHAT WE ARE DOING
[Actions taken to address the incident]
WHAT YOU CAN DO
[Recommended protective actions]
FOR MORE INFORMATION
[Contact information, resources]
We sincerely regret any concern this may cause and are committed
to protecting your information.
[Signature] Status Update
Subject: UPDATE: Security Incident INC-[ID] - [Status]
CURRENT STATUS
--------------
Status: [Contained/Eradicating/Recovering]
Last Update: [Time]
PROGRESS SINCE LAST UPDATE
[Actions completed]
CURRENT ACTIVITIES
[Ongoing response work]
REMAINING ACTIONS
[What still needs to be done]
ESTIMATED RESOLUTION
[Timeframe if known]
NEXT UPDATE
Expected: [Time]
Recovery Checklists
System Recovery Checklist
Account Compromise Recovery
Ransomware Recovery
Post-Incident Activities
Post-Incident Review Meeting
Timing: Within 5 business days of resolution
Attendees:
Incident response team
Affected system owners
Security management
Relevant stakeholders
Agenda:
Incident timeline review
What worked well
What could be improved
Root cause analysis
Preventive measures
Action items and owners
Post-Incident Report Template
INCIDENT POST-MORTEM REPORT
===========================
Incident ID: INC-[YYYY]-[###]
Date: [Report date]
Author: [Name]
Classification: [Internal/Confidential]
EXECUTIVE SUMMARY
[2-3 paragraph summary]
INCIDENT TIMELINE
[Detailed chronological events]
ROOT CAUSE ANALYSIS
[5 Whys or similar analysis]
IMPACT ASSESSMENT
- Systems affected: [list]
- Data impacted: [description]
- Business impact: [description]
- Financial impact: [estimate if known]
RESPONSE EFFECTIVENESS
What worked well:
- [item]
- [item]
Areas for improvement:
- [item]
- [item]
RECOMMENDATIONS
| # | Recommendation | Priority | Owner | Due Date |
|---|----------------|----------|-------|----------|
| 1 | [action] | High | [name] | [date] |
| 2 | [action] | Medium | [name] | [date] |
LESSONS LEARNED
[Key takeaways for future incidents]
APPENDICES
- Detailed logs
- Evidence inventory
- Communication records Metrics to Track
Metric
Target
Purpose
Mean Time to Detect (MTTD)
< 1 hour
Detection capability
Mean Time to Respond (MTTR)
< 4 hours
Response speed
Mean Time to Contain (MTTC)
< 2 hours
Containment effectiveness
Incidents by severity
Decreasing trend
Overall security posture
Repeat incidents
0
Root cause resolution
ISO 27001:2022 Controls Implementation Guide
Implementation guidance for Annex A controls with evidence requirements and audit preparation.
Table of Contents
Control Categories Overview
ISO 27001:2022 Annex A contains 93 controls across 4 categories:
Category
Controls
Focus Areas
Organizational (A.5)
37
Policies, governance, supplier management
People (A.6)
8
HR security, awareness, remote working
Physical (A.7)
14
Perimeters, equipment, environment
Technological (A.8)
34
Access, crypto, network, development
Organizational Controls (A.5)
A.5.1 - Policies for Information Security
Requirement: Define, approve, publish, and communicate information security policies.
Implementation:
Draft information security policy covering scope, objectives, principles
Obtain management approval signature
Communicate to all employees and relevant parties
Review annually or after significant changes
Evidence:
Signed policy document
Communication records (email, intranet)
Acknowledgment records
Review meeting minutes
A.5.2 - Information Security Roles and Responsibilities
Requirement: Define and allocate information security responsibilities.
Implementation:
Create RACI matrix for security activities
Appoint Information Security Manager
Define responsibilities in job descriptions
Establish reporting lines
Evidence:
RACI matrix document
ISM appointment letter
Job descriptions with security duties
Organizational chart
A.5.9 - Inventory of Information and Assets
Requirement: Identify and maintain inventory of information assets.
Implementation:
Create asset register with classification
Assign owners for each asset
Define acceptable use rules
Review quarterly
Evidence:
Asset inventory/register
Classification scheme
Owner assignment records
Review logs
A.5.15 - Access Control
Requirement: Establish and implement rules for controlling access.
Implementation:
Document access control policy
Implement role-based access control (RBAC)
Define access provisioning/deprovisioning process
Conduct access reviews quarterly
Evidence:
Access control policy
RBAC role definitions
Access request forms
Review reports
People Controls (A.6)
A.6.1 - Screening
Requirement: Verify backgrounds of candidates prior to employment.
Implementation:
Define screening requirements by role
Conduct background checks
Verify references and qualifications
Document screening results
Evidence:
Screening policy
Background check reports
Verification records
Consent forms
A.6.3 - Information Security Awareness and Training
Requirement: Ensure personnel receive appropriate awareness and training.
Implementation:
Develop annual training program
Include role-specific training
Conduct phishing simulations
Track completion and effectiveness
Evidence:
Training materials
Completion records
Test/quiz results
Phishing simulation reports
A.6.7 - Remote Working
Requirement: Implement security measures for remote working.
Implementation:
Establish remote working policy
Require VPN for network access
Mandate endpoint protection
Secure home network guidance
Evidence:
Remote working policy
VPN configuration records
Endpoint compliance reports
User acknowledgments
Physical Controls (A.7)
A.7.1 - Physical Security Perimeters
Requirement: Define and use security perimeters to protect information.
Implementation:
Define secure areas and boundaries
Implement access controls (badges, locks)
Monitor entry points
Maintain visitor logs
Evidence:
Site security plan
Access control system records
CCTV footage retention
Visitor logs
A.7.4 - Physical Security Monitoring
Requirement: Monitor premises continuously for unauthorized access.
Implementation:
Deploy CCTV coverage
Implement intrusion detection
Define monitoring procedures
Establish incident response
Evidence:
CCTV deployment records
Monitoring procedures
Alert configurations
Incident logs
Technological Controls (A.8)
A.8.2 - Privileged Access Rights
Requirement: Restrict and manage privileged access.
Implementation:
Implement privileged access management (PAM)
Enforce separate admin accounts
Require MFA for privileged access
Monitor and log privileged activities
Evidence:
PAM solution records
Admin account inventory
MFA enforcement reports
Privileged activity logs
A.8.5 - Secure Authentication
Requirement: Implement secure authentication mechanisms.
Implementation:
Enforce strong password policy
Implement MFA for all users
Use secure authentication protocols
Monitor authentication events
Evidence:
Password policy
MFA enrollment records
Authentication configuration
Failed login reports
A.8.7 - Protection Against Malware
Requirement: Implement detection, prevention, and recovery for malware.
Implementation:
Deploy endpoint protection on all devices
Configure automatic updates
Implement email filtering
Define malware incident response
Evidence:
Endpoint protection deployment
Update/patch status
Email filter configuration
Malware incident records
A.8.8 - Management of Technical Vulnerabilities
Requirement: Identify and address technical vulnerabilities.
Implementation:
Conduct regular vulnerability scans
Define remediation SLAs by severity
Track remediation progress
Verify patches applied
Evidence:
Vulnerability scan reports
Remediation tracking
Patch deployment records
Penetration test reports
A.8.13 - Information Backup
Requirement: Maintain and test backup copies of information.
Implementation:
Define backup policy (frequency, retention)
Implement automated backups
Encrypt backup data
Test restoration regularly
Evidence:
Backup policy
Backup job logs
Encryption configuration
Restoration test records
A.8.15 - Logging
Requirement: Produce, retain, and protect logs of activities.
Implementation:
Define logging requirements
Deploy centralized log management (SIEM)
Set retention periods per compliance
Protect log integrity
Evidence:
Logging policy
SIEM configuration
Log retention settings
Access controls on logs
A.8.24 - Use of Cryptography
Requirement: Define and implement cryptographic controls.
Implementation:
Document cryptography policy
Encrypt data at rest (AES-256)
Encrypt data in transit (TLS 1.3)
Manage keys securely
Evidence:
Cryptography policy
Encryption configuration
Certificate inventory
Key management procedures
Evidence Requirements
Document Evidence
Control Area
Required Documents
Policies
Approved policy documents
Procedures
Documented processes with version control
Records
Completed forms, logs, reports
Contracts
Signed agreements with security clauses
Technical Evidence
Control Area
Required Evidence
Access Control
System configurations, access lists
Logging
SIEM dashboards, sample logs
Encryption
Configuration screenshots, certificate details
Vulnerability
Scan reports, remediation tracking
Retention Requirements
Evidence Type
Minimum Retention
Policies
Current + 2 previous versions
Audit reports
3 years
Access logs
1 year minimum
Incident records
3 years
Training records
Duration of employment + 2 years
Statement of Applicability
SoA Structure
For each Annex A control, document:
Field
Description
Control ID
A.5.1, A.8.24, etc.
Control Name
Official control title
Applicable
Yes/No
Justification
Why applicable or not
Implementation Status
Implemented, Partial, Planned, N/A
Implementation Description
How control is implemented
Evidence Reference
Links to evidence
Sample SoA Entry
Control: A.8.5 - Secure Authentication
Applicable: Yes
Justification: Required for all user and system access to protect
information assets from unauthorized access.
Implementation Status: Implemented
Implementation Description:
- MFA enforced for all user accounts via Azure AD
- Admin accounts require hardware token
- Password policy: 12+ chars, complexity, 90-day rotation
- Failed login lockout after 5 attempts
Evidence:
- Azure AD MFA configuration (screenshot)
- Password policy document (DOC-SEC-015)
- Authentication audit logs (SIEM dashboard) Exclusion Justification Examples
Control
Justification for Exclusion
A.7.x (Physical)
Cloud-only operations, no physical facilities
A.8.19 (Software)
No user-installed software permitted
A.8.23 (Web filter)
Handled by cloud proxy service
Risk Assessment Methodology Guide
Comprehensive guidance for conducting information security risk assessments per ISO 27001 Clause 6.1.2.
Table of Contents
Risk Assessment Process
ISO 27001 Requirements (Clause 6.1.2)
The organization shall:
Define risk assessment process
Establish risk criteria (acceptance, assessment)
Identify information security risks
Analyze and evaluate risks
Ensure repeatable and consistent results
Process Overview
1. Context → 2. Asset ID → 3. Threat ID → 4. Vuln ID → 5. Risk Calc → 6. Treatment
↑ |
└──────────────────── Review & Update ←───────────────────────────────┘
Asset Identification
Asset Categories
Category
Examples
Typical Classification
Information
Patient records, source code, contracts
Confidential-Critical
Software
EHR systems, databases, custom apps
High-Critical
Hardware
Servers, medical devices, network gear
High
Services
Cloud hosting, backup, email
High
People
Admin accounts, key personnel
Critical
Intangibles
Reputation, intellectual property
High
Classification Scheme
Level
Definition
Impact if Compromised
Critical
Business-critical, regulated data
Severe - regulatory fines, safety risk
High
Important business data
Significant - major disruption
Medium
Internal business data
Moderate - operational impact
Low
Non-sensitive data
Minor - limited impact
Public
Intended for public release
Minimal - no impact
Asset Inventory Template
ID
Asset Name
Type
Owner
Location
Classification
Value
A001
Patient DB
Information
DBA Lead
AWS RDS
Critical
$5M
A002
EHR App
Software
App Team
AWS ECS
Critical
$2M
A003
Admin Creds
Access
Security
Vault
Critical
N/A
Threat Analysis
Healthcare Threat Landscape
Threat
Likelihood
Target Assets
Motivation
Ransomware
High
All systems
Financial
Data breach
High
Patient data
Financial/Competitive
Phishing
Very High
User accounts
Access
Insider threat
Medium
Sensitive data
Various
DDoS
Medium
Public services
Disruption
Supply chain
Medium
Third-party systems
Access
Threat Modeling Approaches
STRIDE Model:
S poofing identity
T ampering with data
R epudiation
I nformation disclosure
D enial of service
E levation of privilege
Threat Actor Categories:
Actor
Capability
Motivation
Typical Targets
Nation-state
Very High
Espionage, disruption
Critical infrastructure
Organized crime
High
Financial gain
Healthcare, finance
Hacktivists
Medium
Ideology
Public-facing systems
Insiders
Varies
Financial, revenge
Sensitive data
Script kiddies
Low
Notoriety
Unpatched systems
Vulnerability Assessment
Vulnerability Categories
Category
Examples
Detection Method
Technical
Unpatched software, weak configs
Vulnerability scans
Process
Missing procedures, gaps
Process audits
People
Lack of training, social engineering
Phishing tests
Physical
Inadequate access controls
Physical audits
Vulnerability Scoring (CVSS Alignment)
Score Range
Severity
Example
9.0-10.0
Critical
RCE without authentication
7.0-8.9
High
Authentication bypass
4.0-6.9
Medium
Information disclosure
0.1-3.9
Low
Minor configuration issue
Vulnerability Sources
Automated Scans: Nessus, Qualys, OpenVAS
Penetration Testing: Annual third-party tests
Code Analysis: SAST/DAST tools
Configuration Audits: CIS benchmarks
Threat Intelligence: CVE feeds, vendor advisories
Risk Calculation
Risk Formula
Risk = Likelihood × Impact Likelihood Scale (1-5)
Score
Likelihood
Definition
5
Almost Certain
Expected to occur multiple times per year
4
Likely
Expected to occur at least once per year
3
Possible
Could occur within 2-3 years
2
Unlikely
Could occur within 5 years
1
Rare
Unlikely to occur
Impact Scale (1-5)
Score
Impact
Financial
Operational
Reputational
5
Catastrophic
>$10M
Total shutdown
International news
4
Major
$1M-$10M
Major disruption
National news
3
Moderate
$100K-$1M
Significant impact
Local news
2
Minor
$10K-$100K
Minor disruption
Complaints
1
Negligible
<$10K
Minimal impact
Internal only
Risk Matrix
Impact 1
Impact 2
Impact 3
Impact 4
Impact 5
L5
5 (Low)
10 (Med)
15 (High)
20 (Crit)
25 (Crit)
L4
4 (Low)
8 (Med)
12 (Med)
16 (High)
20 (Crit)
L3
3 (Min)
6 (Low)
9 (Med)
12 (Med)
15 (High)
L2
2 (Min)
4 (Low)
6 (Low)
8 (Med)
10 (Med)
L1
1 (Min)
2 (Min)
3 (Min)
4 (Low)
5 (Low)
Risk Levels
Level
Score Range
Action Required
Critical
20-25
Immediate action, escalate to management
High
15-19
Treatment plan within 30 days
Medium
10-14
Treatment plan within 90 days
Low
5-9
Accept or implement low-cost controls
Minimal
1-4
Accept risk, document decision
Risk Treatment
Treatment Options (ISO 27001)
Option
Description
When to Use
Modify
Implement controls to reduce risk
Most risks
Avoid
Eliminate the risk source
Unacceptable risks
Share
Transfer via insurance/outsourcing
High financial impact
Retain
Accept the risk
Low risks, cost-prohibitive controls
Control Selection Criteria
Effectiveness: Reduces likelihood or impact
Cost: Implementation and maintenance costs
Feasibility: Technical and operational viability
Compliance: Meets regulatory requirements
Integration: Works with existing controls
Residual Risk
After implementing controls:
Residual Risk = Inherent Risk × (1 - Control Effectiveness)
Control Effectiveness
Residual Risk Factor
90%+
Very Low (0.1×)
70-89%
Low (0.2-0.3×)
50-69%
Moderate (0.4-0.5×)
<50%
Limited reduction
Templates and Tools
Risk Register Template
Risk ID
Asset
Threat
Vulnerability
L
I
Inherent
Control
Residual
Owner
Status
R001
Patient DB
Data breach
Weak encryption
4
5
20
AES-256
8
DBA
Open
R002
Admin access
Credential theft
No MFA
5
5
25
MFA
5
Security
Closed
Risk Assessment Report Sections
Executive Summary
Key findings
Critical/high risks count
Overall risk posture
Methodology
Assessment scope
Criteria used
Limitations
Asset Summary
Asset inventory
Classification distribution
Risk Findings
Risk register
Heat map visualization
Trend analysis
Recommendations
Priority treatments
Timeline and resources
Residual risk projection
Appendices
Detailed asset list
Threat catalog
Control mapping
#!/usr/bin/env python3
"""
ISO 27001/27002 Compliance Checker
Verify control implementation status and generate compliance reports.
Supports gap analysis and remediation recommendations.
Usage:
python compliance_checker.py --standard iso27001
python compliance_checker.py --standard iso27001 --gap-analysis --output gaps.md
"""
import argparse
import csv
import json
import sys
from datetime import datetime
from typing import Dict, List, Any, Optional
# ISO 27001:2022 Annex A Controls (simplified)
ISO27001_CONTROLS = {
"organizational" : {
"name" : "Organizational Controls" ,
"controls" : [
{ "id" : "A.5.1" , "name" : "Policies for information security" , "priority" : "high" },
{ "id" : "A.5.2" , "name" : "Information security roles and responsibilities" , "priority" : "high" },
{ "id" : "A.5.3" , "name" : "Segregation of duties" , "priority" : "medium" },
{ "id" : "A.5.4" , "name" : "Management responsibilities" , "priority" : "high" },
{ "id" : "A.5.5" , "name" : "Contact with authorities" , "priority" : "medium" },
{ "id" : "A.5.6" , "name" : "Contact with special interest groups" , "priority" : "low" },
{ "id" : "A.5.7" , "name" : "Threat intelligence" , "priority" : "medium" },
{ "id" : "A.5.8" , "name" : "Information security in project management" , "priority" : "medium" },
{ "id" : "A.5.9" , "name" : "Inventory of information and assets" , "priority" : "high" },
{ "id" : "A.5.10" , "name" : "Acceptable use of information" , "priority" : "high" },
]
},
"people" : {
"name" : "People Controls" ,
"controls" : [
{ "id" : "A.6.1" , "name" : "Screening" , "priority" : "high" },
{ "id" : "A.6.2" , "name" : "Terms and conditions of employment" , "priority" : "high" },
{ "id" : "A.6.3" , "name" : "Information security awareness and training" , "priority" : "high" },
{ "id" : "A.6.4" , "name" : "Disciplinary process" , "priority" : "medium" },
{ "id" : "A.6.5" , "name" : "Responsibilities after termination" , "priority" : "high" },
{ "id" : "A.6.6" , "name" : "Confidentiality agreements" , "priority" : "high" },
{ "id" : "A.6.7" , "name" : "Remote working" , "priority" : "high" },
{ "id" : "A.6.8" , "name" : "Information security event reporting" , "priority" : "high" },
]
},
"physical" : {
"name" : "Physical Controls" ,
"controls" : [
{ "id" : "A.7.1" , "name" : "Physical security perimeters" , "priority" : "high" },
{ "id" : "A.7.2" , "name" : "Physical entry" , "priority" : "high" },
{ "id" : "A.7.3" , "name" : "Securing offices and facilities" , "priority" : "medium" },
{ "id" : "A.7.4" , "name" : "Physical security monitoring" , "priority" : "medium" },
{ "id" : "A.7.5" , "name" : "Protecting against environmental threats" , "priority" : "medium" },
{ "id" : "A.7.6" , "name" : "Working in secure areas" , "priority" : "medium" },
{ "id" : "A.7.7" , "name" : "Clear desk and screen" , "priority" : "medium" },
{ "id" : "A.7.8" , "name" : "Equipment siting and protection" , "priority" : "medium" },
]
},
"technological" : {
"name" : "Technological Controls" ,
"controls" : [
{ "id" : "A.8.1" , "name" : "User endpoint devices" , "priority" : "high" },
{ "id" : "A.8.2" , "name" : "Privileged access rights" , "priority" : "critical" },
{ "id" : "A.8.3" , "name" : "Information access restriction" , "priority" : "high" },
{ "id" : "A.8.4" , "name" : "Access to source code" , "priority" : "high" },
{ "id" : "A.8.5" , "name" : "Secure authentication" , "priority" : "critical" },
{ "id" : "A.8.6" , "name" : "Capacity management" , "priority" : "medium" },
{ "id" : "A.8.7" , "name" : "Protection against malware" , "priority" : "critical" },
{ "id" : "A.8.8" , "name" : "Management of technical vulnerabilities" , "priority" : "critical" },
{ "id" : "A.8.9" , "name" : "Configuration management" , "priority" : "high" },
{ "id" : "A.8.10" , "name" : "Information deletion" , "priority" : "high" },
{ "id" : "A.8.11" , "name" : "Data masking" , "priority" : "medium" },
{ "id" : "A.8.12" , "name" : "Data leakage prevention" , "priority" : "high" },
{ "id" : "A.8.13" , "name" : "Information backup" , "priority" : "critical" },
{ "id" : "A.8.14" , "name" : "Redundancy of information processing" , "priority" : "high" },
{ "id" : "A.8.15" , "name" : "Logging" , "priority" : "critical" },
{ "id" : "A.8.16" , "name" : "Monitoring activities" , "priority" : "high" },
{ "id" : "A.8.17" , "name" : "Clock synchronization" , "priority" : "medium" },
{ "id" : "A.8.18" , "name" : "Use of privileged utility programs" , "priority" : "high" },
{ "id" : "A.8.19" , "name" : "Installation of software" , "priority" : "high" },
{ "id" : "A.8.20" , "name" : "Networks security" , "priority" : "critical" },
{ "id" : "A.8.21" , "name" : "Security of network services" , "priority" : "high" },
{ "id" : "A.8.22" , "name" : "Segregation of networks" , "priority" : "high" },
{ "id" : "A.8.23" , "name" : "Web filtering" , "priority" : "medium" },
{ "id" : "A.8.24" , "name" : "Use of cryptography" , "priority" : "critical" },
{ "id" : "A.8.25" , "name" : "Secure development lifecycle" , "priority" : "high" },
{ "id" : "A.8.26" , "name" : "Application security requirements" , "priority" : "high" },
{ "id" : "A.8.27" , "name" : "Secure system architecture" , "priority" : "high" },
{ "id" : "A.8.28" , "name" : "Secure coding" , "priority" : "high" },
]
},
}
# Remediation recommendations by control
REMEDIATION_GUIDANCE = {
"A.5.1" : "Develop and publish information security policy signed by management" ,
"A.5.2" : "Define RACI matrix for security roles; appoint Information Security Manager" ,
"A.5.9" : "Create asset inventory with owners and classification" ,
"A.6.3" : "Implement annual security awareness training program" ,
"A.6.7" : "Establish remote working policy with technical controls" ,
"A.8.2" : "Implement privileged access management (PAM) solution" ,
"A.8.5" : "Deploy MFA for all user and admin accounts" ,
"A.8.7" : "Deploy endpoint protection on all devices with central management" ,
"A.8.8" : "Implement vulnerability scanning with 30-day remediation SLA" ,
"A.8.13" : "Configure automated backups with encryption and offsite storage" ,
"A.8.15" : "Deploy SIEM with log retention per compliance requirements" ,
"A.8.20" : "Implement firewall, IDS/IPS, and network monitoring" ,
"A.8.24" : "Enforce TLS 1.3 for transit, AES-256 for data at rest" ,
}
def get_control_status (control_id: str , controls_data: Optional[Dict] = None ) -> str :
"""Get implementation status for a control."""
if controls_data and control_id in controls_data:
return controls_data[control_id]
# Default: simulate partial implementation
import random
random.seed( hash (control_id))
statuses = [ "implemented" , "implemented" , "partial" , "partial" , "not_implemented" ]
return random.choice(statuses)
def load_controls_from_csv (filepath: str ) -> Dict[ str , str ]:
"""Load control status from CSV file."""
controls = {}
try :
with open (filepath, "r" , encoding = "utf-8" ) as f:
reader = csv.DictReader(f)
for row in reader:
control_id = row.get( "control_id" , row.get( "id" , "" ))
status = row.get( "status" , "not_implemented" ).lower()
if control_id:
controls[control_id] = status
except FileNotFoundError :
print ( f "Error: Controls file not found: { filepath } " , file = sys.stderr)
sys.exit( 1 )
return controls
def check_compliance (
standard: str ,
controls_data: Optional[Dict] = None ,
domains: Optional[List[ str ]] = None
) -> Dict[ str , Any]:
"""Check compliance against standard controls."""
if standard not in [ "iso27001" , "iso27002" ]:
print ( f "Error: Unsupported standard: { standard } " , file = sys.stderr)
sys.exit( 1 )
results = {
"standard" : standard,
"timestamp" : datetime.now().isoformat(),
"domains" : {},
"summary" : {
"total_controls" : 0 ,
"implemented" : 0 ,
"partial" : 0 ,
"not_implemented" : 0 ,
},
"findings" : [],
}
for domain_key, domain_data in ISO27001_CONTROLS .items():
if domains and domain_key not in domains:
continue
domain_results = {
"name" : domain_data[ "name" ],
"controls" : [],
"implemented" : 0 ,
"partial" : 0 ,
"not_implemented" : 0 ,
}
for control in domain_data[ "controls" ]:
status = get_control_status(control[ "id" ], controls_data)
control_result = {
"id" : control[ "id" ],
"name" : control[ "name" ],
"priority" : control[ "priority" ],
"status" : status,
}
domain_results[ "controls" ].append(control_result)
results[ "summary" ][ "total_controls" ] += 1
if status == "implemented" :
domain_results[ "implemented" ] += 1
results[ "summary" ][ "implemented" ] += 1
elif status == "partial" :
domain_results[ "partial" ] += 1
results[ "summary" ][ "partial" ] += 1
else :
domain_results[ "not_implemented" ] += 1
results[ "summary" ][ "not_implemented" ] += 1
# Add to findings if high priority
if control[ "priority" ] in [ "critical" , "high" ]:
results[ "findings" ].append({
"control_id" : control[ "id" ],
"control_name" : control[ "name" ],
"priority" : control[ "priority" ],
"status" : status,
"remediation" : REMEDIATION_GUIDANCE .get(
control[ "id" ],
"Implement control per ISO 27001 requirements"
),
})
results[ "domains" ][domain_key] = domain_results
# Calculate compliance percentage
total = results[ "summary" ][ "total_controls" ]
implemented = results[ "summary" ][ "implemented" ]
partial = results[ "summary" ][ "partial" ]
results[ "summary" ][ "compliance_percentage" ] = round (
((implemented + partial * 0.5 ) / total) * 100 , 1
) if total > 0 else 0
return results
def generate_gap_analysis (results: Dict[ str , Any]) -> List[Dict[ str , Any]]:
"""Generate gap analysis with prioritized recommendations."""
gaps = []
for finding in results[ "findings" ]:
gap = {
"control_id" : finding[ "control_id" ],
"control_name" : finding[ "control_name" ],
"current_status" : finding[ "status" ],
"priority" : finding[ "priority" ],
"remediation" : finding[ "remediation" ],
"effort" : "medium" if finding[ "priority" ] == "high" else "high" ,
"timeline" : "30 days" if finding[ "priority" ] == "critical" else "90 days" ,
}
gaps.append(gap)
# Sort by priority
priority_order = { "critical" : 0 , "high" : 1 , "medium" : 2 , "low" : 3 }
gaps.sort( key =lambda x: priority_order.get(x[ "priority" ], 99 ))
return gaps
def format_output (
results: Dict[ str , Any],
gap_analysis: bool ,
output_format: str
) -> str :
"""Format compliance results for output."""
if output_format == "json" :
if gap_analysis:
results[ "gap_analysis" ] = generate_gap_analysis(results)
return json.dumps(results, indent = 2 )
# Markdown format
lines = [
f "# { results[ 'standard' ].upper() } Compliance Report" ,
f "" ,
f "**Generated:** { results[ 'timestamp' ] } " ,
f "" ,
f "## Summary" ,
f "" ,
f "| Metric | Value |" ,
f "|--------|-------|" ,
f "| Total Controls | { results[ 'summary' ][ 'total_controls' ] } |" ,
f "| Implemented | { results[ 'summary' ][ 'implemented' ] } |" ,
f "| Partial | { results[ 'summary' ][ 'partial' ] } |" ,
f "| Not Implemented | { results[ 'summary' ][ 'not_implemented' ] } |" ,
f "| **Compliance** | ** { results[ 'summary' ][ 'compliance_percentage' ] } %** |" ,
f "" ,
]
# Domain breakdown
lines.extend([
f "## Compliance by Domain" ,
f "" ,
f "| Domain | Implemented | Partial | Not Impl | Score |" ,
f "|--------|-------------|---------|----------|-------|" ,
])
for domain_key, domain_data in results[ "domains" ].items():
total = len (domain_data[ "controls" ])
score = round (
((domain_data[ "implemented" ] + domain_data[ "partial" ] * 0.5 ) / total) * 100
) if total > 0 else 0
lines.append(
f "| { domain_data[ 'name' ] } | { domain_data[ 'implemented' ] } | "
f " { domain_data[ 'partial' ] } | { domain_data[ 'not_implemented' ] } | { score } % |"
)
# Findings
if results[ "findings" ]:
lines.extend([
f "" ,
f "## Priority Findings" ,
f "" ,
f "| Control | Name | Priority | Status |" ,
f "|---------|------|----------|--------|" ,
])
for finding in results[ "findings" ][: 15 ]: # Top 15
lines.append(
f "| { finding[ 'control_id' ] } | { finding[ 'control_name' ] } | "
f " { finding[ 'priority' ].capitalize() } | { finding[ 'status' ].replace( '_' , ' ' ).capitalize() } |"
)
# Gap analysis
if gap_analysis:
gaps = generate_gap_analysis(results)
lines.extend([
f "" ,
f "## Gap Analysis & Remediation" ,
f "" ,
])
for gap in gaps[: 10 ]: # Top 10 gaps
lines.extend([
f "### { gap[ 'control_id' ] } : { gap[ 'control_name' ] } " ,
f "" ,
f "- **Priority:** { gap[ 'priority' ].capitalize() } " ,
f "- **Current Status:** { gap[ 'current_status' ].replace( '_' , ' ' ).capitalize() } " ,
f "- **Remediation:** { gap[ 'remediation' ] } " ,
f "- **Timeline:** { gap[ 'timeline' ] } " ,
f "" ,
])
return " \n " .join(lines)
def main ():
parser = argparse.ArgumentParser(
description = "ISO 27001/27002 Compliance Checker"
)
parser.add_argument(
"--standard" , "-s" ,
required = True ,
choices = [ "iso27001" , "iso27002" , "hipaa" ],
help = "Compliance standard to check"
)
parser.add_argument(
"--controls-file" , "-c" ,
help = "CSV file with current control implementation status"
)
parser.add_argument(
"--gap-analysis" , "-g" ,
action = "store_true" ,
help = "Include gap analysis with remediation recommendations"
)
parser.add_argument(
"--domains" , "-d" ,
help = "Comma-separated list of domains to check (e.g., organizational,technological)"
)
parser.add_argument(
"--output" , "-o" ,
help = "Output file path (default: stdout)"
)
parser.add_argument(
"--format" , "-f" ,
choices = [ "json" , "markdown" ],
default = "markdown" ,
help = "Output format (default: markdown)"
)
args = parser.parse_args()
# Load control status if provided
controls_data = None
if args.controls_file:
controls_data = load_controls_from_csv(args.controls_file)
# Parse domains
domains = None
if args.domains:
domains = [d.strip().lower().replace( "-" , "_" ) for d in args.domains.split( "," )]
# Check compliance
results = check_compliance(args.standard, controls_data, domains)
# Format output
output = format_output(results, args.gap_analysis, args.format)
# Write output
if args.output:
with open (args.output, "w" , encoding = "utf-8" ) as f:
f.write(output)
print ( f "Report saved to: { args.output } " , file = sys.stderr)
else :
print (output)
if __name__ == "__main__" :
main()
#!/usr/bin/env python3
"""
Security Risk Assessment Tool
Automated risk assessment following ISO 27001 Clause 6.1.2 methodology.
Identifies assets, threats, vulnerabilities, and calculates risk scores.
Usage:
python risk_assessment.py --scope "system-name" --output risks.json
python risk_assessment.py --assets assets.csv --template healthcare
"""
import argparse
import csv
import json
import sys
from datetime import datetime
from typing import Dict, List, Any, Optional
# Threat catalogs by template
THREAT_CATALOGS = {
"general" : [
{ "id" : "T01" , "name" : "Unauthorized access" , "category" : "Access" , "likelihood" : 4 },
{ "id" : "T02" , "name" : "Data breach" , "category" : "Confidentiality" , "likelihood" : 3 },
{ "id" : "T03" , "name" : "Malware infection" , "category" : "Integrity" , "likelihood" : 4 },
{ "id" : "T04" , "name" : "Phishing attack" , "category" : "Social Engineering" , "likelihood" : 5 },
{ "id" : "T05" , "name" : "Denial of service" , "category" : "Availability" , "likelihood" : 3 },
{ "id" : "T06" , "name" : "Insider threat" , "category" : "Personnel" , "likelihood" : 2 },
{ "id" : "T07" , "name" : "Physical theft" , "category" : "Physical" , "likelihood" : 2 },
{ "id" : "T08" , "name" : "System misconfiguration" , "category" : "Technical" , "likelihood" : 4 },
{ "id" : "T09" , "name" : "Third-party compromise" , "category" : "Supply Chain" , "likelihood" : 3 },
{ "id" : "T10" , "name" : "Natural disaster" , "category" : "Environmental" , "likelihood" : 1 },
],
"healthcare" : [
{ "id" : "T01" , "name" : "Patient data breach" , "category" : "Confidentiality" , "likelihood" : 4 },
{ "id" : "T02" , "name" : "Ransomware attack" , "category" : "Availability" , "likelihood" : 4 },
{ "id" : "T03" , "name" : "Medical device tampering" , "category" : "Integrity" , "likelihood" : 3 },
{ "id" : "T04" , "name" : "EHR unauthorized access" , "category" : "Access" , "likelihood" : 4 },
{ "id" : "T05" , "name" : "HIPAA violation" , "category" : "Compliance" , "likelihood" : 3 },
{ "id" : "T06" , "name" : "Clinical data corruption" , "category" : "Integrity" , "likelihood" : 2 },
{ "id" : "T07" , "name" : "Telemedicine interception" , "category" : "Confidentiality" , "likelihood" : 3 },
{ "id" : "T08" , "name" : "Credential theft" , "category" : "Access" , "likelihood" : 5 },
{ "id" : "T09" , "name" : "Third-party vendor breach" , "category" : "Supply Chain" , "likelihood" : 3 },
{ "id" : "T10" , "name" : "Insider data theft" , "category" : "Personnel" , "likelihood" : 2 },
],
"cloud" : [
{ "id" : "T01" , "name" : "Cloud misconfiguration" , "category" : "Technical" , "likelihood" : 5 },
{ "id" : "T02" , "name" : "API vulnerability exploit" , "category" : "Application" , "likelihood" : 4 },
{ "id" : "T03" , "name" : "Account hijacking" , "category" : "Access" , "likelihood" : 4 },
{ "id" : "T04" , "name" : "Data exfiltration" , "category" : "Confidentiality" , "likelihood" : 3 },
{ "id" : "T05" , "name" : "Shared tenancy attack" , "category" : "Infrastructure" , "likelihood" : 2 },
{ "id" : "T06" , "name" : "Service outage" , "category" : "Availability" , "likelihood" : 3 },
{ "id" : "T07" , "name" : "Compliance violation" , "category" : "Compliance" , "likelihood" : 3 },
{ "id" : "T08" , "name" : "Shadow IT exposure" , "category" : "Governance" , "likelihood" : 4 },
{ "id" : "T09" , "name" : "Encryption key exposure" , "category" : "Cryptography" , "likelihood" : 2 },
{ "id" : "T10" , "name" : "CSP vendor lock-in" , "category" : "Strategic" , "likelihood" : 3 },
],
}
# Vulnerability patterns
VULNERABILITY_PATTERNS = {
"access" : [ "No MFA" , "Weak passwords" , "Excessive privileges" , "Shared accounts" ],
"technical" : [ "Unpatched systems" , "Weak encryption" , "Missing logging" , "Open ports" ],
"process" : [ "No incident response" , "Missing backups" , "No change control" , "Lack of monitoring" ],
"people" : [ "Untrained staff" , "No security awareness" , "Social engineering susceptibility" ],
}
# Asset classification criteria
CLASSIFICATION_CRITERIA = {
"critical" : { "description" : "Business-critical, severe impact if compromised" , "impact" : 5 },
"high" : { "description" : "Important assets, significant impact" , "impact" : 4 },
"medium" : { "description" : "Standard business assets, moderate impact" , "impact" : 3 },
"low" : { "description" : "Limited business value, minor impact" , "impact" : 2 },
"minimal" : { "description" : "Public or non-sensitive, negligible impact" , "impact" : 1 },
}
# Risk treatment options
TREATMENT_OPTIONS = {
"critical" : "Immediate mitigation required - implement controls within 7 days" ,
"high" : "Priority mitigation - implement controls within 30 days" ,
"medium" : "Planned mitigation - implement controls within 90 days" ,
"low" : "Accept risk with monitoring or implement low-cost controls" ,
"minimal" : "Accept risk - document acceptance decision" ,
}
def calculate_risk_score (likelihood: int , impact: int ) -> int :
"""Calculate risk score as likelihood × impact."""
return likelihood * impact
def get_risk_level (score: int ) -> str :
"""Determine risk level from score."""
if score >= 20 :
return "critical"
elif score >= 15 :
return "high"
elif score >= 10 :
return "medium"
elif score >= 5 :
return "low"
return "minimal"
def load_assets_from_csv (filepath: str ) -> List[Dict[ str , Any]]:
"""Load asset inventory from CSV file."""
assets = []
try :
with open (filepath, "r" , encoding = "utf-8" ) as f:
reader = csv.DictReader(f)
for row in reader:
asset = {
"id" : row.get( "id" , f "A {len (assets) + 1 :03d } " ),
"name" : row.get( "name" , "Unknown" ),
"type" : row.get( "type" , "Information" ),
"owner" : row.get( "owner" , "Unassigned" ),
"classification" : row.get( "classification" , "medium" ).lower(),
}
assets.append(asset)
except FileNotFoundError :
print ( f "Error: Asset file not found: { filepath } " , file = sys.stderr)
sys.exit( 1 )
except Exception as e:
print ( f "Error reading asset file: { e } " , file = sys.stderr)
sys.exit( 1 )
return assets
def generate_sample_assets (scope: str , template: str ) -> List[Dict[ str , Any]]:
"""Generate sample asset inventory based on scope and template."""
base_assets = []
if template == "healthcare" :
base_assets = [
{ "id" : "A001" , "name" : "Patient Database" , "type" : "Information" , "owner" : "DBA Team" , "classification" : "critical" },
{ "id" : "A002" , "name" : "EHR Application" , "type" : "Software" , "owner" : "App Team" , "classification" : "critical" },
{ "id" : "A003" , "name" : "Medical Imaging System" , "type" : "Software" , "owner" : "Radiology" , "classification" : "high" },
{ "id" : "A004" , "name" : "Database Servers" , "type" : "Hardware" , "owner" : "Infrastructure" , "classification" : "high" },
{ "id" : "A005" , "name" : "Admin Credentials" , "type" : "Access" , "owner" : "Security" , "classification" : "critical" },
{ "id" : "A006" , "name" : "Backup Systems" , "type" : "Service" , "owner" : "IT Ops" , "classification" : "high" },
{ "id" : "A007" , "name" : "Network Infrastructure" , "type" : "Hardware" , "owner" : "Network Team" , "classification" : "high" },
{ "id" : "A008" , "name" : "API Gateway" , "type" : "Software" , "owner" : "Platform Team" , "classification" : "high" },
]
elif template == "cloud" :
base_assets = [
{ "id" : "A001" , "name" : "Cloud Storage Buckets" , "type" : "Service" , "owner" : "Platform" , "classification" : "high" },
{ "id" : "A002" , "name" : "Container Registry" , "type" : "Service" , "owner" : "DevOps" , "classification" : "high" },
{ "id" : "A003" , "name" : "API Services" , "type" : "Software" , "owner" : "Engineering" , "classification" : "critical" },
{ "id" : "A004" , "name" : "Database Instances" , "type" : "Service" , "owner" : "DBA Team" , "classification" : "critical" },
{ "id" : "A005" , "name" : "IAM Configuration" , "type" : "Access" , "owner" : "Security" , "classification" : "critical" },
{ "id" : "A006" , "name" : "Secrets Manager" , "type" : "Service" , "owner" : "Security" , "classification" : "critical" },
{ "id" : "A007" , "name" : "Load Balancers" , "type" : "Infrastructure" , "owner" : "Platform" , "classification" : "high" },
{ "id" : "A008" , "name" : "Monitoring Systems" , "type" : "Service" , "owner" : "SRE" , "classification" : "medium" },
]
else : # general
base_assets = [
{ "id" : "A001" , "name" : "Corporate Data" , "type" : "Information" , "owner" : "Data Team" , "classification" : "high" },
{ "id" : "A002" , "name" : "Business Applications" , "type" : "Software" , "owner" : "IT" , "classification" : "high" },
{ "id" : "A003" , "name" : "Server Infrastructure" , "type" : "Hardware" , "owner" : "Infrastructure" , "classification" : "high" },
{ "id" : "A004" , "name" : "User Credentials" , "type" : "Access" , "owner" : "Security" , "classification" : "critical" },
{ "id" : "A005" , "name" : "Email System" , "type" : "Service" , "owner" : "IT" , "classification" : "medium" },
{ "id" : "A006" , "name" : "File Servers" , "type" : "Hardware" , "owner" : "Infrastructure" , "classification" : "medium" },
{ "id" : "A007" , "name" : "Network Equipment" , "type" : "Hardware" , "owner" : "Network" , "classification" : "high" },
{ "id" : "A008" , "name" : "Backup Infrastructure" , "type" : "Service" , "owner" : "IT Ops" , "classification" : "high" },
]
# Tag assets with scope
for asset in base_assets:
asset[ "scope" ] = scope
return base_assets
def assess_risks (
assets: List[Dict[ str , Any]],
template: str
) -> List[Dict[ str , Any]]:
"""Perform risk assessment on assets."""
threats = THREAT_CATALOGS .get(template, THREAT_CATALOGS [ "general" ])
risks = []
risk_id = 1
for asset in assets:
classification = asset.get( "classification" , "medium" )
impact = CLASSIFICATION_CRITERIA .get(classification, {}).get( "impact" , 3 )
# Map relevant threats to asset
relevant_threats = threats[: 5 ] # Top 5 threats for each asset
for threat in relevant_threats:
likelihood = threat[ "likelihood" ]
score = calculate_risk_score(likelihood, impact)
level = get_risk_level(score)
# Identify potential vulnerabilities
vuln_category = threat[ "category" ].lower()
vulns = VULNERABILITY_PATTERNS .get( "technical" , [ "Unknown vulnerability" ])
if "access" in vuln_category:
vulns = VULNERABILITY_PATTERNS [ "access" ]
elif "personnel" in vuln_category or "social" in vuln_category:
vulns = VULNERABILITY_PATTERNS [ "people" ]
risk = {
"id" : f "R { risk_id :03d } " ,
"asset_id" : asset[ "id" ],
"asset_name" : asset[ "name" ],
"threat_id" : threat[ "id" ],
"threat_name" : threat[ "name" ],
"threat_category" : threat[ "category" ],
"vulnerability" : vulns[ 0 ] if vulns else "Unidentified" ,
"likelihood" : likelihood,
"impact" : impact,
"score" : score,
"level" : level,
"treatment" : TREATMENT_OPTIONS .get(level, "Review required" ),
}
risks.append(risk)
risk_id += 1
# Sort by risk score descending
risks.sort( key =lambda x: x[ "score" ], reverse = True )
return risks
def calculate_residual_risk (risk: Dict[ str , Any], control_effectiveness: float = 0.7 ) -> Dict[ str , Any]:
"""Calculate residual risk after applying controls."""
residual_likelihood = max ( 1 , int (risk[ "likelihood" ] * ( 1 - control_effectiveness)))
residual_score = calculate_risk_score(residual_likelihood, risk[ "impact" ])
return {
"risk_id" : risk[ "id" ],
"inherent_score" : risk[ "score" ],
"control_effectiveness" : control_effectiveness,
"residual_likelihood" : residual_likelihood,
"residual_score" : residual_score,
"residual_level" : get_risk_level(residual_score),
}
def generate_report (
scope: str ,
template: str ,
assets: List[Dict[ str , Any]],
risks: List[Dict[ str , Any]],
output_format: str
) -> str :
"""Generate risk assessment report."""
timestamp = datetime.now().isoformat()
# Calculate summary statistics
risk_counts = { "critical" : 0 , "high" : 0 , "medium" : 0 , "low" : 0 , "minimal" : 0 }
for risk in risks:
risk_counts[risk[ "level" ]] += 1
report_data = {
"metadata" : {
"scope" : scope,
"template" : template,
"timestamp" : timestamp,
"methodology" : "ISO 27001 Clause 6.1.2" ,
},
"summary" : {
"total_assets" : len (assets),
"total_risks" : len (risks),
"risk_distribution" : risk_counts,
"critical_risks" : risk_counts[ "critical" ],
"high_risks" : risk_counts[ "high" ],
},
"assets" : assets,
"risks" : risks,
"residual_risks" : [calculate_residual_risk(r) for r in risks[: 10 ]], # Top 10
}
if output_format == "json" :
return json.dumps(report_data, indent = 2 )
elif output_format == "csv" :
lines = [ "risk_id,asset,threat,likelihood,impact,score,level,treatment" ]
for risk in risks:
lines.append(
f " { risk[ 'id' ] } , { risk[ 'asset_name' ] } , { risk[ 'threat_name' ] } ,"
f " { risk[ 'likelihood' ] } , { risk[ 'impact' ] } , { risk[ 'score' ] } ,"
f " { risk[ 'level' ] } , { risk[ 'treatment' ] } "
)
return " \n " .join(lines)
else : # markdown
lines = [
f "# Security Risk Assessment Report" ,
f "" ,
f "**Scope:** { scope } " ,
f "**Template:** { template } " ,
f "**Date:** { timestamp } " ,
f "**Methodology:** ISO 27001 Clause 6.1.2" ,
f "" ,
f "## Summary" ,
f "" ,
f "| Metric | Value |" ,
f "|--------|-------|" ,
f "| Total Assets | {len (assets) } |" ,
f "| Total Risks | {len (risks) } |" ,
f "| Critical Risks | { risk_counts[ 'critical' ] } |" ,
f "| High Risks | { risk_counts[ 'high' ] } |" ,
f "| Medium Risks | { risk_counts[ 'medium' ] } |" ,
f "" ,
f "## Asset Inventory" ,
f "" ,
f "| ID | Asset | Type | Owner | Classification |" ,
f "|----|-------|------|-------|----------------|" ,
]
for asset in assets:
lines.append(
f "| { asset[ 'id' ] } | { asset[ 'name' ] } | { asset[ 'type' ] } | "
f " { asset[ 'owner' ] } | { asset[ 'classification' ].capitalize() } |"
)
lines.extend([
f "" ,
f "## Risk Register" ,
f "" ,
f "| Risk ID | Asset | Threat | L | I | Score | Level |" ,
f "|---------|-------|--------|---|---|-------|-------|" ,
])
for risk in risks[: 20 ]: # Top 20 risks
lines.append(
f "| { risk[ 'id' ] } | { risk[ 'asset_name' ] } | { risk[ 'threat_name' ] } | "
f " { risk[ 'likelihood' ] } | { risk[ 'impact' ] } | { risk[ 'score' ] } | "
f " { risk[ 'level' ].capitalize() } |"
)
lines.extend([
f "" ,
f "## Treatment Recommendations" ,
f "" ,
])
for level, treatment in TREATMENT_OPTIONS .items():
count = risk_counts[level]
if count > 0 :
lines.append( f "** { level.capitalize() } ( { count } risks):** { treatment } " )
return " \n " .join(lines)
def main ():
parser = argparse.ArgumentParser(
description = "Security Risk Assessment Tool - ISO 27001 Clause 6.1.2"
)
parser.add_argument(
"--scope" , "-s" ,
required = True ,
help = "System or area to assess"
)
parser.add_argument(
"--template" , "-t" ,
choices = [ "general" , "healthcare" , "cloud" ],
default = "general" ,
help = "Assessment template (default: general)"
)
parser.add_argument(
"--assets" , "-a" ,
help = "CSV file with asset inventory"
)
parser.add_argument(
"--output" , "-o" ,
help = "Output file path (default: stdout)"
)
parser.add_argument(
"--format" , "-f" ,
choices = [ "json" , "csv" , "markdown" ],
default = "markdown" ,
help = "Output format (default: markdown)"
)
args = parser.parse_args()
# Load or generate assets
if args.assets:
assets = load_assets_from_csv(args.assets)
else :
assets = generate_sample_assets(args.scope, args.template)
# Perform risk assessment
risks = assess_risks(assets, args.template)
# Generate report
report = generate_report(
args.scope,
args.template,
assets,
risks,
args.format
)
# Output
if args.output:
with open (args.output, "w" , encoding = "utf-8" ) as f:
f.write(report)
print ( f "Report saved to: { args.output } " , file = sys.stderr)
else :
print (report)
if __name__ == "__main__" :
main()