Learn Ethical Hacking (#54) - Compliance and Governance - The Business of Security

Learn Ethical Hacking (#54) - Compliance and Governance - The Business of Security

leh-banner.jpg

What will I learn

  • Why compliance exists and the uncomfortable gap between being compliant and being secure;
  • Major frameworks -- ISO 27001, SOC 2, PCI DSS, NIST CSF, and CIS Controls -- what each covers and who needs which;
  • Regulatory requirements -- what the law demands vs what best practice recommends, and why the difference matters;
  • Risk management -- quantifying risk in dollars, risk appetite, and making business decisions about security spending;
  • The audit process -- what auditors look for, how to prepare, common mistakes, and how to survive without losing your mind;
  • Security policies -- acceptable use, incident response, data classification, access control, and why most policies are fiction;
  • GRC platforms -- tools that track compliance status across multiple frameworks simultaneously;
  • Defense: treating compliance as a floor (not a ceiling), embedding security into business operations, and the economics of doing it right.

Requirements

  • A working modern computer running macOS, Windows or Ubuntu;
  • Understanding of security architecture from Episode 53;
  • No technical lab needed -- this episode is about process, policy, and business;
  • The ambition to learn ethical hacking and security research.

Difficulty

  • Intermediate

Curriculum (of the Learn Ethical Hacking Series):

Learn Ethical Hacking (#54) - Compliance and Governance - The Business of Security

Solutions to Episode 53 Exercises

Exercise 1: STRIDE threat model for web application (abbreviated).

Trust boundaries:
  User Browser <-> Web Server <-> App Server <-> Database <-> Payment API

Data flow diagram:
  [Browser] --HTTPS--> [Nginx] --HTTP--> [Flask API] --TCP/5432--> [PostgreSQL]
  [Flask API] --HTTPS--> [Stripe Payment API]
  Trust boundary 1: Browser <-> Nginx (untrusted user input)
  Trust boundary 2: Flask API <-> Payment API (third-party dependency)
  Trust boundary 3: Flask API <-> PostgreSQL (privilege boundary)

Spoofing:
  - Attacker spoofs admin session via stolen JWT (mitigation: session
    binding to IP + device fingerprint, MFA on admin routes)
  - Attacker forges Stripe webhook callback (mitigation: webhook
    signature verification with shared secret)
Tampering:
  - Attacker modifies cart total client-side via JavaScript console
    (mitigation: server-side price calculation, never trust client)
  - SQL injection modifies product prices in database (mitigation:
    parameterized queries, read-only DB user for web app)
Repudiation:
  - User denies placing order (mitigation: audit logging with
    timestamps, IP addresses, session identifiers)
  - Admin denies deleting customer records (mitigation: immutable
    audit trail in append-only storage)
Information Disclosure:
  - Error messages reveal database schema and query structure
    (mitigation: generic error pages, detailed errors only in logs)
  - API returns full user objects including password hashes
    (mitigation: field-level serialization, response filtering)
Denial of Service:
  - Cart bomb: millions of items added by script (mitigation:
    rate limiting per session, max cart size)
  - Search query triggers full table scan on unindexed column
    (mitigation: query timeout, pagination limits)
Elevation of Privilege:
  - IDOR allows accessing other users' orders via sequential ID
    (mitigation: UUID order IDs + authorization check per request)
  - SQL injection escalates from webapp user to DB superuser
    (mitigation: least-privilege DB role, no GRANT option)

The trust boundary analysis is the part most people skip, and it's the part that matters most. Every time data crosses a trust boundary -- from the browser to the server, from the app to the database, from the app to a third-party API -- that crossing point is where validation must happen. The IDOR example maps directly to what we covered in episode 21 (API security), and the SQL injection scenarios are straight from episodes 12-13. When you do a STRIDE analysis on a real application, you quickly realize that 80% of the attacks from this series target the exact same boundary crossings. The threat model is not separate from the attacks -- it IS the attacks, just from the defender's perspective.

Exercise 2: Network segmentation design (abbreviated).

VLANs:
  VLAN 10 - Users (10.10.10.0/24) -- employee workstations
  VLAN 20 - Servers (10.10.20.0/24) -- application servers
  VLAN 30 - Database (10.10.30.0/24) -- database servers
  VLAN 40 - Management (10.10.40.0/24) -- admin jump boxes only

Firewall rules:
  VLAN 10 -> VLAN 20: ALLOW TCP 443 (HTTPS to app servers)
  VLAN 10 -> VLAN 30: DENY ALL (users cannot reach databases)
  VLAN 10 -> VLAN 40: DENY ALL (no direct management access)
  VLAN 20 -> VLAN 30: ALLOW TCP 5432 (app servers to PostgreSQL)
  VLAN 20 -> VLAN 10: DENY ALL (servers don't initiate to users)
  VLAN 40 -> ALL: ALLOW SSH/RDP (management access to all VLANs)
  ALL -> VLAN 40: DENY ALL (no reverse connections to management)
  DEFAULT: DENY ALL

Attacks prevented:
  - Lateral movement (ep 34): blocked between VLANs at firewall
  - Direct SQL injection exfil (ep 12-13): workstations cannot
    reach database servers, even if credentials are obtained
  - Kerberoasting to DC (ep 33): DC in VLAN 40, only accessible
    from management jump boxes with separate admin credentials
  - Insider direct DB access (ep 48): employees use applications,
    never touch databases directly

This is the architectural defense from episode 53 translated into concrete firewall rules. The DEFAULT: DENY ALL at the bottom is the fail-safe default principle -- everything is blocked unless explicitly allowed. A flat network (episode 34's playground) would have zero rules and full lateral movement. Four VLANs with 7 rules is the minimum viable segmentation that breaks most attack chains from this series.

Exercise 3: BeyondCorp analysis (abbreviated).

Core principles:
  1. Access depends on device + user identity, not network location
  2. All access is authenticated, authorized, and encrypted
  3. Access is granted on a per-request basis

VPN elimination:
  Traditional: user connects to VPN -> full network access
  BeyondCorp: user connects to identity-aware proxy -> access to
  ONE specific application, verified per request. No VPN tunnel.
  No network layer access at all.

Device trust:
  Google maintains a device inventory database. Every device gets
  a trust score: OS version, patch level, disk encryption status,
  EDR agent running, managed vs unmanaged, last check-in time.
  Low-trust devices get degraded access (read-only, or no access).
  A jailbroken phone gets zero access regardless of user identity.

Insider threat defense:
  An employee sitting at their desk in the Google campus has ZERO
  additional privileges compared to someone at a coffee shop.
  Network location is irrelevant. They authenticate to every app
  individually. Being "inside the network" provides no benefit.
  This directly defeats the insider threat scenarios from ep 48:
  a malicious insider cannot leverage network proximity.

The BeyondCorp model is what zero trust (episode 53) looks like when a company actually builds it instead of just talking about it. Google eliminated the VPN entirely. That's the difference between marketing zero trust and engineering zero trust ;-)


Episode 53 covered security architecture -- designing systems that resist attack by structure, not just by detection. We walked through the Saltzer-Schroeder principles, defense in depth as independent layers, network segmentation with Kubernetes NetworkPolicies, zero trust architecture, threat modeling with STRIDE, and the AI slop problem where AI generates the permissive insecure-by-default option. The core takeaway: the best vulnerability scanner is useless if the architecture lets one compromised workstation reach the domain controller.

Today we leave the purely technical domain for the first time in this series.

For 53 episodes, every problem had a technical solution. SQL injection? Parameterized queries. Privilege escalation? Patch the kernel. Flat network? Segment it. Weak passwords? MFA. The solutions were engineering problems and the answers were engineering answers. But here is a question that no amount of engineering can solve: how do you prove to a regulator, a customer, or a business partner that your organization actually does the security it claims to do?

That is the compliance question. And whether you like it or not (and most security professionals emphatically do NOT like it), compliance is the language that the business speaks. The CISO does not get budget by saying "our Kubernetes NetworkPolicies need work." The CISO gets budget by saying "we will fail our SOC 2 audit in Q3 if we do not fix these 12 control gaps, and losing SOC 2 means we lose our three largest enterprise customers." The first statement is technically accurate. The second statement moves money.

Here we go.

The Compliance Paradox

There is an uncomfortable truth at the heart of compliance that every security professional needs to internalize: you can be fully compliant and completely insecure. You can also be wildly non-compliant and impressively secure. Compliance is about meeting a defined standard. Security is about resisting real attackers. They overlap considerably, but they are NOT the same thing.

#!/usr/bin/env python3
"""compliance_vs_security.py -- the gap between checking boxes and stopping attackers"""

BREACH_EXAMPLES = [
    {
        'company': 'Target',
        'year': 2013,
        'compliance': 'PCI DSS compliant (certified by QSA)',
        'breach': '40 million credit card numbers stolen via HVAC vendor access',
        'lesson': 'PCI DSS certified the card data environment. The attacker '
                  'came in through the HVAC network management system, which '
                  'was NOT in scope for PCI. Compliance scope is not attack scope.',
    },
    {
        'company': 'Equifax',
        'year': 2017,
        'compliance': 'SOC 2 Type II certified, subject to multiple regulatory audits',
        'breach': '147 million records exposed via unpatched Apache Struts (CVE-2017-5638)',
        'lesson': 'The vulnerability had a patch available for 2 months before '
                  'the breach. Their vulnerability management POLICY existed. '
                  'Their vulnerability management PRACTICE failed. The auditor '
                  'checked the policy. The attacker checked the patch status.',
    },
    {
        'company': 'Capital One',
        'year': 2019,
        'compliance': 'Multiple AWS security reviews passed',
        'breach': '100 million records via SSRF to AWS metadata (episode 35 attack)',
        'lesson': 'The cloud security configuration was reviewed and approved. '
                  'But the WAF had an overly permissive rule that allowed SSRF '
                  'to the metadata service. The exact attack from episode 35 -- '
                  'a known technique, easily preventable with IMDSv2.',
    },
    {
        'company': 'SolarWinds',
        'year': 2020,
        'compliance': 'SOC 2 certified, FedRAMP authorized',
        'breach': 'Supply chain compromise infected 18,000 organizations (episode 45)',
        'lesson': 'The build pipeline was compromised. No compliance framework '
                  'at the time adequately assessed supply chain build integrity. '
                  'Compliance frameworks follow attacks -- they do not predict them.',
    },
]

print("=== The Compliance Paradox: Compliant But Breached ===\n")
for case in BREACH_EXAMPLES:
    print(f"[{case['year']}] {case['company']}")
    print(f"  Compliance: {case['compliance']}")
    print(f"  Breach: {case['breach']}")
    print(f"  Lesson: {case['lesson']}")
    print()

print("Compliance is a FLOOR, not a CEILING.")
print("Meet the standard. Then exceed it. The attacker does not")
print("care which boxes you checked.")

The Target breach is the textbook example that I keep coming back to. They had PCI DSS certification -- a real audit by a Qualified Security Assessor who verified their controls. And they were breached through the HVAC vendor's remote access credentials. PCI DSS scoped the audit to the cardholder data environment. The attacker entered through a system that was NOT in scope. Compliance defined a perimeter. The attacker ignored it.

Having said that, compliance is not useless. It establishes a minimum baseline, creates accountability, and provides a common language for discussing security with non-technical stakeholders. For pentesters, compliance is how you get paid -- the client needs SOC 2, and that need funds the security work. The mistake is treating compliance as the destination instead of the starting point.

The Major Frameworks

#!/usr/bin/env python3
"""frameworks.py -- the five frameworks every security pro must know"""

FRAMEWORKS = {
    'iso_27001': {
        'full_name': 'ISO/IEC 27001',
        'issued_by': 'International Organization for Standardization',
        'focus': 'Information Security Management System (ISMS)',
        'certification': True,
        'auditor': 'Accredited certification body (third-party)',
        'who_needs_it': [
            'Any organization wanting to demonstrate security maturity',
            'Companies selling to European enterprise customers',
            'Organizations in regulated industries (finance, healthcare)',
        ],
        'what_it_covers': [
            '93 controls across 4 themes (Organizational, People, '
            'Physical, Technological) in Annex A',
            'Risk assessment methodology (you define your own risks)',
            'Management commitment and continuous improvement cycle',
            'Internal audit requirements',
        ],
        'strength': 'Comprehensive, internationally recognized, focuses on '
                    'the MANAGEMENT SYSTEM (not just technical controls). '
                    'If you can only get one certification, get this one.',
        'weakness': 'Process-heavy. You can pass ISO 27001 with excellent '
                   'documentation and mediocre actual security. The audit '
                   'checks that you HAVE a patch management process. It does '
                   'not check that every server is actually patched.',
    },
    'soc2': {
        'full_name': 'SOC 2 (Service Organization Controls)',
        'issued_by': 'AICPA (American Institute of CPAs)',
        'focus': 'Trust Service Criteria: Security, Availability, '
                'Processing Integrity, Confidentiality, Privacy',
        'certification': True,
        'auditor': 'Licensed CPA firm',
        'who_needs_it': [
            'SaaS companies (your enterprise customers will ask)',
            'Cloud service providers',
            'Any organization handling customer data as a service',
        ],
        'what_it_covers': [
            'Type I: controls EXIST at a point in time (snapshot)',
            'Type II: controls OPERATED EFFECTIVELY over 6-12 months',
            'Trust Service Criteria map to specific control activities',
            'Management assertions and auditor opinion',
        ],
        'strength': 'Type II covers a period (not just a moment), which '
                    'means you must maintain controls consistently. The '
                    'report is respected by enterprise procurement teams. '
                    'It is effectively a sales requirement for B2B SaaS.',
        'weakness': 'Expensive ($50K-$200K for the audit alone). The report '
                   'is CONFIDENTIAL -- you need an NDA to share it. And '
                   'the scope is defined by you, which means clever scoping '
                   'can exclude the parts you do not want audited.',
    },
    'pci_dss': {
        'full_name': 'PCI DSS (Payment Card Industry Data Security Standard)',
        'issued_by': 'PCI Security Standards Council (Visa, Mastercard, etc.)',
        'focus': 'Protecting cardholder data -- and ONLY cardholder data',
        'certification': True,
        'auditor': 'QSA (Qualified Security Assessor) for large merchants, '
                  'SAQ (Self-Assessment Questionnaire) for small merchants',
        'who_needs_it': [
            'Anyone who processes, stores, or transmits credit card numbers',
            'Payment processors and payment gateways',
            'E-commerce platforms with card-on-file',
        ],
        'what_it_covers': [
            '12 requirement categories, ~250 sub-requirements',
            'Network segmentation of cardholder data environment (CDE)',
            'Encryption of stored cardholder data (AES-256)',
            'Access control and authentication requirements',
            'Quarterly vulnerability scans by ASV (Approved Scanning Vendor)',
            'Annual penetration testing (episodes 26, 50)',
        ],
        'strength': 'Extremely specific and technical. "Install a firewall" '
                    'is not good enough -- PCI DSS tells you exactly what '
                    'the firewall must do. This specificity makes it the '
                    'most actionable compliance framework.',
        'weakness': 'Narrow scope (only cardholder data). And as Target '
                    'proved, an attacker does not care about your scope '
                    'boundary. Also: PCI compliance is binary (pass/fail) '
                    'which creates perverse incentives to scope NARROWLY '
                    'rather than broadly.',
    },
    'nist_csf': {
        'full_name': 'NIST Cybersecurity Framework',
        'issued_by': 'US National Institute of Standards and Technology',
        'focus': 'Risk-based security program organized around 5 functions: '
                'Identify, Protect, Detect, Respond, Recover',
        'certification': False,
        'auditor': 'None (self-assessment, or contracted assessor)',
        'who_needs_it': [
            'US federal contractors (mandatory under various directives)',
            'Critical infrastructure operators',
            'Any organization wanting a flexible security framework (voluntary)',
        ],
        'what_it_covers': [
            '5 core functions, 23 categories, 108 subcategories',
            'Implementation tiers (Partial, Risk Informed, Repeatable, Adaptive)',
            'Framework profiles (current state vs target state)',
            'Maps to other standards (ISO 27001, CIS, COBIT)',
        ],
        'strength': 'Free. Flexible. Risk-based instead of prescriptive. '
                    'Widely adopted across US private sector. The "5 functions" '
                    'model is the clearest mental framework for thinking about '
                    'a complete security program.',
        'weakness': 'No certification means no external validation. Anyone '
                    'can claim "we follow NIST CSF" without proving it. Also: '
                    'the flexibility that makes it useful also means you can '
                    'implement it weakly and still call it compliance.',
    },
    'cis_controls': {
        'full_name': 'CIS Controls (Center for Internet Security)',
        'issued_by': 'CIS (non-profit)',
        'focus': 'Prioritized list of concrete security actions',
        'certification': False,
        'auditor': 'None (self-assessment)',
        'who_needs_it': [
            'Small-to-medium organizations starting their security program',
            'Organizations that need a practical "where do I start" guide',
            'Teams that want implementation-focused (not audit-focused) guidance',
        ],
        'what_it_covers': [
            '18 controls, 153 safeguards, organized by Implementation Group',
            'IG1: essential hygiene (56 safeguards) -- every organization',
            'IG2: growing organization (74 additional safeguards)',
            'IG3: mature program (23 additional safeguards)',
        ],
        'strength': 'The most PRACTICAL framework. IG1 is literally "the '
                    '56 things you must do first." No ambiguity, no management '
                    'system overhead, just "do these things." Perfect for a '
                    'team of 1-3 security people who need to prioritize.',
        'weakness': 'No certification, less internationally recognized than '
                    'ISO 27001. Enterprise customers rarely ask for CIS Controls '
                    'compliance -- they ask for SOC 2 or ISO 27001.',
    },
}

for key, fw in FRAMEWORKS.items():
    cert = 'YES (third-party audit)' if fw['certification'] else 'NO (self-assessment)'
    print(f"=== {fw['full_name']} ===")
    print(f"  Issued by: {fw['issued_by']}")
    print(f"  Focus: {fw['focus']}")
    print(f"  Certification: {cert}")
    print(f"  Strength: {fw['strength']}")
    print(f"  Weakness: {fw['weakness']}")
    print(f"  Who needs it:")
    for who in fw['who_needs_it']:
        print(f"    - {who}")
    print()

The framework you need depends on who is asking. European enterprise customers: ISO 27001. US SaaS customers: SOC 2. Credit cards: PCI DSS (not optional -- Visa will fine your acquiring bank, who will fine you). US federal contractor: NIST CSF. Small company with two security people: CIS Controls IG1 -- the 56 most important things to do, ranked by priority, with no certification overhead.

In practice, most mature organizations comply with multiple frameworks simultaneously. A SaaS company processing payments might need SOC 2, PCI DSS, ISO 27001, AND NIST CSF. This is where GRC platforms earn their keep -- we'll get to those later.

Risk Management -- Making Security a Business Decision

Security decisions are business decisions. Full stop. "We need to patch this server" is a technical statement. "This unpatched server exposes us to $2.4 million in expected annual losses, and the patch costs $15,000 in downtime" is a business statement. Guess which one gets approved ;-)

#!/usr/bin/env python3
"""risk_management.py -- quantifying security in business terms"""

RISK_FORMULA = """
Risk = Likelihood x Impact

This is the fundamental equation. Everything else is detail.

Likelihood: how probable is this attack?
  HIGH:    APT group actively targeting your industry (ep 52 intelligence)
  MEDIUM:  Script kiddie scanning your public IP range (ep 5)
  LOW:     Insider with physical access to air-gapped backup server
  VERY LOW: Earthquake destroys both primary and DR data centers

Impact: how bad is it when this attack succeeds?
  CATASTROPHIC: Customer PII breach (regulatory fines + lawsuits + reputation)
  HIGH:         CEO email compromise (BEC wire fraud, strategic info leak)
  MEDIUM:       Internal wiki defacement (embarrassing, quickly recoverable)
  LOW:          Test environment compromised (no production data, no customer impact)

Risk response options:
  1. MITIGATE: implement controls to reduce likelihood or impact
     (deploy MFA, segment networks, encrypt data at rest)
  2. TRANSFER: shift the financial risk to someone else
     (buy cyber insurance, outsource to managed SOC provider)
  3. ACCEPT: the risk is low enough to live with
     (DOCUMENT the decision -- this is critical)
  4. AVOID: stop doing the risky activity entirely
     (stop collecting SSNs, stop accepting credit cards directly)
"""

print("=== Risk Management Fundamentals ===")
print(RISK_FORMULA)

# The real power: quantitative risk analysis
QUANTITATIVE_EXAMPLES = [
    {
        'threat': 'Ransomware attack',
        'sle': 2_000_000,
        'sle_breakdown': 'Recovery costs ($500K) + downtime revenue loss ($800K) '
                        '+ reputation damage ($400K) + IR/legal fees ($300K)',
        'aro': 0.30,
        'aro_source': 'Verizon DBIR 2025: ~30% of mid-size companies experienced '
                     'ransomware in prior 12 months',
        'ale': 600_000,
        'justified_spend': 'Any control that reduces ARO below 0.15 (cutting '
                          'expected loss in half) is worth up to $300K/year',
    },
    {
        'threat': 'Business Email Compromise (wire fraud)',
        'sle': 500_000,
        'sle_breakdown': 'Average BEC wire transfer loss per FBI IC3 report. '
                        'Range is huge: $10K to $35M per incident.',
        'aro': 0.25,
        'aro_source': 'BEC attempts target most mid-size companies; 25% success '
                     'rate accounting for those that get caught vs those that dont',
        'ale': 125_000,
        'justified_spend': 'Email gateway + anti-phishing training + wire transfer '
                          'dual-authorization policy. Total cost: ~$80K/year. '
                          'ROI: prevents $125K in expected annual loss.',
    },
    {
        'threat': 'Customer data breach (PII exposure)',
        'sle': 4_500_000,
        'sle_breakdown': 'IBM Cost of a Data Breach 2025: $4.45M average. Includes '
                        'detection ($1.6M), notification ($370K), post-breach ($1.5M), '
                        'lost business ($1.0M)',
        'aro': 0.10,
        'aro_source': 'Roughly 10% of mid-size companies per year based on breach '
                     'notification databases',
        'ale': 450_000,
        'justified_spend': 'DLP deployment + database encryption + access controls '
                          'upgrade. Total cost: ~$200K/year. Prevents $450K in '
                          'expected loss. The CFO signs off on this one quickly.',
    },
]

print("=== Quantitative Risk Analysis ===\n")
print("ALE = ARO x SLE")
print("ALE: Annual Loss Expectancy (expected $ loss per year)")
print("ARO: Annual Rate of Occurrence (probability per year)")
print("SLE: Single Loss Expectancy (cost of one incident)\n")

for ex in QUANTITATIVE_EXAMPLES:
    print(f"--- {ex['threat']} ---")
    print(f"  SLE: ${ex['sle']:,.0f}")
    print(f"    ({ex['sle_breakdown']})")
    print(f"  ARO: {ex['aro']}")
    print(f"    ({ex['aro_source']})")
    print(f"  ALE: ${ex['ale']:,.0f}")
    print(f"  Justified spend: {ex['justified_spend']}")
    print()

This is how you talk to the CFO. Not "we should deploy DLP because data breaches are scary" but "our expected annual loss is $450,000, and DLP at $200K/year reduces it to under $100K -- pays for itself in 7 months." CFOs understand ROI. They do NOT understand CVE numbers. Translate security into their language and the budget conversation changes entirely.

The risk acceptance option deserves attention because most organizations handle it badly. Accepting a risk is valid -- not every risk justifies mitigation cost. But accepting means DOCUMENTING: what the risk is, who accepted it, when, and the expected impact. Without documentation, "we accepted the risk" is indistinguishable from "we forgot about it." When the board asks "did anyone know?" you need a signed document, not shrugs.

Security Policies -- The Documents Nobody Reads

Every compliance framework requires security policies. ISO 27001 has a mandatory "Information Security Policy" as Clause 5.2. SOC 2 needs documented policies mapped to Trust Service Criteria. PCI DSS requires specific policies for everything from firewall management to vendor access. The problem: most security policies are aspirational fiction.

#!/usr/bin/env python3
"""security_policies.py -- what you need and why most are garbage"""

ESSENTIAL_POLICIES = {
    'information_security': {
        'purpose': 'The master policy. Sets scope, roles, responsibilities, '
                  'and tone from the top. Every other policy references this one.',
        'key_sections': [
            'Management commitment statement (signed by CEO or equivalent)',
            'Scope of the ISMS (which systems, which data, which locations)',
            'Roles: CISO, data protection officer, asset owners, all employees',
            'Policy review cycle (annual minimum, triggered by major incidents)',
        ],
        'common_failure': 'Copy-pasted from a template. Contains references '
                         'to departments that do not exist, tools that are not '
                         'deployed, and processes nobody follows. The auditor '
                         'reads the policy. The attacker reads the reality.',
    },
    'acceptable_use': {
        'purpose': 'What employees can and cannot do with company systems.',
        'key_sections': [
            'Personal use of company devices',
            'BYOD rules (personal devices accessing company resources)',
            'Consequences for violations (formal warning -> termination)',
        ],
        'common_failure': 'Written by legal in 2014, never updated. Still '
                         'references "Internet Explorer 8 minimum." Nobody '
                         'has read it since onboarding.',
    },
    'access_control': {
        'purpose': 'Who gets access to what, how, and for how long.',
        'key_sections': [
            'Principle of least privilege (as we discussed in episode 53)',
            'Role-based access control (RBAC) model',
            'Account lifecycle: provisioning, review (quarterly), deprovisioning',
            'MFA requirements (which systems, which methods, exceptions)',
            'Privileged access management (separate admin accounts, ep 33)',
        ],
        'common_failure': 'Policy says "quarterly access reviews." Last review '
                         'was 14 months ago. Policy says "MFA on all systems." '
                         'The legacy ERP system has a hardcoded exception. Policy '
                         'says "least privilege." The DBA has root on everything.',
    },
    'data_classification': {
        'purpose': 'Categories of data sensitivity and handling requirements.',
        'key_sections': [
            'Classification levels: Public, Internal, Confidential, Restricted',
            'Labeling requirements (how do you mark a document as Confidential?)',
            'Handling rules per level (storage, transmission, disposal)',
            'Who can classify and who can reclassify',
        ],
        'common_failure': 'Classification exists on paper. Zero documents are '
                         'actually labeled. Nobody knows which SharePoint folders '
                         'contain Restricted data. The policy is a checkbox for '
                         'the auditor, not a practice for the organization.',
    },
    'incident_response': {
        'purpose': 'What happens when a security incident is detected.',
        'key_sections': [
            'Severity classification (SEV-1 through SEV-4, as we built in ep 51)',
            'Escalation procedures and contact information',
            'Roles during incidents (IC, technical lead, comms, legal)',
            'Evidence handling and chain of custody',
            'Post-incident review requirements',
        ],
        'common_failure': 'The policy references an "IR retainer firm" that '
                         'the company cancelled 2 years ago to cut costs. The '
                         'contact list has phone numbers for people who left. '
                         'The policy was never tested in a tabletop exercise.',
    },
    'change_management': {
        'purpose': 'How changes to production systems are proposed, tested, '
                  'approved, and deployed.',
        'key_sections': [
            'Change request process (who proposes, who approves)',
            'Testing requirements before production deployment',
            'Rollback procedures for failed changes',
            'Emergency change process (when you cannot wait for the CAB)',
        ],
        'common_failure': 'Policy requires CAB approval. In practice, '
                         'developers deploy to production "because it is '
                         'urgent" 80% of the time. Policy exists. Practice does not.',
    },
    'vendor_management': {
        'purpose': 'Security requirements for third-party vendors.',
        'key_sections': [
            'Vendor security assessment before onboarding',
            'Data processing agreements (DPA) for GDPR',
            'Right-to-audit clauses in contracts',
            'Annual vendor review and incident notification requirements',
        ],
        'common_failure': 'Marketing signed up for a new SaaS tool last week. '
                         'Nobody assessed it. It has customer database access. '
                         'This is how supply chain compromises (episode 45) start.',
    },
}

print("=== Essential Security Policies ===\n")
for name, policy in ESSENTIAL_POLICIES.items():
    label = name.replace('_', ' ').title()
    print(f"--- {label} ---")
    print(f"  Purpose: {policy['purpose']}")
    print(f"  Common failure: {policy['common_failure']}")
    print(f"  Key sections:")
    for section in policy['key_sections']:
        print(f"    - {section}")
    print()

The "common failure" column is the reality in most organizations. The policies exist because the auditor requires them. The practices are somewhere between "partially implemented" and "complete fiction." During a pentest engagement (episode 26), when you ask for the access control policy, what you're really learning is the gap between what the organization SAYS it does and what it ACTUALLY does. That gap is where the vulnerabilities live.

The Audit Process -- Surviving Without Losing Your Mind

#!/usr/bin/env python3
"""audit_process.py -- what really happens when the auditors arrive"""

AUDIT_PHASES = {
    'preparation': {
        'timing': '4-8 weeks before audit',
        'actions': [
            'Gather evidence proactively -- do NOT wait for auditor requests. '
            'Screenshots of configurations, access review records, patch '
            'management logs, training completion records.',
            'Self-assess against the standard. Read the requirements. Check '
            'your own controls. Find and fix the obvious gaps NOW.',
            'Prepare your team. Identify who answers which questions. Brief '
            'them on: answer what is asked, do not volunteer extra information.',
            'Organize documentation. A well-organized evidence folder saves '
            'hours of auditor time (which saves you audit hours = money).',
            'Run a pre-audit gap assessment. Many audit firms offer this as '
            'a separate engagement. It is worth the money.',
        ],
        'pro_tip': 'The auditor will ask for evidence of controls operating '
                   'over the audit period. If you deployed MFA last week, you '
                   'do not have 6 months of evidence. Plan ahead.',
    },
    'during_audit': {
        'timing': '1-3 weeks (on-site or remote)',
        'actions': [
            'Answer what is asked. Do NOT volunteer extra information. If the '
            'auditor asks "do you have a patch management process?" say "yes, '
            'here is the policy and here are the patch records." Do NOT say '
            '"well, we mostly patch on time, except for the legacy ERP system '
            'that runs on Windows Server 2012 and nobody wants to touch it."',
            'If you do not know, say "I will get back to you with that." This '
            'is infinitely better than guessing and being wrong.',
            'Demonstrate controls with evidence. Not "we do access reviews" '
            'but "here is the access review from Q1, signed by the manager, '
            'with 3 accounts removed and 2 permissions reduced."',
            'Be honest about gaps. Auditors respect honesty. If you have a '
            'known gap with a remediation plan, say so. If you try to hide '
            'it and the auditor finds it anyway, that is worse.',
            'Take notes on every question and finding. You will need these '
            'for the remediation phase.',
        ],
        'pro_tip': 'The auditor is not your enemy. They are a professional '
                   'evaluating your controls. Making their job easier (organized '
                   'evidence, responsive point of contact, honest answers) makes '
                   'YOUR audit smoother.',
    },
    'after_audit': {
        'timing': 'Ongoing until next audit',
        'actions': [
            'Review all findings. Classify: critical, high, medium, low.',
            'Create remediation plan with deadlines and owners.',
            'Prioritize critical and high findings (these block certification).',
            'Track remediation to completion. Do not let findings sit open.',
            'Prepare for follow-up assessment if the auditor requires evidence '
            'that findings were addressed.',
        ],
        'pro_tip': 'The worst thing you can do is pass the audit and then stop '
                   'caring until next year. The auditor returns in 12 months. '
                   'If they find the same findings as last year, unresolved, '
                   'your certification is at risk.',
    },
}

print("=== The Audit Process ===\n")
for phase, data in AUDIT_PHASES.items():
    label = phase.replace('_', ' ').title()
    print(f"--- {label} ({data['timing']}) ---")
    for action in data['actions']:
        print(f"  - {action}")
    print(f"  PRO TIP: {data['pro_tip']}")
    print()

# Common audit evidence types
EVIDENCE_TYPES = [
    'Access review records (who has access, who approved, when reviewed)',
    'Patch management records (what was patched, when, verification)',
    'Vulnerability scan reports (with remediation evidence for findings)',
    'IR plan and tabletop exercise records (with attendee list and outcomes)',
    'Security awareness training completion records (per-employee)',
    'Change management tickets (with approval chain and testing evidence)',
    'Backup test records (prove backups are actually restorable, not just existing)',
    'Network diagrams (current, not from 3 years ago)',
    'Risk assessment documentation (risk register with scores and treatment)',
    'Vendor assessment records (security questionnaires, DPAs, audit reports)',
]

print("Common audit evidence (have these ready):")
for ev in EVIDENCE_TYPES:
    print(f"  - {ev}")

The "answer what is asked, do not volunteer" rule is the single most important audit advice I can give. The auditor asks "do you encrypt data at rest?" Correct answer: "yes, here is the configuration showing AES-256 on all production databases." Wrong answer: "yes, well, mostly, except the staging environment has a copy of production data that is not encrypted because devs need fast access for debugging." You just created a finding the auditor was not looking for.

GRC Platforms -- Managing the Madness

When you need to comply with ISO 27001, SOC 2, AND PCI DSS simultaneously (and many organizations do), tracking everything in spreadsheets stops working. GRC (Governance, Risk, and Compliance) platforms solve this by mapping controls across frameworks:

#!/usr/bin/env python3
"""grc_platforms.py -- tools for managing compliance at scale"""

GRC_OVERVIEW = {
    'what_they_do': [
        'Track compliance status across multiple frameworks simultaneously',
        'Map CONTROLS to REQUIREMENTS -- one control satisfies multiple frameworks',
        'Automate evidence collection where possible (pull configs from AWS, '
        'Azure, GCP automatically)',
        'Manage risk registers and risk assessments',
        'Track audit findings and remediation progress',
        'Generate compliance reports and dashboards for leadership',
        'Alert on control failures (a server lost its EDR agent, MFA was '
        'disabled on an admin account)',
    ],
    'the_key_value': 'Control mapping. You implement "quarterly access reviews" '
                     'ONCE. That single control satisfies ISO 27001 A.9.2.5, '
                     'SOC 2 CC6.1, PCI DSS Req 7.1.2, and CIS Control 6.1. '
                     'Without a GRC platform you track this in 4 separate '
                     'spreadsheets. With one, you track it once.',
}

PLATFORMS = [
    {
        'name': 'Vanta',
        'focus': 'SOC 2 + ISO 27001 for startups and scale-ups',
        'key_feature': 'Automated evidence collection from cloud providers. '
                      'Connects to AWS, GCP, Azure, GitHub, Okta, etc. and '
                      'continuously monitors controls.',
        'best_for': 'Startups that need SOC 2 fast. Vanta can get you from '
                   'zero to audit-ready in weeks, not months.',
        'pricing': 'SaaS subscription. Varies by company size.',
    },
    {
        'name': 'Drata',
        'focus': 'Continuous compliance monitoring',
        'key_feature': 'Real-time control status dashboards with continuous monitoring.',
        'best_for': 'Organizations wanting ongoing compliance visibility.',
        'pricing': 'SaaS subscription.',
    },
    {
        'name': 'OneTrust',
        'focus': 'Privacy + GRC (strong GDPR/CCPA capabilities)',
        'key_feature': 'Privacy management alongside GRC: cookie consent, DSAR '
                      'management, privacy impact assessments.',
        'best_for': 'Organizations where privacy regulations are the primary driver.',
        'pricing': 'Enterprise. Not cheap.',
    },
    {
        'name': 'Archer (RSA)',
        'focus': 'Enterprise-grade GRC for large organizations',
        'key_feature': 'Extremely customizable for complex org structures.',
        'best_for': 'Large enterprises with dedicated GRC teams.',
        'pricing': 'Enterprise. Very not cheap.',
    },
    {
        'name': 'Eramba (open source)',
        'focus': 'Community-driven GRC platform',
        'key_feature': 'Free and self-hosted. Basic GRC functionality without '
                      'the SaaS price tag.',
        'best_for': 'Small organizations that need GRC but cannot justify '
                   '$50K+ annual SaaS costs. Also useful for learning GRC '
                   'concepts without financial commitment.',
        'pricing': 'Free (community edition). Paid enterprise support available.',
    },
]

print("=== GRC Platforms ===\n")
print("What they do:")
for item in GRC_OVERVIEW['what_they_do']:
    print(f"  - {item}")
print(f"\nKey value: {GRC_OVERVIEW['the_key_value']}\n")

for platform in PLATFORMS:
    print(f"--- {platform['name']} ---")
    print(f"  Focus: {platform['focus']}")
    print(f"  Key feature: {platform['key_feature']}")
    print(f"  Best for: {platform['best_for']}")
    print()

The control mapping is the real value. Without it, organizations implement the same control multiple times for different auditors. With a GRC platform, you implement once, document once, collect evidence once, and map to all applicable frameworks. Compliance teams routinely cut their workload by 40-50% just by consolidating overlapping controls.

Regulatory Requirements -- When the Law Gets Involved

#!/usr/bin/env python3
"""regulations.py -- what the law requires (this is not optional)"""

REGULATIONS = {
    'gdpr': {
        'full_name': 'General Data Protection Regulation (EU)',
        'effective': 'May 2018',
        'applies_to': 'ANY organization processing EU residents personal data, '
                      'regardless of where the organization is located',
        'key_requirements': [
            'Lawful basis for processing (consent, contract, legitimate interest)',
            'Data subject rights (access, rectification, erasure, portability)',
            'Data Protection Impact Assessments (DPIA) for high-risk processing',
            'Data Protection Officer (DPO) required in certain cases',
            'Breach notification to supervisory authority within 72 HOURS',
            'Breach notification to affected individuals "without undue delay"',
            'Privacy by design and by default',
        ],
        'penalties': 'Up to 20M EUR or 4% of global annual turnover (whichever '
                    'is higher). Amazon fined 746M EUR (2021). Meta fined '
                    '1.2B EUR (2023). These are not theoretical numbers.',
        'security_connection': 'Article 32 requires "appropriate technical and '
                              'organizational measures" including encryption, '
                              'access control, regular testing, and the ability '
                              'to restore availability after an incident. Every '
                              'technical control we built in episodes 1-53 maps '
                              'to Article 32.',
    },
    'ccpa_cpra': {
        'full_name': 'California Consumer Privacy Act / California Privacy Rights Act',
        'effective': 'CCPA: Jan 2020, CPRA amendments: Jan 2023',
        'applies_to': 'Businesses collecting California residents personal '
                     'information meeting revenue/data volume thresholds',
        'key_requirements': [
            'Right to know what data is collected and how it is used',
            'Right to delete personal information',
            'Right to opt out of sale/sharing of personal information',
            'Reasonable security measures (less prescriptive than GDPR)',
        ],
        'penalties': '$2,500 per unintentional violation, $7,500 per intentional. '
                    'Private right of action: $100-$750 per consumer per incident.',
        'security_connection': 'The "reasonable security measures" requirement '
                              'is deliberately vague. California AG has pointed '
                              'to CIS Controls IG1 as the baseline. If you are '
                              'breached without them, you lose in court.',
    },
    'hipaa': {
        'full_name': 'Health Insurance Portability and Accountability Act (US)',
        'effective': '1996 (Security Rule: 2005)',
        'applies_to': 'Covered entities (healthcare providers, health plans, '
                     'clearinghouses) and their business associates',
        'key_requirements': [
            'Administrative safeguards (risk analysis, workforce training)',
            'Physical safeguards (facility access controls, workstation security)',
            'Technical safeguards (access control, audit controls, encryption)',
            'Breach notification to HHS and affected individuals',
        ],
        'penalties': '$100 to $50,000 per violation, up to $1.5M per year per '
                    'violation category. Criminal penalties possible for willful '
                    'neglect.',
        'security_connection': 'HIPAA Security Rule requirements map almost 1:1 '
                              'to what we have covered in this series. Risk '
                              'analysis (this episode), access controls (ep 33, 53), '
                              'audit logging (ep 51), encryption (ep 9), incident '
                              'response (ep 51).',
    },
}

print("=== Key Regulations ===\n")
for key, reg in REGULATIONS.items():
    print(f"=== {reg['full_name']} ===")
    print(f"  Effective: {reg['effective']}")
    print(f"  Applies to: {reg['applies_to']}")
    print(f"  Penalties: {reg['penalties']}")
    print(f"  Security connection: {reg['security_connection']}")
    print(f"  Key requirements:")
    for req in reg['key_requirements']:
        print(f"    - {req}")
    print()

The GDPR 72-hour breach notification deadline catches organizations off guard constantly. The clock starts when you become aware -- not when you finish investigating, not when legal reviews the draft. Discover a breach at 2 PM Friday? You have until 2 PM Monday. That's why episode 51's IR playbooks and pre-drafted notification templates matter. You do NOT want to be writing a breach notification from scratch under a 72-hour deadline for the first time.

Those penalty numbers are not hypothetical. Amazon: 746 million euros. Meta: 1.2 billion. When the CISO says "we need budget for data protection," the board compares control costs against regulatory fines -- and the math resolves quickly.

The AI Slop Connection

AI is being used to generate compliance documentation at scale, and the results are... exactly what you'd expect from a system that optimizes for "sounds good" rather than "is true."

#!/usr/bin/env python3
"""ai_compliance_slop.py -- when AI writes your security policies"""

AI_COMPLIANCE_PROBLEMS = [
    {
        'artifact': 'Incident Response Policy',
        'ai_output': 'A beautiful 15-page policy covering all 6 NIST phases, '
                     'with role descriptions, escalation matrices, and '
                     'communication templates. Checks every ISO 27001 box.',
        'reality': 'Nobody in the organization has ever performed a tabletop '
                   'exercise. The "IR team" listed in the policy consists of '
                   'people who do not know they are on the IR team. The "IR '
                   'retainer firm" phone number is a placeholder. The policy '
                   'describes a process that does not exist.',
        'risk': 'The auditor sees the policy and checks the box. The attacker '
                'sees the gap and exploits it. The 72-hour GDPR notification '
                'deadline arrives and nobody knows what to do.',
    },
    {
        'artifact': 'Risk Assessment',
        'ai_output': 'Comprehensive risk register with 200 risks, each scored '
                     'for likelihood and impact, with mitigation strategies and '
                     'risk owners assigned.',
        'reality': 'The AI generated generic risks for a generic company. Half '
                   'the risks do not apply (the company does not process payments, '
                   'but PCI risks are listed). The "risk owners" are job titles, '
                   'not actual people. Nobody reviewed or accepted any of the '
                   'identified risks.',
        'risk': 'A risk assessment that does not reflect your actual environment '
                'is worse than no risk assessment. It gives false confidence that '
                'risks are being managed when they are not.',
    },
    {
        'artifact': 'Data Classification Policy',
        'ai_output': 'Four classification levels with detailed handling '
                     'requirements for each. Labeling procedures. Disposal '
                     'methods. Training requirements.',
        'reality': 'Zero documents in the organization are actually classified. '
                   'No labeling tool is deployed. The classification levels do '
                   'not match the data the organization actually handles. The '
                   'policy is a fiction that satisfies an audit checkbox.',
        'risk': 'When a breach occurs and the regulator asks "was the breached '
                'data classified as Confidential?" the answer is "we have a '
                'classification policy but we never implemented it." That is '
                'a negligence finding.',
    },
]

print("=== AI-Generated Compliance Documentation ===\n")
for problem in AI_COMPLIANCE_PROBLEMS:
    print(f"--- {problem['artifact']} ---")
    print(f"  AI produces: {problem['ai_output']}")
    print(f"  Reality: {problem['reality']}")
    print(f"  Risk: {problem['risk']}")
    print()

print("The most dangerous compliance failure is policies that describe")
print("ASPIRATIONAL security rather than ACTUAL security. AI makes it")
print("trivially easy to generate beautiful, comprehensive policies.")
print("It cannot make those policies true.")

This is the compliance equivalent of the AI-generated architectures from episode 53. AI optimizes for form, not substance. A policy that checks every ISO 27001 box is useless if the processes it describes don't exist. And here's the trap -- using AI to generate compliance documentation is FASTER and CHEAPER than building real processes. The incentive structure pushes organizations toward beautiful fiction instead of ugly truth. The auditor sees the fiction. The attacker finds the truth.

What Comes Next

Compliance gives security a business language -- frameworks for what "good" looks like, risk quantification for budget conversations, and audit processes for external validation. But compliance operates at the organizational level. There is a parallel domain at the individual level: the legal rights of the people whose data you collect and process. Privacy regulations represent a fundamental shift in who owns personal data and what obligations that creates. Understanding how those regulations interact across jurisdictions -- and where they create conflicting obligations -- is where we head next.

Exercises

Exercise 1: Map the CIS Controls (v8, IG1) against the attacks from this series. Pick the 15 most relevant IG1 safeguards and identify: (a) which LEH episode covers the attack it defends against, (b) whether the control is implemented in your lab, (c) which single CIS control would have prevented the most attacks. Save to ~/lab-notes/cis-mapping.md.

Exercise 2: Perform a quantitative risk analysis for 3 scenarios: ransomware, BEC wire fraud, and customer data breach. Estimate SLE and ARO using public data (Verizon DBIR, IBM Cost of a Data Breach). Calculate ALE and determine the justified security budget. Present as a one-page executive summary a CFO could read in 5 minutes. Save to ~/lab-notes/risk-analysis.md.

Exercise 3: Write a Data Classification Policy for a fictional 200-person SaaS company handling PII and payment data. Define 4 levels (Public, Internal, Confidential, Restricted). For each: (a) data examples, (b) storage requirements, (c) transmission requirements, (d) access control, (e) disposal method. Maximum 2 pages. Save to ~/lab-notes/data-classification-policy.md.


De groeten!

@scipio



0
0
0.000
0 comments