Secure SDLC, DevSecOps, Logging, Incident Response, Compliance & Breaches
"Incident response is now considered a critical part of cybersecurity risk management that should be integrated across organizational operations." — NIST SP 800-61 Rev. 3, Incident Response Recommendations and Considerations for Cybersecurity Risk Management, section 2.1 (April 2025)
Summary: Security is not a gate at the end of the project. It is a set of small controls at every stage (requirements, design, code, build, test, release, operate, monitor) plus a rehearsed way to react when a control fails, and a record that proves to auditors and regulators what you did. Focus: The secure software development life cycle (SSDLC) and DevSecOps shift-left controls (abuse cases, threat modelling, secret scanning, SAST, SCA, container and IaC scanning, SBOM, signing, SLSA, pipeline security with OIDC), security testing (DAST, fuzzing, pentest, bug bounty), safe releases (progressive delivery, kill switches), operations (CIS hardening, patching, rotation), security logging (what to log, what never to log, redaction, tamper-evident storage, SIEM, Sigma, alert fatigue), incident response (NIST SP 800-61 Rev. 3, severity, roles, evidence, notification windows, blameless postmortems, tabletop exercises), compliance as a design input (SOC 2, ISO 27001, PCI DSS v4, HIPAA, GDPR) and six breach case studies mapped to controls, with Go and Laravel 13 code. Learning goal: Take a service from idea to production and name, for each stage, the cheapest control that would have stopped the breaches in this chapter; write logs that help an investigator without becoming a leak; and run a first incident (declare, contain, preserve evidence, notify on time, learn) without improvising.
This chapter closes the Security group. It owns the lifecycle view and the operational loop. The mechanics of single controls live in sibling chapters and are linked in one sentence where they appear: the threat model itself in Security Foundations: CIA, Defense in Depth, STRIDE, passwords and sessions in Authentication, token internals in JWT Deep Dive, authorization in Authorization Models, TLS, PKI and secret storage in Cryptography in Practice, web vulnerabilities in OWASP Top 10, network defence in DDoS & Network Security, service identity in Mutual TLS, and metrics, logs and traces in Observability. Database-level controls are in Database Security.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why security must be a lifecycle, not a gate | Why it exists |
| NIST SSDF, SAMM, SLSA, 800-61, Equifax-era lessons | Where it comes from |
| Requirements, abuse cases, threat modelling, code controls | Shift left, Threat modelling, Secrets and code review |
| SAST, SCA, SBOM, container and IaC scanning | SAST, SCA and SBOM, Container and IaC |
| Pipeline security, OIDC, signing, SLSA, reproducible builds | Pipeline security, Signing and SLSA |
| DAST, fuzzing, pentest, bug bounty | Security testing |
| Progressive delivery, feature flags, kill switches | Release |
| Hardening, patching, rotation, WAF tuning | Operate |
| What to log and what never to log | Security logging |
| Tamper-evident storage, retention, SIEM, Sigma, alert fatigue | Storage and detection |
| NIST lifecycle, severity, roles, evidence, communications | Incident response, Roles and severity, Evidence |
| GDPR 72 hours, postmortems, playbooks, tabletop exercises | Notification, Postmortems and exercises |
| SOC 2, ISO 27001, PCI DSS v4, HIPAA, GDPR as design inputs | Compliance, DSAR and erasure |
| MTTD, MTTR, vulnerability SLAs | Metrics |
| Equifax, Capital One, SolarWinds, Log4Shell, Okta, MOVEit | Breach case studies |
| Code | Go, Laravel |
| Exact knobs and messages | Mechanics |
| Classic problems with fixes | Solving the classic problems |
| Which control first | Choosing |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The stages and the cheapest control at each. A control is cheap when it runs automatically on every change and fails the build with a clear message.
| Stage | Question it answers | Cheapest control | Tools you will meet |
|---|---|---|---|
| Requirements | What must never happen? | Abuse cases and compliance constraints written as acceptance criteria | Abuse-case stories, data classification |
| Design | Where can this be attacked? | Threat model plus security architecture review | STRIDE, data-flow diagrams |
| Code | Did we introduce a hole or leak a secret? | Pre-commit secret scanning, review checklist, secure coding standard | gitleaks, trufflehog, pre-commit |
| Build and CI | Is the code, its dependencies and its image clean? | SAST, SCA, container scan, IaC scan, SBOM, signing | Semgrep, CodeQL, gosec, PHPStan, Psalm, govulncheck, composer audit, Trivy, Grype, Checkov, tfsec, Syft, cosign |
| Test | Does it break under hostile input? | DAST, fuzzing, security unit tests, periodic pentest | OWASP ZAP, Go native fuzzing, bug bounty |
| Release | Can we limit and undo damage? | Canary, feature flags, kill switch | Argo Rollouts, Flagger, LaunchDarkly, Unleash |
| Operate | Is the platform hardened and patched? | CIS Benchmarks baseline, patch SLAs, secret rotation, WAF tuning | CIS-CAT, Ansible, ModSecurity, AWS WAF, Cloudflare WAF |
| Monitor | Would we notice an attack? | Structured security logs, SIEM detection rules, alert tuning | Splunk, Elastic, Microsoft Sentinel, Wazuh, Sigma |
| Respond | What do we do at 03:00? | Playbooks, roles, severity levels, rehearsed exercises | NIST SP 800-61 Rev. 3, PagerDuty, incident channel |
The incident clock. Numbers that appear in real obligations (check your own contracts and laws).
| Obligation | Clock | Starts when | Source |
|---|---|---|---|
| GDPR supervisory-authority notification | 72 hours, where feasible | The controller becomes aware of the breach | GDPR Art. 33(1) |
| GDPR notification to affected people | Without undue delay, when high risk | Awareness of a high-risk breach | GDPR Art. 34 |
| PCI DSS incident response | Plan must exist and be tested | Always | PCI DSS v4.x requirement 12.10 |
| HIPAA breach notification to individuals | No later than 60 days after discovery | Discovery of the breach | HIPAA Breach Notification Rule |
| Vulnerability remediation (example policy) | Critical 7 days, high 30, medium 90, low 180 | Finding is confirmed | Internal policy, not a standard |
The loop in five words. Prevent, detect, respond, recover, learn. Prevention is never complete, so the loop is the product: the better the detection and response, the smaller the blast radius of the control you missed.
Why it exists
Software is attacked through the parts nobody was looking at: a library three levels deep, a CI token, a log line, a forgotten support tool. Late security review finds some of this, but fixes found at the end cost an order of magnitude more than fixes found in design, and review at the end cannot see the pipeline, the logs or the people.
| Security as a gate at the end | Security as a lifecycle |
|---|---|
| One review before launch, by a separate team | Small automated checks on every commit, humans on the risky changes |
| Findings arrive as a long PDF | Findings arrive as failing checks with a line number |
| Developers learn about security from blockers | Developers get a standard, a checklist and fast feedback |
| Nobody owns detection after launch | Logs, rules and on-call exist before launch |
| Compliance is a yearly scramble | Evidence is a by-product of the pipeline and the logs |
An everyday picture. A building. Locks and fire doors (prevention) are designed in, not welded on after the opening. Cameras and alarms (detection) only help if someone watches them and the tape is not erased by the burglar. A fire drill (tabletop exercise) is boring until the day it saves lives. The inspector (auditor) wants to see the drill log, not hear a promise.
Three common misunderstandings, up front
- "We pass the scanner, so we are secure." Scanners find known classes of defects. Equifax, SolarWinds and Okta below were not scanner failures: they were inventory, build-system and process failures.
- "Compliance equals security." A SOC 2 report or a PCI attestation says controls existed and operated over a period. It does not say an attacker cannot get in. Treat compliance as a minimum, and design from the threat model.
- "The incident response plan is the document." The plan is the practised habit: who declares, who decides, who talks to customers, where evidence goes. An unread PDF fails at 03:00.
Where it comes from
- NIST SSDF (SP 800-218). The Secure Software Development Framework "recommends ... a core set of high-level secure software development practices that can be integrated into each SDLC implementation", because "few software development life cycle (SDLC) models explicitly address software security in detail". Its practice groups are prepare the organisation, protect the software, produce well-secured software and respond to vulnerabilities.
- OWASP SAMM and the OWASP DevSecOps Guideline. SAMM is a maturity model (governance, design, implementation, verification, operations) for measuring where you are; the DevSecOps Guideline is a vendor-neutral list of pipeline controls aimed at introducing security "without slowing delivery" with a shift-left approach.
- SLSA. Supply-chain Levels for Software Artifacts, a levelled specification (Build L0 to L3) for how builds are run and proven.
- NIST SP 800-61. Rev. 2 (2012) described a circular four-phase life cycle. Rev. 3 (April 2025) says that model fitted a time when incidents were rare and narrow, and re-bases response on the six functions of the Cybersecurity Framework (CSF) 2.0: Govern, Identify, Protect, Detect, Respond, Recover. See Incident response.
- Blameless postmortems. Popularised in Google's SRE book: "Blameless postmortems are a tenet of SRE culture."
- Regulation as a forcing function. GDPR (in force May 2018) added the 72-hour clock, PCI DSS v4.0.x tightened logging and authentication, and breach-notification laws turned incident response from an engineering habit into a legal duty.
The concept catalogue
Each block: plain words, the common misunderstanding, the definition, a timeline, real scenarios, what each product does and the fix. Products are named wherever a feature is named.
Shift left, security requirements and abuse cases Must-know
In plain words: Think about how someone would misuse a feature on the day you write its ticket, not the week before launch.
Common misunderstanding: "Shift left means developers do the security team's job." It means cheap, automated checks move earlier and the security team spends its time on design and on risky changes, instead of reading every pull request.
Definition: Shift left moves security activities toward the start of the lifecycle. SSDLC (secure software development life cycle) is the lifecycle with those activities defined at each stage. DevSecOps is the same idea applied to the delivery pipeline: security checks are pipeline jobs, owned jointly. A security requirement is a testable statement ("passwords are stored with Argon2id"). An abuse case is a user story told from the attacker's side ("as a scraper, I enumerate order ids to read other people's orders").
Ticket: "Customer can download an invoice"
1 Story : As a customer I download my invoice PDF.
2 Abuse case : As an attacker I change invoice_id in the URL to read another customer's invoice (IDOR).
3 Requirement : Every invoice read checks owner_id == session user; 404 (not 403) on mismatch.
4 Test : integration test with two users; fuzz the id parameter.
5 Log : authz.denied event with user id, resource type and id, request id.
6 Compliance : invoice contains PII, so retention 10 years, erasure blocked by tax law (document it).Real scenarios: an IDOR in an invoice download; coupon codes that stack (business-logic abuse); password reset that leaks whether an email exists; an export endpoint without pagination limit that becomes a data-theft tool; a health-data field logged in clear text.
| Product or standard | What it gives you |
|---|---|
| OWASP ASVS | A numbered list of verifiable requirements at three levels |
| OWASP SAMM | A maturity score per practice, a roadmap |
| NIST SSDF (SP 800-218) | Practice groups for producers and customers of software |
| Microsoft SDL | The older, widely copied lifecycle with required activities |
| Jira, GitHub Issues | Where abuse cases live: as acceptance criteria on the story |
Fix: put two lines in the story template, "Abuse cases" and "Data touched", and make the pull-request template ask for both.
Threat modelling and security architecture review Must-know
In plain words: Draw the system, mark where data crosses a trust boundary, and ask what can go wrong at each crossing.
Common misunderstanding: "Threat modelling is a workshop you do once." It is a short, repeated habit tied to changes: a new integration, a new data class, a new trust boundary.
Definition: A threat model is a data-flow diagram plus a list of threats (spoofing, tampering, repudiation, information disclosure, denial of service, elevation of privilege: STRIDE) and a mitigation or accepted risk for each. A security architecture review is a human review of a design against that model and the standards of the organisation (identity, secrets, encryption, logging, network zones). The method itself is taught in Security Foundations.
Design review of "new partner webhook"
1 DFD : partner -> our API gateway -> webhook service -> orders DB
2 Boundary : internet / DMZ / private network
3 S (spoofing) : who is the sender? -> HMAC signature + timestamp, reject replays
4 T (tampering) : body altered in transit? -> TLS plus signature over raw body
5 R (repudiation): can partner deny sending? -> store signature, delivery id, receipt time
6 I (disclosure) : errors leak internals? -> generic 4xx body, details only in logs
7 D (DoS) : flood? -> per-partner rate limit, body size cap
8 E (elevation) : webhook acts as admin? -> dedicated low-privilege service accountReal scenarios: adding a third-party analytics script (data exposure); opening an internal admin tool to a vendor (new trust boundary); moving a monolith table to its own service (new network path for PII); adding an LLM feature that reads user documents.
Fix: a one-page checklist per change class, and a rule "a new trust boundary or a new data class needs a review ticket".
Secrets, pre-commit scanning, coding standards and review checklists Must-know
In plain words: The cheapest breach to prevent is the one where a key is committed to Git. Catch it on the developer's laptop and again in CI.
Common misunderstanding: "I deleted the commit, so the key is gone." Git history, forks, CI caches and clones keep it. A leaked key must be revoked, not hidden.
Definition: Secret scanning matches patterns and entropy in diffs and history. Pre-commit hooks run it before a commit exists. A secure coding standard is a short, enforced rule set per language (Go: crypto/rand not math/rand for tokens, html/template not text/template for HTML, parameterised queries; PHP: Eloquent bindings, no eval, Hash::make). A code review checklist turns the standard into questions a reviewer ticks.
Leaked key timeline (why scanning at commit time matters)
T0 10:02 developer commits .env by mistake and pushes
T1 10:03 public mirror / bot scrapes the push
T2 10:05 first use of the key from an unknown address
T3 10:40 secret scanner in CI fails the PR (too late for T1)
T4 10:41 key revoked, new key issued, access logs reviewed from T0
With a pre-commit hook the commit at T0 never exists.Real scenarios: AWS keys in a public repository; a database URL in a Dockerfile layer; a Stripe key in a mobile app bundle; a token pasted in a support ticket (see Okta).
| Tool | Where it runs | Notes |
|---|---|---|
| gitleaks | Pre-commit and CI, also full history scan | Regex rules plus allowlist file |
| trufflehog | CI, history, also verifies if a credential is live | Fewer false alarms through verification |
| GitHub secret scanning and push protection | Server side, blocks the push | Partner patterns auto-revoke some tokens |
| Semgrep and gosec | CI | Find hard-coded credentials in code (gosec G101) |
| pre-commit framework | Laptop | Same config in every clone |
Review checklist (excerpt): authentication and authorization on every new route; input validated at the boundary; output encoded for its context; no secret or personal data in logs or errors; new dependency justified and pinned; new outbound call has a timeout; error paths do not reveal internals; migrations do not widen access.
Fix: .pre-commit-config.yaml with gitleaks, a CI job with the same rule file, and a runbook that says "found a key: revoke first, clean later".
SAST: Semgrep, CodeQL, gosec, PHPStan and Psalm Must-know
In plain words: A program that reads your source and flags patterns that are usually bugs: string-built SQL, weak hashes, tainted data reaching a dangerous call.
Common misunderstanding: "SAST finds all vulnerabilities, so a clean report is proof." It finds patterns it has rules for; business-logic flaws (the IDOR above) are invisible to it, and noisy rules train people to ignore it.
Definition: Static application security testing analyses code without running it. Pattern tools (Semgrep, gosec) are fast and rule-based. Data-flow tools (CodeQL) build a database of the code and query tainted flows from sources to sinks. Type analysers (PHPStan, Psalm) are not security tools by default, but their taint analysis (Psalm --taint-analysis) and strict levels remove classes of bugs.
PR pipeline, SAST step
1 checkout (full diff against base)
2 semgrep ci --config p/golang --config rules/team.yml -> findings with file:line
3 gosec ./... -> G101 hardcoded creds, G401 weak hash
4 psalm --taint-analysis -> tainted input reaches a sink
5 results to SARIF -> code scanning view; new HIGH findings block merge
6 baseline file keeps old findings quiet; new ones are never baselined silently| Tool | Language | Strength | Typical noise |
|---|---|---|---|
| Semgrep | Many (Go, PHP, JS, ...) | Easy custom rules that look like the code | Pattern matches without data flow |
| CodeQL | Go, JS, Java, C#, Python, ... (not PHP) | Deep taint tracking, queries as code | Needs a build for compiled languages |
| gosec | Go | Go-specific rules G101 to G6xx | Some false positives on test data |
| PHPStan | PHP | Types and dead code; extensions for Laravel (Larastan) | Not a security scanner on its own |
| Psalm | PHP | Taint analysis for injection and XSS | Needs annotations for custom sinks |
Fix: one team rule file (see the Semgrep snippet below), results in SARIF, severity thresholds that block only on new high findings, a weekly job for the baseline.
rules:
- id: go-slog-sensitive-attribute
languages: [go]
severity: ERROR
message: A password, token or secret is passed as a log attribute. Log an ID or a hash instead.
pattern-either:
- pattern: slog.$LEVEL(..., "password", ...)
- pattern: slog.$LEVEL(..., "token", ...)
- pattern: $LOGGER.$LEVEL(..., "password", ...)
- pattern: $LOGGER.$LEVEL(..., "token", ...)
- id: php-log-request-all
languages: [php]
severity: WARNING
message: Logging the whole request payload leaks passwords and tokens. Log selected, non-sensitive fields.
pattern-either:
- pattern: Log::$METHOD(..., $REQ->all())
- pattern: Log::$METHOD(..., request()->all())SCA, dependency policy, SBOM and the lock file Must-know
In plain words: Most of your code is other people's code. Software composition analysis checks which versions you ship and whether any has a known vulnerability.
Common misunderstanding: "A vulnerable library means I am vulnerable." Only if your code can reach the vulnerable function. govulncheck reports reachable symbols; most other SCA tools only report presence, which creates alert fatigue.
Definition: SCA matches your dependency graph to advisory databases (OSV, the Go vulnerability database, the GitHub Advisory Database, FriendsOfPHP security advisories used by composer audit). An SBOM (software bill of materials, formats CycloneDX and SPDX) is the inventory itself, produced by Syft or cyclonedx-gomod. A dependency policy is the rule set a new dependency must satisfy (license, namespace, age, maintainers, no install scripts).
New dependency arrives in a PR
1 go.mod / composer.lock changes
2 syft dir:. -o cyclonedx-json=pr.cdx.json (SBOM of the PR)
3 sbomdiff -base base.cdx.json -head pr.cdx.json -> added / removed / changed
4 policy: license allowlist, denied packages, new-namespace review
5 govulncheck ./... and composer audit --locked -> known, reachable vulnerabilities
6 result: pass, or "needs review: new dependency outside allowed namespaces"| Ecosystem | Tool | What it checks | Exit code |
|---|---|---|---|
| Go | govulncheck | Go vulnerability database; reports only vulnerabilities your code calls | Non-zero if found |
| PHP | composer audit | Advisories for locked packages; abandoned packages; flags --locked, --no-dev, --format | 1 if findings |
| Any | Grype, Trivy | Scan an SBOM, a directory or an image against several databases | --fail-on / --exit-code |
| Any | Dependabot, Renovate | Opens upgrade pull requests | n/a |
Real scenarios: the Log4Shell search ("where do we run Log4j?") answered in minutes because SBOMs existed; a typosquatted package added by a tired developer; a licence change in a transitive dependency blocking a release.
Fix: the policy checker in the Go section compares two SBOMs and enforces the allowlist.
Container and IaC scanning Important
In plain words: The image and the Terraform are code too: old base images, root users and open security groups are vulnerabilities that no source scanner sees.
Common misunderstanding: "Scanning the image once at build is enough." New CVEs appear after the build. Re-scan the registry nightly and on every deploy.
Definition: Container scanning (Trivy, Grype, Clair) lists OS packages and language libraries in an image and matches advisories. IaC scanning (Checkov, tfsec, Trivy config, KICS) evaluates Terraform, Kubernetes manifests and Dockerfiles against policy: no 0.0.0.0/0 on SSH, encryption on, no latest tag, no privileged pod.
| Check | Example finding | Tool |
|---|---|---|
| Base image CVEs | debian:11 with HIGH openssl issue | Trivy, Grype |
| Dockerfile | Runs as root, ADD from URL | Trivy config, Checkov, hadolint |
| Terraform | S3 bucket public, security group open to the world | Checkov, tfsec |
| Kubernetes | privileged: true, no resource limits, hostPath | Checkov, kube-linter, Kyverno at admission |
| Secrets in layers | A token in an earlier image layer | Trivy secret scanner |
Fix: minimal base images (distroless, Alpine, Chainguard), non-root user, read-only root filesystem, and the same policy enforced twice: in CI (fast feedback) and at admission (Kyverno, OPA Gatekeeper) in Kubernetes.
Pipeline security: tokens, runners and OIDC federation Must-know
In plain words: The CI system can deploy to production, so it is production. Do not give it passwords that live forever.
Common misunderstanding: "CI secrets are safe because they are masked in logs." GitHub itself warns that "automatic redaction is not guaranteed" and that any user with write access can read repository secrets through a workflow.
Definition: Pipeline security protects the build system: least-privilege job tokens, protected branches, reviewed workflow changes, ephemeral runners, pinned third-party actions, no secrets for fork pull requests. OIDC federation replaces long-lived cloud keys: the job asks the CI provider for a signed identity token and exchanges it with AWS, Azure or GCP for short-lived credentials tied to repository, branch and environment claims.
Long-lived key (bad) OIDC federation (good)
1 admin creates IAM user + access key 1 admin creates role trusting token.actions.githubusercontent.com
2 key stored as CI secret, valid for years 2 role condition: repo=shop/api, ref=refs/heads/main
3 anyone with write access can read it 3 job requests an OIDC token (permissions: id-token: write)
4 key leaks via log or fork 4 cloud STS returns credentials valid 15 minutes to 1 hour
5 attacker has years of access 5 a stolen token expires before it is useful| Control | GitHub Actions | GitLab CI | Why |
|---|---|---|---|
| Default token permissions | permissions: contents: read at workflow top | Job token scope limits | Least privilege per job |
| Cloud access | id-token: write plus aws-actions/configure-aws-credentials with role-to-assume | id_tokens with aud | No stored keys |
| Third-party code | Pin action to full commit SHA | Pin image digest | A moved tag cannot change your build |
| Fork PRs | No secrets, pull_request not pull_request_target | Protected variables | Fork code is untrusted |
| Runners | Ephemeral, one job each | Ephemeral executors | No cross-job residue |
# .github/workflows/secure-pipeline.yml (pin every third-party action to a full commit SHA in production)
name: secure-pipeline
on:
pull_request:
push:
branches: [main]
# Default token is read-only; each job raises only what it needs.
permissions:
contents: read
jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Secret scan (full history of the PR)
run: |
docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest detect --source /repo --redact
- name: Go vulnerabilities that are actually reachable
run: |
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
- name: SAST (gosec)
run: |
go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...
- name: PHP dependency advisories
run: composer audit --locked --no-dev --format=plain
- name: IaC scan (Checkov)
run: |
pip install checkov
checkov -d infra --quiet
- name: Generate SBOM (Syft, CycloneDX JSON)
run: |
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin
syft dir:. -o cyclonedx-json=pr.cdx.json
- name: Dependency policy and SBOM diff
run: go run ./cmd/sbomdiff -base base.cdx.json -head pr.cdx.json -policy policy.json
release:
needs: checks
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # lets the job request an OIDC token; no cloud keys are stored
packages: write
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Cloud login via OIDC federation (no long-lived access key)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::111122223333:role/ci-release
aws-region: eu-west-1
- name: Build image
run: docker build -t registry.example.com/shop/api:${{ github.sha }} .
- name: Scan image (Trivy), fail on HIGH and CRITICAL
run: |
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:latest \
image --exit-code 1 --severity HIGH,CRITICAL registry.example.com/shop/api:${{ github.sha }}
- name: Push and sign keyless (cosign)
run: |
docker push registry.example.com/shop/api:${{ github.sha }}
cosign sign --yes registry.example.com/shop/api:${{ github.sha }}Signing, provenance, SLSA and reproducible builds Important
In plain words: Prove that the thing running in production was built from the source you reviewed, by the pipeline you trust, and was not swapped on the way.
Common misunderstanding: "A signed image is a safe image." A signature proves who built it, not that the code is good. The compromised SolarWinds updates were, by widespread public reporting, validly signed (inference; not stated on the CISA page).
Definition: cosign (Sigstore) signs container images; keyless signing binds a short-lived certificate to an OIDC identity and records the event in the Rekor transparency log. Provenance is a signed statement of how an artifact was built (builder, source, parameters). SLSA v1.0 Build track: L0 no guarantees, L1 provenance exists, L2 hosted build platform, L3 hardened builds, where "forging the provenance or evading verification requires exploiting a vulnerability that is beyond the capabilities of most adversaries". A reproducible build gives byte-identical output from the same source, so an independent party can check the artifact (Go supports -trimpath and a stable toolchain; reproducibility also needs pinned inputs and no timestamps).
Release with verification
1 CI (hardened, OIDC) builds image@sha256:abc...
2 syft -> SBOM; cosign attest --predicate sbom.json image (attached to the image)
3 cosign sign --yes image (keyless, logged in Rekor)
4 registry stores image + signature + attestation
5 admission controller (Kyverno, Sigstore policy-controller): verify signature and issuer
6 unsigned or wrongly-signed image -> admission denied| SLSA Build level | Promise | Practical meaning |
|---|---|---|
| L0 | None | Local builds, no records |
| L1 | Provenance exists | Pipeline produces provenance, easy to forge |
| L2 | Hosted build platform | Provenance signed by the platform, not by your job |
| L3 | Hardened builds | Isolated builds, signing keys unreachable from build steps |
Security testing: DAST, fuzzing, pentest and bug bounty Important
In plain words: Attack your own running system before someone else does, using machines for breadth and humans for cleverness.
Common misunderstanding: "We did a pentest last year, so we are tested." The system changed on the next deploy. A pentest is a sample taken at one time.
Definition: DAST (OWASP ZAP, Burp Suite) crawls and attacks a running application from outside. Fuzzing feeds generated inputs to code and watches for crashes or invariant violations; Go has it built in since Go 1.18 ("coverage guidance to intelligently walk through the code being fuzzed"). Security unit tests encode abuse cases. A pentest is a time-boxed human attack with a report. A bug bounty (HackerOne, Bugcrowd, a private programme) pays external researchers per valid finding and needs a triage process and a disclosure policy (security.txt).
| Technique | Finds | Misses | When |
|---|---|---|---|
| DAST (ZAP baseline) | Missing headers, reflected XSS, exposed paths | Logic flaws behind login unless scripted | Every deploy to staging |
Fuzzing (Go go test -fuzz) | Parser panics, injection through odd bytes | Business logic | Parsers, decoders, validators; nightly |
| Security unit tests | Regressions of known abuse cases | Unknown cases | Every PR |
| Pentest | Chained flaws, logic, config | Anything not in scope | Yearly and on big changes |
| Bug bounty | Variety, fresh eyes | Needs triage staff | After basics are clean |
Go native fuzzing loop
1 f.Add(seed corpus) seed inputs from real traffic and past bugs
2 go test -fuzz=FuzzScrub mutate inputs guided by coverage
3 failure found writes testdata/fuzz/FuzzScrub/<hash>
4 go test (no -fuzz) replays the saved input as a normal regression test
5 commit the testdata file the bug can never return silentlyRelease: progressive delivery, feature flags and kill switches Important
In plain words: Ship to 1 percent, watch, then widen. Keep a switch that turns the risky thing off without a deploy.
Common misunderstanding: "Rolling back the deploy is the kill switch." A rollback takes minutes and may not undo data changes; a flag flips in seconds.
Definition: Progressive delivery (canary, blue-green, ring deployment) exposes a change to a growing share of traffic with automatic abort on bad signals (Argo Rollouts, Flagger, Spinnaker). A feature flag decouples deploy from release (LaunchDarkly, Unleash, Laravel Pennant). A kill switch is a flag whose purpose is emergency disablement of a feature or an integration.
Risky payment feature
1 deploy with flag payments.new_gateway = off
2 enable for staff accounts, then 1 percent of traffic
3 watch error rate, auth failures, fraud signals for 30 minutes
4 suspicious spike -> flip kill switch (seconds), no deploy needed
5 investigate with the audit log; fix; repeat from step 2| Mechanism | Time to disable | Data side effects undone? |
|---|---|---|
| Rollback deploy | Minutes | No |
| Feature flag kill switch | Seconds | No (stops new writes) |
Maintenance mode (Laravel artisan down) | Seconds | No (stops all traffic) |
| WAF rule | Seconds to minutes | No (blocks a request shape) |
Operate: hardening, patch management, rotation and WAF tuning Important
In plain words: Production drifts. Keep a known-good baseline, patch on a clock, change secrets on a schedule and after every doubt.
Common misunderstanding: "Patching is an ops chore." Equifax shows patching is a security control with an owner, an inventory and a deadline.
Definition: Hardening is configuring systems below defaults to remove attack surface, usually against the CIS Benchmarks (consensus configuration guides for Linux, Kubernetes, cloud providers, PostgreSQL and many more; scored with CIS-CAT). Patch management is inventory, prioritisation (CVSS plus exploitation evidence such as the CISA Known Exploited Vulnerabilities catalogue), rollout and verification. Secret rotation replaces credentials regularly and immediately after suspected exposure (HashiCorp Vault dynamic secrets, AWS Secrets Manager rotation, Kubernetes external secrets). WAF tuning moves a web application firewall (ModSecurity with the OWASP Core Rule Set, AWS WAF, Cloudflare WAF) from log-only to blocking after reviewing false positives.
WAF rollout without breaking customers
1 deploy rules in count/log-only mode for 7 days
2 review matched requests; add exclusions for legitimate API fields
3 switch high-confidence rules (SQLi, known exploits) to block
4 keep lower-confidence rules in log mode and feed them to the SIEM
5 emergency virtual patch: a temporary rule that blocks a new exploit while code is fixed| Area | Baseline | Cadence |
|---|---|---|
| OS and base images | CIS Benchmark level 1 | Rebuild weekly |
| Dependencies | govulncheck, composer audit green | Every build and nightly |
| Cloud secrets | Dynamic or rotated | 30 to 90 days, immediately on exposure |
| TLS certificates | Automated renewal (ACME) | Alert at 30 days; an expired certificate blinded Equifax's inspection tool |
| Admin access | MFA, just-in-time, session recording | Review quarterly |
Security logging: what to log, what never to log Must-know
In plain words: Log who did what to which thing and whether it worked. Never log the keys to the building.
Common misunderstanding: "More logging is always safer." Logs are copied to many systems with weaker access control and long retention. A password in a log is a breach waiting for a log-reader.
Definition: Security logging records events that let you detect and reconstruct an attack: authentication, authorization failures, privilege changes, admin actions, input validation failures, configuration changes. Structured logs are machine-readable (JSON, key-value) with stable field names. PII redaction masks personal data and secrets before the line leaves the process. OWASP's Logging Cheat Sheet has a section "Data to exclude" for exactly this.
One request, three log lines (all share request_id)
1 {"event":"auth.failed","user_hash":"9f2c...","ip":"203.0.113.10","reason":"bad_password","request_id":"r-81"}
2 {"event":"auth.failed","user_hash":"9f2c...","ip":"203.0.113.10","reason":"bad_password","request_id":"r-82"}
3 {"event":"auth.locked","user_hash":"9f2c...","ip":"203.0.113.10","threshold":5,"request_id":"r-86"}
Never: the password, the reset token, the Authorization header, the full card number, raw e-mail in free text.| Log it | Never log it | Log instead |
|---|---|---|
| Login success, failure, MFA result | Passwords, OTP codes | User id or keyed hash of the identifier |
| Authorization denied | Session ids, bearer tokens, cookies | Token id (jti) or last 4 characters |
| Privilege and role changes, admin actions | API keys, private keys | Key id |
| Input validation failures | Full request bodies in bulk | Field name and rule, not the value |
| Payment events | Full card number, CVV | Last 4, token reference |
| Data export and bulk reads | Raw health or ID-document data | Record count, resource type |
| Attribute | Why | Example |
|---|---|---|
| When (UTC, RFC 3339) | Correlation across services | 2026-11-26T10:14:03Z |
| Who (actor id) | Accountability | user:481, svc:billing |
| What (event name) | Detection rules key on it | auth.failed |
| Where (source IP, service, host) | Scoping | 203.0.113.10 |
| Outcome | Success versus attempt | denied |
| Request id and trace id | Join logs, traces, audit | r-81 |
Log injection and forging: user text containing a newline can fake a second log line. Escape control characters (the Go handler below does) or use JSON, which quotes them.
Tamper-evident storage, retention, SIEM, Sigma and alert fatigue Must-know
In plain words: Attackers delete logs. Ship them off the box at once, store a copy nobody can edit, and write rules that turn lines into alarms people trust.
Common misunderstanding: "We have a SIEM, so we have detection." A SIEM is a search engine until someone writes, tests and tunes detection rules. An untuned one produces thousands of alerts and none is read.
Definition: Append-only or WORM (write once, read many) storage accepts new records and refuses edits and deletes (S3 Object Lock in compliance mode, Azure immutable blob storage, PostgreSQL privileges plus a trigger). Tamper-evident means edits are detectable even if possible, typically by a hash chain: each entry commits to the hash of the previous one, so changing or removing an entry breaks every later hash, and the latest hash is kept somewhere else. Retention is how long logs live, set by law and by need (PCI DSS keeps audit-log history for at least twelve months with three months immediately available; many SOC 2 audits sample a 12-month window). A SIEM (Splunk, Elastic Security, Microsoft Sentinel, Wazuh, Google SecOps) collects, normalises, correlates and alerts. Sigma is a vendor-neutral YAML rule format that compiles to the query language of each SIEM. Detection engineering treats rules as code: versioned, tested against recorded attack data, with an owner. Alert fatigue is the state in which responders stop reading alerts because most are false or low value.
Detection rule lifecycle
1 hypothesis : "break-glass freeze outside a declared incident is suspicious"
2 Sigma rule : logsource laravel/audit, selection event=incident.freeze
3 test : replay a recorded fixture; expect one hit
4 deploy : compile to SPL (Splunk), KQL (Sentinel) or Lucene (Elastic)
5 tune : weekly review of false positives; add allowlist for game days
6 metrics : precision, time to triage, alert volume per analyst per shift| SIEM or platform | Query language | Notes |
|---|---|---|
| Splunk | SPL | Commercial; Enterprise Security app for detections |
| Elastic Security | KQL, EQL, ESQL | Open core; detection rules in a public repository |
| Microsoft Sentinel | KQL | Cloud native on Azure; analytics rules |
| Wazuh | Rules in XML, dashboards on OpenSearch | Open source; agent-based, file integrity monitoring |
| Sigma | YAML, converted by sigma-cli or pySigma | Portable rules; thresholds use correlation rules |
title: Application break-glass maintenance freeze outside an incident
id: 8b1f2c1e-7a53-4e6e-9a0c-5d0f3c1a2b77
status: experimental
description: The incident:freeze command ran. Expected only during a declared incident; page the on-call security engineer to confirm.
logsource:
product: laravel
service: audit
detection:
selection:
event: incident.freeze
condition: selection
falsepositives:
- Planned game day or tabletop exercise
level: high
tags:
- attack.impactFix for alert fatigue: every alert needs an owner, a runbook link and an expected action; delete or demote alerts that nobody acted on in 30 days; page only on symptoms with user impact or confirmed compromise. The paging philosophy is in Alerting That Actually Works.
Incident response: the NIST SP 800-61 life cycle Must-know
In plain words: Be ready, notice, stop the bleeding, clean up, get back to normal, and learn. In that order, with one person in charge.
Common misunderstanding: "Incident response is the security team's job after a breach." Rev. 3 treats it as part of risk management across the organisation; engineers, legal, support and communications all have parts.
Definition: SP 800-61 Rev. 2 had four phases: preparation, detection and analysis, containment, eradication and recovery, post-incident activity. Rev. 3 (April 2025) re-bases response on the CSF 2.0 functions: Govern, Identify and Protect are preparation and are "not part of the incident response itself", while Detect, Respond and Recover are the response; improvement (ID.IM) runs through everything and lessons "should often be shared as soon as they are identified, not delayed until after recovery concludes".
First hour of a suspected credential leak
1 10:14 SIEM alert: token-in-log rule fires; on-call acknowledges
2 10:20 triage: real credential, still valid; declare SEV2, name incident commander
3 10:25 contain: revoke the token, block the principal, keep the evidence
4 10:40 preserve: snapshot affected log index to write-once evidence bucket, record hashes
5 11:00 scope: query access logs for every use since the first appearance
6 11:30 decide: personal data involved? start the 72-hour clock at awareness (10:20)
7 next day eradicate (remove source), recover (reissue secrets), review (blameless postmortem)| Phase (Rev. 2 name) | Rev. 3 functions | Typical actions |
|---|---|---|
| Preparation | Govern, Identify, Protect | Policy, asset inventory, logging, backups, contacts, exercises |
| Detection and analysis | Detect | Alerts, triage, scoping, severity decision |
| Containment, eradication, recovery | Respond, Recover | Isolate, revoke, remove cause, restore, verify |
| Post-incident activity | Improvement (ID.IM) | Postmortem, actions, rule and standard updates |
Severity levels, roles and communications Must-know
In plain words: Decide in advance what "bad" means and who is in charge, so nobody argues at 03:00.
Common misunderstanding: "The most senior engineer should lead the incident." The incident commander coordinates; they usually should not be the person typing fixes.
Definition: Severity levels map impact to response: who is paged, how fast, who is told. The incident commander (IC) owns decisions and the timeline. The ops lead fixes. The communications lead writes updates for staff, customers and regulators. The scribe records timestamps. Legal and privacy decide notification duties. Communications use templates so a message under pressure is accurate.
| Severity | Example | Response time | Who joins | Update cadence |
|---|---|---|---|---|
| SEV1 | Confirmed breach of customer personal data, production outage | Page immediately, 24x7 | IC, ops, comms, legal, executive sponsor | Every 30 minutes |
| SEV2 | Credential exposure, active attack contained | Within 15 minutes | IC, ops, security | Hourly |
| SEV3 | Vulnerability exploitable but no evidence of use | Same business day | Owning team, security | Daily |
| SEV4 | Low-risk finding, policy violation | Backlog with SLA | Owning team | On closure |
Customer message template (first update, SEV1)
1 What we know : "On 2026-11-26 we detected unauthorised access to X."
2 What it affects : "Data types: ...; number of affected customers: under investigation."
3 What we did : "We revoked the access and are preserving evidence."
4 What you should do: "Rotate your API keys; no action needed for passwords."
5 Next update : "By 14:00 UTC, then every hour."
Rules: facts only, no speculation, no blame, one spokesperson, legal reviewed.Evidence preservation and forensics basics Important
In plain words: Before you clean, copy. Fixing a machine destroys the story of how it was broken.
Common misunderstanding: "Reimage first, ask questions later." That erases memory, timestamps and files you need to know what was taken (and to prove it to a regulator).
Definition: Evidence preservation is capturing volatile and persistent data in a defensible way: a chain of custody (who held it, when), hashes (SHA-256) of each copy, write-once storage, working only on copies. Order of volatility: memory, network connections, processes, disk, remote logs, backups. NIST SP 800-61r3 recommends (R1 under RS.AN) to "collect and retain evidence from an incident in accordance with the organization's evidence preservation procedures and data retention policies", and notes that formal chain-of-custody "might not be performed for every incident" but collected incident data is still evidence.
Compromised web host, minimum forensic sequence
1 isolate network (security group change), do NOT power off
2 capture memory (LiME, AVML) and write its SHA-256
3 snapshot disk volume (cloud snapshot), mount read-only elsewhere
4 export logs: host, load balancer, cloud trail, application, to evidence bucket (Object Lock)
5 record chain of custody: who, when, tool, hash
6 only then terminate and rebuild the instance from a clean imageNotification windows, legal duties and the 72-hour clock Must-know
In plain words: In many places the law starts a stopwatch when you become aware of a breach of personal data. You must be able to answer "what data, whose, how many" fast.
Common misunderstanding: "We have 72 hours to finish the investigation." You have 72 hours to notify, with what you know; GDPR allows the notice to be given in phases.
Definition: GDPR Art. 33(1): "the controller shall without undue delay and, where feasible, not later than 72 hours after having become aware of it, notify the personal data breach to the supervisory authority ... unless the personal data breach is unlikely to result in a risk to the rights and freedoms of natural persons." Art. 33(2): "Where the notification to the supervisory authority is not made within 72 hours, it shall be accompanied by reasons for the delay." A processor must notify the controller "without undue delay". Art. 34 adds communication to affected individuals when the risk is high.
| Regime | Who is told | Window | Trigger |
|---|---|---|---|
| GDPR Art. 33 | Supervisory authority | 72 hours where feasible | Awareness of a personal data breach likely to cause risk |
| GDPR Art. 34 | Data subjects | Without undue delay | High risk |
| HIPAA Breach Notification Rule | Individuals, HHS, sometimes media | 60 days from discovery at the latest | Breach of unsecured protected health information |
| PCI DSS | Acquirer and card brands per contract | Contractual, usually immediate | Suspected cardholder-data compromise |
| Contracts and SOC 2 | Customers | Often 24 to 72 hours | Contract clause |
Blameless postmortems, runbooks, playbooks and tabletop exercises Must-know
In plain words: Write down what happened and why the system allowed it, never who to punish. Practise before it is real.
Common misunderstanding: "Blameless means nobody is accountable." It means accountability is for fixing the system and finishing the actions. Google's SRE book: a blamelessly written postmortem "assumes that everyone involved in an incident had good intentions and did the right thing with the information they had."
Definition: A postmortem is a written review: timeline, impact, root causes and contributing factors, what went well, what went badly, action items with owners and dates. A runbook is the step list for one task ("rotate the database password"). A playbook sequences decisions and roles for a class of incident ("credential leak", "ransomware"). A tabletop exercise walks the team through a scripted scenario with no systems touched; a game day injects real faults (see Chaos Engineering).
# Playbook: suspected credential leak in logs or a public repository
trigger: secret scanner alert, third-party report or SIEM rule "token-in-log"
severity_default: SEV2
roles: [incident_commander, ops_lead, comms_lead, scribe]
steps:
- id: declare
do: Open an incident channel, name an incident commander, start the timeline (UTC).
- id: contain
do: Revoke or rotate the credential first. Block the principal; do not delete evidence.
- id: preserve
do: Snapshot affected logs and disks to the evidence bucket (write-once), record hashes and who touched them.
- id: scope
do: Query access logs for every use of the credential since first exposure.
- id: decide_notify
do: Legal and privacy decide whether personal data is involved; start the 72-hour GDPR clock at awareness.
- id: eradicate
do: Remove the leak source (log line, repo history, ticket attachment); add a scanner rule that would have caught it.
- id: recover
do: Reissue credentials through the secret manager; verify clients; lift temporary blocks.
- id: review
do: Blameless postmortem within 5 working days; actions get an owner and a due date. Tabletop agenda (90 minutes)
1 00:00 facilitator reads inject 1: "SIEM shows 4 GB leaving the reporting server at 02:10"
2 00:10 team states: severity, who is IC, first three actions
3 00:30 inject 2: "Legal says 12,000 EU customers may be in that file"
4 00:40 team states: notification decision, evidence steps, customer message draft
5 01:10 inject 3: "A journalist emails for comment"
6 01:20 debrief: gaps in contacts, access, runbooks; each gap becomes a ticket with an ownerCompliance as a design input: SOC 2, ISO 27001, PCI DSS v4, HIPAA, GDPR Must-know
In plain words: Rules about what you must be able to show. Design them in; collect the proof from the pipeline instead of screenshots.
Common misunderstanding: "Compliance is paperwork for the legal team." Each framework turns into engineering requirements: logging, access reviews, encryption, change control, retention, deletion.
Definition: SOC 2 is an AICPA attestation against the Trust Services Criteria: Security (the common criteria), Availability, Processing Integrity, Confidentiality, Privacy. Type I examines design at a date; Type II examines operation over a period. ISO/IEC 27001:2022 certifies an information security management system (ISMS), with Annex A controls grouped in four themes: Organizational, People, Physical, Technological. PCI DSS v4.0.x protects cardholder data (twelve requirements; 6 for secure systems and software, 10 for logging and monitoring, 11 for testing, 12 for policy including an incident response plan). HIPAA regulates protected health information in the United States (Privacy, Security and Breach Notification Rules; administrative, physical and technical safeguards). GDPR regulates personal data of people in the EU.
| Framework | Scope | Evidence an engineer provides | Design consequence |
|---|---|---|---|
| SOC 2 Type II | Service organisations | Access reviews, change tickets, alerts and responses over 6 to 12 months | Everything must be logged and reproducible |
| ISO 27001 Annex A | Organisation-wide ISMS | Risk register, controls, internal audit | Risk-based control selection |
| PCI DSS v4.x | Systems storing, processing or transmitting card data | Segmentation, log retention, vulnerability scans, pentests | Shrink scope with tokenisation (see Payment Processing) |
| HIPAA | Covered entities and business associates | Access logs, encryption, BAAs, risk analysis | Audit every access to health records |
| GDPR | Personal data of data subjects in the EU | Records of processing, DPIAs, breach register | Minimise, limit purpose, support erasure |
| GDPR principle (Art. 5) | Engineering meaning |
|---|---|
| Data minimisation | Do not collect or log what you do not need; truncate and hash |
| Purpose limitation | A log used for security is not a marketing dataset |
| Storage limitation | Retention periods enforced by jobs, not intentions |
| Integrity and confidentiality | Encryption, access control, tamper-evident audit logs |
| Accountability | Be able to show all of the above |
DSARs and erasure in logs, backups and event logs Important
In plain words: A person can ask what you hold about them and ask you to delete it. Your logs, backups and event streams must not make that impossible.
Common misunderstanding: "Append-only logs and erasure are incompatible, so we cannot comply." Keep personal data out of immutable stores (use pseudonymous ids), or encrypt per subject and delete the key (crypto-shredding).
Definition: A DSAR (data subject access request) asks for a copy of one person's data (GDPR Art. 15). The right to erasure (Art. 17) requires deletion "without undue delay" in listed cases, with exceptions such as legal obligations. In practice: log pseudonymous ids, keep a lookup table you can delete, set short retention on raw logs, expire backups on a schedule and document that backups age out, and in event-sourced or Kafka systems store personal fields in an erasable store or encrypt them per subject. See Event Sourcing & CQRS and Message Design & Schema Evolution.
Erasure in an event-sourced system
1 event: CustomerRegistered{customer_id=42, name_ref=k42} (name lives in vault under key k42)
2 DSAR erasure request for customer 42 is verified and logged (audit)
3 vault deletes key k42 and the encrypted name blob (crypto-shredding)
4 events stay immutable; replays show "[erased]" for the name
5 logs contain only customer_id=42 (pseudonymous); log retention 30 days removes the rest
6 backups containing the old data expire by schedule; the policy documents thatMetrics: MTTD, MTTR and vulnerability SLAs Important
In plain words: Numbers that show whether you are getting faster at noticing and fixing.
Common misunderstanding: "A lower MTTR proves the team is better." Mean values hide the long tail, and counting only detected incidents flatters MTTD. Report medians and percentiles, and track undetected-until-external-report cases separately.
Definition: MTTD is mean time to detect (first malicious event to detection). MTTR is mean time to respond or recover (detection to containment or resolution; say which). A vulnerability SLA is the maximum time to remediate by severity. Also useful: vulnerability age, percentage of services with an SBOM, percentage of pipelines on OIDC, alert precision, and percentage of exercises with all actions closed.
| Metric | Formula | Why | Pitfall |
|---|---|---|---|
| MTTD | detected_at minus started_at | Detection quality | started_at comes from forensics, often unknown at first |
| MTTR | resolved_at minus detected_at | Response quality | Define "resolved" (contained, or fully recovered) |
| Vulnerability SLA compliance | Findings closed within SLA divided by findings | Patch discipline | Closing by risk-accept hides debt |
| Alert precision | True positives divided by alerts | Alert fatigue | Needs labelled outcomes |
| Dwell time | First compromise to eviction | Attacker advantage | Equifax: about 76 days |
| Severity (example policy) | Remediation SLA | Condition |
|---|---|---|
| Critical or known exploited | 7 days (hours if internet-facing and exploited) | CVSS 9 and above, or listed in the CISA KEV catalogue |
| High | 30 days | CVSS 7 to 8.9 |
| Medium | 90 days | CVSS 4 to 6.9 |
| Low | 180 days or accepted risk | CVSS below 4 |
-- MTTD and MTTR by severity, plus how many incidents beat the response target
SELECT severity,
count(*) AS incidents,
avg(detected_at - started_at) AS mttd,
avg(resolved_at - detected_at) AS mttr,
count(*) FILTER (WHERE resolved_at - detected_at <= interval '4 hours') AS within_4h
FROM incidents
WHERE resolved_at IS NOT NULL
GROUP BY severity
ORDER BY severity;Breach case studies
Each study cites its primary source (fetched and saved); anything else is labelled inference. The point is the mapping from failure to control.
| Breach | Primary source | What happened (as the source states) | Control that would have mattered |
|---|---|---|---|
| Equifax 2017 | GAO-18-559 | Attackers accessed personal information of "at least 145.5 million individuals"; the Apache Struts vulnerability had been publicly identified two days before the first scan on 10 March 2017; the notice went to an out-of-date recipient list; a scan did not find the vulnerable portal; an expired certificate stopped traffic inspection for about ten months; databases were not segmented; attack lasted about 76 days | Asset inventory and patch SLA, certificate expiry monitoring, network segmentation, detection coverage tests |
| Capital One 2019 | Capital One incident page; public court filings | Capital One states an outside individual gained access, that a "configuration vulnerability" was reported through its Responsible Disclosure Program on 17 July 2019 and that it found the incident on 19 July. Widely reported mechanism: a server-side request forgery (SSRF) against a misconfigured web application firewall used to reach cloud metadata credentials (inference from public reporting; not in the saved Capital One page) | IMDSv2 and least-privilege roles, egress filtering, WAF configuration review, anomaly detection on cloud API use |
| SolarWinds 2020 | CISA Emergency Directive 21-01 | Orion versions 2019.4 through 2020.2.1 HF1 were "currently being exploited by malicious actors"; CISA wrote that disconnecting affected devices "is the only known mitigation measure currently available" and required agencies to act | Hardened, verifiable builds (SLSA L3), build-system monitoring, egress control from management servers, vendor risk assessment |
| Log4Shell 2021 | CISA guidance; Apache Log4j security page | CVE-2021-44228 in Log4j 2.0-beta9 to 2.14.1: JNDI message lookups "do not protect against adversary-controlled LDAP [...] and other JNDI related endpoints"; the 2.15.0 fix was incomplete in some configurations (CVE-2021-45046) | SBOM to find usage in minutes, SCA with runtime reachability, egress filtering, WAF virtual patching |
| Okta 2023 | Okta Security root-cause post | From 28 September to 17 October 2023 a threat actor accessed files in the customer support system for 134 customers; HAR files contained session tokens used to hijack 5 customers' sessions; a service account credential saved in a personal Google profile on a managed laptop; for 14 days "Okta did not identify suspicious downloads in our logs" because the download used a different log event | Scrub HAR files before upload, service-account hardening and device policy, audit-log coverage of every access path, customer-side token binding |
| MOVEit 2023 | CISA advisory AA23-158A | From 27 May 2023 CL0P exploited a "previously unknown SQL injection vulnerability (CVE-2023-34362)" in MOVEit Transfer, installing the LEMURLOOT web shell to steal data from databases | Parameterised queries and SAST on the vendor side; for customers: external attack surface inventory, data minimisation and retention on file-transfer servers, web-shell detection |
Equifax 2017 (GAO-18-559)
The GAO report lists four factors named by Equifax: identification, detection, segmentation and data governance. Quote on detection: "an expired digital certificate contributed to the attackers' ability to communicate with compromised servers and steal data without detection." Lesson: a control that fails silently (the certificate) is worse than none, because everyone believes it works. Monitor your monitors.
Capital One 2019
The company's page confirms the timeline (report 17 July, discovery 19 July) and that the attacker was caught. The SSRF-to-metadata chain is the commonly reported path (inference). Lessons that hold either way: require IMDSv2 (session-oriented metadata access, which AWS documents), scope instance roles to what the workload needs, and alert on unusual use of cloud credentials from outside the instance.
SolarWinds 2020
Lesson: the build pipeline is a target and signed software can still be malicious. Controls: build isolation and provenance (SLSA L3), reproducible builds that an independent party can compare, tight egress rules for management software, and an inventory that lets you answer "which of our hosts run this product?" the same day.
Log4Shell 2021
Lesson: a logging library parsed attacker-controlled text and could be told to fetch code. Controls: SBOM and SCA to find every copy (including vendors' products), upgrade quickly, restrict outbound connections from servers (a callback to an attacker's LDAP server is blocked by egress policy), and treat log content as untrusted input.
Okta 2023
Lesson: support systems hold customer secrets. Controls: scrub or reject uploads that contain tokens (HAR files), isolate service accounts, require managed-device and personal-profile separation, and make sure every way of reading a file produces the same audit event. The 14-day detection gap was a logging design flaw, not a missing tool.
MOVEit 2023
Lesson: internet-facing file-transfer appliances keep large amounts of data and are mass-exploited in campaigns (CISA notes earlier campaigns against Accellion FTA and Fortra GoAnywhere). Controls: know your external attack surface, limit retention on transfer servers, segment them, and ship their logs to the SIEM with web-shell detection rules.
Mechanics
Exact knobs
| Knob | Where | Meaning |
|---|---|---|
permissions: id-token: write | GitHub Actions job | Allows the job to request an OIDC token |
permissions: contents: read | GitHub Actions workflow | Read-only default token |
role-to-assume | aws-actions/configure-aws-credentials | IAM role trusted through OIDC |
govulncheck ./... | Go CI | Source mode, reports reachable vulnerabilities |
govulncheck -mode=binary app | Go CI | Scans a built binary |
composer audit --locked --no-dev --format=json | PHP CI | Audit lock file only, production deps, machine-readable |
trivy image --exit-code 1 --severity HIGH,CRITICAL | Container CI | Fail the job on severe findings |
cosign sign --yes | Release job | Keyless signing with Sigstore |
go test -fuzz=FuzzX -fuzztime=30s | Go | Run a fuzz target for a duration |
slog.HandlerOptions.ReplaceAttr | Go | Rewrite attributes before output |
'tap' => [Class::class] | Laravel config/logging.php channel | Customise the Monolog instance |
'days' => 400 | Laravel daily channel | Retention of rotated files |
'permission' => 0640 | Laravel single/daily channel | Log file permissions |
php artisan down --secret=... --retry=60 --render=errors::503 | Laravel | Maintenance mode with bypass token |
S3 Object Lock (compliance mode) | AWS S3 | Nobody, even root, can delete before retention ends |
Messages and codes you will see
| Message or code | Where | Meaning and action |
|---|---|---|
Vulnerability #1: GO-2024-XXXX | govulncheck | A called symbol is vulnerable; upgrade the module shown in "Fixed in" |
Found N security vulnerability advisories affecting M packages | composer audit | Exit code 1; update or document the exception |
G101: Potential hardcoded credentials | gosec | Move the secret to configuration or a secret manager |
HIGH: CVE-... (fixed in x.y.z) | Trivy, Grype | Rebuild with the fixed package |
Error: Not authorized to perform sts:AssumeRoleWithWebIdentity | AWS via OIDC | The role trust policy does not match repository, branch or audience claim |
Error: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable | GitHub Actions | Missing id-token: write permission |
no matching signatures | cosign verify | The image was not signed by the expected identity; do not deploy |
fuzz: elapsed ... new interesting | Go fuzzing | Progress; failures write to testdata/fuzz |
HTTP 503 with Retry-After | Laravel maintenance mode | Expected during break-glass |
42501 audit_log is append-only | PostgreSQL trigger | Insufficient-privilege SQLSTATE raised by the immutability trigger |
The cost of late fixes
A fixed unit of work is cheaper early. The commonly quoted multipliers are folklore of uncertain origin and should not be cited as fact; the direction is certain and you can measure your own: compare time from "finding created" to "finding closed" for issues found in PR checks versus in production. In most organisations the PR-time median is minutes to hours and the production median is days, plus customer impact.
Go
The module academy/secure-sdlc-incident-response uses only the standard library. redact is an slog.Handler that masks secrets and PII with a fuzz test; auditchain is a tamper-evident hash chain; policy and cmd/sbomdiff are the CI policy checker; before is the naive logging.
Before
Three habits that put credentials in logs and allow forged lines.
// Before: the logging habits that turn a log pipeline into a second database of secrets.
package main
import (
"log"
"net/http"
)
func login(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
// BAD: the whole form (password included) goes to the log line.
log.Printf("login attempt form=%v", r.PostForm)
// BAD: the bearer token is logged, so anyone with log access can replay it.
log.Printf("auth header=%s", r.Header.Get("Authorization"))
// BAD: user input is written raw, so a newline forges a second log line.
log.Printf("user=%s failed", r.PostForm.Get("email"))
w.WriteHeader(http.StatusUnauthorized)
}
func main() {
http.HandleFunc("/login", login)
log.Fatal(http.ListenAndServe(":8080", nil))
}After
The redacting handler wraps any slog.Handler. It masks values by key name, scrubs free text (bearer tokens, JWTs, e-mail addresses, Luhn-valid card numbers), neutralises newlines, resolves LogValuer values first and offers a Secret type that cannot print itself.
// Package redact wraps any slog.Handler so secrets and PII never reach the sink.
package redact
import (
"context"
"log/slog"
"regexp"
"strings"
)
// Mask replaces every redacted value.
const Mask = "[REDACTED]"
// sensitiveKeys are matched case-insensitively against attribute keys (substring).
var sensitiveKeys = []string{
"password", "passwd", "secret", "token", "authorization", "cookie",
"api_key", "apikey", "private_key", "ssn", "card", "cvv", "otp",
}
var (
bearerRe = regexp.MustCompile(`(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}`)
jwtRe = regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*`)
emailRe = regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`)
panRe = regexp.MustCompile(`\b\d(?:[ -]?\d){12,18}\b`)
)
// Scrub removes bearer tokens, JWTs, e-mail addresses and card numbers from free text
// and neutralises line breaks (log forging).
func Scrub(s string) string {
s = strings.NewReplacer("\r", `\r`, "\n", `\n`).Replace(s)
s = bearerRe.ReplaceAllString(s, "$1 "+Mask)
s = jwtRe.ReplaceAllString(s, Mask)
s = emailRe.ReplaceAllString(s, Mask)
s = panRe.ReplaceAllStringFunc(s, func(m string) string {
if luhnValid(m) {
return Mask
}
return m
})
return s
}
func luhnValid(s string) bool {
sum, double, n := 0, false, 0
for i := len(s) - 1; i >= 0; i-- {
c := s[i]
if c == ' ' || c == '-' {
continue
}
d := int(c - '0')
if double {
if d *= 2; d > 9 {
d -= 9
}
}
sum += d
double = !double
n++
}
return n >= 13 && n <= 19 && sum%10 == 0
}
func sensitiveKey(k string) bool {
k = strings.ToLower(k)
for _, s := range sensitiveKeys {
if strings.Contains(k, s) {
return true
}
}
return false
}
// Handler redacts attributes before delegating to the wrapped handler.
type Handler struct {
next slog.Handler
groups []string
}
// New wraps next.
func New(next slog.Handler) *Handler { return &Handler{next: next} }
func (h *Handler) Enabled(ctx context.Context, l slog.Level) bool { return h.next.Enabled(ctx, l) }
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
nr := slog.NewRecord(r.Time, r.Level, Scrub(r.Message), r.PC)
r.Attrs(func(a slog.Attr) bool {
nr.AddAttrs(clean(a))
return true
})
return h.next.Handle(ctx, nr)
}
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
out := make([]slog.Attr, len(attrs))
for i, a := range attrs {
out[i] = clean(a)
}
return &Handler{next: h.next.WithAttrs(out), groups: h.groups}
}
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{next: h.next.WithGroup(name), groups: append(append([]string{}, h.groups...), name)}
}
func clean(a slog.Attr) slog.Attr {
a.Value = a.Value.Resolve() // run LogValuer first so hidden fields are seen
if sensitiveKey(a.Key) {
return slog.String(a.Key, Mask)
}
switch a.Value.Kind() {
case slog.KindString:
return slog.String(a.Key, Scrub(a.Value.String()))
case slog.KindGroup:
g := a.Value.Group()
out := make([]any, len(g))
for i, ga := range g {
out[i] = clean(ga)
}
return slog.Group(a.Key, out...)
case slog.KindAny:
if err, ok := a.Value.Any().(error); ok {
return slog.String(a.Key, Scrub(err.Error()))
}
}
return a
}
// Secret is a value type that can never print its content, even through %v or slog.
type Secret string
func (Secret) String() string { return Mask }
func (Secret) LogValue() slog.Value { return slog.StringValue(Mask) }
func (Secret) GoString() string { return Mask }
func (s Secret) Reveal() string { return string(s) }Tests prove each leak is blocked, including groups and With attributes:
package redact
import (
"bytes"
"context"
"fmt"
"log/slog"
"strings"
"testing"
)
func newLogger(buf *bytes.Buffer) *slog.Logger {
return slog.New(New(slog.NewJSONHandler(buf, nil)))
}
func TestSensitiveKeysAreMasked(t *testing.T) {
var buf bytes.Buffer
newLogger(&buf).Info("login", "email_hash", "ab12", "password", "hunter2", "Authorization", "Bearer abcdefgh12345")
out := buf.String()
for _, leak := range []string{"hunter2", "abcdefgh12345"} {
if strings.Contains(out, leak) {
t.Fatalf("leaked %q in %s", leak, out)
}
}
if !strings.Contains(out, `"email_hash":"ab12"`) {
t.Fatalf("safe attribute lost: %s", out)
}
}
func TestFreeTextIsScrubbed(t *testing.T) {
tests := []struct{ name, in, leak string }{
{"bearer", "got header Bearer abcdefghijkl", "abcdefghijkl"},
{"jwt", "token eyJhbGciOi.eyJzdWIiOiIx.sig123", "eyJzdWIiOiIx"},
{"email", "user bob@example.com failed", "bob@example.com"},
{"pan", "card 4111 1111 1111 1111 declined", "4111 1111 1111 1111"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var buf bytes.Buffer
newLogger(&buf).Warn(tc.in)
if strings.Contains(buf.String(), tc.leak) {
t.Fatalf("leaked %q: %s", tc.leak, buf.String())
}
})
}
}
func TestNonLuhnNumberIsKept(t *testing.T) {
if got := Scrub("order 1234567890123"); strings.Contains(got, Mask) {
t.Fatalf("order number wrongly masked: %s", got)
}
}
func TestLogForgingNeutralised(t *testing.T) {
var buf bytes.Buffer
slog.New(New(slog.NewTextHandler(&buf, nil))).Info("x", "user", "a\nlevel=ERROR msg=forged")
if strings.Count(buf.String(), "\n") != 1 {
t.Fatalf("newline survived: %q", buf.String())
}
}
func TestGroupsAndWithAttrs(t *testing.T) {
var buf bytes.Buffer
l := newLogger(&buf).With("api_key", "k-123456").WithGroup("req")
l.Info("call", slog.Group("hdr", slog.String("cookie", "sid=abc")))
out := buf.String()
if strings.Contains(out, "k-123456") || strings.Contains(out, "sid=abc") {
t.Fatalf("leak: %s", out)
}
}
func TestSecretType(t *testing.T) {
s := Secret("topsecret")
for _, got := range []string{fmt.Sprint(s), fmt.Sprintf("%v %s %#v", s, s, s)} {
if strings.Contains(got, "topsecret") {
t.Fatalf("Secret printed itself: %s", got)
}
}
var buf bytes.Buffer
newLogger(&buf).Info("x", "value", s)
if strings.Contains(buf.String(), "topsecret") {
t.Fatalf("slog leaked Secret: %s", buf.String())
}
if s.Reveal() != "topsecret" {
t.Fatal("Reveal must return the value")
}
}
func TestEnabledDelegates(t *testing.T) {
h := New(slog.NewJSONHandler(&bytes.Buffer{}, &slog.HandlerOptions{Level: slog.LevelError}))
if h.Enabled(context.Background(), slog.LevelInfo) {
t.Fatal("info must be disabled")
}
}The fuzz test asserts two properties for any input: no line break survives, and scrubbing twice equals scrubbing once.
package redact
import (
"strings"
"testing"
)
// FuzzScrub checks two properties for any input: no panic, and no line break survives.
// Run: go test ./redact -fuzz=FuzzScrub -fuzztime=30s
func FuzzScrub(f *testing.F) {
seeds := []string{
"", "plain text", "Bearer abcdefghijkl", "4111-1111-1111-1111",
"a\r\nlevel=ERROR", "eyJhbGciOi.eyJzdWIiOiIx.sig", "user@example.com",
}
for _, s := range seeds {
f.Add(s)
}
f.Fuzz(func(t *testing.T, in string) {
out := Scrub(in)
if strings.ContainsAny(out, "\r\n") {
t.Fatalf("line break survived: %q -> %q", in, out)
}
if Scrub(out) != out {
t.Fatalf("not idempotent: %q -> %q -> %q", in, out, Scrub(out))
}
})
}The tamper-evident chain:
// Package auditchain is a tamper-evident, append-only audit log: every entry commits to
// the hash of the previous entry, so editing or deleting any past entry breaks Verify.
package auditchain
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
)
// Entry is one audit record.
type Entry struct {
Seq uint64 `json:"seq"`
Time time.Time `json:"time"`
Actor string `json:"actor"`
Action string `json:"action"`
Target string `json:"target"`
PrevHash string `json:"prev_hash"`
Hash string `json:"hash"`
}
// ErrBroken is returned when the chain does not verify.
var ErrBroken = errors.New("audit chain broken")
// Log is an in-memory chain; production code writes each entry to WORM storage as well.
type Log struct {
mu sync.Mutex
entries []Entry
now func() time.Time
}
// New creates an empty chain.
func New() *Log { return &Log{now: time.Now} }
func digest(e Entry) string {
h := sha256.New()
fmt.Fprintf(h, "%d|%d|%s|%s|%s|%s", e.Seq, e.Time.UnixNano(), e.Actor, e.Action, e.Target, e.PrevHash)
return hex.EncodeToString(h.Sum(nil))
}
// Append adds an entry and returns it.
func (l *Log) Append(actor, action, target string) Entry {
l.mu.Lock()
defer l.mu.Unlock()
e := Entry{Seq: uint64(len(l.entries)), Time: l.now().UTC(), Actor: actor, Action: action, Target: target}
if n := len(l.entries); n > 0 {
e.PrevHash = l.entries[n-1].Hash
}
e.Hash = digest(e)
l.entries = append(l.entries, e)
return e
}
// Entries returns a copy.
func (l *Log) Entries() []Entry {
l.mu.Lock()
defer l.mu.Unlock()
return append([]Entry(nil), l.entries...)
}
// Verify recomputes every hash and link. head is the last hash you stored out of band
// (for example in a separate account); without it, truncating the tail goes unnoticed.
func Verify(entries []Entry, head string) error {
prev := ""
for i, e := range entries {
if e.Seq != uint64(i) || e.PrevHash != prev || digest(e) != e.Hash {
return fmt.Errorf("%w at seq %d", ErrBroken, i)
}
prev = e.Hash
}
if head != "" && prev != head {
return fmt.Errorf("%w: head mismatch (tail truncated?)", ErrBroken)
}
return nil
}package auditchain
import (
"errors"
"testing"
)
func build() *Log {
l := New()
l.Append("alice", "login", "console")
l.Append("alice", "break-glass", "prod-db")
l.Append("bob", "role-grant", "carol")
return l
}
func TestVerifyOK(t *testing.T) {
l := build()
es := l.Entries()
if err := Verify(es, es[len(es)-1].Hash); err != nil {
t.Fatal(err)
}
}
func TestEditDetected(t *testing.T) {
es := build().Entries()
es[1].Actor = "mallory"
if err := Verify(es, ""); !errors.Is(err, ErrBroken) {
t.Fatalf("want ErrBroken, got %v", err)
}
}
func TestDeleteMiddleDetected(t *testing.T) {
es := build().Entries()
es = append(es[:1], es[2:]...)
if err := Verify(es, ""); !errors.Is(err, ErrBroken) {
t.Fatalf("want ErrBroken, got %v", err)
}
}
func TestTailTruncationNeedsHead(t *testing.T) {
es := build().Entries()
head := es[len(es)-1].Hash
short := es[:2]
if err := Verify(short, ""); err != nil {
t.Fatalf("without a stored head truncation is invisible, got %v", err)
}
if err := Verify(short, head); !errors.Is(err, ErrBroken) {
t.Fatalf("with a stored head truncation must be caught, got %v", err)
}
}The CI policy checker compares two CycloneDX SBOMs, enforces a license allowlist, a denied-package list and a namespace rule for new dependencies:
// Package policy checks a CycloneDX-style SBOM against a dependency allowlist and diffs two SBOMs.
package policy
import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
)
// Component is the subset of a CycloneDX component this tool needs.
type Component struct {
Name string `json:"name"`
Version string `json:"version"`
PURL string `json:"purl"`
Licenses []struct {
License struct {
ID string `json:"id"`
} `json:"license"`
} `json:"licenses"`
}
// SBOM is a minimal CycloneDX document.
type SBOM struct {
Components []Component `json:"components"`
}
// Policy lists what is allowed.
type Policy struct {
AllowedLicenses []string `json:"allowed_licenses"`
DeniedPackages []string `json:"denied_packages"`
// AllowNewPrefixes: new dependencies must start with one of these purl prefixes.
AllowNewPrefixes []string `json:"allow_new_prefixes"`
}
// Parse reads an SBOM.
func Parse(r io.Reader) (SBOM, error) {
var s SBOM
dec := json.NewDecoder(io.LimitReader(r, 64<<20))
if err := dec.Decode(&s); err != nil {
return s, fmt.Errorf("parse sbom: %w", err)
}
return s, nil
}
func key(c Component) string {
if c.PURL != "" {
if i := strings.LastIndex(c.PURL, "@"); i > 0 {
return c.PURL[:i]
}
return c.PURL
}
return c.Name
}
// Diff is the change between two SBOMs.
type Diff struct {
Added, Removed []string
Changed []string // "name old -> new"
}
// Compare returns what changed from base to head.
func Compare(base, head SBOM) Diff {
b, h := map[string]string{}, map[string]string{}
for _, c := range base.Components {
b[key(c)] = c.Version
}
for _, c := range head.Components {
h[key(c)] = c.Version
}
var d Diff
for k, v := range h {
ov, ok := b[k]
switch {
case !ok:
d.Added = append(d.Added, k+"@"+v)
case ov != v:
d.Changed = append(d.Changed, fmt.Sprintf("%s %s -> %s", k, ov, v))
}
}
for k, v := range b {
if _, ok := h[k]; !ok {
d.Removed = append(d.Removed, k+"@"+v)
}
}
sort.Strings(d.Added)
sort.Strings(d.Removed)
sort.Strings(d.Changed)
return d
}
// Check returns one violation message per problem; empty means the change is allowed.
func Check(p Policy, d Diff, head SBOM) []string {
var out []string
for _, a := range d.Added {
for _, den := range p.DeniedPackages {
if strings.Contains(a, den) {
out = append(out, "denied package added: "+a)
}
}
ok := len(p.AllowNewPrefixes) == 0
for _, pre := range p.AllowNewPrefixes {
if strings.HasPrefix(a, pre) {
ok = true
}
}
if !ok {
out = append(out, "new dependency outside allowed namespaces (needs review): "+a)
}
}
allowed := map[string]bool{}
for _, l := range p.AllowedLicenses {
allowed[l] = true
}
for _, c := range head.Components {
if len(p.AllowedLicenses) == 0 {
break
}
if len(c.Licenses) == 0 {
out = append(out, fmt.Sprintf("%s@%s has no declared license", c.Name, c.Version))
continue
}
for _, l := range c.Licenses {
if !allowed[l.License.ID] {
out = append(out, fmt.Sprintf("%s@%s license %q not allowed", c.Name, c.Version, l.License.ID))
}
}
}
sort.Strings(out)
return out
}package policy
import (
"strings"
"testing"
)
const baseJSON = `{"components":[
{"name":"gin","version":"1.9.0","purl":"pkg:golang/github.com/gin-gonic/gin@1.9.0","licenses":[{"license":{"id":"MIT"}}]},
{"name":"old","version":"1.0.0","purl":"pkg:golang/example.com/old@1.0.0","licenses":[{"license":{"id":"MIT"}}]}]}`
const headJSON = `{"components":[
{"name":"gin","version":"1.10.0","purl":"pkg:golang/github.com/gin-gonic/gin@1.10.0","licenses":[{"license":{"id":"MIT"}}]},
{"name":"evil","version":"0.0.1","purl":"pkg:npm/evil-left-pad@0.0.1","licenses":[{"license":{"id":"AGPL-3.0-only"}}]},
{"name":"nolic","version":"2.0.0","purl":"pkg:golang/github.com/acme/nolic@2.0.0"}]}`
func load(t *testing.T, s string) SBOM {
t.Helper()
b, err := Parse(strings.NewReader(s))
if err != nil {
t.Fatal(err)
}
return b
}
func TestCompare(t *testing.T) {
d := Compare(load(t, baseJSON), load(t, headJSON))
if len(d.Added) != 2 || len(d.Removed) != 1 || len(d.Changed) != 1 {
t.Fatalf("unexpected diff: %+v", d)
}
if !strings.Contains(d.Changed[0], "1.9.0 -> 1.10.0") {
t.Fatalf("version change lost: %v", d.Changed)
}
}
func TestCheck(t *testing.T) {
head := load(t, headJSON)
d := Compare(load(t, baseJSON), head)
p := Policy{
AllowedLicenses: []string{"MIT", "Apache-2.0", "BSD-3-Clause"},
DeniedPackages: []string{"evil-left-pad"},
AllowNewPrefixes: []string{"pkg:golang/github.com/acme/"},
}
v := strings.Join(Check(p, d, head), "\n")
for _, want := range []string{"denied package added", "outside allowed namespaces", "AGPL-3.0-only", "no declared license"} {
if !strings.Contains(v, want) {
t.Errorf("missing violation %q in:\n%s", want, v)
}
}
}
func TestCleanChangePasses(t *testing.T) {
base := load(t, baseJSON)
if v := Check(Policy{AllowedLicenses: []string{"MIT"}}, Compare(base, base), base); len(v) != 0 {
t.Fatalf("unchanged SBOM must pass, got %v", v)
}
}
func TestParseRejectsGarbage(t *testing.T) {
if _, err := Parse(strings.NewReader("{not json")); err == nil {
t.Fatal("want error")
}
}// Command sbomdiff fails a CI job when an SBOM change violates the dependency policy.
//
// sbomdiff -base main.cdx.json -head pr.cdx.json -policy policy.json
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"academy/secure-sdlc-incident-response/policy"
)
func load(path string) (policy.SBOM, error) {
f, err := os.Open(path)
if err != nil {
return policy.SBOM{}, err
}
defer f.Close()
return policy.Parse(f)
}
func run() int {
base := flag.String("base", "", "SBOM of the base branch (CycloneDX JSON)")
head := flag.String("head", "", "SBOM of the pull request (CycloneDX JSON)")
pol := flag.String("policy", "", "policy JSON file")
flag.Parse()
if *base == "" || *head == "" || *pol == "" {
flag.Usage()
return 2
}
b, err := load(*base)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
h, err := load(*head)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
raw, err := os.ReadFile(*pol)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 2
}
var p policy.Policy
if err := json.Unmarshal(raw, &p); err != nil {
fmt.Fprintln(os.Stderr, "policy:", err)
return 2
}
d := policy.Compare(b, h)
fmt.Printf("added=%d removed=%d changed=%d\n", len(d.Added), len(d.Removed), len(d.Changed))
violations := policy.Check(p, d, h)
for _, v := range violations {
fmt.Println("VIOLATION:", v)
}
if len(violations) > 0 {
return 1
}
return 0
}
func main() { os.Exit(run()) }The policy file the pipeline passes to it:
{
"allowed_licenses": ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC"],
"denied_packages": ["event-stream", "colors"],
"allow_new_prefixes": ["pkg:golang/github.com/", "pkg:golang/golang.org/", "pkg:composer/"]
}The Go angle
log/slog(Go 1.21) separates the front end (Logger) from the back end (Handler). A wrapper handler is the supported extension point;HandlerOptions.ReplaceAttris a lighter hook but sees only leaf attributes and cannot scrub the message.LogValuerlets a type decide how it is logged. TheSecrettype returns a mask, so even a developer who writesslog.Info("x", "k", secret)cannot leak it.govulncheckis reachability-aware: it reports a vulnerability only when your code calls the vulnerable symbol (source mode) or when the binary contains it (binary mode), which keeps alert volume low.- Native fuzzing (
go test -fuzz) is part of the toolchain since Go 1.18; saved failures undertestdata/fuzzbecome permanent regression tests thatgo testruns without the-fuzzflag. - A run of
go test ./redact -fuzz=FuzzScrub -fuzztime=15son the development machine executed about 565,000 inputs without a failure (one run, not a proof).
Laravel
Laravel 13 logging is built on Monolog. Channels are configured in config/logging.php; a tap array lets a class customise the Monolog instance after creation; Log::withContext() adds context to every later entry of the current request and Log::shareContext() shares it across channels.
Before
The same mistake in PHP: dumping the request into the log.
// BAD: every password, token and card field in the request lands in the log
Log::info('login attempt', request()->all());
Log::debug('headers', request()->headers->all());After
A Monolog processor that masks keys and scrubs text, attached to channels with tap:
<?php
namespace App\Logging;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
final class RedactingProcessor implements ProcessorInterface
{
private const SENSITIVE_KEYS = [
'password', 'passwd', 'secret', 'token', 'authorization', 'cookie',
'api_key', 'apikey', 'private_key', 'ssn', 'card', 'cvv', 'otp',
];
public function __invoke(LogRecord $record): LogRecord
{
return $record->with(
message: $this->scrub($record->message),
context: $this->walk($record->context),
extra: $this->walk($record->extra),
);
}
/** @param array<string|int, mixed> $data */
private function walk(array $data): array
{
foreach ($data as $key => $value) {
if (is_string($key) && $this->sensitiveKey($key)) {
$data[$key] = '[REDACTED]';
} elseif (is_array($value)) {
$data[$key] = $this->walk($value);
} elseif (is_string($value)) {
$data[$key] = $this->scrub($value);
} elseif ($value instanceof \Throwable) {
$data[$key] = $this->scrub($value->getMessage());
}
}
return $data;
}
private function sensitiveKey(string $key): bool
{
$key = strtolower($key);
foreach (self::SENSITIVE_KEYS as $needle) {
if (str_contains($key, $needle)) {
return true;
}
}
return false;
}
private function scrub(string $text): string
{
$text = str_replace(["\r", "\n"], ['\r', '\n'], $text);
$text = preg_replace('/\b(bearer|basic)\s+[A-Za-z0-9._~+\/=-]{8,}/i', '$1 [REDACTED]', $text) ?? $text;
$text = preg_replace('/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/', '[REDACTED]', $text) ?? $text;
$text = preg_replace('/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/', '[REDACTED]', $text) ?? $text;
return $text;
}
}<?php
namespace App\Logging;
use Illuminate\Log\Logger;
/**
* Register on a channel in config/logging.php:
* 'single' => ['driver' => 'single', 'path' => storage_path('logs/laravel.log'),
* 'tap' => [App\Logging\RedactingTap::class]],
*/
class RedactingTap
{
public function __invoke(Logger $logger): void
{
foreach ($logger->getHandlers() as $handler) {
$handler->pushProcessor(new RedactingProcessor());
}
}
}A separate audit channel with 400-day retention and restrictive file permissions, and JSON output on stderr for the application log:
<?php
// config/logging.php (excerpt). The audit channel is separate from the app log, daily,
// kept 400 days, and shipped to append-only storage by the log agent.
use App\Logging\RedactingTap;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\JsonFormatter;
return [
'default' => env('LOG_CHANNEL', 'stack'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['stderr_json'],
'ignore_exceptions' => false,
],
'stderr_json' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'handler_with' => ['stream' => 'php://stderr'],
'formatter' => JsonFormatter::class,
'tap' => [RedactingTap::class],
],
'audit' => [
'driver' => 'daily',
'path' => storage_path('logs/audit.log'),
'level' => 'info',
'days' => 400,
'permission' => 0640,
'tap' => [RedactingTap::class],
],
],
];An audit subscriber for authentication events. It logs a keyed hash of the identifier, never the password or the raw e-mail:
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Log;
/**
* Audit trail for authentication events. Never logs the password, the token or the raw e-mail:
* only a keyed hash of the identifier so analysts can correlate without storing PII.
* Register: Event::subscribe(AuditAuthSubscriber::class) in a service provider.
*/
class AuditAuthSubscriber
{
public function onLogin(Login $event): void
{
$this->write('auth.login', $event->user?->getAuthIdentifier(), $event->guard);
}
public function onFailed(Failed $event): void
{
$identifier = $event->credentials['email'] ?? $event->credentials['username'] ?? '';
$this->write('auth.failed', null, $event->guard, ['identifier_hash' => $this->hash((string) $identifier)]);
}
public function onLogout(Logout $event): void
{
$this->write('auth.logout', $event->user?->getAuthIdentifier(), $event->guard);
}
public function onPasswordReset(PasswordReset $event): void
{
$this->write('auth.password_reset', $event->user->getAuthIdentifier(), 'web');
}
public function subscribe(Dispatcher $events): array
{
return [
Login::class => 'onLogin',
Failed::class => 'onFailed',
Logout::class => 'onLogout',
PasswordReset::class => 'onPasswordReset',
];
}
/** @param array<string, scalar> $extra */
private function write(string $event, int|string|null $userId, string $guard, array $extra = []): void
{
Log::channel('audit')->info($event, [
'event' => $event,
'user_id' => $userId,
'guard' => $guard,
'ip' => request()->ip(),
'request_id' => request()->headers->get('X-Request-Id'),
...$extra,
]);
}
private function hash(string $value): string
{
return hash_hmac('sha256', strtolower($value), (string) config('app.key'));
}
}Security headers as middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
$response->headers->set(
'Content-Security-Policy',
"default-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
);
return $response;
}
}Break-glass maintenance mode with an audited bypass secret:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* Incident "break-glass": put the app in maintenance mode with a bypass secret for responders,
* and write who did it to the audit channel. Lift with: php artisan up
*/
class BreakGlassFreeze extends Command
{
protected $signature = 'incident:freeze {incident : Incident id, e.g. INC-2026-0042} {--retry=120}';
protected $description = 'Emergency maintenance mode with an audited bypass secret';
public function handle(): int
{
$secret = Str::random(40);
Artisan::call('down', [
'--secret' => $secret,
'--retry' => (int) $this->option('retry'),
'--render' => 'errors::503',
]);
Log::channel('audit')->warning('incident.freeze', [
'incident' => $this->argument('incident'),
'operator' => (string) (getenv('USER') ?: 'unknown'),
'bypass_secret_set' => true, // the secret itself is never logged
]);
// Show the secret once on the operator's terminal; hand it over through the incident channel.
$this->line("Maintenance mode on. Responder bypass path: /{$secret}");
return self::SUCCESS;
}
}A wrapper around composer audit for local use (CI calls composer audit --locked directly):
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
/**
* Local wrapper around `composer audit` that fails on any advisory and prints a short summary.
* In CI call `composer audit --locked --format=json` directly.
*/
class ComposerAuditCommand extends Command
{
protected $signature = 'security:audit';
protected $description = 'Fail when composer.lock contains packages with security advisories';
public function handle(): int
{
$process = new Process(['composer', 'audit', '--locked', '--format=json']);
$process->setTimeout(120);
$process->run();
$report = json_decode($process->getOutput(), true) ?: [];
$advisories = $report['advisories'] ?? [];
foreach ($advisories as $package => $items) {
foreach ($items as $item) {
$this->error(sprintf('%s: %s (%s)', $package, $item['title'] ?? 'advisory', $item['cve'] ?? 'no CVE'));
}
}
// composer exits non-zero when advisories exist; mirror that to the caller.
return $process->isSuccessful() ? self::SUCCESS : self::FAILURE;
}
}And the SQL that makes the application's audit table append-only plus the MTTD/MTTR query:
-- PostgreSQL: an audit table that the application role can only append to.
CREATE TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id text NOT NULL,
action text NOT NULL,
target text NOT NULL,
request_id text,
prev_hash bytea,
row_hash bytea NOT NULL
);
-- The app role may INSERT and SELECT, never UPDATE or DELETE.
REVOKE ALL ON audit_log FROM app_rw;
GRANT INSERT, SELECT ON audit_log TO app_rw;
-- Belt and braces: even the table owner cannot rewrite history through SQL by accident.
CREATE FUNCTION audit_log_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'audit_log is append-only (% blocked)', TG_OP USING ERRCODE = '42501';
END $$;
CREATE TRIGGER audit_log_no_update_delete
BEFORE UPDATE OR DELETE OR TRUNCATE ON audit_log
FOR EACH STATEMENT EXECUTE FUNCTION audit_log_immutable();
-- Metrics: mean time to detect and resolve, by severity, from an incidents table.
CREATE TABLE incidents (
id text PRIMARY KEY,
severity smallint NOT NULL CHECK (severity BETWEEN 1 AND 4),
started_at timestamptz NOT NULL, -- first malicious or faulty event (from forensics)
detected_at timestamptz NOT NULL,
resolved_at timestamptz
);
SELECT severity,
count(*) AS incidents,
avg(detected_at - started_at) AS mttd,
avg(resolved_at - detected_at) AS mttr
FROM incidents
WHERE resolved_at IS NOT NULL
GROUP BY severity
ORDER BY severity;The Laravel angle
- Use
Log::withContext(['request_id' => $id])in a middleware (the framework docs show exactly this) and adduser_idafter authentication; thetapprocessor then masks anything sensitive that developers add later. - Laravel's
dailyandmonthlychannels keep rotated files for the number ofdaysyou set. Pair that with a log shipper so local retention is not your only copy. php artisan downsupports--secret(bypass token),--retry,--refresh,--renderand--redirect. A break-glass command should always write who pulled it to the audit log.- Framework events (
Login,Failed,Logout,PasswordReset) are the right place to build an audit trail; they fire for every guard, so log the guard name. composer auditfails with exit code 1 when advisories exist;--lockedaudits the lock file regardless of what is installed invendor.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Secret committed to Git | Pre-commit plus CI scan, revoke on find | gitleaks hook, push protection | Stops at the laptop | Needs developer buy-in |
| Password in logs | Redacting handler plus lint rule | redact.Handler, RedactingProcessor, Semgrep rule | Defence in depth: code and runtime | Pattern misses novel secret formats |
| Long-lived CI cloud keys | OIDC federation | Role trust by repo and branch claims | No stored keys | Cloud-side setup per provider |
| Unknown dependency inventory | SBOM per build | Syft, store with the artifact | Log4Shell-style search in minutes | Needs an index you can query |
| Vulnerable but unreachable library | Reachability filter | govulncheck | Less noise | Go only |
| Tampered logs | Ship off-box, WORM storage, hash chain | Object Lock, auditchain | Edits are detectable | Head hash must be stored elsewhere |
| Alert flood | Detection engineering | Sigma in Git, weekly tuning, owners | Trusted alerts | Ongoing effort |
| Silent control failure (expired certificate) | Monitor the monitors | Certificate expiry alerts, synthetic attacks | Finds blind spots | More alerts to manage |
| Slow reaction to a new CVE | Playbook plus inventory | SBOM query, WAF virtual patch, flag | Hours instead of weeks | Needs rehearsal |
| Erasure versus immutable logs | Pseudonymise, crypto-shred | Per-subject key in a vault | Compliance and immutability | Key management |
Leaked key during an incident
Contain first (revoke), then investigate. With OIDC there is nothing long-lived to revoke in CI; with a static key rotate it, search access logs from first exposure, and add a scanner rule for the pattern.
A new critical CVE on Friday afternoon
1 security posts in incident channel: "CVE-2026-XXXX, KEV listed, affects library L"
2 query SBOM store: which services contain L at which version? (minutes)
3 reachability: govulncheck / vendor advisory -> reachable in services A and B
4 mitigate now: WAF virtual patch, feature flag off, egress rule
5 patch A and B behind canary; verify with scanner; close incident
6 postmortem: how long step 2 took; was the SBOM current?Audit log tamper attempt
The Go chain test shows editing, deleting a middle entry and truncating the tail. Editing and middle deletion are detected from the log alone; truncating the tail needs the head hash stored out of band.
Testing security controls
| Test | What it proves | Where |
|---|---|---|
| Redaction unit tests | Known secret shapes never reach the sink | Go redact_test.go, Laravel Pest test with a Monolog TestHandler |
| Fuzz test | Scrubbing never panics, never leaves line breaks, is idempotent | Go FuzzScrub |
| Policy checker tests | Denied package, license and namespace rules fire | Go policy_test.go |
| Chain tests | Edits, deletes and truncation are caught | Go chain_test.go |
| Pipeline canary | A deliberately bad commit (fake key, vulnerable test dependency) fails CI | Scheduled job on a sandbox repository |
| Detection replay | Sigma rule fires on recorded fixture | SIEM test harness |
| Tabletop | People and contacts work | Quarterly |
Choosing
| Situation | Do first | Then | Reason |
|---|---|---|---|
| Start-up with no program | Secret scanning, dependency audit in CI, MFA everywhere, centralised logs | Playbook for credential leak | Highest return, lowest effort |
| Handling card data | Shrink PCI scope with a tokenising provider | Segmentation, logging per requirement 10 | Scope is the cost driver |
| Selling to enterprises | SOC 2 Type I, then Type II | Evidence automation | Procurement blocker |
| Health or EU personal data | Data inventory and minimisation | Breach register and 72-hour drill | Legal duties |
| Large Go or PHP monolith | SAST baseline plus new-finding gate | Incremental fixes | Do not stop the line |
| Many microservices | SBOM per service, central policy | Admission control with signatures | Inventory at scale |
| Just had an incident | Blameless postmortem within a week | Fund the top three actions | Learning decays quickly |
| Which scanner for which question | Use |
|---|---|
| "Is my code insecure?" | SAST (Semgrep, CodeQL, gosec) |
| "Are my dependencies vulnerable?" | SCA (govulncheck, composer audit, Grype) |
| "Is my image or Terraform unsafe?" | Trivy, Checkov, tfsec |
| "Is my running app attackable?" | DAST (ZAP), pentest |
| "Is my parser robust?" | Fuzzing |
| "Is my build trustworthy?" | SLSA provenance, cosign |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One deploy, one log stream, one set of dependencies. The cheapest complete setup: pre-commit secret scan, composer audit or govulncheck in CI, one structured JSON log with the redaction handler, an audit channel for authentication and admin actions, a database role that cannot update the audit table, one playbook (credential leak) and a pager. Example: a Laravel shop with 3 engineers can do all of this in a week.
Modular monolith: boundaries without the network
Modules own their data and their log fields. Add a shared logging contract (field names, redaction list) as a package, authorization checks inside module boundaries, a per-module owner for vulnerability findings, and SBOM per deployable. Threat model each module boundary as if it were a network.
Microservices: every arrow is a decision
Each service has its own pipeline, image, dependencies and secrets, so the controls multiply. Standardise: a golden pipeline template with OIDC, scanning and signing; a shared logging library with request_id propagation and redaction; mTLS and workload identity between services (mTLS); central policy engines (Kyverno, OPA) at admission. Incident response needs a service catalogue (owner, on-call, data classes) so the IC can find the right people in minutes. The messaging chapter Messaging Security covers broker-level controls.
Distributed data: replicas, caches, regions
Personal data spreads to replicas, caches, search indexes, analytics stores and backups; erasure and breach scoping must find all of them, so keep a data map. Logs cross regions: respect data-residency rules (log to a regional store, ship only pseudonymised aggregates). Evidence preservation must cover replicas and snapshots (Backup, PITR & DR). Cache poisoning and stale authorization decisions need TTLs shorter than your revocation target.
Scaling path: 1x, 10x, 100x
| Scale | Security shape | Logging | Response |
|---|---|---|---|
| 1x (one team) | Hooks, CI scanning, MFA | One index, 30 to 90 days hot | One on-call, one playbook |
| 10x (many teams) | Golden pipeline, SBOM store, secret manager | SIEM, detection as code, WORM archive | Severity matrix, rotating IC, quarterly tabletop |
| 100x (platform) | Policy as code, signed provenance enforced, internal red team | Tiered storage, sampling of noise (never of audit), data lake | Follow-the-sun, dedicated detection and response teams, automation (SOAR) |
Lab: break a build, leak a secret, catch it
Expected, not run (except the Go commands, which were run on the development machine).
1 cd docs/snippets/system-design/secure-sdlc-incident-response/go && go test ./...
expected:
ok academy/secure-sdlc-incident-response/auditchain
ok academy/secure-sdlc-incident-response/policy
ok academy/secure-sdlc-incident-response/redact
2 go test ./redact -run xxx -fuzz=FuzzScrub -fuzztime=15s
expected: PASS (a failure would be saved under redact/testdata/fuzz/FuzzScrub/)
3 cat > base.cdx.json: one component gin 1.9.0; cat > pr.cdx.json: gin 1.10.0 plus package evil-left-pad
go run ./cmd/sbomdiff -base base.cdx.json -head pr.cdx.json -policy ../ci/policy.json
expected (exit status 1):
added=1 removed=0 changed=1
VIOLATION: denied package added: ...evil-left-pad@...
4 Laravel: composer require --dev pestphp/pest; write a test that logs ['password' => 'x'] to a Monolog TestHandler
expected: the record context shows [REDACTED]
5 php artisan incident:freeze INC-TEST --retry=60 ; curl -i https://app.example.test/
expected: HTTP/1.1 503 Service Unavailable with Retry-After: 60; storage/logs/audit-*.log has an incident.freeze line
6 php artisan up
expected: application serves againCommon misconceptions
| Belief | Reality |
|---|---|
| "A clean scan means we are secure" | Scanners find known patterns; logic flaws and process failures pass |
| "We are SOC 2 compliant, so we cannot be breached" | Compliance shows controls operated; attackers do not read your report |
| "Deleting the commit removes the leaked key" | Treat the key as public; revoke and rotate |
| "Masked CI secrets cannot leak" | Redaction is not guaranteed; any writer can print a secret through a workflow |
| "A signed artifact is a trustworthy artifact" | Signing proves origin, not intent (SolarWinds) |
| "More logs are always better" | Logs are a data store with PII and secrets risk; log purposefully |
| "We have 72 hours to investigate" | 72 hours to notify, with what you know, where feasible |
| "Blameless means no consequences" | It means system fixes with owners, not scapegoats |
| "A rollback is a kill switch" | Rollback is slower and does not stop data flows; flags and maintenance mode are faster |
| "Append-only logs conflict with erasure" | Keep personal data out of immutable stores or crypto-shred it |
| "Pentest once a year is enough" | It samples one moment; keep automated checks running |
Cheat sheet
| Topic | Remember |
|---|---|
| SSDLC | Controls at every stage, automated, failing with a clear message |
| Abuse case | Story from the attacker's side, becomes an acceptance test |
| Secrets | Pre-commit plus CI scan; leaked means revoked |
| SAST | Semgrep, CodeQL, gosec, PHPStan, Psalm; gate on new high findings only |
| SCA | govulncheck (reachable), composer audit --locked, Grype, Trivy |
| SBOM | Syft, CycloneDX; store per build; diff in PRs |
| Pipeline | Least-privilege token, OIDC federation, pinned actions, ephemeral runners |
| Signing | cosign keyless, provenance, SLSA L3, verify at admission |
| Testing | ZAP, Go fuzzing, security unit tests, pentest, bug bounty |
| Release | Canary, feature flags, kill switch faster than rollback |
| Operate | CIS baseline, patch SLA, rotation, WAF count then block |
| Logging | Who, what, when, where, outcome; never secrets or raw PII |
| Storage | Off-box, WORM, hash chain, head hash elsewhere, defined retention |
| Detection | SIEM plus Sigma as code; tune weekly; every alert has an owner |
| IR | NIST 800-61r3: Govern, Identify, Protect prepare; Detect, Respond, Recover act; improve always |
| Roles | Incident commander, ops lead, comms lead, scribe |
| Clock | GDPR 72 hours from awareness, HIPAA 60 days, contracts often shorter |
| Compliance | SOC 2 TSC, ISO 27001 Annex A, PCI DSS v4, HIPAA, GDPR: collect evidence from the pipeline |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the control you would add at each of the eight lifecycle stages for a new payment webhook. Important
Answer
Answer: Requirements: abuse cases (replay, forged sender) and PCI constraints. Design: threat model. Code: secret scan, review checklist. Build: SAST, SCA, container scan, SBOM, signing. Test: ZAP, fuzz the parser, security unit tests. Release: canary and kill switch. Operate: patch SLA, rotation, WAF tuning. Monitor: structured security logs and a Sigma rule for signature failures.
2 — Why is OIDC federation better than a stored cloud access key in CI? Must-know
Answer
Answer: The job exchanges a short-lived signed identity token for credentials tied to repository and branch claims; there is nothing long-lived to steal, and a stolen token expires quickly.
3 — What does govulncheck do that a presence-based SCA scan does not? Important
Answer
Answer: It reports only vulnerabilities whose symbols your code actually calls (source mode), which cuts false alarms.
4 — Which two things must be true for a hash-chained audit log to detect tail truncation? Good to know
Answer
Answer: The latest (head) hash must be stored outside the log (another account or system), and verification must compare it with the recomputed head.
5 — What belongs in the "never log" column for an authentication event, and what goes there instead? Must-know
Answer
Answer: Passwords, OTPs, session ids, bearer tokens and raw e-mail in free text; log a user id or keyed hash, the outcome and the request id.
6 — When does the GDPR 72-hour clock start, and what if you miss it? Important
Answer
Answer: When the controller becomes aware of the breach. A late notification must be accompanied by reasons for the delay (Art. 33(2)).
7 — Which Rev. 3 functions are preparation and which are the response? Good to know
Answer
Answer: Govern, Identify and Protect are preparation; Detect, Respond and Recover are the response; Improvement (ID.IM) runs through all of them.
8 — What detection failure made Okta's 2023 incident last longer, and how would you design against it? Good to know
Answer
Answer: Downloading through the Files tab generated a different log event than viewing a case attachment, so downloads went unnoticed for 14 days. Make every access path to a resource emit the same audit event and test detection with every path.
9 — Why is a signed SolarWinds update not a counterexample to signing? Important
Answer
Answer: Signing proves origin, not intent. The build system was compromised, so malicious code was signed. SLSA L3 hardening and provenance raise the cost of that attack.
10 — How can an event-sourced system honour an erasure request? Important
Answer
Answer: Store personal fields encrypted under a per-subject key (or in an erasable store) and delete the key; events stay immutable but unreadable.
Glossary
| Term | Meaning |
|---|---|
| SSDLC | Secure software development life cycle: the lifecycle with security activities at each stage |
| DevSecOps | Security checks built into the delivery pipeline and owned jointly |
| Shift left | Moving security work earlier in the lifecycle |
| Abuse case | A story describing how an attacker misuses a feature |
| Threat modelling | Systematic search for threats using a data-flow diagram (STRIDE) |
| Security architecture review | Human review of a design against threats and standards |
| Secure coding standard | Enforced language-specific security rules |
| Code review checklist | Questions a reviewer must answer for security |
| Secret scanning | Detecting credentials in code and history (gitleaks, trufflehog) |
| Pre-commit | Hook that runs checks before a commit is created |
| SAST | Static application security testing of source code |
| Semgrep | Pattern-based multi-language static analysis tool |
| CodeQL | Query-based data-flow analysis engine from GitHub |
| gosec | Static analyser for Go security issues |
| PHPStan | PHP static analyser (types); extensible |
| Psalm | PHP static analyser with taint analysis |
| SCA | Software composition analysis of dependencies |
| govulncheck | Go tool reporting reachable known vulnerabilities |
| composer audit | Composer command listing advisories for locked packages |
| Container scanning | Checking image packages for known vulnerabilities (Trivy, Grype) |
| Trivy | Open-source scanner for images, filesystems, IaC and secrets |
| Grype | Vulnerability scanner for images and SBOMs |
| IaC scanning | Policy checks on Terraform, Kubernetes and Dockerfiles |
| Checkov | Policy-as-code scanner for IaC |
| tfsec | Terraform security scanner, now part of Trivy |
| SBOM | Software bill of materials: inventory of components |
| Syft | Tool that generates SBOMs |
| cosign | Sigstore tool for signing and verifying artifacts |
| SLSA | Supply-chain Levels for Software Artifacts; Build L0 to L3 |
| Reproducible build | Same source gives byte-identical artifacts |
| Pipeline security | Protecting the CI/CD system itself |
| OIDC federation | Exchanging a CI identity token for short-lived cloud credentials |
| Least-privilege token | Credential limited to the minimum permissions |
| DAST | Dynamic testing of a running application (OWASP ZAP) |
| ZAP | OWASP Zed Attack Proxy |
| Fuzzing | Automated input mutation to find crashes and invariant failures |
| Pentest | Time-boxed human attack with a report |
| Bug bounty | Paid external vulnerability reporting programme |
| Progressive delivery | Gradual rollout with automatic abort (canary, blue-green) |
| Kill switch | Flag for emergency disablement of a feature |
| Hardening | Reducing attack surface through configuration |
| CIS Benchmark | Consensus secure configuration guide |
| Patch management | Inventory, prioritise, deploy and verify updates |
| Security logging | Recording events needed to detect and reconstruct attacks |
| Structured logs | Machine-readable logs with stable fields |
| PII redaction | Masking personal data before it is written |
| Tamper-evident | Edits are detectable (hash chain) |
| Append-only / WORM | Storage that refuses edits and deletes |
| Retention | How long data is kept |
| SIEM | Security information and event management (Splunk, Elastic, Sentinel, Wazuh) |
| Sigma rules | Vendor-neutral YAML detection rule format |
| Detection engineering | Treating detection rules as tested, versioned code |
| Alert fatigue | Responders ignoring alerts because of volume and noise |
| Incident response | Detect, respond to and recover from security incidents |
| NIST SP 800-61 | NIST guide to incident response (Rev. 3, April 2025) |
| Severity level | Impact class that drives response speed and audience |
| Incident commander | Person who coordinates the response and decides |
| Evidence preservation | Capturing data defensibly before cleanup |
| Forensics | Reconstructing what happened from evidence |
| Notification window | Legal deadline to report a breach |
| Blameless postmortem | Review focused on system causes, not individuals |
| Runbook | Steps for one operational task |
| Playbook | Decisions and roles for a class of incident |
| Tabletop exercise | Discussion-based rehearsal of an incident |
| SOC 2 | AICPA attestation on the Trust Services Criteria |
| Trust Services Criteria | Security, availability, processing integrity, confidentiality, privacy |
| ISO 27001 | Standard for an information security management system |
| Annex A | ISO 27001 control catalogue: organizational, people, physical, technological |
| PCI DSS v4 | Payment card data security standard |
| HIPAA | US health data law with Security and Breach Notification Rules |
| GDPR | EU data protection regulation |
| Data minimisation | Collect and keep only what is needed |
| DSAR | Data subject access request |
| Right to erasure | GDPR Art. 17 right to deletion |
| MTTD / MTTR | Mean time to detect / to respond or recover |
| Vulnerability SLA | Maximum remediation time by severity |
| Break-glass | Emergency access or action with extra auditing |
References
- NIST SP 800-61 Rev. 3, Incident Response Recommendations and Considerations for Cybersecurity Risk Management: https://csrc.nist.gov/pubs/sp/800/61/r3/final
- NIST SP 800-61 Rev. 3 (PDF): https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-61r3.pdf
- NIST SP 800-218, Secure Software Development Framework (SSDF): https://csrc.nist.gov/pubs/sp/800/218/final
- NIST SP 800-92, Guide to Computer Security Log Management: https://csrc.nist.gov/pubs/sp/800/92/final
- OWASP SAMM: https://owaspsamm.org/
- OWASP DevSecOps Guideline: https://owasp.org/www-project-devsecops-guideline/
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- SLSA v1.0 levels: https://slsa.dev/spec/v1.0/levels
- CIS Benchmarks: https://www.cisecurity.org/cis-benchmarks
- GDPR Art. 33: https://gdpr-info.eu/art-33-gdpr/
- GDPR Art. 5: https://gdpr-info.eu/art-5-gdpr/
- GDPR Art. 17: https://gdpr-info.eu/art-17-gdpr/
- PCI Security Standards Council, PCI DSS: https://www.pcisecuritystandards.org/standards/pci-dss/
- AICPA, SOC 2: https://www.aicpa-cima.com/topic/audit-assurance/audit-and-assurance-greater-than-soc-2
- GAO-18-559, Data Protection: Actions Taken by Equifax and Federal Agencies in Response to the 2017 Breach (report): https://www.gao.gov/assets/gao-18-559.pdf
- GAO-18-559 (product page): https://www.gao.gov/products/gao-18-559
- Capital One, Information on the Capital One cyber incident: https://www.capitalone.com/digital/facts2019/
- CISA Emergency Directive 21-01, Mitigate SolarWinds Orion Code Compromise: https://www.cisa.gov/news-events/directives/ed-21-01-mitigate-solarwinds-orion-code-compromise
- CISA, Apache Log4j Vulnerability Guidance: https://www.cisa.gov/news-events/news/apache-log4j-vulnerability-guidance
- Apache Log4j security page: https://logging.apache.org/security.html
- Okta Security, Unauthorized Access to Okta's Support Case Management System: Root Cause and Remediation: https://sec.okta.com/articles/2023/11/unauthorized-access-oktas-support-case-management-system-root-cause/
- CISA AA23-158A, CL0P Ransomware Gang Exploits CVE-2023-34362 MOVEit Vulnerability: https://www.cisa.gov/news-events/cybersecurity-advisories/aa23-158a
- CISA Known Exploited Vulnerabilities Catalog: https://www.cisa.gov/known-exploited-vulnerabilities-catalog
- Google SRE Book, Postmortem Culture: https://sre.google/sre-book/postmortem-culture/
- Laravel 13 logging: https://laravel.com/docs/13.x/logging
- Laravel 13 configuration (maintenance mode): https://laravel.com/docs/13.x/configuration
- Go package log/slog: https://pkg.go.dev/log/slog
- Go blog, Structured logging with slog: https://go.dev/blog/slog
- Go fuzzing: https://go.dev/doc/security/fuzz
- Go vulnerability management (govulncheck): https://go.dev/doc/security/vuln/
- Composer CLI (audit): https://getcomposer.org/doc/03-cli.md
- Sigstore cosign signing overview: https://docs.sigstore.dev/cosign/signing/overview/
- Anchore Syft: https://github.com/anchore/syft
- Anchore Grype: https://github.com/anchore/grype
- Trivy documentation: https://trivy.dev/latest/docs/
- Checkov: https://www.checkov.io/1.Welcome/What is Checkov.html
- gosec: https://github.com/securego/gosec
- Semgrep documentation: https://semgrep.dev/docs/
- CodeQL documentation: https://codeql.github.com/docs/
- OWASP ZAP documentation: https://www.zaproxy.org/docs/
- Sigma rules: https://github.com/SigmaHQ/sigma
- GitHub Actions OIDC concepts: https://docs.github.com/en/actions/concepts/security/openid-connect
- GitHub Actions security hardening: https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions
- AWS EC2 Instance Metadata Service (IMDSv2): https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
- NVD, CVE-2017-5638 (Apache Struts): https://nvd.nist.gov/vuln/detail/CVE-2017-5638
- NVD, CVE-2021-44228 (Log4Shell): https://nvd.nist.gov/vuln/detail/CVE-2021-44228