Compliance & Risk Management in Cyber Security — Complete Guide
Compliance and risk management is the practice of identifying, assessing, and mitigating security risks while meeting regulatory, legal, and industry standards — ensuring an organization’s security posture is both effective and defensible.
What You’ll Learn
By the end of this tutorial, you’ll understand the major security frameworks (NIST CSF, ISO 27001, SOC 2), key regulations (GDPR, PCI-DSS, HIPAA), how to perform a risk assessment using the FAIR methodology, and how to build a compliance program from scratch.
Why Compliance & Risk Management Matters
Non-compliance costs companies millions in fines — GDPR fines can reach €20M or 4% of global revenue. Beyond fines, a security breach without a compliance framework leads to lawsuits, customer churn, and regulatory sanctions. At DodaTech, Durga Antivirus Pro and Doda Browser maintain SOC 2 compliance to demonstrate security to enterprise customers.
Compliance Learning Path
flowchart LR
A[Cloud Security] --> B[Security Operations]
B --> C[Compliance & Risk]
C --> D{You Are Here}
D --> E[Risk Assessment]
D --> F[Compliance Program]
style D fill:#f90,color:#fff
What Is Compliance & Risk Management? (The “Why” First)
Think of compliance and risk management like building inspections and insurance for a house. Building inspections (compliance) ensure the house meets safety codes. Insurance (risk management) covers you when something goes wrong despite following the codes.
In security terms:
- Compliance: “Prove you follow these security standards” (audits, certifications)
- Risk Management: “Identify what could go wrong and decide what to do about it” (assessments, treatments)
Together, they ensure an organization isn’t just secure — but can prove it’s secure and has a plan for the unexpected.
Major Security Frameworks
NIST Cybersecurity Framework (CSF)
The most widely adopted US framework. Organized around five core functions:
flowchart LR
A[Identify] --> B[Protect]
B --> C[Detect]
C --> D[Respond]
D --> E[Recover]
A --> F{Continuous Improvement}
F --> A
| Function | What It Does | Example Controls |
|---|---|---|
| Identify | Understand your assets and risks | Asset inventory, risk assessment |
| Protect | Implement safeguards | Access control, training, encryption |
| Detect | Find security events | Monitoring, detection processes |
| Respond | Take action on incidents | Response plans, communications |
| Recover | Restore operations | Recovery plans, improvements |
ISO 27001
The international standard for Information Security Management Systems (ISMS). Requires:
- Statement of Applicability — which controls apply to your organization
- Risk assessment and treatment — systematic risk management
- Continuous improvement — regular audits and updates
- 114 controls across 14 domains (Annex A)
Key ISO 27001 domains:
| Domain | Example Controls |
|---|---|
| A.5 — Information security policies | Policy review, management commitment |
| A.6 — Organization of security | Roles, segregation of duties |
| A.7 — Human resources | Background checks, training, termination |
| A.8 — Asset management | Inventory, classification, media handling |
| A.9 — Access control | Least privilege, MFA, review |
| A.10 — Cryptography | Encryption policy, key management |
| A.12 — Operations | Capacity planning, malware protection, backup |
| A.16 — Incident management | Reporting, response, lessons learned |
| A.18 — Compliance | Legal, regulatory, contractual requirements |
SOC 2 (Service Organization Control)
Developed by AICPA, SOC 2 is specifically for technology and cloud service providers. Based on Trust Services Criteria:
- Security — protected against unauthorized access (mandatory)
- Availability — system available for operation and use
- Processing Integrity — processing is complete, accurate, and authorized
- Confidentiality — confidential data is protected
- Privacy — personal data is collected, used, retained in accordance with commitments
SOC 2 Type I vs Type II:
| Type | What It Proves | Duration |
|---|---|---|
| Type I | Controls are designed correctly | Point-in-time |
| Type II | Controls operate effectively over time | 6-12 months |
Major Regulations
GDPR (General Data Protection Regulation)
Applies to any organization processing EU citizen data, regardless of location.
Key requirements:
- Lawful basis for processing personal data
- Data Protection Impact Assessments (DPIAs) for high-risk processing
- Breach notification within 72 hours
- Right to access, rectification, erasure (“right to be forgotten”)
- Data Protection Officer (DPO) for certain organizations
- Data Processing Agreements (DPAs) with vendors
# gdpr_compliance.py — Check GDPR compliance readiness
class GDPRChecklist:
"""GDPR compliance readiness checklist."""
CHECKS = [
{
"id": "GDPR-01",
"control": "Data Processing Register",
"question": "Do you maintain a register of all personal data processing activities?",
"required_by": "Article 30"
},
{
"id": "GDPR-02",
"control": "Consent Mechanism",
"question": "Is consent obtained freely, specific, informed, and unambiguous?",
"required_by": "Article 7"
},
{
"id": "GDPR-03",
"control": "Breach Notification",
"question": "Can you notify supervisory authority within 72 hours of breach discovery?",
"required_by": "Article 33"
},
{
"id": "GDPR-04",
"control": "Data Protection Impact Assessment",
"question": "Do you perform DPIAs for high-risk processing activities?",
"required_by": "Article 35"
},
{
"id": "GDPR-05",
"control": "Right to Erasure",
"question": "Can you delete all personal data for a requesting individual within 30 days?",
"required_by": "Article 17"
},
{
"id": "GDPR-06",
"control": "Data Processing Agreements",
"question": "Do you have DPAs with all vendors who process personal data?",
"required_by": "Article 28"
}
]
def run_checklist(self, answers: dict[str, bool]) -> list[dict]:
"""Run the checklist and generate a compliance report."""
results = []
for check in self.CHECKS:
answer = answers.get(check["id"], False)
results.append({
"control": check["control"],
"compliant": answer,
"status": "PASS" if answer else "FAIL",
"reference": check["required_by"],
"action": "" if answer else check["question"]
})
return results
# Example
checklist = GDPRChecklist()
answers = {
"GDPR-01": True, "GDPR-02": True,
"GDPR-03": False, "GDPR-04": True,
"GDPR-05": False, "GDPR-06": True
}
results = checklist.run_checklist(answers)
print("=== GDPR Compliance Checklist ===")
for r in results:
status_icon = "✓" if r["status"] == "PASS" else "✗"
print(f"{status_icon} {r['control']}: {r['status']}")
if r["action"]:
print(f" Action needed: {r['action']}")
print(f" Reference: {r['reference']}")PCI-DSS (Payment Card Industry Data Security Standard)
Required for any organization that handles credit card data.
12 requirements across 6 goals:
| Goal | Requirements |
|---|---|
| Build secure network | Firewall, secure config |
| Protect cardholder data | Encrypt at rest and in transit |
| Manage vulnerabilities | Anti-malware, secure coding, patching |
| Control access | Limit access, assign unique IDs, restrict physical |
| Monitor networks | Log all access, test systems |
| Maintain policy | Security policy for all personnel |
HIPAA (Health Insurance Portability and Accountability Act)
US healthcare privacy and security regulation. Covers Protected Health Information (PHI).
Key rules:
- Privacy Rule — how PHI can be used and disclosed
- Security Rule — administrative, physical, technical safeguards
- Breach Notification Rule — notification requirements
Risk Assessment Methodology
The FAIR Model (Factor Analysis of Information Risk)
FAIR quantifies risk in financial terms:
# risk_assessment.py — FAIR-based risk quantification
import json
class FAIRRiskAssessment:
"""Quantify cyber risk using the FAIR model."""
def __init__(self, asset_name: str, asset_value: float):
self.asset_name = asset_name
self.asset_value = asset_value # in dollars
self.loss_events = []
def add_threat_scenario(self, name: str,
threat_frequency: float, # Times per year
vulnerability: float, # 0.0 to 1.0
probable_loss_min: float, # $ per event
probable_loss_max: float): # $ per event
"""Add a threat scenario with estimates."""
# Annualized Loss Expectancy (ALE)
annual_occurrences = threat_frequency * vulnerability
avg_loss_per_event = (probable_loss_min + probable_loss_max) / 2
ale = annual_occurrences * avg_loss_per_event
self.loss_events.append({
"scenario": name,
"threat_frequency": threat_frequency,
"vulnerability": vulnerability,
"avg_loss_per_event": avg_loss_per_event,
"annual_occurrences": annual_occurrences,
"annualized_loss_expectancy": round(ale, 2),
"risk_level": "HIGH" if ale > asset_value * 0.1 else (
"MEDIUM" if ale > asset_value * 0.01 else "LOW"
)
})
def report(self) -> dict:
"""Generate risk assessment report."""
total_ale = sum(e["annualized_loss_expectancy"] for e in self.loss_events)
return {
"asset": self.asset_name,
"asset_value": self.asset_value,
"scenarios": self.loss_events,
"total_annualized_loss_expectancy": round(total_ale, 2),
"risk_to_value_ratio": round(total_ale / self.asset_value * 100, 1)
}
# Example: Risk assessment for a customer database
risk = FAIRRiskAssessment("Customer Database (50k records)", 500000)
# Scenario 1: Ransomware
risk.add_threat_scenario(
"Ransomware attack on database server",
threat_frequency=2, # 2 attempts per year
vulnerability=0.15, # 15% chance of successful encryption
probable_loss_min=20000, # $20k minimum loss (downtime + ransom)
probable_loss_max=150000 # $150k maximum loss
)
# Scenario 2: Data breach via web app
risk.add_threat_scenario(
"SQL injection exposing customer records",
threat_frequency=12, # Monthly scan attempts
vulnerability=0.05, # 5% chance of success
probable_loss_min=50000,
probable_loss_max=500000 # GDPR fines, notification costs
)
# Scenario 3: Insider threat
risk.add_threat_scenario(
"Employee exfiltrates customer data",
threat_frequency=1, # Rare
vulnerability=0.1,
probable_loss_min=10000,
probable_loss_max=200000
)
report = risk.report()
print(json.dumps(report, indent=2))Expected output (abbreviated):
{
"asset": "Customer Database (50k records)",
"asset_value": 500000,
"total_annualized_loss_expectancy": 25950.0,
"risk_to_value_ratio": 5.2
}Risk Treatment Options
| Option | What It Means | Example |
|---|---|---|
| Accept | Acknowledge risk, no action | Low-severity risk with low probability |
| Mitigate | Reduce likelihood or impact | Add MFA, patch systems, train staff |
| Transfer | Shift risk to another party | Cyber insurance, third-party vendor |
| Avoid | Eliminate the activity causing risk | Stop storing unnecessary data |
Building a Compliance Program
Step 1: Scoping
Determine what’s in scope:
- Which systems, data, and processes are covered?
- Which regulations and frameworks apply?
- What’s the implementation timeline?
Step 2: Gap Analysis
Compare current state against requirements:
# gap_analysis.py — Identify gaps between current and target state
class ComplianceGapAnalysis:
"""Identify gaps between current and target compliance state."""
def __init__(self, framework: str):
self.framework = framework
self.controls = []
def add_control(self, control_id: str, description: str,
implemented: bool, evidence: str = ""):
"""Add a control with its implementation status."""
self.controls.append({
"id": control_id,
"description": description,
"implemented": implemented,
"evidence": evidence,
"status": "Implemented" if implemented else "GAP"
})
def report(self) -> dict:
"""Generate gap analysis report."""
total = len(self.controls)
implemented = sum(1 for c in self.controls if c["implemented"])
gaps = total - implemented
return {
"framework": self.framework,
"total_controls": total,
"implemented": implemented,
"gaps": gaps,
"compliance_percentage": round(implemented / total * 100, 1) if total > 0 else 0,
"gap_details": [c for c in self.controls if not c["implemented"]]
}
# Example: ISO 27001 gap analysis
gap = ComplianceGapAnalysis("ISO 27001")
gap.add_control("A.9.1.2", "Access to networks and services", True)
gap.add_control("A.9.2.1", "User registration and de-registration", True)
gap.add_control("A.12.6.1", "Management of technical vulnerabilities", False,
"No automated vulnerability scanning in CI/CD")
gap.add_control("A.16.1.5", "Response to information security incidents", False,
"Incident response playbooks not documented")
gap.add_control("A.18.1.4", "Privacy and protection of PII", True)
report = gap.report()
print(f"Framework: {report['framework']}")
print(f"Compliance: {report['compliance_percentage']}% ({report['implemented']}/{report['total_controls']})")
print(f"Gaps: {report['gaps']}")
for g in report['gap_details']:
print(f" [GAP] {g['id']}: {g['description']} — {g['evidence']}")Step 3: Remediation Plan
For each gap, define:
- Action to close the gap
- Owner and deadline
- Resources needed
- Acceptance criteria
Step 4: Evidence Collection
Compliance requires proof:
- Policy documents — signed, dated, version-controlled
- Logs — access logs, change logs, review logs
- Training records — completion certificates, attendance
- Audit trails — who did what, when
- Screen captures — for configurations that aren’t logged
Step 5: Continuous Monitoring
Compliance isn’t a one-time project:
- Internal audits — quarterly
- Automated monitoring — CSPM tools, SIEM rules
- Annual external audits — SOC 2, ISO 27001 recertification
- Control reviews — ensure controls still work as systems change
Common Compliance Mistakes
1. Treating Compliance as a Checklist
Checking boxes without understanding the intent leads to “paper compliance” — looking good on paper but not actually secure. Build meaningful controls, not checkbox-fillers.
2. Ignoring Compliance Until an Audit
Scrambling to collect evidence before an audit is painful and error-prone. Build evidence collection into your daily operations.
3. Over-Scoping
Trying to scope too much into your compliance program on day one. Start with the most critical systems, achieve compliance, then expand.
4. Not Automating Evidence Collection
Manual evidence collection doesn’t scale. Use automated tools: CSPM for cloud configs, SIEM for logs, GRC (Governance, Risk, Compliance) platforms for policy management.
5. Forgetting Third-Party Risk
Your vendors’ security affects your compliance. Have a vendor risk management program: questionnaires, reviews, contractual requirements.
6. Confusing Security with Compliance
You can be compliant and still get breached (Equifax was PCI compliant). Compliance is the minimum — security should exceed it.
7. Not Training Employees
Most compliance failures come from human error — people not following procedures. Regular training and phishing simulations are essential.
Practice Questions
1. What are the five functions of the NIST Cybersecurity Framework?
Identify, Protect, Detect, Respond, Recover. They form a continuous cycle for security improvement.
2. What’s the difference between SOC 2 Type I and Type II?
Type I validates controls are designed correctly at a point in time. Type II validates controls operate effectively over 6-12 months.
3. What’s a key requirement of GDPR regarding breach notification?
Organizations must notify the supervisory authority within 72 hours of becoming aware of a personal data breach.
4. What are the four risk treatment options?
Accept (acknowledge and monitor), Mitigate (reduce likelihood/impact), Transfer (insurance, third-party), Avoid (eliminate the activity).
5. Challenge: Calculate the Annualized Loss Expectancy (ALE) for a phishing attack.
Assume: 20 phishing attempts per year, 8% success rate (vulnerability), average loss of $15,000 per successful attack. ALE = 20 × 0.08 × $15,000 = $24,000/year.
Mini Project: Compliance Dashboard
# compliance_dashboard.py
# Track compliance status across multiple frameworks
from datetime import datetime
import json
class ComplianceDashboard:
"""Track compliance posture across frameworks."""
def __init__(self, organization: str):
self.organization = organization
self.frameworks = {}
def add_framework(self, name: str, controls_total: int, controls_passed: int):
"""Add a framework's compliance status."""
percentage = round(controls_passed / controls_total * 100, 1) if controls_total > 0 else 0
self.frameworks[name] = {
"total": controls_total,
"passed": controls_passed,
"percentage": percentage,
"status": "Compliant" if percentage >= 90 else (
"At Risk" if percentage >= 70 else "Non-Compliant"
)
}
def get_overall(self) -> dict:
"""Calculate overall compliance score."""
if not self.frameworks:
return {"overall_percentage": 0, "status": "No frameworks tracked"}
total = sum(f["passed"] for f in self.frameworks.values())
max_total = sum(f["total"] for f in self.frameworks.values())
overall = round(total / max_total * 100, 1)
return {
"organization": self.organization,
"last_updated": datetime.now().isoformat(),
"overall_percentage": overall,
"status": "Compliant" if overall >= 90 else (
"At Risk" if overall >= 70 else "Non-Compliant"
),
"frameworks": self.frameworks
}
# Example
dashboard = ComplianceDashboard("DodaTech")
dashboard.add_framework("SOC 2", 45, 43)
dashboard.add_framework("ISO 27001", 114, 102)
dashboard.add_framework("GDPR", 15, 14)
dashboard.add_framework("PCI-DSS", 42, 38)
print(json.dumps(dashboard.get_overall(), indent=2))FAQ
Try It Yourself
Perform a mini risk assessment for a personal project:
- List the assets involved (code, database, user data, API keys)
- Identify 3 threat scenarios (data breach, ransomware, account takeover)
- Estimate frequency, vulnerability, and potential loss for each
- Calculate the Annualized Loss Expectancy
- Decide treatment: accept, mitigate, transfer, or avoid
This same risk assessment methodology is used at DodaTech to prioritize security investments for Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
What’s Next
Congratulations on completing this Compliance & Risk Management tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro