
Security Compliance
- 812 installs
- 29.9k repo stars
- Updated July 27, 2026
- davila7/claude-code-templates
security-compliance is a Claude Code skill that quickly generates structured incident response reports after security events or production incidents for developers and security responders who need formal P0–P3 documentat
About
security-compliance is a davila7/claude-code-templates skill that provides an Incident Response Report Template for documenting security and production incidents. The template includes incident ID, P0–P3 severity, status lifecycle (Open, Contained, Resolved, Closed), incident commander assignment, UTC timestamps, executive summary, and classification fields for incident type, attack vector, and affected assets. Developers and responders reach for security-compliance immediately after malware, phishing, data breach, DDoS, or unauthorized access events when a standardized report must be produced fast. The skill accelerates post-incident documentation so teams capture classification, impact, and resolution details in a consistent compliance-ready format.
- Standardized Incident Response Report template with severity levels (P0–P3)
- Pre-filled sections for summary, classification, timeline, and root cause
- Includes executive summary, affected assets, timeline table, and resolution steps
- Designed for rapid population during live incidents or post-mortem documentation
- Supports handoff from monitoring tools to formal security compliance records
Security Compliance by the numbers
- 812 all-time installs (skills.sh)
- +24 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #422 of 2,209 Security skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/davila7/claude-code-templates --skill security-complianceAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 812 |
|---|---|
| repo stars | ★ 29.9k |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 27, 2026 |
| Repository | davila7/claude-code-templates ↗ |
How do you write an incident response report after a security event?
Quickly generate structured incident response reports after security events or production incidents.
Who is it for?
Developers and incident responders who need a standardized security incident report immediately after a production or security event.
Skip if: Proactive vulnerability scanning or compliance policy authoring when no incident has occurred and no report template is needed.
When should I use this skill?
The developer reports a security incident, breach, outage, or production event and needs a formal incident response report document.
What you get
Completed incident response report with ID, severity, status, classification, affected assets, timeline, and executive summary.
- Incident response report
- Executive summary
- Classification record
Files
Security & Compliance Expert
Core Principles
1. Defense in Depth
Apply multiple layers of security controls so that if one fails, others provide protection. Never rely on a single security mechanism.
2. Zero Trust Architecture
Never trust, always verify. Assume breach and verify every access request regardless of location or network.
3. Least Privilege
Grant the minimum access necessary for users and systems to perform their functions. Regularly review and revoke unused permissions.
4. Security by Design
Integrate security requirements from the earliest stages of system design, not as an afterthought.
5. Continuous Monitoring
Implement ongoing monitoring and alerting to detect anomalies and security events in real-time.
6. Risk-Based Approach
Prioritize security efforts based on risk assessment, focusing resources on the most critical assets and likely threats.
7. Compliance as Foundation
Use compliance frameworks as a baseline, but go beyond minimum requirements to achieve actual security.
8. Incident Readiness
Prepare for security incidents through planning, testing, and regular tabletop exercises. Assume compromise will occur.
---
Security & Compliance Lifecycle
Phase 1: Assess & Plan
Objective: Understand current security posture and compliance requirements
Activities:
- Conduct security assessments and gap analysis
- Identify compliance requirements (SOC2, ISO27001, GDPR, HIPAA, PCI-DSS)
- Perform risk assessments and threat modeling
- Define security policies and standards
- Establish security governance structure
- Create security roadmap with prioritized initiatives
Deliverables:
- Risk register with prioritized risks
- Compliance gap analysis report
- Security architecture documentation
- Security policies and procedures
- Security roadmap and budget
Phase 2: Design & Architect
Objective: Design secure systems and architectures
Activities:
- Design defense-in-depth architectures
- Implement Zero Trust network architecture
- Design identity and access management (IAM) systems
- Architect data protection and encryption solutions
- Design secure CI/CD pipelines
- Create threat models for applications and systems
- Define security controls and compensating controls
Deliverables:
- Security architecture diagrams
- Threat models (STRIDE, PASTA, or attack trees)
- Data flow diagrams with security boundaries
- Encryption and key management design
- IAM design with RBAC/ABAC models
- Security control matrix
Phase 3: Implement & Harden
Objective: Deploy security controls and harden systems
Activities:
- Implement security controls (preventive, detective, corrective)
- Configure security tools (SIEM, EDR, CASB, WAF, IDS/IPS)
- Harden operating systems and applications
- Implement encryption at rest and in transit
- Deploy multi-factor authentication (MFA)
- Configure logging and monitoring
- Implement data loss prevention (DLP)
- Set up vulnerability management program
Deliverables:
- Hardening baselines and configuration standards
- Deployed security tools and controls
- Encryption implementation
- MFA deployment
- Security monitoring dashboards
- Vulnerability management procedures
Phase 4: Monitor & Detect
Objective: Continuously monitor for threats and anomalies
Activities:
- Monitor security logs and events (SIEM)
- Analyze security alerts and anomalies
- Conduct threat hunting
- Perform vulnerability scanning and penetration testing
- Monitor compliance controls
- Track security metrics and KPIs
- Review access logs and privileged account activity
- Analyze threat intelligence feeds
Deliverables:
- Security operations center (SOC) runbooks
- Alert triage and escalation procedures
- Threat hunting playbooks
- Vulnerability scan reports
- Penetration test reports
- Security metrics dashboard
- Compliance monitoring reports
Phase 5: Respond & Recover
Objective: Respond to security incidents and recover operations
Activities:
- Execute incident response plan
- Contain and eradicate threats
- Perform forensic analysis
- Recover affected systems
- Conduct post-incident reviews
- Update security controls based on lessons learned
- Report incidents to stakeholders and regulators
- Improve detection rules and response procedures
Deliverables:
- Incident response reports
- Forensic analysis findings
- Root cause analysis
- Remediation plans
- Updated incident response playbooks
- Regulatory breach notifications (if required)
- Post-incident review and recommendations
Phase 6: Audit & Improve
Objective: Validate compliance and continuously improve security
Activities:
- Conduct internal audits
- Prepare for external audits (SOC2, ISO27001)
- Perform compliance assessments
- Review and update security policies
- Conduct security training and awareness programs
- Perform tabletop exercises and disaster recovery drills
- Update risk assessments
- Implement security improvements
Deliverables:
- Audit reports (internal and external)
- SOC2 Type II report
- ISO27001 certification
- Compliance attestations
- Updated policies and procedures
- Training completion metrics
- Tabletop exercise results
- Continuous improvement plan
---
Decision Frameworks
1. Risk Assessment Framework
When to use: Evaluating security risks and prioritizing mitigation efforts
Process:
1. Identify Assets
- What systems, data, and services need protection?
- What is the business value of each asset?
- Who are the asset owners?
2. Identify Threats
- What threat actors might target these assets? (nation-state, cybercriminals, insiders)
- What are their motivations? (financial gain, espionage, disruption)
- What are current threat trends?
3. Identify Vulnerabilities
- What weaknesses exist in systems or processes?
- What security controls are missing or ineffective?
- What are known CVEs affecting your systems?
4. Calculate Risk
Risk = Likelihood × Impact
Likelihood scale (1-5):
1 = Rare (< 5% chance in 1 year)
2 = Unlikely (5-25%)
3 = Possible (25-50%)
4 = Likely (50-75%)
5 = Almost Certain (> 75%)
Impact scale (1-5):
1 = Minimal (< $10K loss, no data breach)
2 = Minor ($10K-$100K, limited data exposure)
3 = Moderate ($100K-$1M, significant data breach)
4 = Major ($1M-$10M, extensive data breach, regulatory fines)
5 = Catastrophic (> $10M, business-threatening)
Risk Score = Likelihood × Impact (max 25)
5. Prioritize Risks
- Critical: Risk score 15-25 (immediate action)
- High: Risk score 10-14 (action within 30 days)
- Medium: Risk score 5-9 (action within 90 days)
- Low: Risk score 1-4 (monitor and accept)
6. Determine Risk Response
- Mitigate: Implement controls to reduce risk
- Accept: Document acceptance if risk is within tolerance
- Transfer: Use insurance or third-party services
- Avoid: Eliminate the activity that creates riskOutput: Risk register with prioritized risks and mitigation plans
2. Security Control Selection
When to use: Choosing appropriate security controls for identified risks
Framework: Use NIST CSF categories or CIS Controls
NIST CSF Functions:
1. Identify (ID)
- Asset Management
- Risk Assessment
- Governance
2. Protect (PR)
- Access Control
- Data Security
- Protective Technology
3. Detect (DE)
- Anomalies and Events
- Security Monitoring
- Detection Processes
4. Respond (RS)
- Response Planning
- Communications
- Analysis and Mitigation
5. Recover (RC)
- Recovery Planning
- Improvements
- Communications
Control Types:
- Preventive: Stop incidents before they occur (MFA, firewalls, encryption)
- Detective: Identify incidents when they occur (SIEM, IDS, log monitoring)
- Corrective: Fix issues after detection (patching, incident response)
- Deterrent: Discourage attackers (security policies, warnings)
- Compensating: Alternative controls when primary controls aren't feasible
Selection Criteria:
1. Does it address the identified risk?
2. Is it cost-effective? (Control cost < Risk value)
3. Is it technically feasible?
4. Does it meet compliance requirements?
5. Can we maintain and monitor it?3. Compliance Framework Selection
When to use: Determining which compliance frameworks to implement
Decision Tree:
What type of organization are you?
├─ SaaS/Cloud Service Provider
│ ├─ Selling to enterprises? → SOC2 Type II (required)
│ ├─ International customers? → ISO27001 (strongly recommended)
│ ├─ Handling health data? → HIPAA + HITRUST
│ └─ Handling payment cards? → PCI-DSS
├─ Healthcare Provider/Payer
│ ├─ U.S.-based → HIPAA (required)
│ ├─ International → HIPAA + GDPR
│ └─ Plus: HITRUST for comprehensive framework
├─ Financial Services
│ ├─ U.S. banks → GLBA, SOX (if public)
│ ├─ Payment processing → PCI-DSS (required)
│ ├─ International → ISO27001, local regulations
│ └─ Plus: NIST CSF for framework
├─ E-commerce/Retail
│ ├─ Accept credit cards → PCI-DSS (required)
│ ├─ EU customers → GDPR (required)
│ ├─ California customers → CCPA
│ └─ B2B sales → SOC2 Type II
└─ General Enterprise
├─ Selling to enterprises → SOC2 Type II
├─ Want broad recognition → ISO27001
├─ Government contracts → FedRAMP, NIST 800-53
└─ Industry-specific → Check sector regulations
Multi-Framework Strategy:
- Start with: SOC2 or ISO27001 (choose one as foundation)
- Add: Data privacy regulations (GDPR, CCPA) as needed
- Layer on: Industry-specific requirements4. Incident Severity Classification
When to use: Triaging and responding to security incidents
Severity Levels:
P0 - Critical (Immediate Response)
- Active breach with data exfiltration occurring
- Ransomware encryption in progress
- Complete system outage of critical services
- Unauthorized access to production databases
- Response: Engage CIRT immediately, executive notification, 24/7 effort
P1 - High (Response within 1 hour)
- Confirmed malware on critical systems
- Attempted unauthorized access to sensitive data
- DDoS attack affecting availability
- Significant vulnerability with active exploits
- Response: Engage CIRT, manager notification, work until contained
P2 - Medium (Response within 4 hours)
- Malware on non-critical systems
- Suspicious account activity
- Policy violations with security impact
- Vulnerability requiring patching
- Response: Security team investigation, business hours
P3 - Low (Response within 24 hours)
- Failed login attempts (below threshold)
- Minor policy violations
- Informational security events
- Response: Standard queue, document findings
Classification Factors:
1. Data confidentiality impact (PHI, PII, financial, IP)
2. System availability impact (revenue, operations)
3. Data integrity impact (corruption, unauthorized changes)
4. Number of affected systems/users
5. Regulatory reporting requirements5. Vulnerability Prioritization
When to use: Prioritizing vulnerability remediation
Framework: Enhanced CVSS with business context
Base CVSS Score × Business Context Multiplier = Priority Score
CVSS Severity Ranges:
- Critical: 9.0-10.0
- High: 7.0-8.9
- Medium: 4.0-6.9
- Low: 0.1-3.9
Business Context Multipliers:
- Internet-facing production system: 2.0×
- Internal production system: 1.5×
- Systems with sensitive data: 1.5×
- Development/test environment: 0.5×
- Active exploit in the wild: 2.0×
- Compensating controls in place: 0.7×
Priority Levels:
- P0 (Critical): Score ≥ 14 → Patch within 24-48 hours
- P1 (High): Score 10-13.9 → Patch within 7 days
- P2 (Medium): Score 6-9.9 → Patch within 30 days
- P3 (Low): Score < 6 → Patch within 90 days or accept risk
Additional Considerations:
- Can the system be isolated/segmented?
- Are there effective detective controls?
- What is the patching complexity/risk?
- Is there a vendor patch available?6. Third-Party Risk Assessment
When to use: Evaluating security risks of vendors and partners
Assessment Framework:
1. Categorize Vendor Risk Level
Low Risk (Minimal assessment):
- No access to systems or data
- Limited integration
- Non-critical service
→ Simple questionnaire
Medium Risk (Standard assessment):
- Limited system access
- Non-sensitive data access
- Important but not critical service
→ Security questionnaire + evidence review
High Risk (Comprehensive assessment):
- Production system access
- Sensitive data processing
- Critical service dependency
→ Full assessment + audit reports + pen test
Critical Risk (Extensive assessment):
- Full production access
- PHI/PII processing
- Business-critical dependency
→ On-site audit + continuous monitoring + SLA
2. Assessment Components
For Medium/High/Critical vendors:
□ Security questionnaire (SIG, CAIQ, or custom)
□ Compliance certifications (SOC2, ISO27001)
□ Insurance certificates (cyber liability)
□ Security policies and procedures
□ Incident response plan
□ Disaster recovery/business continuity plan
□ Data processing agreement (DPA)
□ Penetration test results (for high/critical)
□ Right to audit clause in contract
3. Ongoing Monitoring
- Annual reassessment
- Monitor for breaches/incidents
- Review security updates and patches
- Track compliance certification renewals
- Conduct periodic audits (for critical vendors)
4. Vendor Risk Score
Calculate score (0-100):
- Security maturity: 40 points
- Compliance certifications: 20 points
- Incident history: 15 points
- Financial stability: 15 points
- References and reputation: 10 points
Action based on score:
- 80-100: Approved
- 60-79: Approved with conditions
- 40-59: Requires remediation plan
- < 40: Do not engage---
Key Security Frameworks & Standards
NIST Cybersecurity Framework (CSF)
- Purpose: Risk-based framework for improving cybersecurity
- Structure: 5 Functions, 23 Categories, 108 Subcategories
- Best for: General organizations, government contractors
- Maturity model: Tier 1 (Partial) to Tier 4 (Adaptive)
CIS Critical Security Controls
- Purpose: Prioritized set of actions for cyber defense
- Structure: 18 Controls with Implementation Groups (IG1, IG2, IG3)
- Best for: Practical implementation guidance
- Focus: Defense against common attack patterns
ISO/IEC 27001
- Purpose: International standard for information security management
- Structure: 14 domains, 114 controls (Annex A)
- Best for: International recognition, formal certification
- Requirements: ISMS (Information Security Management System)
SOC 2 Type II
- Purpose: Service organization controls for security and availability
- Structure: Trust Service Criteria (Security, Availability, Confidentiality, Processing Integrity, Privacy)
- Best for: SaaS companies, cloud service providers
- Audit: 3-12 month observation period
NIST 800-53
- Purpose: Security controls for federal systems
- Structure: 20 families, 1000+ controls
- Best for: Government contractors, FedRAMP
- Baselines: Low, Moderate, High impact systems
GDPR (General Data Protection Regulation)
- Purpose: EU data privacy regulation
- Scope: Any organization processing EU residents' data
- Requirements: Lawful basis, consent, data subject rights, breach notification
- Penalties: Up to 4% of global revenue or €20M
HIPAA (Health Insurance Portability and Accountability Act)
- Purpose: Protect health information (PHI)
- Scope: Healthcare providers, payers, business associates
- Requirements: Administrative, Physical, Technical safeguards
- Penalties: $100-$50,000 per violation, criminal charges possible
PCI-DSS (Payment Card Industry Data Security Standard)
- Purpose: Protect cardholder data
- Structure: 12 requirements, 6 control objectives
- Scope: Any organization storing, processing, or transmitting card data
- Levels: Based on transaction volume (Level 1-4)
---
Core Security Domains
1. Identity & Access Management (IAM)
- Authentication mechanisms (MFA, SSO, passwordless)
- Authorization models (RBAC, ABAC, ReBAC)
- Privileged access management (PAM)
- Identity governance and administration (IGA)
- Directory services (Active Directory, LDAP, Okta, Auth0)
2. Network Security
- Network segmentation and micro-segmentation
- Firewalls (next-gen, WAF, application-layer)
- Intrusion detection/prevention (IDS/IPS)
- VPN and secure remote access
- Zero Trust network architecture (ZTNA)
- DDoS protection
3. Data Security
- Encryption at rest and in transit (AES-256, TLS 1.3)
- Key management (KMS, HSM)
- Data classification and labeling
- Data loss prevention (DLP)
- Database security (encryption, masking, tokenization)
- Secrets management (Vault, AWS Secrets Manager)
4. Application Security
- Secure SDLC and DevSecOps
- SAST (Static Application Security Testing)
- DAST (Dynamic Application Security Testing)
- SCA (Software Composition Analysis)
- Secure code review
- OWASP Top 10 mitigation
5. Cloud Security
- Cloud security posture management (CSPM)
- Cloud access security broker (CASB)
- Container security (image scanning, runtime protection)
- Serverless security
- Infrastructure as Code (IaC) security scanning
- Multi-cloud security architecture
6. Endpoint Security
- Endpoint detection and response (EDR)
- Antivirus and anti-malware
- Host-based firewalls
- Device encryption (BitLocker, FileVault)
- Mobile device management (MDM)
- Patch management
7. Security Operations
- Security Information and Event Management (SIEM)
- Security Orchestration, Automation, and Response (SOAR)
- Threat intelligence platforms (TIP)
- Threat hunting
- Vulnerability management
- Penetration testing and red teaming
8. Incident Response
- Incident response plan and playbooks
- Computer forensics and investigation
- Malware analysis
- Threat containment and eradication
- Post-incident review and lessons learned
- Regulatory breach notification
9. Governance, Risk & Compliance (GRC)
- Security policies and procedures
- Risk assessment and management
- Compliance management and auditing
- Security awareness training
- Vendor risk management
- Business continuity and disaster recovery
---
Security Metrics & KPIs
Risk & Compliance Metrics
- Number of critical/high risks open
- Risk remediation time (mean time to remediate)
- Compliance audit findings (open/closed)
- Compliance control effectiveness rate
- Policy acknowledgment completion rate
- Training completion rate
Vulnerability Management Metrics
- Mean time to detect (MTTD) vulnerabilities
- Mean time to patch (MTTP)
- Vulnerability backlog (total open, by severity)
- Patch compliance rate (% systems patched within SLA)
- Vulnerability recurrence rate
Incident Response Metrics
- Mean time to detect (MTTD) incidents
- Mean time to respond (MTTR)
- Mean time to contain (MTTC)
- Mean time to recover (MTTR)
- Number of incidents by severity
- Incident recurrence rate
- False positive rate
Security Operations Metrics
- SIEM alert volume (total, by severity)
- Alert triage time
- Alert false positive rate
- Security tool coverage (% assets monitored)
- Threat hunting coverage (% environment reviewed)
- Penetration test findings
Access Management Metrics
- MFA adoption rate
- Privileged account review completion rate
- Access certification completion rate
- Orphaned account count
- Password policy compliance rate
- Failed login attempt rate
Awareness & Culture Metrics
- Phishing simulation click rate
- Security training completion rate
- Security awareness quiz scores
- Security policy violations
- Security-related helpdesk tickets
---
Security Tools Ecosystem
SIEM (Security Information & Event Management)
- Splunk Enterprise Security
- IBM QRadar
- Microsoft Sentinel
- Elastic Security
- Sumo Logic
EDR/XDR (Endpoint/Extended Detection & Response)
- CrowdStrike Falcon
- SentinelOne
- Microsoft Defender for Endpoint
- Palo Alto Cortex XDR
- Carbon Black
Vulnerability Management
- Tenable Nessus/Tenable.io
- Qualys VMDR
- Rapid7 InsightVM
- Greenbone OpenVAS (open source)
Cloud Security
- Wiz
- Prisma Cloud (Palo Alto)
- Lacework
- Orca Security
- AWS Security Hub / Azure Security Center / GCP Security Command Center
SAST/DAST
- Snyk
- Veracode
- Checkmarx
- SonarQube
- OWASP ZAP (open source)
Container Security
- Aqua Security
- Sysdig Secure
- Prisma Cloud Compute
- Trivy (open source)
Secrets Management
- HashiCorp Vault
- AWS Secrets Manager
- Azure Key Vault
- CyberArk
Identity & Access
- Okta
- Auth0
- Azure AD / Entra ID
- Ping Identity
- CyberArk (PAM)
---
Common Security Workflows
1. Security Incident Response Workflow
1. Detection & Alert
↓
2. Triage & Classification
- Determine severity (P0-P3)
- Assign to responder
↓
3. Investigation
- Gather evidence
- Analyze logs (SIEM)
- Determine scope
↓
4. Containment
- Isolate affected systems
- Block malicious IPs/domains
- Disable compromised accounts
↓
5. Eradication
- Remove malware
- Close vulnerabilities
- Patch systems
↓
6. Recovery
- Restore from backups
- Verify system integrity
- Return to production
↓
7. Post-Incident Review
- Document timeline
- Root cause analysis
- Update playbooks
- Implement improvements
↓
8. Reporting
- Executive summary
- Regulatory notification (if required)
- Stakeholder communication2. Vulnerability Management Workflow
1. Asset Discovery
- Scan network for assets
- Maintain asset inventory
↓
2. Vulnerability Scanning
- Authenticated scans
- Unauthenticated scans
- Agent-based monitoring
↓
3. Assessment & Validation
- Validate findings
- Remove false positives
- Add business context
↓
4. Prioritization
- Apply CVSS + context
- Assign severity (P0-P3)
- Create remediation tickets
↓
5. Remediation
- Patch systems
- Apply compensating controls
- Update configurations
↓
6. Verification
- Rescan to confirm fix
- Update vulnerability status
↓
7. Reporting
- Metrics dashboard
- Executive reports
- Trend analysis3. Access Review Workflow
1. Schedule Review (Quarterly)
↓
2. Generate Access Reports
- User access by role
- Privileged accounts
- Service accounts
- Orphaned accounts
↓
3. Distribute to Managers
- Each manager reviews their team
- Certify appropriate access
↓
4. Review & Certify
- Approve legitimate access
- Flag inappropriate access
- Identify orphaned accounts
↓
5. Remediation
- Revoke unapproved access
- Disable orphaned accounts
- Update RBAC assignments
↓
6. Document & Report
- Certification completion rate
- Access changes made
- Compliance evidence4. SOC2 Audit Preparation Workflow
1. Scoping (3-4 months before)
- Define in-scope systems
- Select Trust Service Criteria
- Engage auditor
↓
2. Gap Assessment (2-3 months before)
- Map controls to requirements
- Identify control gaps
- Create remediation plan
↓
3. Readiness (1-2 months before)
- Implement missing controls
- Document policies/procedures
- Conduct mock audit
↓
4. Evidence Collection (Ongoing)
- Automate evidence gathering
- Organize evidence repository
- Prepare control narratives
↓
5. Audit Kickoff
- Provide evidence to auditor
- Respond to requests
- Schedule interviews
↓
6. Fieldwork (4-6 weeks)
- Auditor tests controls
- Provide additional evidence
- Address findings
↓
7. Report Issuance
- Review draft report
- Address any exceptions
- Receive final SOC2 report
↓
8. Continuous Monitoring
- Monitor control effectiveness
- Prepare for next audit cycle---
Best Practices
Security Architecture
- Design with security in mind from the start (shift-left)
- Apply defense in depth with multiple security layers
- Implement Zero Trust: verify explicitly, use least privilege, assume breach
- Segment networks and limit lateral movement
- Encrypt data at rest and in transit
- Use secure defaults and fail securely
Access Control
- Enforce multi-factor authentication (MFA) everywhere
- Implement least privilege access
- Use just-in-time (JIT) privileged access
- Regularly review and certify access
- Disable accounts promptly on termination
- Avoid shared accounts and service account abuse
Security Operations
- Centralize logging with SIEM
- Automate detection and response where possible
- Maintain an incident response plan and test it
- Conduct regular threat hunting exercises
- Keep vulnerability remediation SLAs aggressive
- Practice incident response through tabletop exercises
Application Security
- Integrate security into CI/CD (DevSecOps)
- Scan code for vulnerabilities (SAST, DAST, SCA)
- Follow OWASP Top 10 guidelines
- Conduct security code reviews for critical changes
- Implement secure API design (authentication, rate limiting, input validation)
- Use security headers (CSP, HSTS, X-Frame-Options)
Cloud Security
- Use infrastructure as code (IaC) with security scanning
- Enable cloud-native security services (GuardDuty, Security Hub)
- Implement CSPM to monitor misconfigurations
- Use cloud-native encryption and key management
- Apply least privilege IAM policies
- Monitor for shadow IT and unauthorized resources
Compliance
- Treat compliance as a continuous process, not one-time
- Map controls to multiple frameworks for efficiency
- Automate evidence collection where possible
- Maintain a compliance calendar for deadlines
- Document everything (if it's not documented, it doesn't exist)
- Conduct internal audits before external audits
Security Culture
- Make security everyone's responsibility
- Conduct regular security awareness training
- Run phishing simulations to test awareness
- Reward security-conscious behavior
- Create clear, accessible security policies
- Foster a culture where reporting security concerns is encouraged
---
Integration with Other Disciplines
With DevOps/Platform Engineering
- Integrate security scanning into CI/CD pipelines
- Automate security testing and compliance checks
- Implement Infrastructure as Code (IaC) security
- Use container scanning and runtime protection
- Coordinate on incident response for production issues
With Enterprise Architecture
- Align security architecture with enterprise architecture
- Participate in architecture review boards
- Ensure security requirements in architecture standards
- Design secure integration patterns
- Define security reference architectures
With IT Operations
- Coordinate on patch management and change control
- Collaborate on monitoring and alerting
- Joint incident response for security and operational incidents
- Align on backup and disaster recovery procedures
- Coordinate access management and privileged access
With Product Management
- Provide security requirements for new features
- Participate in threat modeling for new products
- Balance security with user experience
- Advise on privacy and compliance implications
- Support security as a product differentiator
With Legal/Privacy
- Coordinate on data privacy regulations (GDPR, CCPA)
- Collaborate on breach notification requirements
- Review vendor contracts for security terms
- Support privacy impact assessments
- Align on data retention and deletion policies
---
When to Engage Security & Compliance
Required Engagement
- New system or application design
- Architecture changes affecting security boundaries
- Regulatory compliance initiatives
- Security incidents
- Vendor risk assessments
- Pre-production security reviews
- Audit preparation
- Data breach or suspected breach
Recommended Engagement
- Major feature releases
- Cloud migrations
- M&A due diligence
- Infrastructure changes
- New third-party integrations
- Significant process changes
- Security tool selection
- Policy updates
Continuous Collaboration
- Security review of pull requests (for critical systems)
- Vulnerability remediation prioritization
- Security awareness and training
- Threat intelligence sharing
- Risk assessment updates
- Compliance monitoring
Incident Response Report Template
Incident Summary
Incident ID: INC-2025-XXX Severity: [P0 - Critical | P1 - High | P2 - Medium | P3 - Low] Status: [Open | Contained | Resolved | Closed] Incident Commander: [Name] Date Opened: YYYY-MM-DD HH:MM UTC Date Closed: YYYY-MM-DD HH:MM UTC
Executive Summary: [Brief 2-3 sentence summary of what happened, impact, and resolution]
---
Incident Details
Classification
- Incident Type: [Malware | Phishing | Data Breach | DDoS | Unauthorized Access | Other]
- Attack Vector: [Email | Web Application | Network | Physical | Social Engineering | Other]
- Affected Assets: [List systems, applications, or data affected]
Timeline
| Time (UTC) | Event | Action Taken | Owner |
|---|---|---|---|
| 2025-01-15 14:23 | SIEM alert: Unusual outbound traffic | Analyst began investigation | SOC Analyst |
| 2025-01-15 14:30 | Confirmed malware on web-01 | Server isolated from network | SOC Analyst |
| 2025-01-15 14:45 | CIRT activated | Incident commander assigned | Security Manager |
| 2025-01-15 15:00 | Root cause identified | Vulnerability assessment | Security Engineer |
| 2025-01-15 16:00 | Patch applied to all systems | Systems patched and restarted | IT Operations |
| 2025-01-15 18:00 | Forensic analysis completed | Evidence collected | Forensic Analyst |
| 2025-01-17 10:00 | Systems restored to production | Monitoring in place | IT Operations |
| 2025-01-17 12:00 | Incident closed | Post-incident review scheduled | Incident Commander |
---
Impact Assessment
Systems Affected
- Production Systems: [Number and list]
- Development/Test Systems: [Number and list]
- User Accounts: [Number affected]
Data Impact
- Data Confidentiality: [None | Low | Medium | High | Critical]
- Personal Identifiable Information (PII): [Yes/No, quantity if applicable]
- Protected Health Information (PHI): [Yes/No, quantity if applicable]
- Financial Data: [Yes/No, quantity if applicable]
- Intellectual Property: [Yes/No]
- Other Sensitive Data: [Specify]
- Data Integrity: [None | Low | Medium | High | Critical]
- Data modified or corrupted: [Yes/No, describe]
- Data Availability: [None | Low | Medium | High | Critical]
- Systems offline: [Duration]
- Services unavailable: [List]
Business Impact
- Downtime: X hours
- Estimated Financial Loss: $X,XXX
- Direct costs (response, recovery): $X,XXX
- Indirect costs (downtime, productivity): $X,XXX
- Potential regulatory fines: $X,XXX
- Customers Affected: [Number]
- Reputation Impact: [None | Minor | Moderate | Significant | Severe]
---
Root Cause Analysis
What Happened
[Detailed description of the incident from start to finish]
How It Happened
[Technical explanation of the attack vector and vulnerabilities exploited]
Why It Happened
[Underlying causes: missing patches, misconfiguration, human error, etc.]
Contributing Factors
- Factor 1: [Description]
- Factor 2: [Description]
- Factor 3: [Description]
---
Response Actions
Detection
[How the incident was detected: SIEM alert, user report, etc.]
Containment
Short-term Containment:
- [Action 1: e.g., Isolated affected systems from network]
- [Action 2: e.g., Disabled compromised user accounts]
- [Action 3: e.g., Blocked malicious IPs at firewall]
Long-term Containment:
- [Action 1: e.g., Patched vulnerable systems]
- [Action 2: e.g., Implemented compensating controls]
Eradication
- [Action 1: e.g., Removed malware from all systems]
- [Action 2: e.g., Closed vulnerable attack vector]
- [Action 3: e.g., Reset all potentially compromised credentials]
Recovery
- [Action 1: e.g., Restored systems from clean backups]
- [Action 2: e.g., Verified system integrity]
- [Action 3: e.g., Returned systems to production with enhanced monitoring]
Evidence Collected
- Forensic Images: [List systems imaged]
- Log Files: [List log sources collected]
- Network Captures: [PCAP files if applicable]
- Malware Samples: [Hashes and analysis]
- Other Evidence: [Specify]
---
External Notifications
Regulatory Notifications Required
- [ ] GDPR Breach Notification (72 hours to supervisory authority)
- Submitted: [Yes/No]
- Date: YYYY-MM-DD
- Reference Number: [Number]
- [ ] State Breach Notification Laws (varies by state)
- States: [List]
- Notification Deadline: YYYY-MM-DD
- Status: [Completed/In Progress/Not Required]
- [ ] HIPAA Breach Notification (60 days)
- HHS Notification: [Yes/No/Not Required]
- Affected Individuals: [Number]
- Media Notification: [Yes/No/Not Required]
- [ ] Other Regulatory Requirements:
- [Specify regulation and status]
Other Notifications
- [ ] Cyber Insurance: Notified on YYYY-MM-DD, Claim #XXXXX
- [ ] Law Enforcement: [FBI/Local PD] contacted on YYYY-MM-DD
- [ ] Third-Party Vendors: [List vendors notified]
- [ ] Customers: [Number notified, method, date]
- [ ] Media: [Statement issued Yes/No, date]
---
Lessons Learned
What Went Well
1. [Example: SIEM alert triggered immediately, enabling fast detection] 2. [Example: Incident response team responded within SLA] 3. [Example: Recent backups were available and clean]
What Could Be Improved
1. [Example: Vulnerability should have been patched 30 days ago] 2. [Example: Incident response playbook was outdated] 3. [Example: Communication with affected users was delayed]
Action Items
| # | Action Item | Owner | Due Date | Priority | Status |
|---|---|---|---|---|---|
| 1 | Implement automated patch management for critical systems | IT Manager | 2025-02-15 | High | Open |
| 2 | Update incident response playbook with ransomware procedures | Security Manager | 2025-02-01 | High | Open |
| 3 | Conduct security awareness training on phishing | HR/Security | 2025-03-01 | Medium | Open |
| 4 | Deploy EDR solution on all endpoints | IT Security | 2025-03-15 | High | Open |
| 5 | Implement immutable backups | IT Operations | 2025-02-28 | High | Open |
| 6 | Create customer communication templates | Communications | 2025-02-01 | Medium | Open |
---
Post-Incident Review
Review Meeting Date: YYYY-MM-DD Attendees: [List participants]
Discussion Summary: [Summary of post-incident review meeting discussion]
Key Decisions: 1. [Decision 1] 2. [Decision 2]
---
Compliance & Legal
Regulatory Compliance Status
- GDPR: [Compliant | Breach Notification Filed | Under Review]
- HIPAA: [Compliant | Breach Notification Filed | Not Applicable]
- PCI-DSS: [Compliant | Incident Reported to Acquiring Bank | Not Applicable]
- SOC 2: [Control Deficiency Noted | No Impact | Not Applicable]
Legal Review
- Legal Counsel Consulted: [Yes/No]
- Litigation Risk: [None | Low | Medium | High]
- Privilege Considerations: [Any communications under attorney-client privilege]
---
Metrics
Response Metrics
- Mean Time to Detect (MTTD): X hours
- Mean Time to Respond (MTTR): X hours
- Mean Time to Contain (MTTC): X hours
- Mean Time to Recover (MTTR): X hours
- Total Incident Duration: X hours
Cost Metrics
- Direct Response Costs: $X,XXX
- Recovery Costs: $X,XXX
- Downtime Costs: $X,XXX
- Notification Costs: $X,XXX
- Total Estimated Cost: $X,XXX
---
Appendices
Appendix A: Technical Details
[Detailed technical analysis, IoCs, malware analysis, etc.]
Appendix B: Evidence Inventory
[Complete list of all evidence collected with chain of custody]
Appendix C: Communications
[Copies of all internal and external communications]
Appendix D: Forensic Reports
[Attach or reference detailed forensic analysis reports]
---
Sign-off
Incident Commander: _____________________ Date: __________ CISO: _____________________ Date: __________ Legal: _____________________ Date: __________
---
Document Version: 1.0 Last Updated: YYYY-MM-DD Classification: Confidential - Internal Use Only
id,name,asset_value,exposure_factor,aro,likelihood,impact,category,owner
R-001,Ransomware Attack on Production Infrastructure,10000000,0.6,0.15,4,5,Cybersecurity,CISO
R-002,Data Breach - Customer PII Exposure,5000000,0.8,0.2,4,5,Data Privacy,CISO
R-003,Phishing Attack Leading to Credential Compromise,2000000,0.3,0.5,5,3,Cybersecurity,Security Manager
R-004,Unpatched Critical Vulnerabilities,3000000,0.4,0.3,4,4,Vulnerability Management,IT Security
R-005,Insider Threat - Malicious Employee,4000000,0.5,0.1,2,5,Insider Risk,HR
R-006,DDoS Attack on Public Services,1500000,0.2,0.25,3,3,Availability,IT Operations
R-007,Third-Party Vendor Breach,3500000,0.6,0.2,3,4,Third-Party Risk,Procurement
R-008,Cloud Misconfiguration Exposure,2500000,0.7,0.4,4,4,Cloud Security,Cloud Architect
R-009,SQL Injection in Customer Portal,4500000,0.9,0.15,3,5,Application Security,AppSec Lead
R-010,Physical Security Breach at Data Center,8000000,0.3,0.05,2,5,Physical Security,Facilities
R-011,Lost or Stolen Laptop with Unencrypted Data,500000,0.8,0.3,3,3,Endpoint Security,IT Security
R-012,Compliance Violation - GDPR,2000000,0.3,0.15,3,4,Compliance,Privacy Officer
R-013,Social Engineering Attack,1000000,0.2,0.6,5,2,Human Factor,Security Awareness
R-014,Zero-Day Exploit,6000000,0.5,0.05,2,5,Vulnerability Management,CISO
R-015,Supply Chain Attack,7000000,0.6,0.1,2,5,Supply Chain,Procurement
SOC 2 Control Documentation Example
Control: CC6.1 - Logical Access Controls
Control Objective
The entity implements logical access security software, infrastructure, and architectures over protected information assets to protect them from security events to meet the entity's objectives.
---
Sub-Control: Multi-Factor Authentication (MFA) for Production Access
Control ID
CC6.1-MFA-01
Control Description
Multi-factor authentication (MFA) is required for all user access to production systems, including applications, databases, cloud infrastructure, and administrative consoles. MFA must be configured to require at least two of the following factors:
- Something you know (password)
- Something you have (hardware token, authenticator app)
- Something you are (biometric)
Control Owner
Primary: IT Security Manager Secondary: Cloud Infrastructure Lead
Control Type
- [x] Preventive
- [ ] Detective
- [ ] Corrective
Control Frequency
- [x] Continuous (system-enforced)
- [ ] Daily
- [ ] Weekly
- [ ] Monthly
- [ ] Quarterly
- [ ] Annually
- [ ] Event-driven
---
Implementation Details
Scope
In-Scope Systems:
- AWS production accounts (all regions)
- Azure production subscriptions
- Kubernetes production clusters
- Production databases (PostgreSQL, MySQL)
- CI/CD pipeline (production deployments)
- VPN access to production network
- Jump servers / bastion hosts
- SIEM and security tooling
Out-of-Scope:
- Development and test environments (MFA recommended but not required)
- Internal corporate applications (covered under separate control)
MFA Solutions Implemented
1. Okta - Primary identity provider for SSO
- Enforces MFA for all production application access
- Supported factors: Okta Verify (push), Google Authenticator (TOTP), YubiKey (hardware token)
2. AWS IAM - Cloud infrastructure access
- MFA required for console access
- MFA required for CLI/API access using temporary credentials
- Hardware MFA (YubiKey) required for root account
3. Azure AD - Microsoft cloud services
- Conditional access policy enforces MFA for production resource access
- Supported factors: Microsoft Authenticator, SMS, phone call
4. SSH Certificates - Linux server access
- Short-lived SSH certificates issued after MFA authentication via Okta
- Certificate validity: 8 hours
Technical Implementation
AWS MFA Policy (Example)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyAllExceptListedIfNoMFA",
"Effect": "Deny",
"NotAction": [
"iam:CreateVirtualMFADevice",
"iam:EnableMFADevice",
"iam:GetUser",
"iam:ListMFADevices",
"iam:ListVirtualMFADevices",
"iam:ResyncMFADevice",
"sts:GetSessionToken"
],
"Resource": "*",
"Condition": {
"BoolIfExists": {
"aws:MultiFactorAuthPresent": "false"
}
}
}
]
}Okta Policy Configuration
- Policy Name: Production Access MFA
- Users: All employees with production access
- Applications: All production applications
- MFA Requirement: Required at every sign-on
- Allowed Factors: Okta Verify (push), TOTP, YubiKey
- Factor Enrollment: Required within 24 hours of production access grant
Azure Conditional Access Policy
- Policy Name: Require MFA for Production Resources
- Users: All users
- Cloud apps: All production Azure resources (tagged: Environment=Production)
- Conditions: Any location
- Access controls: Require MFA
- Session: Sign-in frequency = 8 hours
---
Control Testing
Test Procedures
Test 1: MFA Enrollment Verification
Objective: Verify all users with production access have MFA enrolled
Test Steps: 1. Export list of all users with production access from Okta 2. Query MFA enrollment status for each user 3. Verify 100% enrollment rate 4. For any users without MFA, verify access has been revoked
Expected Evidence:
- Okta user report showing MFA enrollment status
- Screenshot of enrollment rate: 100%
Test Frequency: Quarterly
---
Test 2: MFA Enforcement Testing
Objective: Verify MFA cannot be bypassed
Test Steps: 1. Attempt to access production AWS console without MFA
- Expected: Access denied
2. Attempt to access production application without MFA
- Expected: Redirect to MFA enrollment/challenge
3. Attempt to SSH to production server without MFA
- Expected: Certificate issuance fails without MFA
Expected Evidence:
- Screenshots of access denial without MFA
- Log entries showing MFA enforcement
Test Frequency: Annually (during audit)
---
Test 3: Sample User Access Verification
Objective: Verify sample of users have appropriate MFA configured
Test Steps: 1. Auditor selects random sample of 25 users with production access 2. For each user, verify:
- MFA is enrolled
- At least 2 factors registered
- Last MFA usage within past 30 days (for active users)
3. Document any exceptions
Expected Evidence:
- Okta user detail report for each sampled user
- MFA authentication logs
Test Frequency: Annually (during audit)
---
Evidence Collection
Automated Evidence
Evidence is collected automatically on the following schedule:
| Evidence Type | Frequency | Location | Retention |
|---|---|---|---|
| Okta MFA Enrollment Report | Weekly | GRC Tool / Evidence Repository | 7 years |
| AWS MFA Usage Report | Weekly | S3 Bucket (compliance-evidence) | 7 years |
| Azure MFA Sign-in Logs | Daily | Azure Monitor / Log Analytics | 2 years |
| MFA Authentication Logs | Real-time | SIEM (Splunk) | 1 year |
Evidence Collection Script
#!/usr/bin/env python3
"""
Automated MFA evidence collection for SOC 2 audit
Runs weekly via cron job
"""
import requests
import json
from datetime import datetime
OKTA_API_KEY = "xxx" # Retrieved from secrets manager
OKTA_DOMAIN = "company.okta.com"
def collect_mfa_enrollment():
"""Collect MFA enrollment status for all users"""
headers = {
"Authorization": f"SSWS {OKTA_API_KEY}",
"Content-Type": "application/json"
}
# Get all active users
users_url = f"https://{OKTA_DOMAIN}/api/v1/users?filter=status eq \"ACTIVE\""
users = requests.get(users_url, headers=headers).json()
enrollment_data = []
for user in users:
# Get MFA factors for each user
factors_url = f"https://{OKTA_DOMAIN}/api/v1/users/{user['id']}/factors"
factors = requests.get(factors_url, headers=headers).json()
enrollment_data.append({
"user_id": user['id'],
"email": user['profile']['email'],
"mfa_enrolled": len(factors) > 0,
"factor_count": len(factors),
"factors": [f['factorType'] for f in factors]
})
# Calculate enrollment rate
total_users = len(enrollment_data)
enrolled_users = sum(1 for u in enrollment_data if u['mfa_enrolled'])
enrollment_rate = (enrolled_users / total_users * 100) if total_users > 0 else 0
# Save evidence
evidence = {
"collection_date": datetime.now().isoformat(),
"control_id": "CC6.1-MFA-01",
"total_users": total_users,
"enrolled_users": enrolled_users,
"enrollment_rate": round(enrollment_rate, 2),
"users": enrollment_data
}
filename = f"mfa_enrollment_{datetime.now().strftime('%Y%m%d')}.json"
with open(f"/evidence/mfa/{filename}", "w") as f:
json.dump(evidence, f, indent=2)
print(f"Evidence collected: {filename}")
print(f"Enrollment rate: {enrollment_rate:.2f}%")
return evidence
if __name__ == "__main__":
collect_mfa_enrollment()---
Exception Management
Current Exceptions
| User | Reason | Approval | Expiration | Compensating Control |
|---|---|---|---|---|
| service-account@company.com | API-only account, no interactive login | CISO | 2025-12-31 | API key rotation every 90 days, IP allowlist |
Exception Approval Process
1. User submits exception request via Jira Service Desk 2. Control owner reviews and recommends approval/denial 3. CISO approves exceptions >30 days 4. Exceptions reviewed quarterly 5. All exceptions documented in GRC tool
---
Related Controls
| Control ID | Control Name | Relationship |
|---|---|---|
| CC6.1-PWD-01 | Password Complexity Requirements | Prerequisite (MFA requires strong password) |
| CC6.2-ACC-01 | Quarterly Access Reviews | Complementary (verify MFA users still need access) |
| CC7.2-LOG-01 | Authentication Logging | Detective control (logs MFA authentications) |
| CC8.1-JIT-01 | Just-in-Time Access | Related (JIT access also requires MFA) |
---
Control Effectiveness Metrics
KPIs
1. MFA Enrollment Rate: Target 100%
- Current: 100% (500/500 users)
- Trend: ✓ Maintained 100% for past 12 months
2. MFA Bypass Attempts: Target 0 successful bypasses
- Current: 0 successful bypasses
- Blocked attempts: 3 (all blocked by system)
3. MFA-Related Helpdesk Tickets: Target <5 per month
- Current: 2 per month average
- Trend: ↓ Decreasing (user training effective)
4. Average Time to MFA Enrollment: Target <24 hours after access grant
- Current: 4.2 hours average
- Trend: → Stable
---
Change History
| Date | Version | Change Description | Changed By |
|---|---|---|---|
| 2024-01-15 | 1.0 | Initial control implementation | IT Security Manager |
| 2024-06-01 | 1.1 | Added Azure AD MFA for Microsoft services | Cloud Architect |
| 2024-09-15 | 1.2 | Implemented SSH certificate-based authentication | Security Engineer |
| 2025-01-10 | 1.3 | Updated to require hardware tokens for privileged users | CISO |
---
Audit Trail
2024 SOC 2 Type II Audit
- Audit Firm: Deloitte & Touche LLP
- Audit Period: January 1, 2024 - December 31, 2024
- Test Results: No exceptions noted
- Auditor Comments: "The Company has effectively implemented MFA for all production system access. Control operates effectively throughout the audit period."
- Report Date: February 15, 2025
Previous Audits
| Audit Period | Audit Firm | Result | Exceptions |
|---|---|---|---|
| 2023 (Full Year) | Deloitte | Passed | 0 |
| 2023 (Initial, 3 months) | Deloitte | Passed | 0 |
---
Continuous Improvement
Planned Enhancements
1. Phishing-Resistant MFA (Q2 2025)
- Migrate to FIDO2/WebAuthn hardware keys for all privileged users
- Phase out SMS/phone call factors (vulnerable to SIM swapping)
2. Risk-Based Authentication (Q3 2025)
- Implement adaptive MFA based on risk signals (location, device, behavior)
- Reduce MFA prompts for low-risk access while maintaining security
3. Passwordless Authentication (Q4 2025)
- Pilot passwordless authentication using biometrics + hardware keys
- Eliminate password-based attacks
---
Control Sign-off
Control Owner: John Smith, IT Security Manager Date: January 15, 2025
Reviewed by: Jane Doe, CISO Date: January 16, 2025
Next Review Date: July 15, 2025 (Semi-annual review)
cve_id,title,cvss_score,affected_system,asset_criticality,exposure,data_sensitivity,exploit_available,exploit_in_wild,compensating_controls,discovered_date
CVE-2021-44228,Apache Log4j Remote Code Execution (Log4Shell),10.0,prod-web-01.company.com,5,internet_facing,highly_confidential,true,true,false,2025-01-10
CVE-2023-23397,Microsoft Outlook Elevation of Privilege,9.8,mail-server-01.company.com,4,internet_facing,highly_confidential,true,true,false,2025-01-12
CVE-2024-12345,OpenSSL Information Disclosure,7.5,api-gateway.company.com,5,internet_facing,highly_confidential,true,false,false,2025-01-15
CVE-2023-44487,HTTP/2 Rapid Reset DDoS,7.5,load-balancer-01.company.com,4,internet_facing,confidential,true,true,true,2025-01-08
CVE-2024-23456,PostgreSQL SQL Injection,9.1,db-prod-01.company.com,5,internal,highly_confidential,false,false,false,2025-01-11
CVE-2022-1234,Jenkins Remote Code Execution,8.8,jenkins.internal.company.com,3,internal,confidential,true,false,true,2025-01-14
CVE-2023-56789,WordPress Cross-Site Scripting,6.1,blog.company.com,2,internet_facing,public,true,false,true,2025-01-09
CVE-2024-99999,Custom App Authentication Bypass,8.2,customer-portal.company.com,5,internet_facing,highly_confidential,false,false,false,2025-01-16
CVE-2023-11111,Nginx Path Traversal,7.3,proxy-server-01.company.com,3,internal,confidential,true,false,false,2025-01-13
CVE-2024-22222,Docker Container Escape,8.6,k8s-node-03.company.com,4,internal,confidential,true,false,true,2025-01-10
CVE-2023-33333,MySQL Privilege Escalation,6.7,db-dev-01.company.com,2,isolated,confidential,false,false,false,2025-01-12
CVE-2024-44444,Python Flask CSRF Vulnerability,5.4,internal-tool.company.com,2,internal,confidential,true,false,false,2025-01-15
CVE-2023-55555,Redis Unauthorized Access,7.8,cache-server-01.company.com,4,internal,confidential,true,false,true,2025-01-11
CVE-2024-66666,VMware vCenter RCE,9.8,vcenter.company.com,5,internal,highly_confidential,true,true,false,2025-01-09
CVE-2023-77777,Spring Framework Code Injection,7.4,app-server-02.company.com,3,internal,confidential,true,false,false,2025-01-14
Security & Compliance Expert
A comprehensive skill pack for security professionals implementing defense-in-depth security architectures, achieving compliance with industry frameworks, conducting threat modeling and risk assessments, managing security operations and incident response, and embedding security throughout the SDLC.
Overview
This skill pack provides frameworks, methodologies, tools, and best practices for:
- Security Architecture: Zero Trust, defense in depth, network segmentation, cloud security
- Compliance: SOC 2, ISO 27001, GDPR, HIPAA, PCI-DSS, FedRAMP
- Threat Modeling & Risk Assessment: STRIDE, PASTA, attack trees, quantitative/qualitative risk analysis
- Security Operations: SOC operations, SIEM, incident response, threat hunting
- Application Security: OWASP Top 10, secure SDLC, DevSecOps, API security
Quick Start
For New Security Professionals
Getting Started Checklist: 1. Read SKILL.md for core principles and lifecycle 2. Review security-architecture.md for foundational concepts 3. Study compliance-frameworks.md for your industry 4. Practice with risk calculator: python scripts/risk_calculator.py --interactive
First 30 Days:
- Week 1: Learn security fundamentals and core principles
- Week 2: Understand your organization's compliance requirements
- Week 3: Shadow SOC operations and incident response
- Week 4: Conduct first risk assessment using provided tools
For Experienced Security Professionals
Quick Reference:
- Security Operations: SOC playbooks, SIEM use cases, IR procedures
- Threat Modeling: STRIDE methodology, attack trees, vulnerability scoring
- Application Security: Secure coding, OWASP Top 10, DevSecOps pipeline
Common Tasks:
- Risk assessment:
python scripts/risk_calculator.py risks.csv - Vulnerability prioritization:
python scripts/vuln_prioritizer.py vulnerabilities.csv - Incident response: Use incident-response-template.md
File Structure
security-compliance/
├── SKILL.md # Core security frameworks and workflows
├── README.md # This file
├── reference/
│ ├── security-architecture.md # Zero Trust, defense in depth, cloud security
│ ├── compliance-frameworks.md # SOC2, ISO27001, GDPR, HIPAA, PCI-DSS
│ ├── threat-modeling-risk.md # Threat modeling, risk assessment, vulnerability management
│ ├── security-operations.md # SOC operations, SIEM, incident response
│ └── application-security.md # Secure SDLC, OWASP Top 10, DevSecOps
├── scripts/
│ ├── risk_calculator.py # Risk assessment calculator (quantitative & qualitative)
│ └── vuln_prioritizer.py # Vulnerability prioritization tool
└── examples/
├── risks.csv # Sample risk data
├── vulnerabilities.csv # Sample vulnerability data
├── incident-response-template.md # Complete incident response report template
└── soc2-control-example.md # SOC 2 control documentation exampleCommon Scenarios
Scenario 1: Conducting a Risk Assessment
Situation: You need to assess cybersecurity risks for your organization and create a risk register.
Steps: 1. Review risk assessment methodology in threat-modeling-risk.md 2. Create CSV file with your risks (use risks.csv as template) 3. Run risk calculator:
python scripts/risk_calculator.py risks.csv --output risk_report.csv4. Review report and prioritize high-risk items 5. Create risk mitigation plans for Critical and High risks 6. Present findings to leadership using summary statistics
Expected Outcome: Comprehensive risk register with quantitative ALE calculations and qualitative risk levels, enabling data-driven prioritization of security investments.
---
Scenario 2: Achieving SOC 2 Type II Compliance
Situation: Your SaaS company needs SOC 2 Type II certification to close enterprise deals.
Steps: 1. Read SOC 2 section in compliance-frameworks.md 2. Follow 6-month readiness roadmap:
- Months 6-4: Scoping, gap assessment, policy development
- Months 4-2: Control implementation, evidence preparation
- Months 2-0: Observation period, audit execution
3. Use soc2-control-example.md as template for documenting controls 4. Implement automated evidence collection (Python scripts provided in examples) 5. Conduct mock audit 1 month before real audit 6. Work with auditor during field work
Expected Outcome: SOC 2 Type II report within 6-8 months, enabling enterprise sales.
---
Scenario 3: Responding to a Security Incident
Situation: Your SOC detected ransomware on multiple systems.
Steps: 1. Follow incident response lifecycle in security-operations.md 2. Use IR playbook for ransomware (included in security-operations.md) 3. Document everything using incident-response-template.md 4. Execute response:
- Preparation: Activate CIRT, establish communication channels
- Detection: Determine scope (number of systems infected)
- Containment: Isolate affected systems, disable VPN
- Eradication: Remove malware, close vulnerability
- Recovery: Restore from offline backups, verify integrity
- Post-Incident: Conduct review, implement improvements
5. Assess breach notification requirements (GDPR, state laws) 6. Conduct post-incident review within 5 days
Expected Outcome: Contained incident with minimal data loss, documented response for audit trail, actionable improvements to prevent recurrence.
---
Scenario 4: Prioritizing Vulnerability Remediation
Situation: Vulnerability scan identified 500+ vulnerabilities across your infrastructure. You need to prioritize patching.
Steps: 1. Export vulnerabilities to CSV (use vulnerabilities.csv as template) 2. Add business context:
- Asset criticality (1-5)
- Exposure (internet_facing, internal, isolated)
- Data sensitivity (highly_confidential, confidential, public)
- Exploit availability and active exploitation
- Compensating controls
3. Run vulnerability prioritizer:
python scripts/vuln_prioritizer.py vulnerabilities.csv --output prioritized.csv4. Review prioritized list (P0 = Critical, P1 = High, P2 = Medium, P3 = Low) 5. Create remediation tickets with SLA:
- P0: Patch within 24-48 hours
- P1: Patch within 7 days
- P2: Patch within 30 days
- P3: Patch within 90 days
6. Track remediation progress
Expected Outcome: Focused remediation efforts on highest-risk vulnerabilities, reducing critical exposures within days instead of months.
---
Scenario 5: Implementing Zero Trust Architecture
Situation: Your organization is moving to cloud and wants to implement Zero Trust.
Steps: 1. Read Zero Trust section in security-architecture.md 2. Follow Zero Trust implementation roadmap:
- Phase 1 (Months 1-3): Foundation - Strong IAM, MFA everywhere, asset inventory, logging
- Phase 2 (Months 4-6): Visibility - Map data flows, deploy EDR, implement UEBA
- Phase 3 (Months 7-9): Segmentation - Micro-segmentation, security zones, application-layer controls
- Phase 4 (Months 10-12): Automation - Automated policy enforcement, SOAR, threat intelligence
- Phase 5 (Ongoing): Optimization - Continuous policy refinement, threat hunting
3. Implement three tenets:
- Verify explicitly (MFA, device posture, context)
- Use least privilege (JIT access, RBAC)
- Assume breach (monitor continuously, segment)
4. Deploy technology stack:
- Identity: Okta, Azure AD
- Network: Micro-segmentation, ZTNA
- Endpoint: EDR, device compliance
- Data: Encryption, DLP
Expected Outcome: Zero Trust architecture reducing blast radius of breaches, enabling secure remote work, improving compliance posture.
---
Python Scripts
Risk Calculator
Calculate risk scores using both qualitative (risk matrix) and quantitative (ALE) methodologies.
Features:
- Quantitative: Single Loss Expectancy (SLE), Annualized Loss Expectancy (ALE)
- Qualitative: Risk matrix (Likelihood × Impact), risk levels (Critical/High/Medium/Low)
- Cost-benefit analysis for security controls
- Interactive mode for one-off assessments
- CSV batch processing
Usage:
# Interactive mode
python scripts/risk_calculator.py --interactive
# Process CSV file
python scripts/risk_calculator.py examples/risks.csv
# Generate report
python scripts/risk_calculator.py risks.csv --output risk_report.csvSample Output:
Risk Assessment Summary
============================================================
Total Risks: 15
Total ALE: $3,250,000
Risk Level Distribution:
Critical: 3
High: 5
Medium: 4
Low: 3
Top 5 Risks by ALE:
Ransomware Attack on Production Infrastructure: $900,000
Data Breach - Customer PII Exposure: $800,000
Cloud Misconfiguration Exposure: $700,000
...---
Vulnerability Prioritizer
Prioritize vulnerabilities based on CVSS score combined with business context.
Features:
- Enhanced CVSS scoring with business context
- Factors: Asset criticality, exposure, data sensitivity, exploitability, compensating controls
- Priority levels (P0-P3) with SLA recommendations
- Rationale generation for prioritization decisions
- Filter by priority level
Usage:
# Interactive mode
python scripts/vuln_prioritizer.py --interactive
# Process CSV file
python scripts/vuln_prioritizer.py examples/vulnerabilities.csv
# Generate report
python scripts/vuln_prioritizer.py vulnerabilities.csv --output prioritized.csv
# Filter critical only
python scripts/vuln_prioritizer.py vulnerabilities.csv --filter-level P0Sample Output:
Vulnerability Summary
============================================================
Total Vulnerabilities: 15
Priority Distribution:
P0: 2
P1: 5
P2: 5
P3: 3
Exploitability:
Public exploits available: 11
Active exploitation: 4
Top Prioritized Vulnerabilities
CVE ID System CVSS Priority Level Due Date
------------------------------------------------------------------------------------------
CVE-2021-44228 prod-web-01.company.com 10.0 30.00 P0 2025-01-11
CVE-2024-66666 vcenter.company.com 9.8 29.40 P0 2025-01-10
...---
Best Practices
Security Architecture
- Design with security from the start (shift-left)
- Apply defense in depth - multiple security layers
- Implement Zero Trust: verify explicitly, use least privilege, assume breach
- Segment networks to limit lateral movement
- Encrypt data at rest and in transit with strong algorithms
Compliance
- Treat compliance as continuous, not one-time certification
- Map controls across frameworks to maximize efficiency
- Automate evidence collection where possible
- Maintain compliance calendar for deadlines
- Document everything - if it's not documented, it doesn't exist
Risk Management
- Conduct risk assessments at least annually
- Use both qualitative (risk matrix) and quantitative (ALE) methods
- Focus on business impact, not just technical severity
- Accept risk explicitly when mitigation isn't cost-effective
- Track risk remediation with clear ownership and deadlines
Security Operations
- Centralize logging with SIEM for correlation
- Tune alerts to reduce false positives (<20% target)
- Maintain incident response plan and test it (tabletop exercises)
- Measure metrics: MTTD, MTTR, MTTC, MTTR
- Conduct proactive threat hunting regularly
Application Security
- Integrate security into CI/CD pipeline (DevSecOps)
- Use SAST, DAST, and SCA scanning
- Follow OWASP Top 10 guidelines
- Conduct security code reviews for critical changes
- Never store secrets in code - use secrets manager
---
Integration with Other Skills
With DevOps/Platform Engineering
- Embed security in CI/CD pipelines (SAST, DAST, SCA, container scanning)
- Implement Infrastructure as Code (IaC) security scanning
- Automate security testing and compliance checks
- Coordinate on incident response for production issues
- Share responsibility for cloud security
With Enterprise Architecture
- Align security architecture with enterprise architecture
- Participate in architecture review boards
- Define security reference architectures and patterns
- Ensure security requirements in architecture standards
- Design secure integration patterns for systems
With IT Operations
- Coordinate on patch management and change control
- Collaborate on monitoring, logging, and alerting
- Joint incident response (security + operational)
- Align on backup/disaster recovery procedures
- Manage privileged access together
With Product Management
- Provide security requirements for new features
- Participate in threat modeling for new products
- Balance security with user experience
- Advise on privacy and compliance implications
- Support security as product differentiator
With Legal/Privacy
- Coordinate on data privacy regulations (GDPR, CCPA)
- Collaborate on breach notification requirements
- Review vendor contracts for security terms
- Support privacy impact assessments (DPIA)
- Align on data retention and deletion policies
---
Key Frameworks Reference
NIST Cybersecurity Framework (CSF)
Functions: Identify → Protect → Detect → Respond → Recover Best for: General organizations, government contractors Maturity: Tier 1 (Partial) to Tier 4 (Adaptive)
CIS Critical Security Controls
Structure: 18 controls, 3 Implementation Groups Best for: Practical, prioritized implementation Focus: Defend against common attack patterns
ISO/IEC 27001
Structure: ISMS with 14 domains, 93 controls (2022 version) Best for: International recognition, formal certification Process: Plan → Do → Check → Act
SOC 2 Type II
Criteria: Security (required) + Availability, Confidentiality, Processing Integrity, Privacy (optional) Best for: SaaS companies, cloud service providers Audit: 3-12 month observation period
OWASP Top 10 (2021)
1. Broken Access Control 2. Cryptographic Failures 3. Injection 4. Insecure Design 5. Security Misconfiguration 6. Vulnerable and Outdated Components 7. Identification and Authentication Failures 8. Software and Data Integrity Failures 9. Security Logging and Monitoring Failures 10. Server-Side Request Forgery (SSRF)
---
Metrics & KPIs
Risk Management
- Number of critical/high risks open
- Risk remediation time (mean)
- Compliance control effectiveness rate
Vulnerability Management
- Mean time to patch (MTTP) by severity
- Vulnerability backlog (by severity)
- Patch compliance rate
Security Operations
- Mean time to detect (MTTD)
- Mean time to respond (MTTR)
- Mean time to contain (MTTC)
- False positive rate (target <20%)
Incident Response
- Number of incidents by severity
- Incident recurrence rate
- SLA compliance rate
Application Security
- Vulnerabilities found per 1000 lines of code
- Security defects escaping to production
- SAST/DAST scan coverage
---
Additional Resources
Training & Certifications
- CISSP (Certified Information Systems Security Professional)
- CISM (Certified Information Security Manager)
- CEH (Certified Ethical Hacker)
- OSCP (Offensive Security Certified Professional)
- CCSP (Certified Cloud Security Professional)
- Security+ (CompTIA)
Communities
- OWASP (Open Web Application Security Project)
- SANS Reading Room
- r/netsec, r/AskNetsec (Reddit)
- Information Security Stack Exchange
- Local ISACA and ISC² chapters
Tools
- SIEM: Splunk, Elastic Security, Microsoft Sentinel
- EDR: CrowdStrike, SentinelOne, Microsoft Defender
- Vulnerability Scanning: Tenable, Qualys, Rapid7
- SAST/DAST: Snyk, Veracode, Checkmarx, SonarQube
- Cloud Security: Wiz, Prisma Cloud, Orca Security
---
Contributing
This skill pack is continuously updated based on evolving threats, new regulations, and industry best practices. Contributions and feedback are welcome.
License
This skill pack is provided for educational and professional development purposes.
Application Security & Secure SDLC
Secure Software Development Lifecycle (SDLC)
Security Activities by SDLC Phase
┌─────────────────────────────────────────────────────────────┐
│ Requirements Phase │
├─────────────────────────────────────────────────────────────┤
│ □ Security requirements gathering │
│ □ Privacy impact assessment │
│ □ Compliance requirements (GDPR, HIPAA, PCI-DSS) │
│ □ Data classification │
│ □ Abuse case development │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Design Phase │
├─────────────────────────────────────────────────────────────┤
│ □ Threat modeling (STRIDE, PASTA) │
│ □ Security architecture review │
│ □ Data flow diagrams with trust boundaries │
│ □ Authentication/authorization design │
│ □ Encryption and key management design │
│ □ Security control selection │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Development Phase │
├─────────────────────────────────────────────────────────────┤
│ □ Secure coding training for developers │
│ □ IDE security plugins (e.g., SonarLint) │
│ □ Pre-commit hooks (secrets scanning) │
│ □ Code reviews with security focus │
│ □ SAST (Static Application Security Testing) │
│ □ SCA (Software Composition Analysis) │
│ □ Unit tests for security functions │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Testing Phase │
├─────────────────────────────────────────────────────────────┤
│ □ DAST (Dynamic Application Security Testing) │
│ □ Penetration testing │
│ □ Security test cases execution │
│ □ Fuzz testing │
│ □ Authentication/authorization testing │
│ □ Container/infrastructure scanning │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Deployment Phase │
├─────────────────────────────────────────────────────────────┤
│ □ Security configuration review │
│ □ Secrets management (no hardcoded credentials) │
│ □ Security hardening (disable unnecessary services) │
│ □ Infrastructure as Code (IaC) security scanning │
│ □ Deploy security monitoring/logging │
│ □ WAF/API gateway configuration │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Maintenance Phase │
├─────────────────────────────────────────────────────────────┤
│ □ Vulnerability scanning (continuous) │
│ □ Security patch management │
│ □ Dependency updates (address CVEs) │
│ □ Security monitoring and incident response │
│ □ Periodic penetration testing (annually) │
│ □ Threat intelligence monitoring │
└─────────────────────────────────────────────────────────────┘---
OWASP Top 10 (2021) & Mitigation
A01:2021 - Broken Access Control
Description: Restrictions on what authenticated users can do are not properly enforced.
Examples:
- Accessing other users' data by modifying URL parameter (
/user/123→/user/124) - Elevation of privilege (acting as admin without being admin)
- IDOR (Insecure Direct Object Reference)
- Missing authorization checks on API endpoints
Code Example (Vulnerable):
# Vulnerable: No authorization check
@app.route('/user/<user_id>/profile')
def get_user_profile(user_id):
user = User.query.get(user_id)
return jsonify(user.to_dict())Code Example (Secure):
# Secure: Verify user owns the resource
@app.route('/user/<user_id>/profile')
@login_required
def get_user_profile(user_id):
# Check if logged-in user is requesting their own profile
if current_user.id != int(user_id):
abort(403) # Forbidden
user = User.query.get(user_id)
return jsonify(user.to_dict())Mitigation:
- Deny by default
- Implement access control checks on every request
- Use centralized authorization (RBAC, ABAC)
- Log access control failures
- Disable directory listing on web servers
---
A02:2021 - Cryptographic Failures
Description: Failures related to cryptography that lead to exposure of sensitive data.
Examples:
- Transmitting data in cleartext (HTTP instead of HTTPS)
- Using weak cryptographic algorithms (MD5, SHA1, DES)
- Hardcoded encryption keys
- No encryption of sensitive data at rest
Code Example (Vulnerable):
# Vulnerable: Weak hash, no salt
import hashlib
def hash_password(password):
return hashlib.md5(password.encode()).hexdigest()Code Example (Secure):
# Secure: Strong hash with salt
import bcrypt
def hash_password(password):
salt = bcrypt.gensalt(rounds=12)
return bcrypt.hashpw(password.encode(), salt)
def verify_password(password, hashed):
return bcrypt.checkpw(password.encode(), hashed)Mitigation:
- Use TLS 1.2+ for all data in transit
- Use strong, modern encryption algorithms (AES-256, RSA-2048+)
- Use bcrypt, scrypt, or Argon2 for password hashing
- Never store sensitive data unnecessarily
- Use proper key management (KMS, Hardware Security Modules)
---
A03:2021 - Injection
Description: User-supplied data is not validated, filtered, or sanitized.
Examples:
- SQL injection
- NoSQL injection
- OS command injection
- LDAP injection
Code Example (Vulnerable SQL Injection):
# Vulnerable: String concatenation
@app.route('/search')
def search():
query = request.args.get('q')
sql = f"SELECT * FROM products WHERE name LIKE '%{query}%'"
results = db.execute(sql)
return jsonify(results)Code Example (Secure):
# Secure: Parameterized queries
@app.route('/search')
def search():
query = request.args.get('q')
sql = "SELECT * FROM products WHERE name LIKE ?"
results = db.execute(sql, (f'%{query}%',))
return jsonify(results)Code Example (Vulnerable Command Injection):
# Vulnerable: Passing user input to shell
import os
@app.route('/ping')
def ping():
host = request.args.get('host')
result = os.system(f'ping -c 1 {host}')
return str(result)Code Example (Secure):
# Secure: Use library instead of shell command
import subprocess
@app.route('/ping')
def ping():
host = request.args.get('host')
# Validate input
import re
if not re.match(r'^[a-zA-Z0-9.-]+$', host):
return "Invalid host", 400
# Use array format (no shell interpretation)
try:
result = subprocess.run(['ping', '-c', '1', host],
capture_output=True,
timeout=5,
check=False)
return result.stdout.decode()
except subprocess.TimeoutExpired:
return "Timeout", 408Mitigation:
- Use parameterized queries (prepared statements)
- Use ORM frameworks
- Input validation (allowlist preferred over blocklist)
- Escape special characters
- Use language-specific APIs instead of shell commands
---
A04:2021 - Insecure Design
Description: Missing or ineffective security design patterns.
Examples:
- No rate limiting on authentication (allows brute force)
- No defense against automated attacks (bots)
- Insufficient logging for security events
Mitigation:
- Threat modeling during design phase
- Secure design patterns (rate limiting, circuit breakers)
- Defense in depth
- Separation of duties
---
A05:2021 - Security Misconfiguration
Description: Improperly configured security settings.
Examples:
- Default credentials not changed
- Unnecessary features enabled (directory listing, debug mode)
- Error messages revealing stack traces
- Missing security headers
Secure Configuration Example:
# Flask example with security headers
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
# Enforce HTTPS and security headers
Talisman(app,
force_https=True,
strict_transport_security=True,
content_security_policy={
'default-src': "'self'",
'script-src': "'self' 'unsafe-inline'",
'style-src': "'self' 'unsafe-inline'"
},
content_security_policy_nonce_in=['script-src'],
referrer_policy='strict-origin-when-cross-origin',
feature_policy={
'geolocation': "'none'",
'camera': "'none'",
'microphone': "'none'"
}
)
# Disable debug mode in production
app.config['DEBUG'] = False
# Custom error handlers (don't reveal stack traces)
@app.errorhandler(500)
def internal_error(error):
# Log error details server-side
app.logger.error(f'Server Error: {error}')
# Return generic message to user
return "Internal server error", 500Nginx Security Headers:
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
# Disable server version disclosure
server_tokens off;---
A06:2021 - Vulnerable and Outdated Components
Description: Using components with known vulnerabilities.
Examples:
- Outdated libraries with known CVEs
- Unsupported software versions
- Not scanning dependencies for vulnerabilities
Mitigation:
- Inventory all dependencies
- Monitor for CVEs (use Snyk, Dependabot, Renovate)
- Update dependencies regularly
- Remove unused dependencies
Example: package.json with automated scanning:
{
"name": "secure-app",
"scripts": {
"audit": "npm audit",
"audit:fix": "npm audit fix"
},
"dependencies": {
"express": "^4.18.2",
"helmet": "^7.0.0"
}
}GitHub Dependabot configuration (.github/dependabot.yml):
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
reviewers:
- "security-team"
labels:
- "dependencies"
- "security"---
A07:2021 - Identification and Authentication Failures
Description: Weaknesses in authentication and session management.
Examples:
- Weak password requirements
- No brute force protection
- Session fixation
- Insecure session tokens
Secure Authentication Example:
from flask import Flask, session, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import bcrypt
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex(32) # Strong random secret
# Rate limiting (brute force protection)
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["100 per hour"]
)
# Session configuration
app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS only
SESSION_COOKIE_HTTPONLY=True, # No JavaScript access
SESSION_COOKIE_SAMESITE='Lax', # CSRF protection
PERMANENT_SESSION_LIFETIME=timedelta(hours=1) # Session timeout
)
@app.route('/login', methods=['POST'])
@limiter.limit("5 per minute") # Max 5 login attempts per minute
def login():
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user and bcrypt.checkpw(password.encode(), user.password_hash):
# Regenerate session ID (prevent session fixation)
session.clear()
session['user_id'] = user.id
session['login_time'] = datetime.utcnow()
return {"status": "success"}
else:
# Generic error message (don't reveal if username exists)
return {"error": "Invalid credentials"}, 401Password Policy:
import re
def validate_password(password):
"""
Enforce strong password requirements:
- Minimum 12 characters
- At least one uppercase letter
- At least one lowercase letter
- At least one digit
- At least one special character
"""
if len(password) < 12:
return False, "Password must be at least 12 characters"
if not re.search(r'[A-Z]', password):
return False, "Password must contain uppercase letter"
if not re.search(r'[a-z]', password):
return False, "Password must contain lowercase letter"
if not re.search(r'\d', password):
return False, "Password must contain digit"
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
return False, "Password must contain special character"
# Check against common passwords (implement breach password check)
# Example: Use haveibeenpwned API
return True, "Password is strong"---
A08:2021 - Software and Data Integrity Failures
Description: Code and infrastructure that does not protect against integrity violations.
Examples:
- Unsigned or unverified software updates
- Insecure CI/CD pipeline
- Insecure deserialization
Mitigation:
- Code signing
- Verify software signatures before installation
- Use SRI (Subresource Integrity) for CDN resources
- Secure CI/CD pipeline
Example: SRI for CDN resources:
<!-- With Subresource Integrity -->
<script src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>---
A09:2021 - Security Logging and Monitoring Failures
Description: Insufficient logging and monitoring.
Examples:
- Login attempts not logged
- No alerting on suspicious activity
- Logs not retained long enough
Secure Logging Example:
import logging
from logging.handlers import RotatingFileHandler
from flask import request, g
# Configure secure logging
handler = RotatingFileHandler('security.log', maxBytes=10000000, backupCount=10)
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
)
handler.setFormatter(formatter)
security_logger = logging.getLogger('security')
security_logger.addHandler(handler)
security_logger.setLevel(logging.INFO)
@app.before_request
def log_request():
# Log all requests with security context
security_logger.info(f'Request: {request.method} {request.path} from {request.remote_addr}')
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user and verify_password(password, user.password_hash):
security_logger.info(f'Successful login: {username} from {request.remote_addr}')
session['user_id'] = user.id
return {"status": "success"}
else:
# Log failed login attempt
security_logger.warning(f'Failed login attempt: {username} from {request.remote_addr}')
return {"error": "Invalid credentials"}, 401What to Log:
Authentication Events:
□ Login success/failure (username, IP, timestamp)
□ Logout
□ Password change
□ MFA enrollment/removal
□ Account lockout
Authorization Events:
□ Access denied (403 errors)
□ Privilege escalation attempts
□ Admin actions
Input Validation Failures:
□ SQL injection attempts
□ XSS attempts
□ Path traversal attempts
System Events:
□ Application start/stop
□ Configuration changes
□ Error conditions
NEVER LOG:
✗ Passwords or password hashes
✗ Session tokens or API keys
✗ Credit card numbers or PII
✗ Cryptographic keys---
A10:2021 - Server-Side Request Forgery (SSRF)
Description: Application fetches a remote resource without validating the user-supplied URL.
Code Example (Vulnerable):
# Vulnerable: No URL validation
@app.route('/fetch')
def fetch_url():
url = request.args.get('url')
response = requests.get(url)
return response.textCode Example (Secure):
from urllib.parse import urlparse
import ipaddress
# Secure: Validate and restrict URLs
ALLOWED_DOMAINS = ['api.trusted-partner.com', 'cdn.example.com']
def is_safe_url(url):
parsed = urlparse(url)
# Only allow HTTPS
if parsed.scheme != 'https':
return False
# Check against allowlist
if parsed.hostname not in ALLOWED_DOMAINS:
return False
# Prevent access to internal IPs
try:
ip = ipaddress.ip_address(parsed.hostname)
if ip.is_private or ip.is_loopback:
return False
except ValueError:
# Hostname is not an IP (which is fine)
pass
return True
@app.route('/fetch')
def fetch_url():
url = request.args.get('url')
if not is_safe_url(url):
return "Invalid URL", 400
try:
response = requests.get(url, timeout=5)
return response.text
except requests.exceptions.RequestException:
return "Error fetching URL", 500---
DevSecOps Pipeline
CI/CD Security Integration
# .github/workflows/security.yml
name: Security Checks
on: [push, pull_request]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Secrets scanning
- name: Gitleaks
uses: gitleaks/gitleaks-action@v2
# Dependency scanning
- name: Dependency Check
uses: dependency-check/Dependency-Check_Action@main
with:
project: 'my-app'
path: '.'
format: 'HTML'
# SAST (Static Application Security Testing)
- name: SonarCloud Scan
uses: SonarSource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
# Container scanning
- name: Build Docker image
run: docker build -t myapp:${{ github.sha }} .
- name: Trivy container scan
uses: aquasecurity/trivy-action@master
with:
image-ref: 'myapp:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
# IaC scanning
- name: Checkov IaC scan
uses: bridgecrewio/checkov-action@master
with:
directory: terraform/
framework: terraform
# Upload results
- name: Upload SARIF results
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: trivy-results.sarifPre-commit Hooks
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
- repo: https://github.com/PyCQA/bandit
rev: 1.7.5
hooks:
- id: bandit
args: ['-r', 'src/']
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
args: ['--maxkb=500']
- id: detect-private-key
- id: check-yaml
- id: check-json---
API Security
API Security Best Practices
1. Authentication:
# JWT-based API authentication
from flask import Flask, request, jsonify
from functools import wraps
import jwt
from datetime import datetime, timedelta
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'error': 'Token is missing'}), 401
try:
# Remove "Bearer " prefix if present
if token.startswith('Bearer '):
token = token[7:]
data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
current_user = User.query.get(data['user_id'])
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token has expired'}), 401
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'}), 401
return f(current_user, *args, **kwargs)
return decorated
@app.route('/api/protected', methods=['GET'])
@token_required
def protected_route(current_user):
return jsonify({'message': f'Hello, {current_user.username}'})2. Rate Limiting:
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["1000 per day", "100 per hour"],
storage_uri="redis://localhost:6379"
)
@app.route('/api/login', methods=['POST'])
@limiter.limit("5 per minute")
def api_login():
# Login logic
pass3. Input Validation:
from marshmallow import Schema, fields, validate, ValidationError
class UserRegistrationSchema(Schema):
username = fields.Str(required=True, validate=validate.Length(min=3, max=50))
email = fields.Email(required=True)
password = fields.Str(required=True, validate=validate.Length(min=12))
age = fields.Int(validate=validate.Range(min=18, max=120))
@app.route('/api/register', methods=['POST'])
def register():
schema = UserRegistrationSchema()
try:
data = schema.load(request.json)
except ValidationError as err:
return jsonify({'errors': err.messages}), 400
# Proceed with registration
# ...4. CORS Configuration:
from flask_cors import CORS
# Restrict CORS to specific origins
CORS(app, resources={
r"/api/*": {
"origins": ["https://trusted-frontend.com"],
"methods": ["GET", "POST"],
"allow_headers": ["Content-Type", "Authorization"]
}
})---
Container Security
Dockerfile Security Best Practices
# Use specific version (not 'latest')
FROM python:3.11.7-slim-bookworm
# Run as non-root user
RUN useradd --create-home --shell /bin/bash appuser
# Set working directory
WORKDIR /app
# Copy only requirements first (layer caching)
COPY requirements.txt .
# Install dependencies without cache
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY --chown=appuser:appuser . .
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 5000
# Health check
HEALTHCHECK --interval=30s --timeout=3s \
CMD python healthcheck.py || exit 1
# Run application
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]Container Scanning
# Scan container image with Trivy
trivy image myapp:latest
# Scan for critical and high severity vulnerabilities only
trivy image --severity CRITICAL,HIGH myapp:latest
# Scan and fail CI if vulnerabilities found
trivy image --exit-code 1 --severity CRITICAL myapp:latestThis comprehensive application security guide provides developers with the knowledge and code examples needed to build secure applications following industry best practices.
Security Operations & Incident Response
Security Operations Center (SOC)
SOC Structure
Tier 1: Alert Triage (L1 Analyst)
├─ Monitor SIEM dashboards and security alerts
├─ Perform initial triage and classification
├─ Escalate confirmed incidents to Tier 2
├─ Document all activities in ticketing system
└─ Response Time: 15 minutes for critical alerts
Tier 2: Incident Investigation (L2 Analyst)
├─ Deep investigation of escalated incidents
├─ Contain threats and perform forensic analysis
├─ Coordinate with IT teams for remediation
├─ Escalate to Tier 3 for complex threats
└─ Response Time: 1 hour for critical incidents
Tier 3: Threat Hunting & Advanced Analysis (L3 Analyst)
├─ Proactive threat hunting
├─ Advanced forensics and malware analysis
├─ Create custom detection rules
├─ Research emerging threats
└─ Mentor junior analysts
SOC Manager
├─ Oversee SOC operations
├─ Manage team performance and training
├─ Report metrics to leadership
├─ Coordinate with other departments
└─ Budget and resource planningSIEM Configuration
Log Sources to Ingest:
Critical Priority (Real-time):
├─ Firewall logs (allow/deny, connections)
├─ IDS/IPS alerts
├─ EDR/antivirus alerts
├─ Authentication logs (successes and failures)
├─ VPN connections
├─ Privileged account activity
└─ Database access logs (for sensitive data)
High Priority (Near real-time, <5 min delay):
├─ Web application logs (access, errors)
├─ Cloud infrastructure logs (AWS CloudTrail, Azure Activity)
├─ Email gateway logs (spam, malware detection)
├─ DLP alerts
└─ File integrity monitoring
Medium Priority (15-30 min delay):
├─ Application logs
├─ DNS query logs
├─ Proxy logs
├─ Network flow data (NetFlow/IPFIX)
└─ Patch management logs
Low Priority (Hourly or daily):
├─ Backup logs
├─ System performance metrics
└─ Non-security application logsEssential SIEM Use Cases:
# 1. Brute Force Attack Detection
use_case: "Detect brute force login attempts"
data_sources:
- Windows Security Event Logs (Event ID 4625)
- Linux auth logs
- VPN logs
- Application authentication logs
detection_logic: |
More than 10 failed login attempts
FROM same source IP
TO same user account
WITHIN 5-minute window
actions:
- Alert: High severity
- Block source IP (automatic via firewall integration)
- Notify account owner
- Create incident ticket
# 2. Unusual Privileged Account Activity
use_case: "Detect anomalous admin account usage"
data_sources:
- Active Directory logs
- Unix/Linux sudo logs
- PAM session logs
detection_logic: |
Privileged account login
OUTSIDE business hours (8 AM - 6 PM)
OR FROM unusual location
OR ON unusual system
actions:
- Alert: Critical severity
- Require MFA step-up authentication
- Notify security team and account owner
- Create incident ticket
# 3. Data Exfiltration Detection
use_case: "Detect large outbound data transfers"
data_sources:
- Firewall logs
- Proxy logs
- DLP alerts
- Cloud storage logs
detection_logic: |
Outbound data transfer > 1 GB
TO external destination
FROM single user/system
WITHIN 1-hour window
actions:
- Alert: High severity
- Block connection if still active
- Investigate user/system activity
- Check for data classification violations
# 4. Malware Detection
use_case: "Detect malware execution"
data_sources:
- EDR alerts
- Antivirus logs
- Process execution logs (Sysmon)
- Network connections
detection_logic: |
Malware signature match
OR suspicious process execution (PowerShell obfuscation)
OR connection to known C2 IP
OR file hash matches threat intelligence
actions:
- Alert: Critical severity
- Isolate endpoint from network (EDR integration)
- Kill malicious process
- Collect forensic artifacts
- Create incident ticket
# 5. Insider Threat - Abnormal File Access
use_case: "Detect abnormal access to sensitive files"
data_sources:
- File server audit logs
- Database query logs
- SharePoint access logs
detection_logic: |
User accesses > 100 files
CONTAINING sensitive data (SSN, credit card, PHI)
WITHIN 1-hour window
WHERE user has no recent history of accessing these files
actions:
- Alert: High severity
- Notify manager and security team
- Investigate user activity
- Check for USB device insertion
- Review data transfer logsThreat Hunting
Threat Hunting Process:
1. Hypothesis Generation
├─ Based on threat intelligence (e.g., "APT group targeting our industry")
├─ Based on recent attacks (e.g., "Check for Log4Shell exploitation attempts")
└─ Based on anomalies (e.g., "Unusual PowerShell activity in environment")
2. Investigation
├─ Query SIEM and EDR for indicators
├─ Analyze logs for suspicious patterns
├─ Review network traffic
└─ Examine endpoint artifacts
3. Discovery
├─ Confirm presence or absence of threat
├─ Document findings
└─ Assess impact if threat found
4. Response
├─ Containment and eradication if threat confirmed
├─ Create detection rule for future prevention
└─ Share findings with team
5. Continuous Improvement
├─ Update threat intelligence
├─ Refine detection rules
└─ Document lessons learnedExample Threat Hunt: Living Off the Land (LOLBins)
# Hypothesis: Attackers using native Windows tools for malicious activity
# Hunt 1: Suspicious PowerShell execution
# SIEM query to find encoded PowerShell commands
index=windows EventCode=4688
NewProcessName="*powershell.exe"
CommandLine="*-enc*" OR CommandLine="*-encodedcommand*"
| stats count by Computer, User, CommandLine
| where count > 0
# Hunt 2: Unusual certutil usage (commonly used to download malware)
index=windows EventCode=4688
NewProcessName="*certutil.exe"
CommandLine="*-urlcache*" OR CommandLine="*-decode*"
| stats count by Computer, User, CommandLine
# Hunt 3: WMIC used for lateral movement
index=windows EventCode=4688
NewProcessName="*wmic.exe"
CommandLine="*/node:*"
| stats count by Computer, User, CommandLine
# Hunt 4: BITSAdmin downloading files
index=windows EventCode=4688
NewProcessName="*bitsadmin.exe"
CommandLine="*/transfer*"
| stats count by Computer, User, CommandLine
# Hunt 5: Malicious use of regsvr32
index=windows EventCode=4688
NewProcessName="*regsvr32.exe"
CommandLine="*/s*" AND CommandLine="*http*"
| stats count by Computer, User, CommandLine---
Incident Response
Incident Response Lifecycle
1. Preparation
↓
2. Detection & Analysis
↓
3. Containment
↓
4. Eradication
↓
5. Recovery
↓
6. Post-Incident ActivityIncident Response Plan Structure
# Incident Response Plan
## 1. Preparation
### Incident Response Team (CIRT)
| Role | Name | Contact | Responsibilities |
|------|------|---------|-----------------|
| Incident Commander | Jane Doe | +1-555-0101 | Overall coordination |
| Security Lead | John Smith | +1-555-0102 | Technical investigation |
| IT Lead | Bob Johnson | +1-555-0103 | System remediation |
| Communications | Alice Brown | +1-555-0104 | Internal/external comms |
| Legal | Carol White | +1-555-0105 | Legal implications |
| HR | Dave Lee | +1-555-0106 | Insider threats |
### Tools and Resources
- SIEM: Splunk (https://siem.company.com)
- EDR: CrowdStrike (https://falcon.crowdstrike.com)
- Ticketing: Jira Service Desk (security-incidents project)
- Communication: Dedicated Slack channel #incident-response
- Forensic workstation: Located in SOC, admin laptop with encrypted drive
- Incident response jump bag: USB with tools, clean OS images, cables
### Contact Information
- Internal IT Help Desk: x5000
- Security Team On-Call: +1-555-SECURITY
- Legal Department: legal@company.com
- PR/Communications: pr@company.com
- Cyber Insurance: PolicyCo, +1-800-CYBER-INSURE, Policy #12345
- External IR Firm: MandiantFire, +1-888-RESPOND
- Law Enforcement: FBI Cyber Division, Agent Smith, +1-202-555-CYBER
## 2. Detection & Analysis
### Incident Classification
| Severity | Definition | Examples | Response Time |
|----------|-----------|----------|---------------|
| P0 - Critical | Active breach, data exfiltration, ransomware | Active data theft, ransomware encryption, complete system compromise | Immediate (24/7) |
| P1 - High | Confirmed malware, unauthorized access | Malware on critical system, confirmed intrusion | 1 hour |
| P2 - Medium | Suspicious activity requiring investigation | Potential malware, failed intrusion attempt | 4 hours |
| P3 - Low | Policy violation, informational | Minor policy violation, phishing email (no click) | 24 hours |
### Initial Assessment Questions
When receiving an incident report, gather:
1. **What happened?** (Description of the incident)
2. **When did it occur?** (Date and time)
3. **Who discovered it?** (Reporter name and contact)
4. **Which systems are affected?** (Hostnames, IP addresses)
5. **What is the current status?** (Ongoing, contained, resolved)
6. **What data is at risk?** (PII, PHI, financial, IP)
7. **Has law enforcement been notified?** (Yes/No)
8. **What immediate actions were taken?** (System isolated, account disabled)
### Incident Documentation
Create ticket in Jira with:
- Incident ID (auto-generated)
- Classification (P0-P3)
- Timeline of events
- Systems affected
- Actions taken
- Evidence collected
- Next steps
## 3. Containment
### Short-term Containment (Stop the Bleeding)
**Network-Based Containment**:Isolate compromised system (via firewall)
Block inbound and outbound traffic except to/from SOC analyst workstation
iptables -A INPUT -s <SOC_IP> -j ACCEPT iptables -A OUTPUT -d <SOC_IP> -j ACCEPT iptables -P INPUT DROP iptables -P OUTPUT DROP
Block malicious IP at perimeter firewall
(Use firewall management interface or API)
Disable compromised user account
Active Directory
Disable-ADAccount -Identity compromised_user
Linux
usermod -L compromised_user
**Endpoint-Based Containment**:Using EDR (CrowdStrike example via API)
curl -X POST "https://api.crowdstrike.com/devices/v2/actions/contain" \ -H "Authorization: Bearer $FALCON_TOKEN" \ -d '{"ids": ["device_id_here"], "action_parameters": []}'
Kill malicious process
Windows
taskkill /F /IM malware.exe /T
Linux
pkill -9 -f malware
**Account-Based Containment**:Reset password and revoke sessions
Azure AD
Revoke-AzureADUserAllRefreshToken -ObjectId user@company.com
Force password change on next login
Set-ADUser -Identity compromised_user -ChangePasswordAtLogon $true
Disable API keys/tokens
(Application-specific, e.g., AWS IAM)
aws iam delete-access-key --user-name compromised_user --access-key-id AKIA...
### Long-term Containment
- Patch vulnerable systems
- Implement compensating controls (WAF rules, additional monitoring)
- Rebuild compromised systems from clean images
- Update detection rules to prevent recurrence
## 4. Eradication
### Malware Removal
Identify all affected systems
Search EDR for same malware hash or C2 communications
Remove malware from each system
Preferred: Reimage from clean backup
If reimaging not possible:
- Use EDR to quarantine/delete malicious files
- Remove persistence mechanisms (registry, scheduled tasks, services)
- Clear cached credentials
Windows: Remove scheduled task
schtasks /Delete /TN "Malicious Task" /F
Windows: Remove registry persistence
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "Malware" /f
Linux: Remove cron job
crontab -e # Remove malicious line
### Vulnerability Remediation
Patch vulnerable systems
Ubuntu/Debian
apt-get update && apt-get upgrade -y
RHEL/CentOS
yum update -y
Windows (via PowerShell)
Install-WindowsUpdate -AcceptAll -AutoReboot
Application-specific (e.g., Log4Shell)
Upgrade Log4j to 2.17.1+
Set JVM option: -Dlog4j2.formatMsgNoLookups=true
### Credential Reset
Force password reset for all potentially compromised accounts
Generate list of users who logged in during breach window
Bulk password reset (Azure AD example)
$users = Get-AzureADUser -All $true | Where-Object {$_.UserPrincipalName -like "*@company.com"} foreach ($user in $users) { Set-AzureADUser -ObjectId $user.ObjectId -PasswordPolicies "DisablePasswordExpiration" -Password (ConvertTo-SecureString "TempPassword123!" -AsPlainText -Force) Set-AzureADUser -ObjectId $user.ObjectId -ForceChangePasswordNextLogin $true }
Rotate service account credentials
Rotate API keys and tokens
Rotate database passwords
Rotate encryption keys (where feasible)
## 5. Recovery
### System Restoration
Restore from clean backup (verified malware-free)
Validate backup integrity
sha256sum backup.tar.gz
Compare to known good hash
Restore data
tar -xzf backup.tar.gz -C /restore/location
Rebuild from golden image (preferred for compromised systems)
Deploy fresh OS from trusted source
Apply all patches
Reinstall applications
Restore data only (not configurations that may contain backdoors)
### Validation Testing
Before returning systems to production:
□ Antivirus/EDR scan shows clean □ No outbound connections to malicious IPs □ File integrity monitoring shows no unexpected changes □ No unauthorized user accounts or scheduled tasks □ All patches applied □ Passwords rotated □ System logs reviewed for anomalies □ Functionality testing completed □ Monitoring/alerting configured
### Return to Normal Operations
- Gradual restoration (not all systems at once)
- Enhanced monitoring for 30 days post-incident
- User communication about password resets
- Document all changes made
## 6. Post-Incident Activity
### Post-Incident Review (PIR)
**Within 5 business days of incident closure, conduct PIR meeting**
Attendees: CIRT members, affected business units, leadership
Agenda:
1. Incident timeline review
2. What went well?
3. What could be improved?
4. Root cause analysis
5. Action items for improvement
### Incident Report Template
Incident Report: [Incident ID]
Executive Summary
Brief non-technical summary of what happened, impact, and resolution.
Incident Details
- Incident ID: INC-2025-001
- Severity: P1 (High)
- Detected: 2025-01-15 14:23 UTC
- Contained: 2025-01-15 16:45 UTC
- Resolved: 2025-01-17 10:00 UTC
- Total Duration: 44 hours
Timeline
| Time (UTC) | Event |
|---|---|
| 2025-01-15 14:23 | SIEM alert: Unusual outbound traffic from web server |
| 2025-01-15 14:30 | Analyst confirms malware on web-01.company.com |
| 2025-01-15 14:45 | Server isolated from network |
| 2025-01-15 15:00 | CIRT activated, incident commander assigned |
| 2025-01-15 16:00 | Root cause identified: Unpatched Log4Shell vuln |
| 2025-01-15 16:45 | All vulnerable servers patched and restarted |
| 2025-01-16 09:00 | Forensic analysis completed |
| 2025-01-17 10:00 | Systems restored, monitoring in place, incident closed |
Root Cause
Apache web server running vulnerable version of Log4j (2.14.1) was exploited via crafted HTTP User-Agent header. Patch released on 2021-12-10 was not applied due to lack of automated patch management.
Impact Assessment
- Systems Affected: 3 web servers (web-01, web-02, web-03)
- Data Compromised: None confirmed
- Downtime: 12 hours (web services offline during remediation)
- Financial Impact: Estimated $50,000 (12 hours downtime × $4,200/hour)
- Customers Affected: None (no data breach)
- Regulatory: No breach notification required
Actions Taken
1. Isolated affected servers from network 2. Captured forensic images 3. Analyzed malware (CobaltStrike beacon) 4. Identified 3 vulnerable systems 5. Patched Log4j on all servers 6. Rebuilt servers from clean images 7. Deployed WAF rule to block exploit attempts 8. Reset all service account passwords
Lessons Learned
What Went Well
- SIEM alert fired immediately
- CIRT responded within 15 minutes
- Isolation prevented lateral movement
- Backups were recent and intact
What Could Be Improved
- Patch management process too slow (vulnerability was 1 month old)
- No vulnerability scanning for application dependencies
- Incident response playbook for ransomware needed update
Recommendations
1. Implement automated patch management (Priority: High, Owner: IT, Due: 2025-02-15)
- Deploy Patch Manager to automate patching
- SLA: Critical patches within 7 days
2. Add SCA scanning to CI/CD (Priority: High, Owner: AppSec, Due: 2025-02-28)
- Use Snyk or similar to scan for vulnerable dependencies
- Block deployments with critical vulnerabilities
3. Update incident response playbooks (Priority: Medium, Owner: Security, Due: 2025-03-15)
- Add ransomware playbook
- Add supply chain attack playbook
- Conduct tabletop exercise
4. Enhance vulnerability scanning (Priority: Medium, Owner: Security, Due: 2025-03-01)
- Configure Nessus to scan for application vulnerabilities
- Integrate with vulnerability management workflow
Regulatory Reporting
- GDPR Breach Notification: Not required (no personal data compromised)
- State Breach Laws: Not required
- Cyber Insurance: Notified on 2025-01-15, claim filed
Sign-off
- Incident Commander: Jane Doe, 2025-01-18
- CISO: John Smith, 2025-01-18
---
## Security Metrics & KPIs
### SOC Metrics
Detection Metrics:
- name: "Mean Time to Detect (MTTD)"
formula: "Time from incident occurrence to detection" target: "<1 hour for critical incidents" measurement: "Automated via SIEM"
- name: "Alert Volume"
formula: "Total alerts per day/week/month" target: "Trending down (improving signal-to-noise)" measurement: "SIEM dashboard"
- name: "False Positive Rate"
formula: "(False positives / Total alerts) × 100" target: "<20%" measurement: "Track in ticketing system"
Response Metrics:
- name: "Mean Time to Respond (MTTR)"
formula: "Time from detection to initial response" target: "P0: <15 min, P1: <1 hour, P2: <4 hours" measurement: "Ticket timestamps"
- name: "Mean Time to Contain (MTTC)"
formula: "Time from detection to containment" target: "P0: <1 hour, P1: <4 hours" measurement: "Ticket timestamps"
- name: "Mean Time to Resolve (MTTR)"
formula: "Time from detection to incident closure" target: "P0: <72 hours, P1: <7 days" measurement: "Ticket timestamps"
Effectiveness Metrics:
- name: "Incidents by Severity"
formula: "Count of P0/P1/P2/P3 incidents per month" target: "Zero P0, minimal P1 incidents" measurement: "Ticket reports"
- name: "Repeat Incidents"
formula: "(Repeat incidents / Total incidents) × 100" target: "<5%" measurement: "Track root causes in tickets"
- name: "SLA Compliance"
formula: "(Incidents meeting SLA / Total incidents) × 100" target: ">95%" measurement: "Automated via ticketing system"
Team Metrics:
- name: "Analyst Utilization"
formula: "Hours on incidents / Total work hours" target: "60-80% (balance investigation and improvement)" measurement: "Time tracking"
- name: "Training Completion"
formula: "(Analysts completing training / Total analysts) × 100" target: "100% quarterly" measurement: "LMS reporting"
- name: "Threat Hunts Conducted"
formula: "Number of proactive threat hunts per month" target: "Minimum 4 hunts per month" measurement: "Track in project board"
### Sample SOC Dashboard
┌─────────────────────────────────────────────────────────────┐ │ Security Operations Dashboard - January 2025 │ ├─────────────────────────────────────────────────────────────┤ │ Detection & Response Times │ │ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │ │ │ MTTD │ MTTR │ MTTC │ MTT-Resolve │ │ │ │ 42 min │ 18 min │ 2.1 hours │ 15 hours │ │ │ │ ↓ 12% MoM │ ↓ 5% MoM │ → 0% MoM │ ↓ 20% MoM │ │ │ └─────────────┴─────────────┴─────────────┴─────────────┘ │ │ │ │ Incident Volume (January 2025) │ │ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │ │ │ Critical │ High │ Medium │ Low │ │ │ │ 2 (P0) │ 12 (P1) │ 45 (P2) │ 87 (P3) │ │ │ └─────────────┴─────────────┴─────────────┴─────────────┘ │ │ │ │ Alert Metrics │ │ Total Alerts: 15,234 │ False Positives: 2,841 (18.6%) │ │ True Positives: 146 │ Under Investigation: 23 │ │ │ │ Top Attack Vectors │ │ 1. Phishing (62 incidents) │ │ 2. Brute force login (31 incidents) │ │ 3. Malware (18 incidents) │ │ 4. Vulnerability exploitation (12 incidents) │ │ 5. Insider threat (2 incidents) │ │ │ │ Threat Hunting │ │ Hunts Conducted: 5 │ Threats Found: 1 │ New Rules: 3 │ │ │ │ SLA Compliance: 97.3% (Target: >95%) │ └─────────────────────────────────────────────────────────────┘
---
## Tabletop Exercises
### Ransomware Tabletop Exercise
**Objective**: Test incident response procedures for ransomware attack
**Duration**: 90 minutes
**Participants**:
- Incident Commander
- Security team
- IT team
- Legal
- Communications
- Executive sponsor
**Scenario**:
Wednesday, 9:00 AM: The IT help desk receives multiple calls from users reporting that files are encrypted and they see a ransom note demanding $500,000 in Bitcoin.
Initial Investigation:
- 50+ workstations affected across 3 departments
- Ransomware appears to be spreading
- Backup server also appears to be encrypted
- Ransom note gives 48-hour deadline
Your Task: Respond to this incident using your incident response plan.
**Exercise Flow**:
Inject 1 (0:00): Initial notification
- Question: Who do you notify first?
- Question: What immediate containment actions do you take?
- Expected: Activate CIRT, isolate network segments, disable VPN
Inject 2 (0:15): Scope determination
- Update: EDR shows 127 affected systems, ransomware is REvil variant
- Question: How do you determine the full scope?
- Question: Do you pay the ransom?
- Expected: Query EDR for all infected systems, check backups, legal consult
Inject 3 (0:30): Backup assessment
- Update: Backup server encrypted, but offline backups from 48 hours ago exist
- Question: How do you verify backup integrity?
- Question: What is your recovery strategy?
- Expected: Test restore from offline backups, prioritize critical systems
Inject 4 (0:45): External communication
- Update: News outlet calls asking about a data breach
- Question: What do you tell them?
- Question: Do you need to notify regulators?
- Expected: Escalate to communications team, assess breach notification requirements
Inject 5 (1:00): Recovery decisions
- Update: Backups verified clean, recovery will take 3-5 days
- Question: What is your recovery priority order?
- Question: How do you prevent reinfection?
- Expected: Restore critical systems first, implement enhanced monitoring, patch vulnerabilities
Inject 6 (1:15): Post-incident
- Question: What improvements are needed to prevent recurrence?
- Question: What metrics will you track?
- Expected: Better backup strategy, EDR on all systems, security awareness training
**Facilitator Notes**:
- Pause after each inject for discussion
- Ask probing questions to test knowledge
- Document gaps in procedures or knowledge
- Create action items for improvements
**After Action Report**:
Ransomware Tabletop Exercise - After Action Report
Strengths
- Team quickly activated CIRT
- Network isolation performed correctly
- Good understanding of legal/regulatory requirements
- Clear communication during exercise
Areas for Improvement
1. Backup Strategy
- Current: Backups stored online, vulnerable to ransomware
- Recommendation: Implement 3-2-1 backup strategy (3 copies, 2 media types, 1 offsite)
- Owner: IT Manager
- Due: 2025-03-01
2. Incident Response Playbook
- Current: Generic IR plan, lacks ransomware-specific procedures
- Recommendation: Create ransomware playbook with decision trees
- Owner: Security Manager
- Due: 2025-02-15
3. Executive Decision Making
- Current: Unclear who has authority to approve ransom payment
- Recommendation: Define authority matrix in IR plan
- Owner: CISO
- Due: 2025-02-01
4. Communication Templates
- Current: No pre-approved external communication templates
- Recommendation: Create templates for customers, media, regulators
- Owner: Communications Director
- Due: 2025-02-15
Next Steps
- Schedule follow-up tabletop in 6 months
- Conduct technical drill (actual backup restoration test)
- Update incident response plan based on lessons learned
---
## Playbooks
### Phishing Email Response Playbook
Phishing Email Response Playbook
Trigger
User reports suspicious email via "Report Phishing" button or to security@company.com
Severity Classification
- P1 (High): User clicked link or entered credentials
- P2 (Medium): User opened attachment
- P3 (Low): User did not interact with email
Response Steps
Step 1: Triage (Within 15 minutes)
□ Review reported email □ Classify severity (P1/P2/P3) □ Check email gateway logs for delivery count
# Exchange example
Get-MessageTrace -SenderAddress "phishing@evil.com" -StartDate (Get-Date).AddHours(-24)Step 2: Analysis
□ Analyze email headers (sender IP, SPF/DKIM/DMARC results) □ Check URLs in email (use URL sandbox like urlscan.io) □ Analyze attachments (upload to VirusTotal, do not execute) □ Search threat intelligence for IOCs (AlienVault OTX, VirusTotal)
Step 3: Containment
□ Delete email from all mailboxes
# Office 365 example
$SearchName = "Phishing Campaign - evil.com"
New-ComplianceSearch -Name $SearchName -ExchangeLocation All -ContentMatchQuery '(subject:"Invoice 12345") AND (from:phishing@evil.com)'
Start-ComplianceSearch -Identity $SearchName
# After search completes:
New-ComplianceSearchAction -SearchName $SearchName -Purge -PurgeType HardDelete□ Block sender domain/IP at email gateway □ Block malicious URLs at web proxy/firewall
Step 4: Credential Reset (If P1 - User Clicked/Entered Credentials)
□ Force password reset for affected user
Set-ADUser -Identity affected_user -ChangePasswordAtLogon $true□ Revoke active sessions
Revoke-AzureADUserAllRefreshToken -ObjectId user@company.com□ Monitor account for suspicious activity (24-48 hours) □ Enable additional logging on account
Step 5: Malware Scan (If P2 - User Opened Attachment)
□ Isolate endpoint (if not already quarantined by EDR) □ Run full antivirus/EDR scan □ Check for IOCs from attachment analysis □ If malware found, follow Malware Incident Playbook
Step 6: User Communication
□ Notify affected users that email was malicious □ Thank users who reported (reinforce positive behavior) □ If credentials reset, provide instructions □ For P3 (no interaction), no additional user action needed
Step 7: Documentation
□ Update incident ticket with:
- Email headers and content
- Number of recipients
- Number who clicked/opened
- IOCs identified
- Actions taken
□ Add IOCs to threat intelligence platform □ Create detection rules for similar emails
Step 8: Prevention
□ Update email gateway rules to block similar emails □ Add sender domain to blacklist □ If widespread campaign, send security awareness notice □ Consider additional user training if many users clicked
This comprehensive security operations and incident response guide provides SOC teams with the structure, processes, and playbooks needed to detect, respond to, and recover from security incidents effectively.
Related skills
How it compares
Pick this for post-incident report generation rather than proactive penetration testing or secrets-scanning skills.
FAQ
What fields does security-compliance include in incident reports?
security-compliance uses an Incident Response Report Template with incident ID, P0–P3 severity, status, incident commander, UTC open/close timestamps, executive summary, incident type, attack vector, and affected assets. The format supports malware, phishing, breach, DDoS, and ac
When should teams use security-compliance?
security-compliance should be used immediately after a security or production incident when a formal response report is required. The skill speeds structured documentation during containment or resolution, not for preventive scanning or policy design without an active incident.
Is Security Compliance safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.