1. Foundations of Cyber Security
This chapter builds the conceptual vocabulary that every other chapter depends on: what "security" actually means as a measurable property, who attacks systems and why, how organizations decide which risks to spend money on, and what the law and professional ethics permit you to do. None of it requires a terminal, but all of it determines whether the technical work in later chapters is aimed at the right targets. Skipping these foundations is the most common reason technically strong practitioners produce findings nobody acts on.
<a id="11-core-security-principles"></a>
1.1 Core Security Principles
These are the design principles that recur in every system you will ever assess. They were mostly articulated in the 1970s, and they have survived because they describe trade-offs inherent to shared computing rather than any particular technology.
Confidentiality, Integrity, Availability (CIA Triad)
Theory
Before you can secure something, you need a precise answer to "what would count as a failure?" Saying a system was "hacked" is useless for engineering. The CIA triad gives three independent properties, and nearly every security incident is a violation of at least one.
Think of a hospital records room. Confidentiality is the lock on the door: only authorized people may read a chart. Integrity is the tamper-evident binding: nobody may alter a dosage without that change being authorized and traceable. Availability is the simple fact that when a doctor needs the chart at 3 a.m., it is there. A hospital that burns its records achieves perfect confidentiality and integrity, and is useless. The three properties pull against each other, and security engineering is the business of choosing the balance deliberately rather than by accident.
A critical nuance: these are properties of information and services, not of machines. The same server can satisfy confidentiality while catastrophically failing availability, and those are different engineering problems with different controls.
Examples
┌─────────────────┐
│ CONFIDENTIALITY│
│ Only authorized│
│ parties read │
└────────┬────────┘
│
┌──────┴──────┐
│ ASSET │
│ (data / │
│ service) │
└──┬───────┬──┘
│ │
┌──────────────┘ └──────────────┐
┌────────┴────────┐ ┌────────┴────────┐
│ INTEGRITY │ │ AVAILABILITY │
│ Unaltered and │ │ Reachable when │
│ authentic │ │ legitimately │
│ │ │ needed │
└─────────────────┘ └─────────────────┘
| Incident | C | I | A | Notes |
|---|---|---|---|---|
| Database dump posted publicly | X | Data still correct and online | ||
| Ransomware encrypts file shares | X | X | X | Modern strains exfiltrate before encrypting |
| Attacker edits a payment account number | X | Often more damaging than a read | ||
| Volumetric DDoS against a public API | X | No data touched at all | ||
| Backup tape lost in transit | X | Availability unaffected if primary is intact | ||
| Silent disk corruption in cold storage | X | No attacker required; CIA is not only about adversaries |
The three properties map to three different classes of control. The following shows the same file protected along each axis:
import hashlib
import os
import shutil
from cryptography.fernet import Fernet
def protect_confidentiality(plaintext: bytes, key: bytes) -> bytes:
"""Encryption makes the bytes unreadable without the key."""
return Fernet(key).encrypt(plaintext)
def protect_integrity(data: bytes) -> str:
"""A digest detects modification; it does not prevent it.
Note: a bare hash only detects *accidental* change. An attacker who can
rewrite the file can also rewrite the stored hash, which is why real
integrity needs a keyed MAC or a signature (see Chapter 3)."""
return hashlib.sha256(data).hexdigest()
def protect_availability(path: str, replica_dir: str) -> str:
"""Redundancy is the control. Encryption and hashing do nothing here."""
os.makedirs(replica_dir, exist_ok=True)
return shutil.copy2(path, replica_dir) # copy2 preserves mtime metadata
Key Takeaways
- Every security requirement should be traceable to confidentiality, integrity, or availability; if it is not, question whether it is a security requirement.
- The three properties are independent: a control that protects one frequently does nothing for the others, and may actively harm them.
- Integrity failures are routinely underestimated because they are quiet; a wrong number is harder to notice than a missing file.
- Non-adversarial causes (hardware failure, operator error, expired certificates) violate CIA just as effectively as attackers, and cause more outages in practice.
- Extended models add authenticity, possession, and utility (the Parkerian Hexad), but CIA remains the working vocabulary.
🧪 Practice
- For the system you use most at work or school, write one sentence describing what a confidentiality failure, an integrity failure, and an availability failure would each look like in concrete business terms.
- Classify these five events by property, allowing multiple: an expired TLS certificate blocking all logins; a developer pushing production credentials to a public repository; a cosmic-ray bitflip in a financial ledger; a disgruntled employee deleting a shared drive; a misconfigured cache serving user A's profile to user B.
- Pick one control you already rely on (disk encryption, backups, code signing, rate limiting) and argue which properties it protects and which it leaves completely untouched.
- Interview-style: "A client says their top priority is confidentiality, so they want everything encrypted at rest. What questions do you ask before agreeing?" Hint: think about where the decryption key lives at runtime, which threat the control actually defeats, and what happens to availability when key management fails.
Authentication, Authorization, Accounting (AAA)
Theory
CIA says what to protect; AAA is the machinery that enforces it at the moment of access. The three steps are sequential and are frequently confused, which is itself a source of vulnerabilities.
Picture a conference. Authentication is showing ID at registration to prove you are the person named on the badge. Authorization is the badge colour deciding whether you may enter the speaker lounge. Accounting is the door scanner logging that you entered at 14:32. Notice that these fail independently: a perfectly authenticated user may be wrongly authorized, and a correctly authorized action is worthless to an investigator if nothing recorded it.
The ordering matters enormously. Authorization decisions must be made after identity is established and must be made server-side on every request. The single most common web vulnerability class (broken access control) is the result of applications that authenticate correctly and then authorize by trusting a value the client supplied.
Examples
Request ──► [ AUTHENTICATION ] Who is making this claim?
│ Credential verified against a trusted store
│ Output: a principal identity
▼
[ AUTHORIZATION ] Is this principal permitted THIS action
│ on THIS object, right now?
│ Output: permit / deny
▼
[ ACCOUNTING ] Record who did what, when, from where,
│ and whether it was permitted.
▼
Resource access
from dataclasses import dataclass
@dataclass(frozen=True)
class Principal:
user_id: str
roles: frozenset[str]
def handle_delete_invoice(request, invoice_id: str, store, audit_log):
# 1. AUTHENTICATION: derive identity from a server-validated session,
# never from a client-supplied header or body field.
principal = store.resolve_session(request.session_cookie)
if principal is None:
audit_log.write(event="auth_failure", target=invoice_id, actor=None)
raise Unauthorized()
# 2. AUTHORIZATION: re-check ownership on the server for THIS object.
# Checking only the role is the classic IDOR bug: a valid "billing"
# user could otherwise delete another tenant's invoice.
invoice = store.get_invoice(invoice_id)
permitted = "billing" in principal.roles and invoice.tenant == principal_tenant(principal)
if not permitted:
audit_log.write(event="authz_denied", target=invoice_id, actor=principal.user_id)
raise Forbidden()
store.delete_invoice(invoice_id)
# 3. ACCOUNTING: log the successful, state-changing action too.
# Logging only failures leaves an investigator blind to abuse by
# legitimately authorized accounts.
audit_log.write(event="invoice_deleted", target=invoice_id, actor=principal.user_id)
| Stage | Question | Typical mechanism | Typical failure |
|---|---|---|---|
| Authentication | Who are you? | Password + MFA, certificate, token | Credential stuffing, weak reset flow |
| Authorization | May you do this? | RBAC, ABAC, ACL, policy engine | IDOR, client-side-only checks, role creep |
| Accounting | What happened? | Audit log, SIEM pipeline | Missing logs, no integrity, short retention |
Key Takeaways
- Authentication proves identity; authorization grants permission; the two are separate decisions and separate code paths.
- Authorization must be enforced server-side, per request, per object. Identity alone is never sufficient.
- Accounting must capture successful privileged actions, not only failures, or insider abuse becomes invisible.
- The "second A" is sometimes given as Accounting and sometimes Auditing; in network equipment contexts (RADIUS, TACACS+) it specifically means session usage records.
- An unlogged action is, for practical purposes, an action that did not happen as far as investigation and dispute resolution are concerned.
🧪 Practice
- Write the three AAA questions for an ATM withdrawal and name the concrete mechanism that answers each.
- Find an endpoint in any codebase you have access to that takes an object identifier from the client. Trace whether an ownership check happens server-side after authentication, and write down the exact line where it occurs or note that it is missing.
- Design the minimum set of fields an audit record needs so that, six months later, an investigator can answer "who changed this record and from where?" Justify each field.
- Interview-style: "A JWT contains a claim
role: admin. The API reads that claim and grants admin access. What is wrong with this design?" Hint: consider who controls the token contents, what verification must happen before any claim is trusted, and what happens when a user is demoted while holding an unexpired token.
Non-repudiation and Accountability
Theory
Accountability answers "who did this?" for an internal investigation. Non-repudiation goes further: it produces evidence strong enough that the actor cannot credibly deny the action to a third party such as a court or an arbitrator. The difference is the strength of the proof and who is meant to be convinced.
A shared log-in is the enemy of both. If five engineers use the same admin account, your logs can prove the account acted, but they cannot attribute the act to a person, and any individual can plausibly deny it. Accountability therefore has a prerequisite that is organizational, not technical: unique identities, never shared.
Non-repudiation additionally requires that the evidence be produced by something only the actor controls, and that the evidence cannot be forged by the party holding it. A digital signature satisfies this because the verifier only ever holds the public key and cannot create signatures with it. A plain server-side log does not, because the log owner could have written the entry themselves. This distinction is why signed approvals matter in payment and release workflows.
Examples
Tamper-evident logging through hash chaining: each entry commits to the one before it, so altering an old record invalidates every subsequent link.
entry 1 entry 2 entry 3
┌──────────┐ ┌──────────┐ ┌──────────┐
│ data │ ┌───►│ data │ ┌───►│ data │
│ prev: 000│ │ │ prev: H1 │ │ │ prev: H2 │
└────┬─────┘ │ └────┬─────┘ │ └────┬─────┘
│ H1 ────┘ │ H2 ────┘ │ H3
▼ ▼ ▼
hash of hash of hash of
entry 1 entry 2 entry 3
Editing entry 1 changes H1 → entry 2's "prev" no longer matches → detected.
import hashlib
import json
def append_entry(chain: list[dict], actor: str, action: str) -> list[dict]:
"""Each record binds to the previous digest, making silent edits detectable."""
prev_digest = chain[-1]["digest"] if chain else "0" * 64
body = {"actor": actor, "action": action, "prev": prev_digest}
# Canonical serialization matters: key order must be deterministic or the
# digest will not reproduce during verification.
encoded = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
chain.append({**body, "digest": hashlib.sha256(encoded).hexdigest()})
return chain
def verify(chain: list[dict]) -> bool:
expected_prev = "0" * 64
for record in chain:
if record["prev"] != expected_prev:
return False # a link was broken: an earlier entry was altered
body = {k: record[k] for k in ("actor", "action", "prev")}
encoded = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
if hashlib.sha256(encoded).hexdigest() != record["digest"]:
return False # this entry's own contents were altered
expected_prev = record["digest"]
return True
| Property | Convinces | Requires | Example |
|---|---|---|---|
| Accountability | The organization | Unique identity + reliable logs | SIEM attribution of a config change |
| Non-repudiation | A third party | Private key held solely by actor | Digitally signed contract or release artifact |
Key Takeaways
- Accountability requires unique, non-shared identities before it requires any logging technology.
- Non-repudiation requires evidence the verifier could not have fabricated, which in practice means asymmetric signatures.
- A log the administrator can silently edit supports accountability weakly and non-repudiation not at all; hash chaining, write-once storage, or shipping to a separately administered system fixes this.
- Clock accuracy underpins both: without trusted time synchronization, event ordering across systems is unprovable.
- Non-repudiation is a legal concept as much as a cryptographic one; key compromise, coercion, and malware on the signing device are standard repudiation defences.
🧪 Practice
- List every shared or generic account in an environment you administer or have studied, and for each one write what evidence you would currently be able to produce about who used it.
- Extend the hash-chain example so that each entry also records a monotonically increasing sequence number, then explain which attack this additionally detects that the chain alone does not.
- Explain why shipping logs to a separate account or system that operators cannot write to is a stronger control than making the local log file append-only.
- Interview-style: "Our audit logs are stored in the same database the application writes to, using the same credentials. Is that sufficient for non-repudiation?" Hint: ask what an attacker who achieves application-level code execution can do to the evidence, and who the evidence is supposed to convince.
Defense in Depth
Theory
Every control fails. Patches lag, rules are misconfigured, signatures miss novel samples, and people click things. If your security depends on one control being perfect, your security is as reliable as that control's worst day. Defense in depth accepts failure as the normal case and arranges controls so that no single failure is sufficient for compromise.
The castle analogy is standard: moat, wall, gate, keep, guards. Each layer is individually defeatable; what matters is that defeating all of them in sequence takes time, skill, and noise. The modern framing is more useful still: the "Swiss cheese model" from safety engineering. Every layer has holes. An incident happens only when holes in successive layers line up. Good design makes layers fail differently so their holes do not align.
That last point is the one people miss. Three vendors' signature-based antivirus products are not three layers; they fail the same way against the same novel sample. Antivirus plus application allowlisting plus network egress restriction plus offline backups are genuinely independent, because an attacker needs a qualitatively different capability to defeat each.
Examples
Attacker
│
▼
┌────────────────────────────────────────────────┐
│ PERIMETER firewall, WAF, DDoS scrubbing │ defeated by a valid
├────────────────────────────────────────────────┤ phished credential
│ IDENTITY MFA, conditional access │ ← stops the phish here
├────────────────────────────────────────────────┤
│ NETWORK segmentation, egress filtering │ ← limits lateral reach
├────────────────────────────────────────────────┤
│ HOST hardening, EDR, allowlisting │ ← blocks tooling
├────────────────────────────────────────────────┤
│ APPLICATION input validation, authz checks │
├────────────────────────────────────────────────┤
│ DATA encryption, tokenization, DLP │ ← limits value of theft
├────────────────────────────────────────────────┤
│ RECOVERY immutable offline backups │ ← last resort vs ransomware
└────────────────────────────────────────────────┘
│
▼ Compromise requires holes to align in EVERY layer.
A worked example of independence. Consider the ransomware chain and the layer that breaks it:
| Attacker step | Independent control that breaks it |
|---|---|
| Phishing email delivers a link | Mail filtering, user reporting culture |
| Credential captured | Phishing-resistant MFA (FIDO2) |
| Tooling executed on endpoint | Application allowlisting, EDR |
| Lateral movement to file server | Network segmentation, least privilege |
| Mass encryption | Backup immutability, volume shadow protection |
| Extortion over stolen data | Egress filtering, data minimization, encryption |
Key Takeaways
- Assume every individual control fails; design so that no single failure is sufficient.
- Layers must fail for different reasons, or they are redundancy rather than depth.
- Depth buys detection time as much as prevention: each layer an attacker must cross is another chance to generate an alert.
- Depth is not an excuse for weak layers; it is the reason a weak layer does not end the story.
- Cost grows with layers, so depth is prioritized around the assets a business impact analysis identifies as critical.
🧪 Practice
- Take a laptop stolen from a café and list every layer that stands between the thief and the company data on it. Mark which layers are genuinely independent.
- Identify a place in a system you know where two controls look like two layers but share a single point of failure (a common identity provider, a shared credential, one vendor's detection engine).
- Draw the layer diagram for a public web application and mark, for each layer, the single most likely reason it would fail in practice.
- Interview-style: "We have a next-generation firewall, a WAF, and an IPS from three vendors. Is that defense in depth?" Hint: ask what input each one inspects and whether an attack over an authenticated, encrypted channel from a trusted internal host is seen by any of them.
Least Privilege and Need to Know
Theory
The blast radius of any compromise is bounded by what the compromised identity could do. If a web server's database account can read every table, then an SQL injection flaw reads every table. If it can read only the three tables the feature requires, the same flaw is a much smaller incident. Least privilege is the discipline of ensuring every subject (user, service, process) holds the minimum permissions needed for its function, for the minimum time.
Need to know is the data-scoped sibling of the same idea: permission to access a category of data does not imply permission to access every record in it. A support agent may legitimately need to read customer records, but not the record of a celebrity they are curious about. Need to know is enforced by scoping and monitoring rather than by role alone.
The practical enemy is privilege creep: permissions accumulate as people change roles and nothing is ever revoked. After five years, a long-serving employee's account is often the most over-privileged in the organization. This is why least privilege is a process (periodic access review, automated expiry, just-in-time elevation) and not a one-time configuration.
Examples
-- Over-privileged: one account for everything. An injection flaw anywhere
-- in the application becomes total database compromise.
GRANT ALL PRIVILEGES ON appdb.* TO 'app'@'%';
-- Least privilege: separate principals per function, minimum verbs,
-- minimum objects, and no schema-modification rights at runtime.
CREATE USER 'app_reader'@'10.0.2.%' IDENTIFIED BY '...';
GRANT SELECT ON appdb.products TO 'app_reader'@'10.0.2.%';
GRANT SELECT ON appdb.categories TO 'app_reader'@'10.0.2.%';
CREATE USER 'app_orders'@'10.0.2.%' IDENTIFIED BY '...';
GRANT SELECT, INSERT ON appdb.orders TO 'app_orders'@'10.0.2.%';
-- Deliberately absent: DELETE, DROP, and any access to appdb.users
-- Host restriction '10.0.2.%' means a stolen credential is useless off-subnet.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadOnlyOneBucketPrefix",
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::reports-prod/monthly/*",
"Condition": {
"IpAddress": {"aws:SourceIp": "198.51.100.0/24"},
"Bool": {"aws:SecureTransport": "true"}
}
}
]
}
The policy above constrains four dimensions at once: verb (GetObject only), object (one prefix, not the whole bucket), network origin, and transport. Compare with the common anti-pattern "Action": "s3:*", "Resource": "*", which grants deletion of every bucket in the account.
Key Takeaways
- Permissions define blast radius; reducing them converts total compromises into partial ones.
- Scope on every available dimension: action, object, time, network origin, and conditions.
- Need to know restricts access to specific records, not just record types; roles alone rarely express it.
- Privilege creep is the default outcome without scheduled access reviews and automatic expiry.
- Just-in-time elevation (temporary, approved, logged) is usually better than standing administrative rights.
🧪 Practice
- List the permissions your own primary work account holds and mark each as "used in the last 90 days" or not. Propose a revocation list.
- Rewrite an over-broad IAM or database grant you can find into a least-privilege version, documenting what functionality each retained permission supports.
- Describe how you would implement need to know for a support tool that reads customer records, given that support agents genuinely need broad read access. Consider break-glass access, justification prompts, and detection.
- Interview-style: "A batch job fails intermittently, and granting it database owner makes the failures stop. What do you do?" Hint: the question is about diagnosing which specific permission was missing, and about what temporary mitigation with an expiry looks like versus a permanent grant.
Separation of Duties
Theory
Least privilege limits what one identity can do. Separation of duties (SoD) goes a step further for high-impact processes: it ensures that no single person can complete a sensitive transaction alone, even if their individual permissions are legitimate. The goal is to require collusion for fraud or sabotage, because collusion is harder to arrange and easier to detect.
The classic example is accounts payable: the person who creates a supplier must not be the person who approves payments to it. Each permission is individually reasonable; the combination enables invoice fraud with no technical compromise at all. In engineering, the parallel is the author of a change not being the sole approver and deployer of it.
A related control is the two-person rule (dual control), where two identities must act simultaneously for one operation, such as two key custodians to recover a hardware security module. SoD is also a protection for employees: it removes the opportunity, and therefore removes suspicion.
Examples
UNSAFE: one actor owns the whole chain
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Create │──►│ Approve │──►│ Deploy │──►│ Review │ all = Alice
└─────────┘ └─────────┘ └─────────┘ └─────────┘
SAFE: duties split, collusion required
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Create │──►│ Approve │──►│ Deploy │──►│ Review │
│ Alice │ │ Bob │ │ system │ │ Carol │
└─────────┘ └─────────┘ └─────────┘ └─────────┘
▲
automation holds the deploy credential,
so no human needs standing production access
| Process | Duty A | Duty B (must differ) | Fraud prevented |
|---|---|---|---|
| Payments | Create vendor | Approve payment | Fictitious supplier |
| Code | Author change | Approve merge | Malicious or careless code reaching production |
| Identity | Request account | Approve entitlement | Self-granted privilege |
| Logging | Operate system | Administer audit log | Covering tracks |
| Cryptography | Hold key share 1 | Hold key share 2 | Unilateral key use |
# Branch protection expressing SoD for a release pipeline
protection:
required_pull_request_reviews:
required_approving_review_count: 1
require_code_owner_reviews: true
dismiss_stale_reviews: true # re-approval required after new commits
enforce_admins: true # admins are not exempt, or the control is theatre
restrictions:
push_access: [] # nobody pushes directly; CI deploys
Note enforce_admins: true. An SoD control that privileged users can bypass provides assurance only against people who were not going to commit fraud anyway.
Key Takeaways
- SoD requires collusion for abuse; least privilege reduces what one identity can reach. They are complementary, not alternatives.
- Identify toxic combinations of permissions, not just excessive individual ones.
- Controls that administrators can bypass do not implement SoD; exemptions must be logged and reviewed.
- In small teams, full SoD may be impossible; compensating controls are detective (mandatory review of a peer's actions, alerting on self-approval).
- Automation can hold the credential for the final step so that no human has standing access to the sensitive action.
🧪 Practice
- Write down three pairs of permissions in your environment that are dangerous in combination but benign apart.
- A four-person startup cannot separate development from deployment. Design the compensating detective controls you would recommend, and state what residual risk remains.
- Examine a CI/CD configuration you have access to and determine whether a single person could author, approve, and ship a change. Document the exact mechanism that would stop them, or confirm that none exists.
- Interview-style: "How would you detect a violation of separation of duties after the fact?" Hint: think about which fields in the approval and deployment records must be compared, and why identity provider data is needed to catch two accounts belonging to one person.
Fail-Safe Defaults
Theory
Systems spend a surprising amount of time in states their designers did not anticipate: a dependency is down, a config file is malformed, a token has expired, a rule did not match. The question fail-safe defaults answers is: when the system does not know, what does it do?
Saltzer and Schroeder's 1975 formulation is to base access decisions on permission rather than exclusion. In practice this means default deny: enumerate what is allowed and refuse everything else. The alternative, default allow with a blocklist, requires you to have anticipated every bad input in advance, which is not achievable. This is exactly why input allowlisting beats blocklisting, and why firewall rulebases end with an implicit deny.
There is an important caveat. "Fail-safe" and "fail-secure" can conflict with safety. A data centre door that fails locked protects assets but may trap people in a fire; building codes therefore mandate fail-open for egress. The principle is not "always deny on failure" but "decide the failure behaviour deliberately, and let the consequence of being wrong drive the choice."
Examples
# ANTI-PATTERN: fails open. Any unexpected exception grants access,
# so an outage of the policy service becomes an authorization bypass.
def is_allowed_bad(user, resource):
try:
return policy_service.check(user, resource)
except Exception:
return True # "don't break the app"
# FAIL-CLOSED: unknown state denies, and the failure is made loud so the
# resulting outage is diagnosed instead of silently tolerated.
def is_allowed(user, resource):
try:
return policy_service.check(user, resource)
except PolicyServiceUnavailable:
logger.error("policy service unavailable; denying", extra={"user": user.id})
metrics.increment("authz.fail_closed")
raise ServiceUnavailable() # 503, not a silent permit
import re
# BLOCKLIST: endless whack-a-mole. Every bypass is a new patch, and the
# list can never be proven complete.
BLOCKED = re.compile(r"(\.\./|<script|'\s*OR\s*1=1)", re.IGNORECASE)
def validate_bad(filename: str) -> bool:
return not BLOCKED.search(filename) # misses encodings, unicode, new tricks
# ALLOWLIST: states precisely what is acceptable; everything else is rejected
# by construction, including inputs nobody has invented yet.
SAFE_FILENAME = re.compile(r"\A[A-Za-z0-9_-]{1,64}\.(csv|pdf)\Z")
def validate(filename: str) -> bool:
return SAFE_FILENAME.fullmatch(filename) is not None
Firewall rulebase, read top to bottom:
1. allow tcp any -> 10.0.1.10 port 443 (published web service)
2. allow tcp 10.0.2.0/24 -> 10.0.1.20 port 5432 (app tier to database)
3. deny ip any -> any log ◄── explicit terminating rule
logged, so denies are visible
Key Takeaways
- Default deny: enumerate the permitted set; reject everything else, including the unanticipated.
- Allowlists are provably bounded; blocklists are an open-ended arms race.
- Fail closed for authorization and authentication, and make the failure visible rather than silent.
- Deliberately choose fail-open only where life safety or a stated availability requirement outweighs the security loss, and document that decision.
- Log denials. A default-deny rule that drops silently hides both attacks and misconfigurations.
🧪 Practice
- Find an exception handler in any code you have access to that returns a permissive value on error. Rewrite it to fail closed and describe the operational consequence.
- Rewrite a blocklist-style input validator as an allowlist, and list two inputs the original would have let through.
- For a badge-controlled server room, argue both sides of fail-open versus fail-locked on power loss, and state what additional control makes the safer choice acceptable.
- Interview-style: "Your authentication provider is down. Should users be allowed in?" Hint: there is no single right answer; the interviewer wants to hear you separate the decision by system criticality and say what you would have agreed with the business beforehand.
Security vs. Usability Trade-offs
Theory
Security controls impose friction, and humans route around friction. This is not a character flaw; it is predictable behaviour. A password policy demanding 16 characters, four character classes, and rotation every 30 days reliably produces Summer2026! followed by Autumn2026!, plus a sticky note. The control was theoretically strong and practically counterproductive.
The useful mental model is that you are not choosing a point on a line between "secure" and "usable". You are choosing a control, and some controls are better on both axes. Hardware security keys are both more usable and more phishing-resistant than one-time codes typed from an app. Single sign-on reduces password count and improves central revocation. Passkeys remove the password while strengthening it. When a trade-off genuinely exists, apply the friction where the risk is: step-up authentication for a wire transfer, not for reading the staff canteen menu.
This also reframes "the user is the weakest link". If users consistently circumvent a control, the control is misdesigned for its context. Measuring circumvention is a design signal, not a reason to blame people.
Examples
| Control | Security effect | Usability effect | Verdict |
|---|---|---|---|
| Forced 30-day password rotation | Weak; encourages predictable patterns | High burden | Abandoned by NIST SP 800-63B |
| Long passphrase + breach-list check | Strong | Low burden | Recommended |
| SMS one-time code | Blocks credential stuffing; weak to SIM swap and phishing | Moderate | Better than nothing |
| FIDO2 / passkey | Phishing-resistant by origin binding | Lower burden than typing codes | Best available |
| Full-disk encryption | Strong for lost devices | Near-zero once provisioned | Always enable |
| Blocking all USB storage | Strong against exfiltration and drive-drops | Can be severe | Depends on role |
# Risk-based (adaptive) authentication: spend the user's patience only where
# the risk justifies it, rather than taxing every interaction equally.
def required_assurance(action, context) -> str:
if action.is_read_only and context.device_is_managed:
return "session" # no extra prompt at all
if action.moves_money or action.changes_credentials:
return "reauth_with_phishing_resistant_factor"
if context.ip_country != context.usual_country or context.device_is_new:
return "step_up_mfa" # unusual context, not unusual action
return "session"
Friction budget, allocated by impact:
low impact ┌──────────────────────────────────────┐ high impact
(read menu) │░░ ██│ (wire transfer)
└──────────────────────────────────────┘
minimal maximal
friction friction
Spending the same friction everywhere exhausts the budget on
interactions that did not need it, and users then disable or
work around the control when it finally matters.
Key Takeaways
- Controls users circumvent provide negative security: the risk remains and the workaround adds new exposure.
- Prefer controls that improve both axes (passkeys, SSO, device-bound credentials) before accepting a trade-off.
- Allocate friction proportionally to impact through step-up and risk-based authentication.
- Measure circumvention rates and support-ticket volume as security telemetry, not just as help-desk data.
- Guidance evolves: mandatory periodic password rotation was standard advice and is now explicitly discouraged absent evidence of compromise.
🧪 Practice
- Identify one security control in your environment that people routinely work around. Document the workaround and propose a redesign that removes the incentive.
- Define a step-up authentication policy for an online bank: list which actions require re-authentication and justify each threshold.
- Estimate the annual time cost of a 90-day rotation policy for 500 employees, then argue whether the security benefit justifies it using current NIST guidance.
- Interview-style: "Leadership wants MFA on every internal application, and the support desk is overwhelmed with lockouts. What do you propose?" Hint: consider SSO with a single strong factor, device trust as a signal, self-service recovery, and which applications genuinely warrant re-prompting.
<a id="12-threat-landscape"></a>
1.2 Threat Landscape
Defending a system requires a realistic model of who might attack it, what they want, and how they operate. This section builds that model from first principles and introduces the two frameworks the industry uses to describe adversary behaviour.
Assets, Vulnerabilities, Threats, and Risk
Theory
These four words are used interchangeably in casual conversation and precisely in security work. Getting them straight is what lets you prioritize, because risk is the only one of the four that has a magnitude you can compare against a budget.
- An asset is something with value: customer data, a payment service's uptime, source code, a reputation, a human life.
- A vulnerability is a weakness that could be exploited: an unpatched library, an absent authorization check, an untrained employee, a single power feed.
- A threat is a potential cause of harm: a ransomware crew, a careless insider, a flood. A threat needs an actor with capability and intent, or a natural cause.
- Risk is the combination: the likelihood that a threat exploits a vulnerability, multiplied by the impact if it does.
The crucial relationship is that risk requires all three to coexist. A severe vulnerability in software you do not run is not a risk. A determined adversary with no applicable weakness is not a risk. A perfectly exploitable flaw in a system holding nothing of value is a low risk. This is why vulnerability scanner output sorted by CVSS score is not a remediation plan: it describes vulnerability severity in the abstract, with no knowledge of your assets, your exposure, or your compensating controls.
Examples
THREAT VULNERABILITY ASSET
(actor with (exploitable weakness) (thing of value)
capability
+ intent)
│ │ │
└────────────┬───────────┘ │
▼ │
LIKELIHOOD ────────────┬────────────────┘
▼
IMPACT
│
▼
RISK = likelihood × impact
Remove ANY of the three inputs and the risk collapses:
• no asset value → nothing to lose
• no vulnerability → nothing to exploit
• no credible threat → nothing to exploit it
from dataclasses import dataclass
@dataclass
class Risk:
asset: str
threat: str
vulnerability: str
likelihood: float # 0..1 per year
impact_eur: float # single-occurrence loss
@property
def annualized_loss(self) -> float:
"""Expected yearly cost. Comparable across unrelated risks, which is
what lets a finite budget be allocated rationally."""
return self.likelihood * self.impact_eur
register = [
Risk("Customer PII database", "Cybercrime group", "SQLi in legacy report page",
likelihood=0.30, impact_eur=800_000),
Risk("Checkout service", "DDoS-for-hire", "No upstream scrubbing",
likelihood=0.50, impact_eur=120_000),
Risk("Build server", "Malicious insider", "Shared admin credential",
likelihood=0.05, impact_eur=2_000_000),
]
# Sorting by expected loss, not by CVSS, puts money where it reduces most harm.
for r in sorted(register, key=lambda x: x.annualized_loss, reverse=True):
print(f"{r.asset:<28} {r.annualized_loss:>12,.0f} EUR/yr")
| Term | Question it answers | Example |
|---|---|---|
| Asset | What do we stand to lose? | Patient records |
| Vulnerability | Where are we weak? | Unauthenticated API endpoint |
| Threat | Who or what could hurt us? | Ransomware affiliate |
| Exposure | Can the threat reach the weakness? | Endpoint is internet-facing |
| Risk | How much should we care? | Expected annual loss of 240,000 EUR |
Key Takeaways
- Risk needs an asset, a vulnerability, and a credible threat simultaneously; removing any one eliminates it.
- Vulnerability severity is not risk: severity ignores asset value, exposure, and compensating controls.
- Expressing risk as expected loss makes unrelated risks comparable and budgets defensible.
- Exposure is the often-missing fifth term: an internal-only flaw and an internet-facing one differ by orders of magnitude.
- You control vulnerabilities and (partly) impact. You rarely control threats, which is why control selection targets the former.
🧪 Practice
- For one system you know well, list its three most valuable assets, then for each name a vulnerability and a plausible threat actor.
- Take any two entries from a vulnerability scanner report with the same CVSS score and argue why they should receive different remediation priority.
- Build a five-row risk register using the dataclass above with realistic numbers for a small e-commerce company, and defend your likelihood estimates.
- Interview-style: "A scanner reports a critical CVE on an internal server. Is it a critical risk?" Hint: ask what reaches that server, what runs on it, what it stores, and whether the vulnerable code path is even enabled in your configuration.
Threat Actor Types and Motivations
Theory
"Hackers" is not a threat model. Different adversaries have different budgets, patience, tolerance for being caught, and goals, and those differences change what defences actually matter. A crew that monetizes access within 48 hours is defeated by controls that make you a slower target than the next organization. An adversary with a multi-year objective and a national budget is not deterred by relative difficulty at all.
Two attributes do most of the predictive work:
Capability determines whether an actor can use novel exploits and custom tooling or only public ones. Intent determines whether they are targeting you specifically or simply harvesting whoever is exposed. Opportunistic attacks are defeated by not being the easiest target; targeted attacks are not, because the attacker does not move on.
Motivation matters because it predicts behaviour after access. Financial actors look for data to sell and systems to encrypt. Espionage actors look for documents and stay quiet. Hacktivists seek publicity, so they deface or leak. Knowing the likely motivation tells you which detections and which recovery plans to invest in.
Examples
| Actor | Motivation | Capability | Targeting | Typical outcome |
|---|---|---|---|---|
| Script kiddie | Status, curiosity | Low; public tools | Opportunistic | Defacement, nuisance DoS |
| Hacktivist | Ideology, publicity | Low to moderate | Symbolic targets | Leaks, defacement |
| Insider | Grievance, greed, error | Variable; legitimate access | Inherent | Data theft, sabotage |
| Organized crime | Profit | Moderate to high | Opportunistic at scale | Ransomware, fraud, extortion |
| Nation-state / APT | Espionage, disruption | Very high; custom exploits | Highly targeted | Long-term quiet access |
| Competitor | Commercial advantage | Variable, often outsourced | Targeted | IP theft |
| Terrorist / extremist | Fear, disruption | Low to moderate | Symbolic, critical services | Disruption attempts |
high ┌──────────────────────┬──────────────────────┐
│ Organized crime │ Nation-state │
│ (scaled, fast, │ (patient, custom │
│ profit-driven) │ tooling, quiet) │
CAPABILITY ├──────────────────────┼──────────────────────┤
│ Script kiddies │ Hacktivists / │
│ (public tools, │ motivated insiders │
│ noisy) │ (specific grudge) │
low └──────────────────────┴──────────────────────┘
opportunistic targeted
TARGETING INTENT
Lower-left is defeated by basic hygiene and being a harder target.
Upper-right requires detection and response, because prevention will
eventually fail against a sufficiently resourced, patient adversary.
Key Takeaways
- Model adversaries by capability and targeting intent; these predict which defences pay off.
- Opportunistic attacks are deterred by relative difficulty; targeted attacks are not.
- Motivation predicts post-access behaviour, which determines what you must detect and how you recover.
- Most organizations face commodity crime and insiders far more often than nation-states; design for the common case first.
- Threat actors increasingly specialize and trade with each other, so a single intrusion may involve several parties with different goals.
🧪 Practice
- Write a one-paragraph threat profile for an organization of your choosing, naming the three most plausible actor types and what each would want.
- Explain why "we're too small to be a target" is usually wrong, using the concept of opportunistic targeting.
- For a hospital, a cryptocurrency exchange, and a political NGO, rank the seven actor types in the table by relevance and justify the top choice for each.
- Interview-style: "How would your defensive priorities differ for a company facing commodity ransomware versus one facing state-sponsored espionage?" Hint: contrast rapid recovery and backup immutability against long-dwell-time detection, egress monitoring, and supply chain assurance.
Script Kiddies, Hacktivists, and Insiders
Theory
These three sit at the lower-capability end of the spectrum but cause a disproportionate share of real incidents, for different reasons.
Script kiddies use tools they did not write and often do not understand. Their significance is volume: automated scanning means any internet-facing host is probed within minutes of appearing. They are defeated almost entirely by hygiene (patching, no default credentials, no exposed admin interfaces). Their value to defenders is as a continuous test of your baseline.
Hacktivists are driven by ideology and seek visibility. The technical bar is similar, but the targeting is symbolic, so timing clusters around political events, and the damage is reputational more than financial. Doxxing and leaking are common, which means confidentiality is often the property at risk.
Insiders are the hardest case because every preventive control assumes an untrusted outsider. An insider is already authenticated, already inside the network, and already authorized for much of what they touch. Importantly, most insider incidents are unintentional: a misdirected email, a public cloud bucket, a lost laptop. Malicious insiders are rarer but costlier, and the common triggers are well documented (termination, passed-over promotion, financial pressure, recruitment by an outside party).
Insider risk is therefore managed by a different toolkit: least privilege and SoD to limit reach, behavioural detection to spot anomalous use of legitimate access, and above all HR-coordinated joiner-mover-leaver processes.
Examples
| Insider type | Intent | Example | Primary control |
|---|---|---|---|
| Negligent | None | Emails a client list to a personal account to work at home | Training, DLP, easy sanctioned alternatives |
| Compromised | None (account is hijacked) | Credentials phished and reused by an outsider | MFA, impossible-travel detection |
| Malicious | Harm or gain | Downloads the CRM database before resigning | Least privilege, egress monitoring, offboarding |
| Third party | Variable | Contractor retains access after contract ends | Access reviews, time-boxed accounts |
Behavioural indicators worth correlating (none is conclusive alone):
ACCESS PATTERN │ CONTEXT
─────────────────────────┼──────────────────────────────────
Bulk record export │ Resignation submitted
Access outside work hours │ Performance plan started
Access to systems outside │ Unusual overseas travel
the person's role │ Contract ending within 30 days
Mass file renaming │ Recent access-request denials
Use of personal cloud │
storage / USB │
─────────────────────────┴──────────────────────────────────
Correlation is the point: "bulk export" alone is a false positive
factory; "bulk export by an account whose owner resigned yesterday"
is a case worth a human review.
-- A detective control: flag unusually large exports relative to a user's
-- own 30-day baseline, rather than against a fixed global threshold.
SELECT u.user_id,
d.export_rows,
b.median_rows,
d.export_rows / NULLIF(b.median_rows, 0) AS ratio
FROM daily_exports d
JOIN user_baseline_30d b ON b.user_id = d.user_id
JOIN users u ON u.user_id = d.user_id
WHERE d.export_rows > 10000 -- ignore trivial activity
AND d.export_rows > 10 * b.median_rows -- ten times this person's own norm
ORDER BY ratio DESC;
Key Takeaways
- Script kiddies validate your baseline hygiene; they are high-volume and low-sophistication.
- Hacktivist activity correlates with news cycles, so threat windows are partly predictable.
- Most insider incidents are accidents, so training and safer defaults prevent more harm than surveillance does.
- Insiders defeat perimeter thinking entirely; least privilege, SoD, and behavioural analytics are the applicable controls.
- Offboarding is a security control. Timely, complete deprovisioning closes the single most common insider gap.
- Insider monitoring has legal and ethical limits that vary by jurisdiction; involve HR and legal before deploying it.
🧪 Practice
- Write the deprovisioning checklist for an employee leaving your organization, including systems that are not managed by central IT.
- Propose three detections for malicious insider data theft, and for each state the most likely false positive and how you would suppress it.
- Explain why monitoring employee behaviour requires legal review in the EU, referencing GDPR principles of necessity and proportionality.
- Interview-style: "How do you defend against someone who is authorized to access the data they are stealing?" Hint: prevention is largely unavailable; focus on limiting scope, detecting deviation from an individual's own baseline, and raising the cost of removing data from the environment.
Organized Cybercrime Groups
Theory
Modern cybercrime is a service economy with specialization, subcontracting, and customer support. Understanding it as a business explains defensive priorities better than any technical detail, because business economics predict behaviour.
The ecosystem has distinct roles. Initial access brokers compromise organizations and sell the access rather than using it. Ransomware-as-a-service operators build and maintain the malware, run the leak site, and handle negotiation, taking a percentage. Affiliates rent the platform and do the intrusion. Separate specialists provide bulletproof hosting, money laundering, and exploit development.
The consequence for defenders is twofold. First, the actor who breaks in may not be the one who extorts you, and weeks may pass between the two. That gap is a detection opportunity. Second, because affiliates are paid on results and have alternatives, they behave like rational economic agents: they prefer targets where time-to-payment is shortest. Being modestly harder than average meaningfully reduces your exposure, in a way it does not for targeted adversaries.
Double extortion (encrypt and also steal, threatening publication) emerged specifically because good backups defeated encryption-only attacks. This is the clearest illustration of the economic feedback loop: improve a control at scale and the business model adapts.
Examples
┌────────────────────┐ sells access ┌────────────────────┐
│ Initial Access │ ───────────────► │ Affiliate │
│ Broker │ (VPN creds, │ (does intrusion, │
│ (phishing, exposed │ web shells) │ escalation, │
│ RDP, stolen creds)│ │ exfiltration) │
└────────────────────┘ └─────────┬──────────┘
│ rents platform,
│ pays ~20-30% cut
▼
┌────────────────────┐ ┌────────────────────┐
│ Money laundering │ ◄─────ransom──── │ RaaS Operator │
│ (mixers, mules, │ │ (builds malware, │
│ cash-out) │ │ runs leak site, │
└────────────────────┘ │ negotiates) │
└────────────────────┘
Defensive implication: three distinct phases, often separated by days
or weeks, each with different detectable behaviour.
| Attack phase | Business purpose | Where defenders can intervene |
|---|---|---|
| Access acquisition | Inventory for sale | MFA, patch external services, credential monitoring |
| Access validation | Confirm the goods | Login anomaly detection, dormant-account alerts |
| Escalation and discovery | Assess payment capacity | EDR, privileged-access monitoring |
| Exfiltration | Build extortion leverage | Egress filtering, data volume alerts |
| Encryption | Force urgency | Immutable backups, shadow-copy protection |
| Negotiation | Extract payment | Pre-agreed IR plan, legal and insurance counsel |
Key Takeaways
- Cybercrime is specialized and commoditized; a single incident often involves multiple independent parties.
- The gap between initial access and extortion is often weeks, which is the defender's best detection window.
- Affiliates are economically rational and opportunistic, so marginal difficulty yields real risk reduction.
- Double extortion exists because backups worked; expect controls to drive adaptation rather than elimination.
- Paying a ransom is a business and legal decision with sanctions implications, and it does not reliably restore data or prevent publication.
🧪 Practice
- List the five most likely initial access vectors into your organization and state the control that closes each.
- Explain why immutable, offline backups changed attacker behaviour, and what that implies about the durability of any single control.
- Sketch the decision points your organization would face in the first 24 hours of a ransomware incident, identifying who must be contacted and in what order.
- Interview-style: "Why might paying a ransom be the wrong decision even when it is the cheapest option on paper?" Hint: consider sanctions and legal exposure, the reliability of decryption tools, the fact that stolen data is already copied, and the effect on future targeting.
Nation-State Actors and APTs
Theory
An Advanced Persistent Threat is defined by its adjectives, and each one is a design constraint for defenders.
Advanced means access to capabilities others lack: previously unknown (zero-day) exploits, custom implants, and supply chain positions. Persistent is the most important word: the objective is long-term access, not a single smash-and-grab. Such an actor will spend months, re-enter after being evicted, and maintain multiple independent footholds. Threat means a human organization with direction and funding, not opportunistic automation.
Three consequences follow. First, prevention will eventually fail, so detection and response capability is the actual defence. Second, these actors deliberately blend in: they prefer stolen valid credentials and built-in administrative tooling ("living off the land") precisely because it does not look anomalous to signature-based detection. Third, incomplete eradication is worse than none, because a partially evicted adversary learns what you detect and adapts.
Note that "APT" has drifted to describe any sophisticated actor, including well-funded criminal groups. The useful distinction is objective: espionage and prepositioning for disruption, versus monetization. Espionage actors want to remain undetected indefinitely, which is why dwell times are measured in months.
Examples
| Dimension | Organized crime | Nation-state / APT |
|---|---|---|
| Objective | Fast monetization | Intelligence, access, prepositioning |
| Time horizon | Days to weeks | Months to years |
| On detection | Moves to another victim | Adapts and persists |
| Tooling | Commodity, purchased | Custom implants plus native tools |
| Exploits | Known vulnerabilities, fast | Zero-days where justified |
| Noise | Deliberate at the end | Minimized throughout |
| Target choice | Opportunistic at scale | Selected for intelligence value |
| Best defence | Hygiene, immutable backups | Detection, segmentation, supply chain assurance |
Dwell time and why it matters
Day 0 Day 30 Day 90 Day 200 Day 210
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
Initial Credential Lateral Collection Detection
access harvesting movement and slow (often by an
(phish or (quiet, uses (valid accounts, exfiltration external party)
supply native tools) native admin over months
chain) tooling)
├────────────────────────────────────────────────────────────┤
Every day here is a day of undetected access.
Reducing dwell time is the single most useful metric against APTs,
because it bounds how much can be collected before eviction.
Key Takeaways
- Persistence is the defining property: eviction, not prevention, is the hard problem.
- Assume prevention fails; invest in detection coverage, logging retention, and response readiness.
- Living-off-the-land techniques mean behavioural and anomaly detection matters more than signatures.
- Eradication must be complete and coordinated; a partial eviction teaches the adversary your detection capability.
- Reducing dwell time bounds the damage, making it the most meaningful program metric against this actor class.
- Supply chain compromise is a favoured route because it bypasses a target's own perimeter entirely.
🧪 Practice
- Explain why an organization should not immediately reset all credentials upon discovering a suspected APT, and what should happen first.
- List the log sources you would need, and for how long you would retain them, to investigate an intrusion discovered 200 days after it began.
- Describe three ways a supply chain compromise bypasses perimeter defences, and name a control that addresses each.
- Interview-style: "Your EDR flags
certutil.exedownloading a file from an external host. Why is this interesting, and what makes it hard to detect at scale?" Hint: think about why attackers prefer signed, built-in binaries, and what legitimate administrative baseline you would need to distinguish abuse from normal use.
Attack Surface and Attack Vectors
Theory
The attack surface is the complete set of points where an unauthorized party could attempt to interact with a system. An attack vector is a specific path taken through that surface. Surface is a property of your architecture; vector is a property of a particular attack.
The engineering value of the concept is that surface is something you can deliberately shrink, and shrinking it reduces risk without needing to predict any specific attack. Every listening port, every API parameter, every installed package, every third-party script, every employee with an inbox is surface. Code that is not deployed cannot be exploited; a service not listening cannot be reached.
Attack surface divides usefully into four domains. The network surface is everything reachable over a network. The software surface is every input a program parses, including dependencies. The human surface is every person who can be persuaded to act. The physical surface is every port, cable, and door.
The hardest problem in practice is not reducing known surface but discovering unknown surface: forgotten subdomains, a staging environment exposed with production data, an old VPN appliance nobody patches. Attack surface management is therefore a continuous discovery exercise, not a one-time audit, and it is why attackers invest heavily in reconnaissance.
Examples
A typical web application's attack surface
┌─ NETWORK ─────────────────────────────────────────────────┐
│ 443/tcp app 22/tcp bastion 5432/tcp db (internal) │
│ forgotten: staging.example.com, old-vpn.example.com │ ◄─ unknown
└───────────────────────────────────────────────────────────┘ surface
┌─ SOFTWARE ────────────────────────────────────────────────┐
│ every route/parameter, file upload parser, 400+ transitive│
│ npm dependencies, deserialization of session data │
└───────────────────────────────────────────────────────────┘
┌─ HUMAN ───────────────────────────────────────────────────┐
│ support desk (password reset), finance (invoice fraud), │
│ developers (dependency typosquatting, malicious PRs) │
└───────────────────────────────────────────────────────────┘
┌─ PHYSICAL ────────────────────────────────────────────────┐
│ office reception, unlocked network ports, USB on kiosks │
└───────────────────────────────────────────────────────────┘
| Reduction technique | Domain | Effect |
|---|---|---|
| Decommission unused services | Network | Removes listeners entirely |
| Bind to localhost or private subnet | Network | Removes external reachability |
| Remove unused dependencies | Software | Eliminates inherited vulnerabilities |
| Disable unused API methods and fields | Software | Fewer parsers exposed to input |
| Feature flags off by default | Software | Unreleased code is not reachable |
| Restrict who can approve payments | Human | Fewer people worth targeting |
| Disable unused physical ports | Physical | Removes drop-in access |
# Enumerate the local network surface: what is actually listening, and on
# which interface. A service bound to 127.0.0.1 is not network surface;
# the same service on 0.0.0.0 is exposed to everything that can route to it.
ss -tulpn | awk 'NR==1 || $5 !~ /127\.0\.0\.1|\[::1\]/'
Key Takeaways
- Attack surface is architectural and reducible; vectors are specific paths through it.
- The most reliable security improvement is removing functionality rather than defending it.
- Unknown surface (forgotten hosts, stale DNS, shadow IT) causes a large share of breaches, so discovery must be continuous.
- Dependencies are surface: a transitive package you never call is still code in your process.
- Humans and physical access are genuine surface and are frequently excluded from technical scoping to the attacker's benefit.
🧪 Practice
- Run a listening-port enumeration on a machine you own and justify, service by service, why each one needs to be reachable from where it is reachable.
- Count the direct and transitive dependencies of any project you work on and identify three you could remove.
- Write an attack surface inventory for a small company's internet presence, including DNS records, third-party SaaS, and employee-facing services.
- Interview-style: "How would you discover attack surface the organization does not know it has?" Hint: think about certificate transparency logs, DNS enumeration, cloud account inventory across regions, and expired-but-still-resolving records.
Cyber Kill Chain Model
Theory
The Lockheed Martin Cyber Kill Chain, published in 2011, models an intrusion as a sequence of seven dependent stages. Its core insight is strategic rather than descriptive: because the stages are dependent, breaking any one of them stops the attack. The defender does not need to win at every stage; the attacker needs to win at every stage.
This reframed defence from "keep attackers out" to "find the cheapest stage at which to break the chain." It also introduced the idea of measuring your detection and response coverage per stage, which exposes a common pattern: most organizations concentrate almost everything at delivery and exploitation and have nearly nothing at command-and-control or actions-on-objectives, which is precisely where a successful intrusion spends most of its time.
The model's limitations are well known and worth stating. It is perimeter-centric and linear, so it fits a straightforward external intrusion well and describes insider threats, supply chain compromise, and credential-based attacks poorly. Many real intrusions skip stages entirely: an attacker who buys valid VPN credentials performs no exploitation at all. Treat it as a planning scaffold rather than a faithful description of adversary behaviour.
Examples
STAGE ATTACKER ACTION DEFENDER OPPORTUNITY
──────────────────────────────────────────────────────────────────────────
1. Reconnaissance │ Research targets, │ Reduce public exposure,
│ harvest emails, scan │ monitor for scanning
──────────────────────────────────────────────────────────────────────────
2. Weaponization │ Build payload │ (No visibility: happens
│ + exploit pairing │ entirely on their side)
──────────────────────────────────────────────────────────────────────────
3. Delivery │ Email, web, USB, │ Mail filtering, proxy,
│ compromised supplier │ user reporting
──────────────────────────────────────────────────────────────────────────
4. Exploitation │ Trigger the flaw │ Patching, exploit
│ │ mitigations, EDR
──────────────────────────────────────────────────────────────────────────
5. Installation │ Establish persistence │ Allowlisting, autorun
│ │ monitoring, EDR
──────────────────────────────────────────────────────────────────────────
6. Command & Control │ Open channel to │ Egress filtering, DNS
│ operator │ monitoring, TLS inspection
──────────────────────────────────────────────────────────────────────────
7. Actions on │ Steal, encrypt, │ DLP, segmentation,
Objectives │ destroy, move laterally │ anomaly detection, backups
──────────────────────────────────────────────────────────────────────────
Each stage depends on the previous one succeeding.
Break ANY link → intrusion fails.
A coverage self-assessment is the model's most practical use:
| Stage | Preventive control | Detective control | Coverage gap? |
|---|---|---|---|
| Delivery | Mail filtering | Phishing reports | Strong |
| Exploitation | Patch SLA, ASLR/DEP | EDR alerts | Strong |
| Installation | Allowlisting | Persistence monitoring | Moderate |
| C2 | Egress deny-by-default | DNS/proxy analytics | Often weak |
| Actions | Segmentation, DLP | Volume anomaly alerts | Often weakest |
Key Takeaways
- The stages are dependent, so breaking any single link defeats the intrusion.
- Use the model to map control coverage per stage and expose where you have none.
- Most programs over-invest in early stages and under-invest in C2 and actions-on-objectives.
- Weaponization offers essentially no defender visibility; do not plan controls there.
- The model is linear and perimeter-centric, so it fits external malware intrusions better than insider, credential-based, or supply chain attacks.
🧪 Practice
- Map your organization's existing controls onto the seven stages and identify the stage with the weakest coverage.
- Explain how a credential-stuffing attack against a cloud service maps onto the kill chain, and which stages are absent.
- Argue which single stage gives the best return on new investment for a company with good patching and no egress filtering.
- Interview-style: "What are the Cyber Kill Chain's limitations?" Hint: consider insider threats, attacks using only valid credentials and native tools, non-linear or looping intrusions, and the fact that it says nothing about what happens after objectives are met.
MITRE ATT&CK Framework Overview
Theory
ATT&CK (Adversarial Tactics, Techniques, and Common Knowledge) is a continuously curated knowledge base of adversary behaviour observed in real intrusions. Where the Kill Chain gives seven abstract phases, ATT&CK gives a structured matrix of tactics (the adversary's goal, such as Persistence or Credential Access) and, under each, dozens of techniques and sub-techniques describing concretely how that goal is achieved, each with a stable identifier such as T1059 for Command and Scripting Interpreter.
Its importance is that it created a shared vocabulary. Before ATT&CK, a threat report, a detection rule, and a product datasheet each described the same behaviour in incompatible prose. Now a report can say an actor uses T1566.001, a detection engineer can write a rule tagged T1566.001, and coverage can be measured.
The second key idea is that it is organized around behaviour rather than indicators. An IP address or file hash changes trivially; the technique of achieving persistence through a scheduled task is comparatively expensive for an adversary to abandon. This is the reasoning formalized in the Pyramid of Pain (Chapter 13). Detections written at the behavioural level survive adversary tool changes.
The standard failure mode is chasing "100% ATT&CK coverage". The matrix is not a checklist; techniques are not equally relevant to your platforms, and a technique can be implemented in many ways, so a single rule rarely covers one fully. Prioritize by which techniques the actors relevant to you actually use.
Examples
Tactics (columns) flow roughly left to right; techniques fill each column.
Initial Execution Persistence Priv.Esc Defense Credential
Access Evasion Access
──────────── ──────────── ───────────── ─────────── ──────────── ────────────
Phishing Command & Scheduled Valid Impair OS Credential
(T1566) Scripting Task (T1053) Accounts Defenses Dumping
(T1059) (T1078) (T1562) (T1003)
──────────── ──────────── ───────────── ─────────── ──────────── ────────────
Valid Native API Create Exploit Masquerading Brute Force
Accounts (T1106) Account for Priv (T1036) (T1110)
(T1078) (T1136) Esc (T1068)
──────────── ──────────── ───────────── ─────────── ──────────── ────────────
Note T1078 (Valid Accounts) appears under several tactics: one technique
can serve multiple adversary goals, which is why the matrix is not a
linear sequence.
| Aspect | Cyber Kill Chain | MITRE ATT&CK |
|---|---|---|
| Granularity | 7 phases | Hundreds of techniques, with sub-techniques |
| Shape | Linear sequence | Matrix; non-linear, techniques repeat |
| Built from | Conceptual model | Observed real-world intrusions |
| Best for | Strategy, executive communication | Detection engineering, red/purple teaming |
| Updates | Static since publication | Continuously maintained |
# A Sigma detection rule tagged with the technique it covers, which is what
# makes coverage measurable across a whole rule library.
title: Scheduled Task Created by Non-Administrative Process
id: 7c9c7b2e-0b1a-4f4a-9f4e-2a6f3c1d9e11
status: experimental
description: Detects scheduled task creation, a common persistence technique
tags:
- attack.persistence
- attack.t1053.005 # Scheduled Task/Job: Scheduled Task
logsource:
product: windows
service: security
detection:
selection:
EventID: 4698 # A scheduled task was created
filter_known_good:
SubjectUserName|startswith: 'svc_deploy' # tune out sanctioned automation
condition: selection and not filter_known_good
falsepositives:
- Software installers and legitimate administrative scripts
level: medium
Key Takeaways
- ATT&CK provides a shared, stable vocabulary for adversary behaviour, enabling comparison across reports, rules, and products.
- Tactics are goals; techniques are methods. Techniques recur across multiple tactics.
- Behaviour-based detections outlive indicator-based ones because changing technique costs an adversary more than changing infrastructure.
- Use it to measure and prioritize detection coverage against relevant actors, not to pursue total coverage.
- Separate matrices exist for Enterprise, Mobile, and ICS; use the one that matches your environment.
- A technique marked "covered" by one rule is usually only partly covered, since most techniques have many procedural variants.
🧪 Practice
- Pick any three techniques from the Credential Access tactic and describe, for each, one log source that would reveal it.
- Take a published threat report and extract its ATT&CK technique identifiers, then check whether you have any detection for the three most frequently cited.
- Explain, with an example, why "we detect T1059" is an incomplete statement.
- Interview-style: "How would you use ATT&CK to prioritize detection engineering with limited resources?" Hint: combine the techniques used by actors that actually target your sector with the techniques your current telemetry could plausibly detect, and start where those two sets overlap.
<a id="13-security-governance-and-risk"></a>
1.3 Security Governance and Risk
Governance is how an organization decides what security it will buy, who is accountable, and how that decision is documented and reviewed. This section covers the artefacts and methods that translate technical findings into decisions a business can actually make.
Security Policies, Standards, and Procedures
Theory
Technical controls without governing documents produce an environment where every team does something reasonable and no two teams do the same thing. The documentation hierarchy exists to separate intent (which changes rarely and needs executive authority) from implementation (which changes constantly and needs engineering ownership).
- A policy states intent and is mandatory. It is short, technology-neutral, and approved at executive level: "All remote access to corporate systems must be authenticated with multi-factor authentication."
- A standard makes the policy measurable and is also mandatory: "Accepted factors are FIDO2 security keys or platform authenticators. SMS is not accepted."
- A procedure gives the step-by-step instructions to comply: "To enrol a security key, open the identity portal, select Security, and ..."
- A guideline is recommended but not mandatory: "Prefer enrolling two keys so that loss of one does not cause lockout."
The separation matters because mixing them creates documents that are simultaneously too rigid and impossible to maintain. Naming a specific product version in a policy forces an executive-level approval cycle for a routine upgrade. Conversely, a policy with no standard beneath it is unenforceable, because "strong authentication" cannot be audited.
Every policy needs an owner, a review date, and defined exception handling. Exceptions are inevitable; an exception process with an expiry date, a compensating control, and a named approver turns an invisible violation into a tracked, time-boxed risk.
Examples
┌─────────────────────────────────────────┐
│ POLICY WHY + WHAT (mandatory)│ approved: executive
│ "Remote access must use MFA." │ changes: rarely
└────────────────────┬────────────────────┘
▼
┌─────────────────────────────────────────┐
│ STANDARD MEASURABLE (mandatory)│ approved: security
│ "FIDO2 or platform authenticator only. │ changes: yearly
│ SMS prohibited. Session max 12h." │
└────────────────────┬────────────────────┘
▼
┌─────────────────────────────────────────┐
│ PROCEDURE HOW (mandatory steps) │ approved: IT owner
│ "1. Open portal 2. Security 3. ..." │ changes: often
└────────────────────┬────────────────────┘
▼
┌─────────────────────────────────────────┐
│ GUIDELINE ADVICE (optional) │ approved: IT owner
│ "Enrol a backup key." │
└─────────────────────────────────────────┘
---
title: Remote Access Policy
id: POL-007
version: 3.1
owner: Chief Information Security Officer
approved_by: Executive Committee
approved_on: 2026-02-14
next_review: 2027-02-14
applies_to: All employees, contractors, and third parties
---
## 1. Purpose
Limit unauthorized access to corporate systems from outside the corporate network.
## 2. Policy statements
2.1 All remote access MUST be authenticated using multi-factor authentication.
2.2 Remote access MUST originate from a device enrolled in corporate management.
2.3 Access MUST be revoked within 4 hours of employment termination.
## 3. Exceptions
Exceptions MUST be requested via the risk register, MUST document a compensating
control, MUST name an accountable owner, and MUST expire within 90 days.
## 4. Compliance
Violations are handled under the Disciplinary Procedure (HR-002).
## 5. Related documents
STD-014 Authentication Standard; PRC-031 Security Key Enrolment Procedure
Note the use of MUST, which carries the meaning defined in RFC 2119. Using "should" where you mean "must" is the most common drafting error, and auditors read the words literally.
Key Takeaways
- Policy states mandatory intent; standards make it measurable; procedures give steps; guidelines advise.
- Keep product names and versions out of policies so that routine changes do not require executive re-approval.
- Every document needs an owner, approval record, review date, and version.
- An exception process with expiry dates and compensating controls converts hidden non-compliance into managed risk.
- Precise modal verbs (must, must not, should) determine enforceability and are read literally during audits.
- A policy nobody can comply with trains the organization to ignore policy generally.
🧪 Practice
- Take a one-line security rule from your environment and write it out across all four document levels.
- Review an existing policy and identify any statements that belong in a standard or procedure instead. Explain the maintenance cost of each misplacement.
- Design an exception request form, listing the minimum fields needed for a reviewer to make an informed decision.
- Interview-style: "How would you handle a business unit that cannot comply with a security policy?" Hint: the answer is a documented, time-boxed exception with a compensating control and an accountable owner, not an informal agreement or silent non-enforcement.
Qualitative vs. Quantitative Risk Assessment
Theory
Having identified risks, you must rank them, and there are two broad methods with different costs and different credibility.
Qualitative assessment uses ordinal categories: likelihood "Likely", impact "Major", resulting in "High" risk. It is fast, needs no historical data, and is accessible to non-specialists. Its weakness is that the labels are not numbers. "High" risks cannot be summed, and two assessors frequently disagree about what "Likely" means. Risk matrices also produce range compression, where genuinely different risks collapse into the same cell.
Quantitative assessment uses money and probability. The classical formulation is:
- SLE (Single Loss Expectancy) = Asset Value x Exposure Factor
- ARO (Annualized Rate of Occurrence) = expected occurrences per year
- ALE (Annualized Loss Expectancy) = SLE x ARO
ALE is directly comparable to the annual cost of a control, which makes the investment decision explicit: if a control costing 40,000 EUR per year reduces ALE by 150,000 EUR, it pays for itself. Modern practice (such as the FAIR model) improves on point estimates by using probability distributions and Monte Carlo simulation, which produces a range and makes uncertainty visible rather than hiding it inside a single number.
In practice most organizations use both: qualitative triage across the whole estate, then quantitative analysis for the small number of risks where a large spending decision depends on the answer.
Examples
Qualitative 5x5 matrix
IMPACT
Negligible Minor Moderate Major Severe
┌───────────┬───────┬─────────┬───────┬────────┐
Almost │ M │ H │ H │ C │ C │
certain │ │ │ │ │ │
├───────────┼───────┼─────────┼───────┼────────┤
Likely │ L │ M │ H │ H │ C │
├───────────┼───────┼─────────┼───────┼────────┤
Possible│ L │ M │ M │ H │ H │
├───────────┼───────┼─────────┼───────┼────────┤
Unlikely│ L │ L │ M │ M │ H │
├───────────┼───────┼─────────┼───────┼────────┤
Rare │ L │ L │ L │ M │ M │
└───────────┴───────┴─────────┴───────┴────────┘
L=Low M=Medium H=High C=Critical
Weakness: a 2M EUR loss and a 20M EUR loss may both land in "Severe",
and the matrix gives you no way to tell them apart.
def ale(asset_value: float, exposure_factor: float, aro: float) -> float:
"""exposure_factor is the fraction of asset value lost per occurrence."""
sle = asset_value * exposure_factor
return sle * aro
# Laptop theft across a 500-device fleet
current = ale(asset_value=2_000, exposure_factor=1.0, aro=15) # 15 thefts/yr
print(f"ALE before control: {current:,.0f} EUR") # 30,000 EUR
# Full-disk encryption does not stop theft; it reduces the LOSS per theft
# to the hardware value alone by removing the data-breach component.
breach_cost_per_device = 25_000
current_total = current + (breach_cost_per_device * 15) # 405,000 EUR
after_fde = current + 0 # 30,000 EUR
control_cost = 12_000 # annual tooling + operational overhead
benefit = current_total - after_fde - control_cost
print(f"Net annual benefit: {benefit:,.0f} EUR") # 363,000 EUR
| Aspect | Qualitative | Quantitative |
|---|---|---|
| Output | Ordinal category (High) | Currency (ALE 240,000 EUR) |
| Speed | Fast | Slow; needs data |
| Data needed | Expert judgement | Loss data, frequency estimates |
| Comparable across risks | Poorly | Directly |
| Supports cost-benefit | No | Yes |
| Main weakness | Subjective, range compression | False precision from weak inputs |
Key Takeaways
- Qualitative is fast and broad; quantitative supports financial decisions. Most programs need both.
- ALE = SLE x ARO, and ALE is directly comparable to annual control cost.
- Ordinal risk ratings cannot be meaningfully added, averaged, or compared across business units.
- Quantitative methods are only as good as their inputs; use ranges and distributions to represent genuine uncertainty.
- Define likelihood and impact bands numerically even in qualitative work, so that "Likely" means the same thing to every assessor.
🧪 Practice
- Define the five likelihood bands of a qualitative matrix in explicit numeric terms (for example, "Likely = 25-60% in any 12-month period").
- Calculate the ALE for a web server outage, stating your assumptions for hourly revenue, outage duration, and annual frequency.
- Demonstrate range compression by finding two genuinely different risks that land in the same matrix cell, then show how ALE separates them.
- Interview-style: "Management says your quantitative risk numbers are made up. How do you respond?" Hint: concede that inputs are estimates, then argue that explicit estimates with stated ranges are auditable and improvable, whereas the judgement embedded in a colour-coded matrix is neither.
Risk Treatment: Accept, Mitigate, Transfer, Avoid
Theory
Once a risk is assessed, exactly four responses exist. Every security decision you will ever make is one of these, and naming them explicitly prevents the most common governance failure: unconscious acceptance, where a risk is identified, nothing is done, and nobody formally owns the decision.
Mitigate (reduce) means applying controls to lower likelihood or impact. This is the default engineering reflex and is often, but not always, correct.
Transfer (share) means moving the financial consequence elsewhere, typically through cyber insurance or contractual indemnity with a supplier. Critically, you transfer cost, not accountability. Regulators and customers still hold you responsible, and reputational damage is not insurable.
Avoid means eliminating the activity that creates the risk: discontinuing a feature, exiting a market, deleting a dataset. It is the most complete treatment and the most frequently overlooked. "Do we need to store this at all?" prevents more breaches than any encryption project.
Accept means deciding, consciously and in writing, to bear the risk. This is legitimate when the cost of treatment exceeds the expected loss. It requires a named accountable owner at an appropriate level of seniority and a review date; otherwise it is not acceptance but neglect.
Residual risk is what remains after treatment. There is always some, and it must itself be accepted explicitly.
Examples
IMPACT
low high
┌─────────────────┬─────────────────┐
high │ MITIGATE │ AVOID or │
│ (reduce │ MITIGATE │
│ likelihood) │ heavily │
L ├─────────────────┼─────────────────┤
I │ ACCEPT │ TRANSFER │
K │ (monitor, │ (insure) │
E low │ review) │ + mitigate │
───── └─────────────────┴─────────────────┘
Rough heuristic only: a cheap mitigation for a low/low risk is still
worth doing, and insurance never removes the regulatory obligation.
| Treatment | Action | Example | Watch out for |
|---|---|---|---|
| Mitigate | Add or strengthen controls | Deploy MFA, patch, segment | Control cost exceeding the risk |
| Transfer | Shift financial consequence | Cyber insurance, supplier indemnity | Exclusions; accountability does not transfer |
| Avoid | Stop doing the activity | Delete the dataset, retire the feature | Business impact of removal |
| Accept | Document and bear it | Low-impact legacy system, 6-month review | Acceptance without an owner or review date |
# A risk register entry: the acceptance is a decision record, not a note
- risk_id: R-2026-041
description: Legacy reporting server runs an end-of-life OS
asset: Internal sales reports
likelihood: Possible
impact: Moderate
inherent_rating: High
treatment: mitigate
controls_applied:
- Network segmentation; reachable only from the reporting VLAN
- Read-only database credentials
- Decommission scheduled 2026-11-30
residual_rating: Low
residual_accepted_by: Director of Sales Operations # named human, not a team
accepted_on: 2026-03-02
review_on: 2026-09-02 # acceptance expires
Key Takeaways
- There are exactly four treatments; naming the chosen one prevents risk from being ignored by default.
- Transfer moves cost, not accountability, and insurance policies contain significant exclusions.
- Avoidance is underused: not collecting or not building removes the risk completely.
- Acceptance is valid only with a named owner at appropriate seniority and a defined review date.
- Residual risk always exists after treatment and must be explicitly accepted in its own right.
- The cost of a control should not exceed the expected loss it prevents, which requires the quantitative methods above.
🧪 Practice
- For three risks in your environment, state the chosen treatment and the name of the role that should own the decision.
- Find a dataset your organization stores that it could stop storing, and estimate the risk reduction from avoidance.
- Read a cyber insurance policy summary and list three exclusions that would surprise a business stakeholder.
- Interview-style: "When is accepting a risk the right answer?" Hint: when treatment cost exceeds expected loss; the interviewer wants to hear the conditions that make acceptance legitimate rather than negligent, including seniority of the approver and a review cycle.
Business Impact Analysis
Theory
A Business Impact Analysis (BIA) answers a question risk assessment does not: if a given business process stopped, how bad would it get, and how quickly? It is the input to continuity and disaster recovery planning, and it is deliberately threat-agnostic. It does not matter whether the payroll system is down due to ransomware, a failed migration, or a flood; the BIA asks what happens to the business during the outage.
This is where the key recovery metrics are defined:
- RTO (Recovery Time Objective): the maximum tolerable time to restore the process. It drives architecture spend (hot standby versus restore-from-backup).
- RPO (Recovery Point Objective): the maximum tolerable data loss, measured in time. It drives backup and replication frequency.
- MTD / MTPD (Maximum Tolerable Downtime): the point beyond which the damage becomes existential. RTO must be comfortably shorter.
The analysis also surfaces dependencies, which is where most recovery plans fail in practice. A process rated non-critical often turns out to be a prerequisite for a critical one: an authentication directory is boring until nothing can log in, and a certificate authority is invisible until every internal service fails simultaneously.
Impact must be measured over time, because it is rarely linear. An hour without the e-commerce checkout is a revenue dip; a week is a customer migration to a competitor. Regulatory and contractual deadlines also create step changes in impact.
Examples
Impact accumulation for an online checkout outage
impact │ ╭──────── contract
│ ╭────╯ penalties
│ ╭───────────╯ + churn
│ ╭──────────╯ ◄ not linear:
│ ╭────────╯ impact escalates
│ ╭──────╯ at thresholds
│╭──╯
└┴───┴────┴────────┴──────────┴───────────┴──────────────► time
1h 4h 8h 24h 72h 1 week
▲ ▲ ▲
│ │ └── MTD: beyond here the business
│ │ may not recover
│ └── RTO target: 8h (must be well inside MTD)
└── RPO: 1h of transactions is the maximum tolerable data loss
| Process | RTO | RPO | Depends on | Peak-period note |
|---|---|---|---|---|
| Card payment capture | 15 min | 0 (no loss tolerable) | Network, HSM, acquirer link | Black Friday: RTO 5 min |
| Customer-facing website | 4 h | 1 h | DNS, CDN, product database | — |
| Internal email | 8 h | 4 h | Identity provider | — |
| Payroll | 48 h | 24 h | HR database, bank interface | Month-end: RTO 4 h |
| Analytics warehouse | 5 days | 24 h | Source system extracts | — |
def recovery_investment_tier(rto_hours: float) -> str:
"""RTO drives architecture, and therefore cost, more than any other input."""
if rto_hours <= 0.25:
return "active-active multi-region (highest cost)"
if rto_hours <= 4:
return "warm standby with automated failover"
if rto_hours <= 24:
return "restore from backup to pre-provisioned infrastructure"
return "restore from backup to newly provisioned infrastructure (lowest cost)"
Key Takeaways
- BIA is threat-agnostic: it measures consequence of disruption, not cause.
- RTO drives recovery architecture cost; RPO drives backup and replication frequency.
- RTO must be meaningfully shorter than MTD, or the plan does not actually protect the business.
- Dependency mapping is the highest-value part of a BIA, because hidden shared dependencies invalidate recovery plans.
- Impact grows non-linearly and varies by calendar period; a single RTO figure can be misleading.
- Business owners, not IT, set RTO and RPO, because they are statements about business tolerance.
🧪 Practice
- Pick three processes in an organization you know and assign each an RTO and RPO, justifying the figures in business terms.
- Draw the dependency graph for one critical process down to third-party services, and identify the single points of failure.
- Explain why an RPO of zero is extremely expensive, and describe the architecture it demands.
- Interview-style: "Every department says their system is critical with an RTO of one hour. How do you resolve that?" Hint: force the trade-off by attaching cost to each tier and asking who funds it, and rank by quantified revenue, safety, legal, and reputational consequence rather than by assertion.
Security Controls: Preventive, Detective, Corrective
Theory
Controls are classified by when they act relative to an incident, and a mature program needs all three classes because each compensates for the limits of the others.
Preventive controls stop an incident from occurring: a locked door, a firewall rule, input validation, MFA. They are the most valuable when they work and the most dangerous to over-rely on, because their failures are silent by nature. A preventive control that has quietly stopped working looks exactly like one that is working.
Detective controls identify that something has occurred: logs, intrusion detection, file integrity monitoring, a SIEM alert, a review. They do not stop anything. Their value is bounded entirely by whether anyone responds, which is why an unmonitored alert queue provides zero security while appearing on the control inventory.
Corrective controls restore the system after an incident: restoring from backup, failing over, revoking credentials, patching the exploited flaw. Closely related are recovery controls (returning to normal operation) and compensating controls (an alternative when the primary control cannot be implemented).
Two additional types appear in certification material. Deterrent controls discourage attempts (warning banners, visible cameras), working psychologically rather than technically. Directive controls instruct behaviour (policies, signage, training).
The practical framing: prevention fails, so you need detection; detection only tells you, so you need correction.
Examples
TIME ────────────────────────────────────────────────────────────────►
before during after
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────────┐
│ DETERRENT │ │ DETECTIVE │ │ CORRECTIVE │
│ warning banner │ │ SIEM alert │ │ restore backup │
│ visible cameras │ │ IDS signature │ │ revoke credential │
├──────────────────┤ │ log review │ │ patch the flaw │
│ PREVENTIVE │ │ file integrity │ ├──────────────────────┤
│ MFA, firewall │ │ monitoring │ │ RECOVERY │
│ encryption │ └──────────────────┘ │ failover, rebuild │
│ input validation│ │ resume operations │
└──────────────────┘ └──────────────────────┘
| Scenario | Preventive | Detective | Corrective |
|---|---|---|---|
| Stolen laptop | Full-disk encryption | Asset check-in tracking | Remote wipe, re-issue |
| Phishing | Mail filtering, FIDO2 | User report, login anomaly | Credential reset, session revoke |
| Ransomware | Allowlisting, patching | EDR behavioural alert | Restore from immutable backup |
| SQL injection | Parameterized queries | WAF alert, error-rate spike | Patch, rotate DB credentials |
| Insider export | Least privilege | Volume anomaly detection | Disable account, legal action |
# Compensating control: the primary control cannot be applied, so an
# alternative achieves a comparable risk reduction and is documented as such.
compensating_control = {
"primary_control": "Patch to vendor-supported version",
"why_not_possible": "Vendor ended support; application certified only on v4",
"compensating_measures": [
"Host isolated in dedicated VLAN; no inbound except from app tier",
"Virtual patching rules at the WAF for the three known CVEs",
"File integrity monitoring with 15-minute alerting",
"Daily offline backup with quarterly restore test",
],
"residual_risk": "Medium",
"accepted_by": "CIO",
"expires": "2026-11-30", # compensating controls are temporary by design
}
Key Takeaways
- Classify controls by timing: preventive (before), detective (during), corrective (after).
- Preventive controls fail silently, which is exactly why detective controls are mandatory rather than optional.
- A detective control with no response process provides no security while still appearing in the inventory.
- Compensating controls are legitimate when documented, approved, and time-bound.
- Deterrent and directive controls act on human behaviour and are cheap, but are ineffective against determined or automated adversaries.
- Map controls across all three timings for each significant risk; gaps usually appear in correction.
🧪 Practice
- For a risk of your choosing, list one control of each type and identify which is currently weakest in your environment.
- Find a detective control in your organization and trace exactly who would act on its output, how quickly, and what happens outside business hours.
- Write a compensating control package for a system that cannot be patched, using the structure above.
- Interview-style: "Why is a preventive control alone insufficient?" Hint: discuss silent failure, the inability to verify effectiveness without detection, and the fact that you cannot respond to something you never learn about.
Administrative, Technical, and Physical Controls
Theory
The second classification axis describes how a control is implemented, and it exists to stop security programs from becoming purely technical. Combined with the timing axis above, it produces a grid that makes coverage gaps visible.
Administrative (also called managerial) controls are implemented through people and process: policies, risk assessments, background checks, training, access reviews, vendor due diligence. They are often dismissed by engineers as paperwork, but they determine whether technical controls are configured, maintained, and funded at all.
Technical (also called logical) controls are implemented in hardware and software: encryption, firewalls, MFA, EDR, logging, access control lists.
Physical controls protect the tangible environment: locks, fences, badge readers, cameras, mantraps, fire suppression, environmental monitoring. They are easy to neglect in cloud-centric organizations, yet physical access to a device typically defeats most logical controls, and the risk does not vanish when it is outsourced to a cloud provider; it is inherited, which is why provider audit reports exist.
The three categories must reinforce each other. A badge system (physical) is worthless if offboarding never revokes badges (administrative). Encryption (technical) is worthless if the key management procedure (administrative) stores the key beside the data.
Examples
│ PREVENTIVE │ DETECTIVE │ CORRECTIVE
───────────────────┼───────────────────┼───────────────────┼──────────────────
ADMINISTRATIVE │ security policy │ access review │ incident response
│ background check │ internal audit │ plan, disciplinary
│ awareness training│ log review duty │ process
───────────────────┼───────────────────┼───────────────────┼──────────────────
TECHNICAL │ MFA, encryption │ SIEM, IDS, EDR │ automated backup
│ firewall, ACLs │ file integrity │ restore, session
│ input validation │ monitoring │ revocation
───────────────────┼───────────────────┼───────────────────┼──────────────────
PHYSICAL │ locks, mantraps │ CCTV, door alarms │ fire suppression,
│ fences, guards │ visitor logs │ spare hardware
───────────────────┴───────────────────┴───────────────────┴──────────────────
Fill this grid for a real risk: empty cells are your coverage gaps.
A worked example for the risk "unauthorized access to the server room":
| Preventive | Detective | Corrective | |
|---|---|---|---|
| Administrative | Visitor escort policy, authorization list | Quarterly badge-holder review | Investigation procedure, revocation |
| Technical | Badge reader with per-door ACL | Door-open alerts, badge logs to SIEM | Immediate badge deactivation |
| Physical | Mantrap, reinforced door, rack locks | CCTV with retention | Replacement locks, re-keying |
Key Takeaways
- Administrative controls govern whether technical controls are built, maintained, and funded.
- Technical controls are enforceable and scalable but cannot compensate for absent process.
- Physical access generally defeats logical controls, so physical security remains in scope even in cloud environments.
- In cloud models, physical controls are inherited from the provider and verified through audit reports rather than implemented directly.
- Use the three-by-three grid per significant risk; empty cells are gaps, and clusters reveal over-investment.
🧪 Practice
- Complete the three-by-three grid for the risk "customer database exfiltrated by an external attacker".
- Identify a technical control in your environment that is undermined by a missing administrative process.
- For a fully cloud-hosted company, list which physical controls still apply directly and which are inherited from providers.
- Interview-style: "Our data is in the cloud, so physical security is not our problem. Do you agree?" Hint: separate the provider's data centre controls from the offices, laptops, home working environments, and removable media that remain entirely yours.
Security Awareness Training Programs
Theory
A large share of incidents begin with a person taking a reasonable-looking action. No technical control fully covers this, because the actions involved (opening an attachment, approving a login, paying an invoice) are indistinguishable from legitimate work. Awareness training exists to change the probability of those decisions.
The standard failure mode is annual compliance training: a slide deck and a quiz that satisfy an auditor and change no behaviour. Effective programs differ in three ways. They are continuous rather than annual, because recall decays within weeks. They are role-specific, because the finance team faces invoice fraud while developers face dependency confusion and malicious pull requests. And they are measured by behaviour rather than completion rate, because completion measures attendance, not capability.
The most important metric is often overlooked. Reporting rate matters more than click rate. An organization where 30% click a simulated phish but 60% report it within ten minutes is in a far better position than one where 5% click and nobody reports, because reporting triggers response while silence hides a real intrusion.
Simulated phishing must be run carefully. Punitive programs destroy reporting culture: people who fear sanction hide mistakes, which is the opposite of what defenders need. Simulations that exploit sensitive themes (fake bonus announcements, fake layoff notices) generate lasting resentment and are widely regarded as unethical. The goal is a workforce that reports quickly and without fear, not one that is afraid of email.
Examples
Metrics that matter, in order of usefulness
WEAK ────────────────────────────────────────────────────────► STRONG
completion quiz click rate reporting time-to-report
rate score on simulated rate (median minutes)
phishing
│ │ │ │ │
│ │ │ │ └─ directly bounds
│ │ │ │ attacker dwell
│ │ │ └─ turns people into sensors
│ │ └─ measures susceptibility, not resilience
│ └─ measures short-term recall only
└─ measures attendance, not security
| Audience | Primary threat | Training focus |
|---|---|---|
| All staff | Phishing, pretexting | Report first, verify out of band |
| Finance | Invoice fraud, BEC | Callback verification on bank detail changes |
| Developers | Dependency and secret exposure | Secure defaults, secret handling, review habits |
| IT administrators | Credential theft, MFA fatigue | Privileged hygiene, never approve unexpected prompts |
| Executives | Whaling, deepfake voice | Out-of-band confirmation of unusual instructions |
| Support desk | Social engineering for resets | Strict identity proofing, no exceptions under pressure |
def program_health(metrics: dict) -> list[str]:
"""Behavioural signals, not completion rates, indicate real resilience."""
findings = []
if metrics["report_rate"] < 0.30:
findings.append("Low reporting: staff are not acting as sensors.")
if metrics["median_report_minutes"] > 30:
findings.append("Slow reporting: response starts after damage is done.")
if metrics["click_rate"] < 0.02 and metrics["report_rate"] < 0.20:
# Suspiciously low clicks with low reporting usually means the
# simulation was too easy or was circulated in advance.
findings.append("Simulation likely unrealistic; increase difficulty.")
if metrics["repeat_clickers"] > 0.05:
findings.append("Concentrated risk: target coaching, not mass training.")
return findings
Key Takeaways
- Annual compliance training changes little; frequent, short, role-specific reinforcement changes behaviour.
- Reporting rate and time-to-report are better program metrics than click rate or completion.
- Punitive responses to simulation failures suppress reporting and make the organization less safe.
- Avoid simulations using emotionally sensitive pretexts; the damage to trust outlasts the lesson.
- A fast, blame-free reporting channel is itself a detective control and is often the earliest signal of a real campaign.
- Training reduces but never eliminates human error; it is a layer, not a substitute for phishing-resistant authentication.
🧪 Practice
- Design a twelve-month awareness plan with four role-specific modules and state the behavioural metric for each.
- Write the one-paragraph internal communication that follows a simulated phishing exercise, in a way that encourages reporting rather than shame.
- Explain why an organization with a 25% click rate and a 70% report rate may be safer than one with a 3% click rate and a 5% report rate.
- Interview-style: "How do you measure whether awareness training is working?" Hint: focus on behaviour change over time, especially reporting speed and repeat-clicker concentration, and address how you separate training effects from changes in simulation difficulty.
<a id="14-legal-ethical-and-professional-context"></a>
1.4 Legal, Ethical, and Professional Context
Security work is constrained by law and professional obligation in ways that most engineering is not: the same action is either a service or a crime depending entirely on authorization. This section covers the rules that define that boundary and the compliance frameworks that shape what organizations are required to do.
The content below is an educational overview, not legal advice. Computer crime, privacy, and sector rules differ substantially between jurisdictions and change frequently. Obtain qualified legal counsel for any real engagement or incident.
Computer Crime Legislation
Theory
The single concept underpinning computer crime law worldwide is authorization. Nearly every statute criminalizes access to a computer system without authorization, or in excess of the authorization granted. The technique used is largely irrelevant: there is no legal distinction between a sophisticated exploit and simply typing a URL you were not meant to visit. This is why a competent penetration tester and a criminal may perform identical keystrokes, and why written permission is the only thing separating them.
Representative statutes include the Computer Fraud and Abuse Act (CFAA) in the United States, the Computer Misuse Act 1990 in the United Kingdom, Directive 2013/40/EU as implemented in member state law (for example Article 615-ter of the Italian Criminal Code), and equivalents elsewhere. Common offence categories are unauthorized access, unauthorized access with intent to commit a further offence, unauthorized modification or impairment, and the supply of tools intended for those purposes.
Several points matter in practice. Harm is often not required: merely accessing without authorization can be an offence even if nothing is taken or broken. Terms of service have historically been used to define the boundary of authorization, a theory that the US Supreme Court narrowed in Van Buren v. United States (2021), holding that exceeding authorized access concerns areas of a system placed off limits rather than improper purpose for data one may already access. Jurisdiction is complicated: the location of the attacker, the target, and the data may invoke several legal systems at once. And dual-use tool provisions in some jurisdictions criminalize distributing tools likely to be used for offences, which has long been a concern for security researchers publishing proof-of-concept code.
Examples
The authorization boundary is the whole of the legal distinction
SAME TECHNICAL ACTION
───────────────────────────────────────────────────────────────
Scanning a host, finding an exposed admin panel, logging in with
default credentials, reading a database.
┌───────────────────────────────┐
│ Written authorization from │
│ someone empowered to grant │ ──► Penetration test
│ it, covering THIS asset, │ (lawful service)
│ THIS time window, THESE │
│ techniques │
└───────────────────────────────┘
┌───────────────────────────────┐
│ No authorization, OR │
│ authorization from someone │ ──► Criminal offence
│ without the power to grant │ in most jurisdictions
│ it, OR outside the agreed │
│ scope or window │
└───────────────────────────────┘
"I was only testing" and "I meant no harm" are motive, not authorization.
| Offence category | Typical wording | Everyday example |
|---|---|---|
| Unauthorized access | Causing a computer to perform a function with intent to secure unauthorized access | Logging in with found credentials |
| Access with further intent | Unauthorized access intending to commit another offence | Accessing to commit fraud |
| Unauthorized modification | Impairing operation or reliability of data | Defacing a site, deploying ransomware |
| Impairment of availability | Denial of service | Volumetric flooding |
| Tool supply | Making or supplying articles for use in offences | Distributing purpose-built intrusion tooling |
Risk signals that should stop you immediately during testing:
• The asset is not named in the scope document
• The IP resolves to a third-party provider you have no agreement with
• You have found real customer personal data
• A technique would degrade availability and was not pre-approved
• The engagement window has expired
• You cannot identify who authorized this in writing
Key Takeaways
- Authorization, not technique, is the legal line; identical actions are lawful or criminal depending on it.
- Many statutes require no harm or data loss for an offence to be complete.
- Authorization must come from someone with the actual authority to grant it for that specific asset.
- Cross-border activity can engage multiple jurisdictions simultaneously, including where data merely transits.
- Dual-use tool provisions mean publishing exploit code carries jurisdiction-specific legal risk.
- Good intentions provide no defence; obtain scope in writing before touching anything.
🧪 Practice
- Summarize the main computer crime statute in your own jurisdiction and list its offence categories.
- Explain why a cloud-hosted target usually requires authorization from both the customer and consideration of the provider's testing policy.
- Describe three situations during a test where you should stop and seek clarification, and what you would do with data already collected.
- Interview-style: "You discover a serious vulnerability in a company's website while browsing normally. What do you do next?" Hint: distinguish observing an issue from probing it further; discuss how additional testing without permission changes your legal position, and how you would report it safely.
Ethical Hacking and Rules of Engagement
Theory
Ethical hacking is offensive security practised under explicit authorization for a defensive purpose. What makes it ethical is not the practitioner's intention but the documented agreement that defines what may be done, to what, when, and by whom. That document is the Rules of Engagement (RoE), and it protects everyone: the client knows what will happen, and the tester has evidence of authorization if something goes wrong.
The RoE must answer a specific set of questions. Scope lists in-scope targets precisely (IP ranges, domains, applications, accounts) and, just as importantly, explicit exclusions. Timing defines the window, which matters because testing during peak business hours carries availability risk. Permitted techniques state whether social engineering, denial of service, physical intrusion, or exploitation of discovered flaws is allowed; finding a vulnerability and exploiting it are separate permissions. Handling of discovered data states what happens if the tester obtains real personal data. Emergency contacts and a stop condition define how to halt immediately. Evidence handling defines how findings and captured data are stored and destroyed.
The authorization letter (sometimes called a get-out-of-jail-free letter, misleadingly) is a signed statement from someone empowered to grant access, which the tester carries during the engagement. For third-party-hosted assets, the client's authorization may be insufficient on its own; cloud providers publish their own testing policies, and shared hosting affects other tenants.
Two professional obligations deserve emphasis. Stay in scope, even when an out-of-scope system is trivially reachable and obviously vulnerable. Report it as an observation and seek written scope extension. And do no avoidable harm: prefer the least invasive proof that demonstrates impact.
Examples
# Rules of Engagement: the operative sections, abbreviated
engagement:
client: Example Manufacturing SpA
authorized_by: Chief Technology Officer (named signatory, signed 2026-04-02)
window:
start: 2026-04-14T09:00+02:00
end: 2026-04-25T18:00+02:00
blackout: ["2026-04-18 month-end financial close"]
scope:
in_scope:
- 203.0.113.0/27 # DMZ, client-owned addresses
- app.example.com # production web application
- vpn.example.com
out_of_scope:
- 203.0.113.32/27 # shared hosting; other tenants present
- "*.partner-portal.example.com" # third-party operated
- All ICS/OT networks # safety risk; separate engagement
permitted_techniques:
network_scanning: true
exploitation_of_discovered_vulnerabilities: true # explicitly granted
privilege_escalation: true
lateral_movement: limited_to_in_scope_hosts
password_cracking_offline: true
social_engineering: false # requires separate written approval
denial_of_service: false # never implied by "exploitation"
physical_intrusion: false
data_handling:
on_encountering_personal_data: "Stop collection, record location and record
count only, notify client contact within 2 hours, do not download."
evidence_storage: "Encrypted volume, tester-controlled, deleted 30 days after
report acceptance; deletion certificate provided."
communications:
primary_contact: "Head of Infrastructure, +39 ..., available 24/7"
critical_finding_sla: "Report within 4 hours of discovery, before continuing"
stop_condition: "Either party may halt testing immediately by phone; testing
does not resume without written confirmation."
Decision flow when something unexpected appears
Discovery during testing
│
▼
Is the asset explicitly in scope? ──no──► STOP. Document only.
│ Notify client contact.
yes Request written scope change.
│
▼
Does proving impact risk availability
or touch real personal data? ──yes──► STOP. Notify. Agree the
│ minimum safe proof first.
no
▼
Proceed with the least invasive demonstration,
log timestamps and actions for the report.
Key Takeaways
- Written, specific authorization from an empowered signatory is the foundation; verbal approval is not sufficient.
- Scope must list exclusions explicitly, and testers must stay inside it regardless of temptation.
- Permission to find a vulnerability does not imply permission to exploit it, and neither implies permission to cause an outage.
- Third-party-hosted and shared infrastructure may require the provider's authorization in addition to the client's.
- Define in advance what happens on encountering real personal data, and prefer counting records to downloading them.
- Agree critical-finding reporting timelines and a stop condition before testing begins.
🧪 Practice
- Write a scope section for testing a small company's public website and VPN, including at least three explicit exclusions and your reasoning.
- Explain why "exploitation permitted" and "denial of service permitted" must be separately negotiated, with an example where exploitation risks availability.
- Draft the data handling clause for an engagement where the tester is likely to encounter health records.
- Interview-style: "Mid-test you gain domain administrator access. What do you do?" Hint: discuss immediate notification, demonstrating impact with the least invasive evidence, avoiding further lateral movement without fresh approval, and what you record for the report.
Responsible Disclosure and Bug Bounties
Theory
When a researcher finds a vulnerability in someone else's product, two interests collide. The vendor needs time to build and ship a fix. Users need to know they are at risk. Publishing immediately exposes users to attack; never publishing leaves them exposed indefinitely and removes any pressure to fix.
Coordinated vulnerability disclosure (the preferred modern term, replacing "responsible disclosure", which implied researchers who disclose otherwise are irresponsible) resolves this with a negotiated timeline. The researcher reports privately, the vendor acknowledges and remediates, and both publish after the fix is available or after an agreed deadline passes. Deadlines of 90 days are common, with shorter periods where exploitation is already observed. The deadline is what makes the process work; without it, reports can be acknowledged and ignored indefinitely.
Bug bounty programs formalize this and add payment. Their most valuable component is often not the money but the safe harbour statement: a public commitment not to pursue legal action against researchers who follow the program rules. Without safe harbour, a researcher reporting a flaw is disclosing their own potentially unlawful access to the only party able to prosecute them.
Program scope matters as much as in a penetration test. Bounty scope documents define which assets are eligible, which techniques are forbidden (typically denial of service, social engineering against staff, and physical attacks), and what must happen on encountering user data.
The security.txt standard (RFC 9116) addresses a mundane but real obstacle: researchers frequently cannot find anyone to report to, and reports sent to general contact addresses are discarded. A single well-known file removes that failure mode.
Examples
Coordinated disclosure timeline
Day 0 Day 2 Day 7 Day 45 Day 90
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
Report Vendor Vendor confirms Fix ready, Public
submitted acknow- and assigns patch released disclosure
privately ledges severity + CVE to customers + advisory
│ │
├───────────────── embargo period ─────────────────────────┤
│
Clock does not stop for vendor silence. If no fix exists by the
deadline, the researcher may publish anyway. If the flaw is being
exploited in the wild, the timeline compresses sharply.
# /.well-known/security.txt (RFC 9116)
Contact: mailto:security@example.com
Contact: https://example.com/vulnerability-report
Expires: 2027-01-31T23:59:00.000Z
Encryption: https://example.com/pgp-key.txt
Acknowledgments: https://example.com/security/hall-of-fame
Preferred-Languages: en, it
Policy: https://example.com/security/disclosure-policy
Canonical: https://example.com/.well-known/security.txt
| Model | Who may participate | Payment | Typical scope control |
|---|---|---|---|
| Coordinated disclosure | Anyone who finds a flaw | None | Vendor policy, negotiated timeline |
| Public bug bounty | Anyone | Per-finding bounty | Published scope and exclusions |
| Private bounty | Invited researchers | Per-finding bounty | Narrower scope, NDA common |
| Vulnerability disclosure program | Anyone | None; recognition only | Published policy, safe harbour |
| Penetration test | Contracted firm | Fixed fee | Contract and RoE |
Key Takeaways
- Coordinated disclosure balances user exposure against vendor remediation time through a firm deadline.
- Safe harbour language is the critical element of any disclosure program, because without it reporting is self-incrimination.
- Bug bounty scope and exclusions bind researchers exactly as rules of engagement bind testers.
- Publish a security.txt file; unreachable security contacts are a common reason flaws go unreported.
- Demanding payment in exchange for withholding details is extortion, not disclosure, regardless of framing.
- Bounties complement but never replace testing and secure development, since they only find what researchers happen to look for.
🧪 Practice
- Write a security.txt file for an organization you know, and explain the purpose of the Expires field.
- Read a major vendor's bug bounty policy and list its excluded techniques and its safe harbour wording.
- Argue for and against a strict 90-day disclosure deadline from the perspectives of a researcher, a vendor, and an enterprise customer running the software.
- Interview-style: "A researcher reports a critical flaw and says they will publish in 14 days. How do you respond?" Hint: cover acknowledging quickly, establishing a technical channel, negotiating realistically with evidence rather than legal threats, and why threatening the reporter tends to accelerate publication.
Privacy Regulations: GDPR and CCPA
Theory
Privacy law changed security engineering by making data handling a legal obligation with direct financial consequences, rather than a matter of internal policy. The two most influential regimes take different philosophical approaches, and the difference shapes system design.
The EU General Data Protection Regulation (GDPR) is a rights-based regime built on the premise that processing personal data requires justification. Its foundational concept is the lawful basis: you may not process personal data at all unless one of six bases applies (consent, contract, legal obligation, vital interests, public task, legitimate interests). Core principles include purpose limitation, data minimisation (collect only what is necessary), storage limitation, accuracy, integrity and confidentiality, and accountability. It grants individuals rights of access, rectification, erasure, portability, restriction, and objection. It applies extraterritorially to organizations targeting people in the EU regardless of where the organization sits.
The California Consumer Privacy Act as amended by the CPRA is a consumer-protection regime centred on transparency and opt-out rights, particularly the right to opt out of the sale or sharing of personal information. It generally does not require a lawful basis before processing; it requires disclosure and a mechanism to decline.
Three practical engineering obligations recur. Breach notification under GDPR requires notifying the supervisory authority within 72 hours of becoming aware of a personal data breach where risk to individuals is likely, which means detection capability and a rehearsed decision process are legal necessities, not maturity goals. Privacy by design and by default requires data protection to be built in rather than added. And data subject rights require that systems can actually find, export, and delete one person's data across every store, including backups and analytics pipelines, which is an architectural requirement most systems fail to meet if it is not designed in.
Examples
| Aspect | GDPR (EU/EEA) | CCPA/CPRA (California) |
|---|---|---|
| Model | Rights-based; processing needs justification | Consumer protection; disclose and allow opt-out |
| Basis to process | Required before processing | Not generally required |
| Consent | Freely given, specific, informed, unambiguous; opt-in | Opt-out for sale/sharing; opt-in for minors |
| Key rights | Access, rectification, erasure, portability, objection | Know, delete, correct, opt out, limit sensitive use |
| Breach notice | Authority within 72 hours; individuals if high risk | Notice to affected residents; AG in volume cases |
| Penalties | Up to 4% of global annual turnover or 20M EUR | Per-violation civil penalties, higher for minors |
| Scope trigger | Offering goods/services to or monitoring EU data subjects | Revenue or data-volume thresholds |
# Data minimisation expressed in code: collect and retain only what the
# stated purpose requires, and make retention a property of the schema.
from dataclasses import dataclass, field
from datetime import date, timedelta
@dataclass
class CustomerRecord:
# Necessary for the contract (order fulfilment)
customer_id: str
email: str
shipping_address: str
# Retained only as long as the purpose requires; enforced by a job
# that deletes expired records rather than by good intentions.
created_on: date
retention_days: int = 365 * 7 # statutory invoice retention
# Deliberately NOT collected: date of birth, gender, phone number.
# Each would need its own lawful basis and its own purpose.
@property
def delete_after(self) -> date:
return self.created_on + timedelta(days=self.retention_days)
def erasure_targets(customer_id: str) -> list[str]:
"""A right-to-erasure request must reach every store, which is why
knowing the full inventory of data locations is an architectural
requirement rather than a documentation exercise."""
return [
"primary_postgres.customers",
"primary_postgres.orders", # may be exempt: legal retention
"search_index.customers",
"analytics_warehouse.events", # pseudonymised, still in scope
"crm_saas.contacts", # processor; must be instructed
"backup_snapshots", # document the approach and timeline
"log_aggregation.access_logs", # IP addresses are personal data
]
Key Takeaways
- GDPR requires a lawful basis before processing; CCPA/CPRA focuses on disclosure and opt-out rights.
- Data minimisation is the strongest practical security control available, because data never collected cannot be breached.
- The 72-hour GDPR notification clock makes detection and a rehearsed assessment process legally necessary.
- Systems must be able to locate, export, and delete an individual's data across all stores; this must be designed in.
- IP addresses, device identifiers, and pseudonymised records are generally personal data under GDPR.
- Both regimes apply based on whose data you handle, not where your company is incorporated.
🧪 Practice
- Inventory the personal data fields collected by one application you work on and state the lawful basis and retention period for each.
- Trace what would have to happen, system by system, to fully honour an erasure request in that application, including backups.
- Write the decision checklist your team would follow in the first 24 hours after discovering possible unauthorized access to personal data.
- Interview-style: "Does encryption mean a stolen database is not a reportable breach?" Hint: consider whether the keys were also exposed, the strength and state of the encryption, and the fact that the assessment concerns risk to individuals rather than the technical control alone.
Industry Frameworks: NIST CSF, ISO 27001
Theory
Frameworks exist because designing a security program from scratch produces gaps that are obvious only in hindsight. They provide a structured, peer-reviewed checklist of what a complete program contains, and a common language for discussing maturity with auditors, insurers, and customers.
The NIST Cybersecurity Framework is a voluntary, outcome-oriented framework organized around functions. Version 2.0 (2024) uses six: Govern (added in 2.0, covering strategy, roles, and risk management decisions), Identify, Protect, Detect, Respond, and Recover. Each function contains categories and subcategories describing outcomes rather than implementations, which is why it adapts across sectors and sizes. It is descriptive and flexible, and there is no certification.
ISO/IEC 27001 specifies requirements for an Information Security Management System (ISMS): a managed, auditable process for setting objectives, assessing risk, selecting controls, and continually improving. Its distinguishing feature is certification: an accredited body audits the organization and issues a certificate, which is why it appears in procurement requirements and vendor questionnaires. The 2022 revision restructured Annex A into 93 controls across four themes (organizational, people, physical, technological).
The important point for practitioners is what each is for. The CSF is a good instrument for assessing and communicating current versus target capability, including to a non-technical board. ISO 27001 is the right choice when a certificate is commercially necessary. CIS Critical Security Controls serve a third purpose: a prioritized, prescriptive list of specific actions, which is often the most useful starting point for a small organization that needs to know what to do on Monday.
None of them makes an organization secure. They make it organized, which is a precondition. Compliance and security overlap substantially but are not the same thing, and certified organizations are breached regularly.
Examples
NIST CSF 2.0 functions
┌─────────────────────────────────────────────────────┐
│ GOVERN │
│ strategy, roles, policy, risk appetite, oversight │
│ (added in 2.0; informs all other functions) │
└─────────────────────────────────────────────────────┘
▲ ▲ ▲ ▲ ▲
┌────┴───┐ ┌────┴───┐ ┌────┴───┐ ┌────┴───┐ ┌────┴───┐
│IDENTIFY│ │PROTECT │ │ DETECT │ │RESPOND │ │RECOVER │
├────────┤ ├────────┤ ├────────┤ ├────────┤ ├────────┤
│ asset │ │ access │ │ moni- │ │ incident│ │ restore│
│ inven- │ │ control│ │ toring │ │ mgmt │ │ plans │
│ tory │ │ aware- │ │ adverse│ │ analysis│ │ comms │
│ risk │ │ ness │ │ event │ │ mitiga- │ │ improve│
│ assess │ │ data │ │ analy- │ │ tion │ │ ment │
│ supply │ │ secu- │ │ sis │ │ repor- │ │ │
│ chain │ │ rity │ │ │ │ ting │ │ │
└────────┘ └────────┘ └────────┘ └────────┘ └────────┘
| NIST CSF 2.0 | ISO/IEC 27001:2022 | CIS Controls v8 | |
|---|---|---|---|
| Nature | Outcome-based framework | Management system standard | Prioritized control list |
| Certifiable | No | Yes, by accredited bodies | No |
| Prescriptive | Low | Moderate (Annex A) | High |
| Best for | Assessing and communicating maturity | Meeting procurement and audit demands | Knowing what to implement first |
| Structure | 6 functions, categories, subcategories | Clauses 4-10 plus 93 Annex A controls | 18 controls, 3 implementation groups |
| Cost | Free | Certification and surveillance audits | Free |
A current-versus-target profile, the CSF's most practical output
Function Current Target Gap
─────────────────────────────────────────────────────────────────
GOVERN Partial ██░░░░░░░░ Risk-informed roles undefined
IDENTIFY Risk-inf. ██████░░░░ Repeatable asset inventory stale
PROTECT Repeat. ███████░░░ Adaptive no allowlisting
DETECT Partial ██░░░░░░░░ Repeatable no out-of-hours triage ◄ priority
RESPOND Partial ██░░░░░░░░ Repeatable IR plan never tested ◄ priority
RECOVER Risk-inf. █████░░░░░ Repeatable restores untested
Key Takeaways
- NIST CSF 2.0 organizes outcomes under Govern, Identify, Protect, Detect, Respond, Recover.
- ISO 27001 certifies a management system, which is why it appears in contracts and vendor assessments.
- CIS Controls are prescriptive and prioritized, making them the most actionable starting point for small teams.
- Frameworks produce organization and comparability, not security; certified organizations are still breached.
- The CSF's current-versus-target profile is an effective way to justify investment to non-technical leadership.
- Most organizations map one set of controls to several frameworks at once to avoid duplicated audit effort.
🧪 Practice
- Score an organization you know against the six CSF functions and identify the two weakest.
- Explain to a hypothetical CEO why ISO 27001 certification does not guarantee the company will not be breached.
- Take any five CIS Controls and map each to the CSF function it most supports.
- Interview-style: "A customer demands ISO 27001 certification. How do you advise leadership?" Hint: separate the commercial driver from the security benefit, and discuss timeline, scope definition, cost of surveillance audits, and what genuine improvement the ISMS would produce versus certification alone.
Sector Compliance: PCI DSS, HIPAA, SOX
Theory
Beyond general frameworks, specific sectors carry mandatory regimes tied to the kind of data or process involved. They differ from voluntary frameworks in that non-compliance carries direct, enforceable consequences, and they tend to be far more prescriptive.
PCI DSS (Payment Card Industry Data Security Standard) is a contractual requirement imposed by the card brands on anyone who stores, processes, or transmits cardholder data. It is unusually specific, mandating network segmentation, encryption, access control, logging, and regular testing. Its most important strategic lesson is scope reduction: the standard applies to the cardholder data environment, so using a payment provider's hosted fields or tokenization so that card numbers never touch your systems dramatically shrinks what must be audited. The cheapest way to comply is to handle less data.
HIPAA (Health Insurance Portability and Accountability Act) governs protected health information in the United States. Its Security Rule splits safeguards into administrative, physical, and technical categories, mapping neatly onto the control taxonomy covered earlier. Notably, many specifications are "addressable" rather than "required", meaning an entity may implement an equivalent alternative if it documents why. Business associates handling PHI on behalf of covered entities are directly liable.
SOX (Sarbanes-Oxley Act) is financial legislation, not security legislation, but Section 404 requires management to attest to the effectiveness of internal controls over financial reporting. Because those reports are produced by IT systems, SOX drives IT general controls: change management, access control, and segregation of duties around financial systems. Its security relevance is almost entirely about integrity and accountability rather than confidentiality.
The common thread is that all three ultimately demand evidence. An undocumented control that works is a finding; a documented control with retained evidence is compliance.
Examples
| PCI DSS | HIPAA | SOX | |
|---|---|---|---|
| Protects | Cardholder data | Protected health information | Financial reporting integrity |
| Applies to | Anyone handling card data | Covered entities and business associates | US public companies |
| Legal nature | Contractual (card brands) | Federal regulation | Federal law |
| CIA emphasis | Confidentiality | Confidentiality, integrity, availability | Integrity, accountability |
| Key mechanism | Prescriptive controls, segmentation | Administrative/physical/technical safeguards | ITGC: change, access, SoD |
| Consequence | Fines, higher fees, loss of ability to accept cards | Civil and criminal penalties | Executive liability, restatement |
| Validation | SAQ or QSA assessment, ASV scans | Self-assessment; OCR enforcement | External auditor attestation |
PCI scope reduction: the single highest-value architectural decision
BEFORE: card data enters your systems
┌──────────┐ PAN ┌───────────┐ PAN ┌──────────┐
│ Browser │ ────────► │ Your web │ ──────► │ Your DB │
└──────────┘ │ server │ └──────────┘
└───────────┘
In scope: web servers, app servers, database, backups, logs,
the network they sit on, and every admin who can reach them.
AFTER: tokenization / hosted fields
┌──────────┐ PAN ┌─────────────────┐
│ Browser │ ────────► │ Payment provider│ (their scope, their audit)
└────┬─────┘ └────────┬────────┘
│ │ token
│ token ▼
└────────────────► ┌───────────┐
│ Your app │ stores only a meaningless token
└───────────┘
In scope: dramatically less. The data you never hold cannot be
stolen from you, and need not be audited.
SOX IT general controls, expressed as questions an auditor will ask:
Change management
• Can you show that this production change was approved?
• Can you show the approver was not the author? ◄ SoD
Access control
• Who can modify financial data, and who approved that access?
• When was that access list last reviewed, and by whom?
Operations
• Can you demonstrate the job that produced this figure ran
successfully, and that failures would have been noticed?
Note how little of this is about attackers: SOX is about whether the
numbers can be trusted, which is an integrity and accountability problem.
Key Takeaways
- Sector regimes are mandatory and prescriptive, unlike voluntary frameworks.
- PCI DSS scope reduction through tokenization or hosted payment fields is usually the cheapest route to compliance.
- HIPAA's addressable specifications permit alternatives, but only with documented justification.
- SOX is about financial reporting integrity; its security impact is on change management, access, and segregation of duties.
- All three require retained evidence; an effective but undocumented control fails an audit.
- Compliance is a floor, not a ceiling, and organizations that treat the audit as the goal tend to be secure only at audit time.
🧪 Practice
- Describe two concrete architectural changes that would reduce PCI DSS scope for an online shop.
- Map five HIPAA Security Rule safeguards onto the administrative, technical, and physical control taxonomy.
- Explain why SOX pushes organizations toward separation of duties in deployment pipelines, with a concrete example.
- Interview-style: "We passed our PCI assessment, so we are secure. What is wrong with that statement?" Hint: address point-in-time assessment versus continuous state, the narrowness of the assessed scope, and the many risks outside cardholder data entirely.
Chain of Custody and Evidence Handling Ethics
Theory
Evidence that cannot be shown to be unaltered is evidence that can be dismissed. Chain of custody is the unbroken, documented record of who held an item of evidence, when, and what they did with it, from collection to presentation. Its purpose is to let a third party verify that the evidence presented is the same evidence collected. A technically perfect forensic finding is worthless in a legal or disciplinary proceeding if there is a gap in that record.
The core technical practice is to work on copies and prove they are identical. Acquire a bit-for-bit image using a write blocker, compute a cryptographic hash of the original and the image, verify they match, store the original untouched, and perform all analysis on a working copy whose hash you can re-verify afterwards. If the hashes match before and after analysis, the analyst can demonstrate that the examination changed nothing.
Order of volatility governs collection sequence: data that disappears soonest is collected first. CPU registers and cache, then memory, then network state and running processes, then disk, then remote logs, then archived media. This creates genuine tension, because capturing memory alters memory, and powering off destroys it entirely. The resolution is documentation: record what you did and why, accept that any live acquisition perturbs the system, and be able to explain it.
The ethical obligations are substantial. An investigator must remain objective, seeking evidence that exonerates as rigorously as evidence that implicates; competent, not performing techniques they cannot explain; and respectful of privacy, limiting examination to the authorized scope. Finding unrelated personal material does not authorize reading it. Investigators also frequently encounter situations where the organization's interest conflicts with legal obligations to report, and that conflict should be escalated rather than resolved privately.
Examples
Order of volatility: collect top to bottom
MOST VOLATILE ┌──────────────────────────────────────┐
seconds │ CPU registers, cache │
├──────────────────────────────────────┤
minutes │ RAM: processes, keys, network conns, │
│ unencrypted data, injected code │ ◄ lost on power-off
├──────────────────────────────────────┤
minutes │ Network state: ARP, routing, sockets │
├──────────────────────────────────────┤
hours-days │ Temporary files, swap, running state │
├──────────────────────────────────────┤
persistent │ Disk contents │
├──────────────────────────────────────┤
persistent │ Remote/central logs, SIEM │
├──────────────────────────────────────┤
LEAST VOLATILE │ Backups, archived media, printouts │
└──────────────────────────────────────┘
Tension: pulling the plug preserves disk state but destroys memory,
which is where encryption keys and fileless malware live. Decide
deliberately, and document the decision and its justification.
# Acquire, then prove the copy is identical to the source.
# A hardware or software write blocker must be in place before this runs.
# 1. Hash the source device before imaging
sha256sum /dev/sdb | tee source-hash.txt
# 2. Create the image, logging errors rather than silently skipping them
dd if=/dev/sdb of=evidence-2026-10-01.img bs=4M conv=noerror,sync status=progress
# 3. Hash the image and compare: equal digests show a faithful copy
sha256sum evidence-2026-10-01.img | tee image-hash.txt
# 4. Re-verify after analysis to show the working copy was not modified
sha256sum evidence-2026-10-01.img | diff - image-hash.txt && echo "INTACT"
CHAIN OF CUSTODY FORM
Case reference: IR-2026-0147
Item: Dell Latitude laptop, S/N ABC123XYZ, asset tag LT-0881
Description: Device assigned to user jdoe; seized from desk 3rd floor
Acquisition: Image evidence-2026-10-01.img
SHA-256: 9f2c...a41e (recorded at acquisition)
┌────────────┬──────────┬────────────────┬──────────────┬───────────┐
│ Date/Time │ Released │ Received by │ Purpose │ Signature │
│ (UTC) │ by │ │ │ │
├────────────┼──────────┼────────────────┼──────────────┼───────────┤
│ 2026-10-01 │ A. Rossi │ M. Bianchi │ Seizure from │ [sig] │
│ 09:14 │ (HR) │ (IR lead) │ workplace │ │
├────────────┼──────────┼────────────────┼──────────────┼───────────┤
│ 2026-10-01 │ M.Bianchi│ Evidence safe │ Secure │ [sig] │
│ 11:40 │ │ (locked, #12) │ storage │ │
├────────────┼──────────┼────────────────┼──────────────┼───────────┤
│ 2026-10-02 │ Evidence │ L. Conti │ Forensic │ [sig] │
│ 08:05 │ safe │ (examiner) │ imaging │ │
└────────────┴──────────┴────────────────┴──────────────┴───────────┘
Any unexplained gap in this table is an opening to challenge the
evidence in its entirety, regardless of the technical findings.
Key Takeaways
- Chain of custody is an unbroken documented record; a single gap can invalidate otherwise sound findings.
- Hash before and after, work only on verified copies, and keep originals untouched.
- Collect in order of volatility, but document the trade-offs made during live acquisition.
- Any live acquisition alters the system; this is acceptable when recorded and explained, and fatal when hidden.
- Investigators must be objective, competent, and scope-limited; incidental personal data must not be examined.
- Involve legal counsel early, because preservation obligations and reporting duties can attach before an investigation concludes.
🧪 Practice
- Design a chain of custody form for your organization, listing every field needed to defend the record under challenge.
- Argue both sides of pulling the power versus performing a live memory acquisition on a suspected ransomware host.
- Explain why hashing the image again after analysis matters, and what it proves that the initial hash alone does not.
- Interview-style: "During an investigation into data theft, you find evidence of unrelated misconduct. What do you do?" Hint: consider the authorized scope of your examination, who owns the decision to widen it, and why continuing to investigate on your own initiative jeopardizes both the evidence and your position.
<a id="2-background-and-tools"></a>