This lesson combines 2 topics: SAST, DAST and Secret Scanning, and Logging, Audit and Incident Response.
Learning Objectives
- Understand SAST (Static), DAST (Dynamic), IAST (Interactive) and when to use each
- Use SonarQube, Semgrep, CodeQL for SAST with low false-positive rules
- Deploy DAST with OWASP ZAP, Burp Suite, Nuclei for web apps
- Set up secret scanning: gitleaks, truffleHog, GitHub native secret scanning
- Integrate SCA (Software Composition Analysis) with SBOM/dependency scanning
- Place scans in pre-commit hooks (husky) and the CI/CD pipeline
- Design a fail-build process plus exceptions for critical findings
- Identify the security-relevant events to log (auth, privileged action, data access, config change)
- Avoid leaking PII/secrets into logs: redaction and structured logging with a schema
- Design centralized logging: ELK, Splunk, Datadog, CloudWatch Logs with retention requirements
- Understand SIEM: correlation rules, alerting, threat intel
- Apply the NIST Incident Response lifecycle: Preparation → Detection → Containment → Eradication → Recovery → Lessons Learned
- Prepare runbooks, on-call rotation, tabletop exercises
- Forensics 101: preserve evidence, chain of custody, timeline reconstruction
- GDPR 72h breach notification and similar regulations
Part 1: SAST, DAST and Secret Scanning
1. SAST vs DAST vs IAST: overview
| Criteria | SAST | DAST | IAST |
|---|---|---|---|
| Input | Source code | App URL/endpoint | Instrumented app + test traffic |
| Needs running app? | No | Yes | Yes |
| False positive | High (needs tuning) | Low (real vulns) | Very low |
| Finds | SQLi, XSS patterns, hardcoded secrets, insecure crypto APIs | SQLi, XSS, IDOR confirmed via real requests | Both of the above + runtime data flow |
| Language | Per-language tool | Language-agnostic | Needs an agent per language |
| When | Every PR | Nightly or pre-prod | In the test environment |
| Code coverage | 100% reachable | Only endpoints the test calls | Only code executed by tests |
Best practice: use all 3 layers: SAST (early, broad), DAST (verifies real exploits), SCA for deps (Day 9). IAST is a bonus when budget allows.
2. SAST: Static Application Security Testing
How it works
SAST reads source code (or bytecode) and applies rule pattern matching + dataflow analysis:
Example "SQL injection" rule:
Source: HTTP request param (req.query.id, request.GET[...])
Sink: raw SQL string ("SELECT ... " + var, cursor.execute(f"..."))
Path: source → sink without sanitizer → ALERT
Popular tools
| Tool | Type | Strengths | Weaknesses |
|---|---|---|---|
| SonarQube / SonarCloud | Multi-language | Quality + security, good dashboard, free tier | Security rules limited compared to specialized tools |
| Semgrep | Multi-language | Rules written as YAML patterns, fast, good community rules, free OSS | Not as deep on dataflow as CodeQL |
| CodeQL (GitHub) | Multi-language | Deep dataflow analysis, free for public repos | Writing custom rules is complex (QL language) |
| Snyk Code | Multi-language | AI-based, few FPs | Commercial |
| Checkmarx, Veracode, Fortify | Enterprise | Broad coverage | Expensive, slow |
Semgrep: a real example
# .semgrep.yml — custom rule detecting SQL string concat
rules:
- id: python-sql-string-concat
pattern-either:
- pattern: |
$CURSOR.execute("..." + $X)
- pattern: |
$CURSOR.execute(f"...{$X}...")
message: |
SQL string concatenation/f-string detected — use a parameterized query.
languages: [python]
severity: ERROR
# Run locally
semgrep --config auto .
# Run with community rules
semgrep --config "p/security-audit" --config "p/owasp-top-ten" .
# In CI (GitHub Actions)
semgrep ci --sarif --output=semgrep.sarif
CodeQL in GitHub Actions
# .github/workflows/codeql.yml
name: CodeQL
on:
push: { branches: [main] }
pull_request: { branches: [main] }
schedule:
- cron: "0 0 * * 1" # weekly Monday
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
security-events: write
actions: read
contents: read
strategy:
matrix:
language: [javascript, python]
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: security-extended # broader, more FP but deeper
- uses: github/codeql-action/analyze@v3
Findings show up in the Security → Code scanning alerts tab.
Reducing false positives
Anti-pattern: enable every "kitchen sink" rule → 10000 findings → team ignores them all
→ SAST becomes useless
Best practice:
1. Start with "security-audit" or "OWASP Top 10" rules (high signal)
2. Triage: dismiss false positives with a reason (codeql has suppress comments)
3. Tune custom rules for your domain (e.g., the company's standardized crypto pattern)
4. Severity-based gating: only fail the build on HIGH/CRITICAL
5. Diff scan in PRs (only check changed code) instead of a full scan
3. DAST: Dynamic Application Security Testing
How it works
DAST acts like an external attacker: it sends requests with malicious payloads and observes the responses.
Tools
| Tool | Type | Use case |
|---|---|---|
| OWASP ZAP | Free, open-source | Standard pick, good CI integration |
| Burp Suite | Free Community + Pro | Manual pentesting, intercept proxy |
| Nuclei | Template-based | Fast scans with community templates (CVE, misconfig) |
| Acunetix, Netsparker | Commercial | Enterprise, GUI-friendly |
OWASP ZAP in CI
# .github/workflows/zap.yml
name: ZAP Baseline Scan
on:
schedule:
- cron: "0 2 * * *" # nightly 2 AM
workflow_dispatch:
jobs:
zap:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: ZAP Baseline Scan
uses: zaproxy/action-baseline@v0.12.0
with:
target: 'https://staging.example.com'
rules_file_name: '.zap/rules.tsv'
cmd_options: '-a' # active scan (not just passive)
ZAP has 2 modes:
- Baseline (passive): only analyzes responses, sends no payloads → safe for prod
- Active scan: injects payloads (SQLi, XSS) → run only on staging/test
Nuclei: template-based fast scan
# Run popular CVE templates
nuclei -u https://example.com -t cves/ -t vulnerabilities/
# Example template (.yaml):
# id: nginx-default-page
# requests:
# - method: GET
# path: ["{{BaseURL}}"]
# matchers:
# - type: word
# words: ["Welcome to nginx!"]
The community maintains thousands of templates (https://github.com/projectdiscovery/nuclei-templates). Run them in CI to check for infrastructure misconfigurations.
Authenticated scan
By default DAST scans as an anonymous user → it misses vulnerabilities behind login. Configure ZAP with a session token:
# ZAP context with auth
auth:
loginUrl: https://staging/login
loggedInIndicatorRegex: "Logout"
username: dast-user@example.com
password: ${{ secrets.DAST_PASSWORD }}
Warning: create a dedicated user for DAST, never use an admin (DAST may fire a DELETE /admin/users test).
4. IAST: Interactive
IAST = SAST insight + DAST reality. An agent (instrumentation) is embedded in the app in the test environment and tracks:
- Source: user data coming in (request params)
- Sink: SQL execute, system command exec, eval
- Flow: traces data from the source through function calls to the sink
When integration tests run, the IAST agent sees req.body.id flowing into db.query("SELECT ... " + id) without passing a sanitizer → a precise finding (exact line + the real request).
Tools: Contrast Security, Seeker (Synopsys), Veracode IAST. Few open-source options. Requires runtime instrumentation: supports Java, .NET, Node, Python, but each is configured differently.
When to use it: the team has good integration test coverage, wants low-FP findings, and has budget for commercial tools. It does not replace SAST; it complements it.
5. Secret scanning in CI
The problem
A developer commits a .env containing an AWS key → pushes to a public GitHub repo → 60 seconds later a bot has finished scanning and starts mining crypto on your account. This is the most common incident, not a hypothetical.
Tools
| Tool | Type | Characteristics |
|---|---|---|
| gitleaks | OSS Go binary | Fast, custom TOML rules, easy CI integration |
| truffleHog | OSS Python | Entropy detection + regex, verifies whether a secret is still live |
| GitHub Secret Scanning | Native | Free for public repos, has a partner program (AWS, Stripe... auto-revoke) |
| GitGuardian | Commercial | Dashboard, alerting, full history scan |
gitleaks in pre-commit and CI
# Install
brew install gitleaks
# Scan working dir + staged
gitleaks detect --source . --verbose
# Scan the entire history
gitleaks detect --source . --log-opts="--all"
# .pre-commit-config.yaml (used with the pre-commit framework)
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
# CI: .github/workflows/secret-scan.yml
name: Secret Scan
on: [pull_request, push]
jobs:
gitleaks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 } # full history
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GitHub native secret scanning
Enable it under Settings → Security → Code security:
- Secret scanning: GitHub scans commits + PRs and alerts maintainers
- Push protection: blocks a push if a secret pattern matches
- Partner program: GitHub forwards leaked keys to the provider (AWS, GCP, Stripe...), which auto-revokes and notifies
Free for public repos since 2023. Private repos need GitHub Advanced Security.
Handling a leaked secret
WRONG: a "revert" commit — the secret is still in git history
RIGHT:
1. Revoke/rotate the secret IMMEDIATELY (AWS console, Stripe dashboard...)
2. Rotate first, clean history later (a history rewrite does not remove it from forks/clones)
3. Notify the team — anyone using that key needs the new one
4. Check the provider's audit log: has the key already been abused?
5. (Optional) git filter-repo / BFG to remove it from history (if the repo is private)
6. SCA: Software Composition Analysis
(Covered in depth on Day 9: Supply Chain, SBOM & Dependency Scanning. This is a summary of its role in the DevSecOps pipeline.)
SCA scans dependencies (npm, pip, Maven, Go modules) against a CVE database:
| Tool | Characteristics |
|---|---|
| Dependabot (GitHub) | Free, auto-PR when a CVE appears |
| Snyk | Multi-ecosystem, good prioritization |
| Trivy | OSS, scans both containers and deps |
| OWASP Dependency-Check | Free, OWASP project |
| OSV-Scanner (Google) | Uses the OSV database, multi-ecosystem |
SCA + SBOM: generate a CycloneDX/SPDX SBOM for every build (syft, cdxgen) and attach it to the release. This satisfies Executive Order 14028 for the US government and the SLSA framework.
7. Pre-commit hook: client-side scan
Git hooks vs Husky
Git hooks: .git/hooks/pre-commit is a bash script, not version-controlled by default; every developer has to install it by hand.
Husky (Node ecosystem): commit hooks live in .husky/ (version-controlled), and npm install sets them up automatically.
pre-commit framework (Python, multi-language): YAML config, installs hooks automatically.
Husky setup
npm install --save-dev husky lint-staged
npx husky init
// package.json
{
"scripts": {
"prepare": "husky"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix",
"prettier --write"
]
}
}
# .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# 1. Lint + format
npx lint-staged
# 2. Secret scan staged files
gitleaks protect --staged --verbose --redact
# 3. Quick SAST on changed files
git diff --cached --name-only --diff-filter=ACM | \
xargs -r semgrep --config p/security-audit --error
Pre-commit trade-offs
| Pros | Cons |
|---|---|
| Catches issues early, before the commit | Slows down the commit experience |
| Protects developers from mistakes | Developers can bypass it with --no-verify |
| No CI round trip needed | Does not replace CI (CI is authoritative) |
Rule: pre-commit is defense in depth, not the only defense. CI must still scan independently (because
--no-verifycan bypass it).
8. CI/CD: fail the build and the exception process
Severity-based gating
# Example: fail on HIGH/CRITICAL, warn on MEDIUM
- name: Trivy
uses: aquasecurity/trivy-action@master
with:
image-ref: app:latest
severity: HIGH,CRITICAL
exit-code: 1 # fail build
ignore-unfixed: true # skip CVEs without a fix
Exception process (controlled allow-list)
Not every finding can be fixed right away (vendor has not patched, false positive). You need a process to accept risk for a limited time:
# .trivyignore — CVE allow-list with reason + expiry
CVE-2024-12345 exp:2025-01-31 # vendor has not fixed, mitigated by NetworkPolicy
CVE-2024-67890 exp:2025-03-15 # FP — not reachable in the code path
# Gitleaks allow-list in .gitleaks.toml
[allowlist]
description = "Test fixtures with fake credentials"
paths = [
'''tests/fixtures/.*''',
]
commits = [
'''abc123...''', # specific commit reviewed
]
Exception governance
1. Finding appears → CI fails
2. Developer opens an "Exception Request" (Jira/Backlog ticket)
3. Security team reviews:
- Valid reason? (FP, vendor delay, business critical)
- Mitigation? (WAF rule, NetworkPolicy, monitoring)
- Expiry? (30d, 90d — never permanent)
4. Approved → added to the allow-list with an expiry
5. A nightly CI job checks expiry and re-opens the ticket when it expires
Without an exception process, developers will bypass the scan (--no-verify, commenting out the scan) → security debt grows out of control.
Part 2: Logging, Audit and Incident Response
1. What to log for security purposes?
Not every log has security value. Focus on events that help you detect, investigate, prove:
| Event type | Example | Why it matters |
|---|---|---|
| Authentication | Login success/fail, MFA challenge, password reset | Brute force, credential stuffing detection |
| Authorization | Access denied, role assumption, privilege escalation | Detects horizontal/vertical privilege abuse |
| Privileged action | sudo, admin user creating an IAM key, modifying a firewall rule | Insider threat, post-compromise activity |
| Data access | Database query, S3 GetObject on PII, report export | GDPR audit, data exfiltration detection |
| Configuration change | IAM policy modified, SG rule added, production deploy | Change tracking, blame-free root cause |
| Security tool event | WAF block, IDS alert, EDR detection, AV quarantine | Active attack indicator |
| Application error | 5xx, exception stack trace with security context | Vulnerability exploitation evidence |
Minimum log fields for every event
{
"timestamp": "2025-06-05T10:23:45.123Z", // ISO 8601 UTC + millisecond
"event_id": "auth.login.success",
"actor": { // who
"user_id": "u_12345",
"session_id": "s_abc...",
"ip": "203.0.113.42",
"user_agent": "Mozilla/5.0..."
},
"action": "login", // did what
"resource": "user/u_12345", // on what
"result": "success", // outcome
"request_id": "req_xyz...", // to correlate with upstream/downstream
"trace_id": "trace_abc...", // distributed tracing
"metadata": {
"mfa_used": true,
"method": "password"
}
}
Why structured (JSON)? SIEM/log platforms query specific fields (
event_id:auth.login.fail AND actor.ip:203.0.113.42). Plain-text logs → slow grep + unreliable parsing.
2. PII and secrets in logs: Redact!
The problem
# ❌ BAD
logger.info(f"User signup: {request.json}")
# → the log contains the full email, password, credit card
2025-06-05T10:23:45Z INFO User signup: {"email":"alice@example.com","password":"hunter2","ssn":"123-45-6789","cc":"4111-1111-1111-1111"}
Consequence: a log file leak (CloudWatch Logs IAM misconfig, public S3 export, pwned dev workstation) = leaking the PII of thousands of users → GDPR fine of 4% of revenue.
Redaction patterns
# Allow-list approach: only log approved fields
ALLOWED_FIELDS = {"user_id", "email_hash", "role", "country"}
def safe_log(event, payload):
safe_payload = {k: v for k, v in payload.items() if k in ALLOWED_FIELDS}
logger.info(event, extra=safe_payload)
# Or deny-list — remove sensitive fields
SENSITIVE = {"password", "ssn", "credit_card", "api_key", "token"}
def redact(payload):
return {k: ("***REDACTED***" if k in SENSITIVE else v) for k, v in payload.items()}
Pino (Node) built-in redact
import pino from "pino";
const logger = pino({
redact: {
paths: [
"password",
"*.password",
"req.headers.authorization",
"req.headers.cookie",
"user.ssn",
"user.creditCard.number",
],
censor: "[REDACTED]",
},
});
logger.info({ user: { email: "a@x.com", ssn: "123-45-6789" } });
// → user.ssn = "[REDACTED]"
Email/identifier: hash instead of plain text
import hashlib
def email_hash(email):
return hashlib.sha256(email.lower().strip().encode()).hexdigest()[:16]
logger.info("user.login", extra={"email_hash": email_hash(user.email)})
# → keeps the ability to correlate requests from the same user without exposing the email
Log filter / processor layer
Place a filter in the pipeline (Fluentd, Vector, Logstash) to remove sensitive fields before they are indexed. If the app logs something "by mistake", the filter still saves you.
# Vector config — drop field
[transforms.redact]
type = "remap"
inputs = ["app-logs"]
source = '''
del(.password)
del(.credit_card)
if exists(.ssn) { .ssn = "***" }
'''
3. Centralized logging and retention
Architecture
Choosing a platform
| Platform | Characteristics | Use case |
|---|---|---|
| ELK / Elastic Stack | OSS, self-hosted, powerful | Teams with DevOps capacity |
| Splunk | Enterprise, strong SIEM/SOAR | Compliance, regulated industries |
| Datadog Logs | SaaS, integrated with APM/metrics | Cloud-native, no desire to run ops |
| AWS CloudWatch Logs | AWS-native, Logs Insights queries | AWS service integration, low volume |
| Grafana Loki | OSS, label-based, cheap | Large log volume, metric-style queries |
| OpenSearch | AWS fork of Elastic | Avoiding the Elastic license, AWS native |
Retention requirements
| Standard | Retention |
|---|---|
| PCI-DSS | 1 year online, 3 months immediately accessible |
| HIPAA | 6 years |
| SOX | 7 years |
| GDPR | "Storage limitation" — no longer than necessary, typically 6-24 months |
| ISO 27001 | Defined in policy (typically 1-3 years) |
Hot/Warm/Cold tier
# AWS CloudWatch — Log group with 365-day retention
aws logs put-retention-policy \
--log-group-name /aws/lambda/api \
--retention-in-days 365
# Export to S3 (cheaper long-term)
aws logs create-export-task \
--log-group-name /aws/lambda/api \
--from $(date -d "30 days ago" +%s)000 \
--to $(date +%s)000 \
--destination security-logs-archive-bucket \
--destination-prefix lambda-api/
Log integrity
Attackers may delete logs to cover their tracks. Protections:
- Append-only / WORM (Write Once Read Many): S3 Object Lock, immutable index
- Off-host: ship logs off the server before the attacker takes over the machine
- CloudTrail Lake / log signing: hash chain, nobody can tamper with it
- Centralized + RBAC: the log platform is fully separated from the production account
4. SIEM: Security Information & Event Management
SIEM = log aggregation + correlation + alerting + an investigation UI for security.
Core capabilities
Tools
| SIEM | Characteristics |
|---|---|
| Splunk Enterprise Security | Industry leader, expensive |
| Microsoft Sentinel | Cloud-native, Azure-integrated, pay-per-GB |
| Elastic Security | Free tier, OSS base |
| Datadog Cloud SIEM | SaaS, tied to the observability stack |
| AWS Security Lake + Athena | Cheap storage + ad-hoc queries, no real-time alerting |
| Wazuh | OSS HIDS + SIEM-lite |
Example correlation rule
-- Splunk SPL: brute force attempt
index=auth event_id="auth.login.fail"
| stats count by actor.ip, _time span=5m
| where count >= 10
| eval risk=case(count >= 50, "high", count >= 20, "medium", true(), "low")
# Elastic detection rule (KQL)
event.category:authentication AND event.outcome:failure
| histogram time=5m
| where count() >= 10
Alert fatigue
The biggest risk with a SIEM: 100 alerts a day → analyst burnout → alerts get ignored → a real attack is missed.
Anti-pattern: enable "kitchen sink" rules, arbitrary thresholds
→ 100 alerts/day, 95% benign
Best practice:
1. Tune thresholds against a baseline (5σ above normal)
2. Suppress known-benign sources (e.g., vulnerability scanner IP)
3. Severity-based routing (critical → PagerDuty, low → ticket queue)
4. Auto-close alerts resolved within 24h that do not re-trigger
5. Attach a runbook to every alert: who investigates, what to do
5. Incident Response Lifecycle (NIST SP 800-61 Rev. 2)
Severity matrix (example)
| Severity | Definition | Response SLA |
|---|---|---|
| SEV-1 Critical | Production down, data breach, active ransomware | < 15 minutes, all-hands |
| SEV-2 High | Partial outage, suspicious activity confirmed | < 1 hour |
| SEV-3 Medium | Single component degraded, possible threat | < 4 hours |
| SEV-4 Low | Cosmetic, FYI | Next business day |
Roles during an incident
| Role | Responsibility |
|---|---|
| Incident Commander (IC) | Makes decisions, does not fix things personally — coordinates |
| Tech Lead | Hands-on debugging, proposes the fix |
| Communications Lead | Updates the status page, notifies stakeholders and customers |
| Scribe | Records the timeline, decisions, commands run |
| Subject Matter Experts | On demand for the affected components |
6. Runbook, on-call, tabletop exercise
Runbook
A document for each incident type: not a design doc, not a full architecture. Just "when alert X fires, do 1, 2, 3".
# Runbook: Suspicious S3 download spike
## Symptom
CloudTrail GetObject count > 5σ above baseline within 5 minutes from a single IAM user/role.
## Severity
SEV-2 default. Bump to SEV-1 if the bucket contains PII (data-classification: confidential).
## Triage (first 5 minutes)
1. Identify actor: `aws cloudtrail lookup-events --lookup-attributes ...`
2. Check actor history: what actions are normal? First time accessing this bucket?
3. Check source IP: GeoIP, is it within the VPN range?
## Containment
- If IAM user: disable access key
aws iam update-access-key --access-key-id AKIA... --status Inactive --user-name
- If IAM role: detach permission policy or revoke sessions
aws iam put-role-policy --role-name
- Block IP via WAF/SG if confirmed malicious
## Eradication
- Rotate compromised credential
- Audit other resources the actor accessed in the past 7 days
## Recovery
- Re-enable access after rotating + verifying the cause
- Monitor 24h for similar behavior
## Escalation
- Bucket contains PII → notify DPO within 12h (prepare GDPR 72h notification)
- Bucket contains PCI data → notify card brand via the PCI process
On-call rotation
Primary on-call: receives the first page, responds < 15 minutes (SEV-1)
Secondary: backup if primary does not acknowledge after N minutes
Manager on-call: escalation for business decisions (PR, customer comm)
Tool: PagerDuty, Opsgenie, Splunk On-Call
Pattern: weekly rotation, follow-the-sun for global teams
Tabletop exercise
A paper drill (nothing actually runs in production). Once per quarter. Example scenario:
- Facilitator: "At 3AM on Sunday, CloudTrail detects IAM user
ci-deploycreating 50 EC2 instances in region eu-central-1 (a region you do not use). You get paged. What do you do?" - Team discusses step by step: who does what, which commands run, who to escalate to
- Facilitator injects new developments ("the EC2 instances are running a crypto miner", "the AWS bill is already +$5000")
- After the tabletop: record the gaps (e.g., nobody knows who has permission to revoke IAM, no runbook for mass EC2 creation) → create action items
7. Forensics 101
During a serious incident (data breach, ransomware), evidence must be preserved in order to:
- Analyze the root cause
- Present in court if there are legal implications
- Report to regulators
Chain of Custody principle
Every piece of evidence (disk image, log file, memory dump) must have:
- Who collected: name, ID, timestamp
- From where: hostname, IP, path
- How: command used (e.g., dd, fmem)
- Hash integrity: SHA-256 at the moment of collection
- Storage: who has accessed it from collection until now
- Each transfer: signed log
# Collect EC2 disk image (snapshot EBS)
aws ec2 create-snapshot --volume-id vol-abc123 \
--description "IR-2025-06-05 host-compromise"
# Hash snapshot for integrity
aws ec2 describe-snapshots --snapshot-ids snap-xyz | sha256sum > evidence.sha256
# Memory dump (Linux)
sudo ./avml memory.dump # Microsoft AVML tool
sha256sum memory.dump >> evidence.sha256
Timeline reconstruction
Tools: Plaso/log2timeline (super timeline), Splunk SPL transaction command, Datadog timeline view.
Live vs Dead forensics
- Live (host running): capture memory, network connections, running processes. Lost on reboot. Risk: your own actions leave traces.
- Dead (offline): image the disk, analyze offline. Loses in-memory evidence (decrypted secrets, network state).
IR best practice: snapshot first (preserve state) → isolate (revoke creds, NSG block) → investigate on the snapshot copy, not on prod.
8. GDPR 72-hour breach notification
GDPR Article 33: if a personal data breach poses a "likely risk to rights and freedoms", the controller must notify the Data Protection Authority (DPA) within 72 hours of becoming aware of it (not from when it happened).
T+0 : Detection (e.g., alert or tipoff)
T+24h : Initial assessment — scope, data type, count
T+48h : Containment + impact analysis
T+72h : Notify DPA + (if high risk) notify data subjects
If information is still incomplete → send a "preliminary"
notification with what you have, promise to supplement later.
The notification must include:
- The nature of the breach, data types, estimated number of people affected
- Name + contact details of the DPO
- Likely consequences
- Measures taken or planned
Equivalents:
- CCPA / California: similar to GDPR but for California residents
- HIPAA (US): notify HHS within 60 days
- PCI-DSS: notify the card brand "immediately", as defined by each brand
- Vietnam Decree 13/2023: notify the Ministry of Public Security within 72h, similar to GDPR
Implication for developers: logs + audit trails must be ready to answer "which data was accessed, by whom, when, how many records" in < 72h. This is why you log everything security-relevant and keep it for ≥ 1 year.
Review Questions
-
SAST and DAST look for the same kind of bug (e.g., SQLi). When do their results differ?
Show answer
- SAST FP, DAST does not flag: SAST flags
db.query("SELECT " + x)butxis actually a fixed enum in the code → not exploitable. DAST does not see it because no endpoint passes user input there. - DAST finds it, SAST misses: the vulnerability lives in a dependency (e.g., an ORM bug): the app code is clean and SAST does not scan deps. Or it is a runtime configuration vulnerability (e.g., CORS misconfig) that is not in the source code.
- Both find it: the "classic" bug:
req.body.idgoes straight into raw SQL.
That is why you need both layers + SCA for deps to cover the different surfaces.
- SAST FP, DAST does not flag: SAST flags
-
Why does SAST have a high FP rate, and how do you reduce it?
Show answer
SAST scans code without running it → it does not know the runtime context. Some causes of FPs:
- A variable looks dangerous but is sanitized elsewhere (the rule cannot track it)
- Dead code (never executed)
- Pattern matching that is too broad (e.g., flagging every
eval, even whenevalonly runs on a constant)
Reducing FPs: (1) start with a focused rule set (OWASP Top 10, security-audit) instead of "all rules", (2) tune custom rules for the codebase, (3) suppress with a clearly written reason (CodeQL has
// codeql[js/sql-injection]), (4) only fail the build on HIGH/CRITICAL, (5) diff-scan PRs instead of scanning the full repo. -
What is the difference between a ZAP baseline scan and an active scan? What is the danger of running against the wrong environment?
Show answer
- Baseline (passive): only analyzes responses from the traffic ZAP crawls itself, sends no malicious payloads. Safe to run on staging or even production (if rate-limited).
- Active scan: sends SQLi, XSS, command injection payloads. It can create junk data, call DELETE endpoints, crash services.
Danger: running an active scan on production → it can delete real data, trigger orders/emails with a
<script>payload, cause an outage. Always verify the target URL before running an active scan. Create a dedicated DAST user with narrow permissions. -
Why is a pre-commit hook alone not enough for secret scanning?
Show answer
Pre-commit runs on the developer machine. Developers can bypass it with
git commit --no-verify(intentionally or accidentally). Pre-commit also does not exist if the developer has not installed Husky/the pre-commit framework (first clone of the repo, or using the GitHub web editor).You need defense in depth: (1) pre-commit to catch issues early, (2) an independent CI scan (the authoritative gate), (3) GitHub native secret scanning + push protection (blocks right at git push). Push protection is the last layer: it blocks before the commit reaches the shared remote.
-
When gitleaks reports an AWS key in an old commit, what is the correct first action?
Show answer
Revoke/rotate the key IMMEDIATELY in the AWS console (deactivate the old access key, create a new one). Reason: the key is already in git history and may have been made public through forks/clones/mirrors within seconds/minutes. Rewriting git history (BFG, filter-repo) does not solve it, because:
- Existing forks/clones still have the old history
- GitHub caches and archives (archive.org) may already have copied it
- Bots scanning public repos typically find keys in < 60 seconds
After rotating: audit CloudTrail to see what actions the key was used for, notify the team members who used that key, and only then rewrite history if needed.
-
Why is structured logging (JSON) better than plain text for security purposes?
Show answer
SIEM/log platforms query specific fields:
event.category:auth AND user.id:u_123 AND source.ip:203.0.113.42. Plain text requires regex grep: slow, unreliable (e.g., email Alice@Example.com vs ALICE@example.com), and impossible to aggregate (e.g., "count distinct IPs"). Structured logs also let you correlate across services via trace_id, request_id.Standard schemas: ECS (Elastic Common Schema), OCSF (Open Cybersecurity Schema Framework), CIM (Splunk).
-
Why is PII in logs dangerous, and how do you redact it correctly?
Show answer
Logs are usually indexed in many places (CloudWatch, SIEM, archive), and many people access them for debugging. PII in logs = PII in many systems → 1 compromised log platform = millions of PII records leaked. GDPR also requires PII to exist only where necessary.
Redaction: (1) allow-list the fields permitted in logs (safest: new fields cannot leak by accident), (2) deny-list SENSITIVE fields, (3) hash email/identifiers to keep correlation without exposing raw values, (4) a log filter layer (Vector, Logstash) that removes fields before indexing, as a backup layer when the app logs something by mistake.
-
The NIST IR lifecycle puts Containment before Eradication. What is the difference?
Show answer
- Containment: stops the attack from spreading. Quick actions such as disabling an IAM key, isolating a host from the network, blocking an IP. No root cause yet, it only reduces the bleeding.
- Eradication: removes the root cause once the attack is understood. Remove malware, patch the vulnerability, rotate related creds, close lateral movement paths.
Why separate them: in a crisis, the first goal is to stop the bleeding as fast as possible; root cause takes time to analyze. If you try to eradicate before containing, the attacker can exfiltrate more while you are still investigating.
-
How does a tabletop exercise differ from a live simulation, and why do you still need it?
Show answer
Tabletop: discussion on paper/whiteboard, no real commands run. Fast (2-3 hours), no outage risk, focuses on decision-making and communication.
Live drill / chaos engineering: actually kills instances, simulates a breach. More time-consuming, risky if run in the wrong environment.
You still need tabletops because they: (1) test runbook coverage (are any scenarios missing?), (2) find communication gaps (who calls whom, the escalation path), (3) are low cost, so you can run them every quarter. Live drills complement them, not replace them, and typically run 1-2 times a year for critical scenarios.
-
Why does "snapshot before investigating" matter in forensics?
Show answer
Investigative actions (logging into the server, running ps, restarting a process) change the state of the evidence: file access timestamps change, memory is overwritten, log lines are added. If the attacker set a trap (e.g., a shell script that deletes itself when it detects an admin login), you lose the evidence.
Best practice: (1) snapshot the disk (EBS snapshot, VM snapshot) as an immutable copy, (2) take a memory dump before reboot/isolation, (3) export logs off-host before the attacker can edit them, (4) investigate on the copy and leave prod untouched for the forensic team. If legal matters are involved, the chain of custody must document every access from the moment of the snapshot.
Hands-on Exercises
Part 1: SAST, DAST and Secret Scanning
# 1. Install and run gitleaks
brew install gitleaks
gitleaks detect --source . --verbose
# Create a "honeypot" commit to test
echo 'AWS_KEY="<AWS-docs example access key ID>"' > .env.test
git add .env.test
gitleaks protect --staged --verbose
# → Finding: AWS access key
# 2. Install Semgrep and scan
pipx install semgrep # or brew install semgrep
semgrep --config auto .
# Or a security-focused rule set
semgrep --config "p/security-audit" --config "p/owasp-top-ten" .
# 3. Set up the pre-commit framework
pipx install pre-commit
cat > .pre-commit-config.yaml <<'EOF'
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
- repo: https://github.com/returntocorp/semgrep
rev: v1.50.0
hooks:
- id: semgrep
args: ["--config", "p/security-audit", "--error"]
EOF
pre-commit install
pre-commit run --all-files
# 4. Run ZAP baseline (Docker)
docker run --rm -v $(pwd):/zap/wrk -t \
ghcr.io/zaproxy/zaproxy:stable \
zap-baseline.py -t https://example.com -r zap-report.html
# 5. Run Nuclei
brew install nuclei
nuclei -u https://example.com -t cves/
# 6. Set up a combined GitHub workflow
# Copy the snippets from sections 2 and 5 into .github/workflows/
Part 2: Logging, Audit and Incident Response
# 1. Set up structured logging in a Node app
npm install pino pino-pretty
cat > app.js <<'EOF'
const pino = require("pino");
const logger = pino({
level: "info",
redact: {
paths: ["password", "*.password", "req.headers.authorization", "*.ssn"],
censor: "[REDACTED]",
},
});
logger.info({ user: { id: "u_1", email: "a@x.com", ssn: "123-45-6789" } }, "user.signup");
EOF
node app.js | jq
# 2. CloudWatch Logs Insights query
aws logs start-query \
--log-group-name /aws/lambda/api \
--start-time $(date -d '1 hour ago' +%s) \
--end-time $(date +%s) \
--query-string 'fields @timestamp, actor.ip, action | filter event_id="auth.login.fail" | stats count() by actor.ip | sort count() desc | limit 20'
# 3. Set 365-day retention on the log group
aws logs put-retention-policy \
--log-group-name /aws/lambda/api \
--retention-in-days 365
# 4. Test gitleaks log: create a sample runbook
mkdir -p runbooks
cat > runbooks/aws-key-leak.md <<'EOF'
# Runbook: AWS Key Detected in Public Repo
## Triage (5 min)
1. Identify key: AKIA prefix → console
2. aws iam list-access-keys --user-name <user>
## Contain
1. aws iam update-access-key --status Inactive ...
2. Notify on-call + key owner
## Eradicate
1. Rotate key, delete old
2. Audit CloudTrail with old key for 24h
EOF
# 5. Tabletop scenario (read and discuss with the team)
cat <<'EOF'
SCENARIO: Monday 9 AM, customer support receives a ticket
"I received a password reset email I did not request". 30 minutes later,
50 similar tickets. CloudTrail shows IAM user "cs-bot" calling
sts:AssumeRole into the prod role 200 times.
Q1: Severity?
Q2: Who gets paged first? Who is IC?
Q3: What are the actions in the first 5 minutes?
Q4: When do you notify customers? Legal? DPO?
Q5: When does the GDPR clock start?
EOF
References
- OWASP SAST tools
- Semgrep registry
- CodeQL documentation
- OWASP ZAP user guide
- Nuclei templates
- gitleaks
- GitHub secret scanning
- NIST SP 800-61 Rev. 2 — Computer Security Incident Handling Guide
- NIST SP 800-61 Rev. 3 (April 2025, supersedes Rev. 2, CSF 2.0 based)
- Elastic Common Schema (ECS)
- OCSF — Open Cybersecurity Schema Framework
- AWS CloudWatch Logs
- GDPR Article 33 — Breach notification
- SANS Incident Handler's Handbook