devHọc Dev

Week 2 - Day 11: SAST, DAST, Secret Scanning, Logging and Incident Response

Week 2 – Day 11

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

│Code│RunningApp│Production├───────────────┼────────────────┼────────────────SAST│✓│✗│✗(Static)│scansource││──────────────────┤───────────────┼────────────────┼────────────────DAST│✗│✓│(withcaveat)(Dynamic)││black-box│││fuzzendpoints│──────────────────┤───────────────┼────────────────┼────────────────IAST│✗│✓│✗(Interactive)││instrumented│││duringtest│──────────────────┤───────────────┼────────────────┼────────────────RASP│✗│✓│✓(Runtime│││blockattacksSelf-Protection)│││atruntime
CriteriaSASTDASTIAST
InputSource codeApp URL/endpointInstrumented app + test traffic
Needs running app?NoYesYes
False positiveHigh (needs tuning)Low (real vulns)Very low
FindsSQLi, XSS patterns, hardcoded secrets, insecure crypto APIsSQLi, XSS, IDOR confirmed via real requestsBoth of the above + runtime data flow
LanguagePer-language toolLanguage-agnosticNeeds an agent per language
WhenEvery PRNightly or pre-prodIn the test environment
Code coverage100% reachableOnly endpoints the test callsOnly 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:

Sourcecode──►Parser──►AST/IR──►Ruleengine──►Findings│││├──Patternmatch(regexAST)│├──Tainttracking(userinput→sink)│└──Controlflowanalysis▼Symboltable,callgraph

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
ToolTypeStrengthsWeaknesses
SonarQube / SonarCloudMulti-languageQuality + security, good dashboard, free tierSecurity rules limited compared to specialized tools
SemgrepMulti-languageRules written as YAML patterns, fast, good community rules, free OSSNot as deep on dataflow as CodeQL
CodeQL (GitHub)Multi-languageDeep dataflow analysis, free for public reposWriting custom rules is complex (QL language)
Snyk CodeMulti-languageAI-based, few FPsCommercial
Checkmarx, Veracode, FortifyEnterpriseBroad coverageExpensive, 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.

DASTScanner──►HTTPrequest──►RunningApp◄──Response││▼├──CrawlendpointDatabase/dependencies├──Injectpayload(SQLi,XSS,SSRF,commandinjection)├──Detectanomaly(errortrace,timedelay,blindboolean)└──Reportfinding

Tools

ToolTypeUse case
OWASP ZAPFree, open-sourceStandard pick, good CI integration
Burp SuiteFree Community + ProManual pentesting, intercept proxy
NucleiTemplate-basedFast scans with community templates (CVE, misconfig)
Acunetix, NetsparkerCommercialEnterprise, 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

ToolTypeCharacteristics
gitleaksOSS Go binaryFast, custom TOML rules, easy CI integration
truffleHogOSS PythonEntropy detection + regex, verifies whether a secret is still live
GitHub Secret ScanningNativeFree for public repos, has a partner program (AWS, Stripe... auto-revoke)
GitGuardianCommercialDashboard, 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:

ToolCharacteristics
Dependabot (GitHub)Free, auto-PR when a CVE appears
SnykMulti-ecosystem, good prioritization
TrivyOSS, scans both containers and deps
OWASP Dependency-CheckFree, 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

ProsCons
Catches issues early, before the commitSlows down the commit experience
Protects developers from mistakesDevelopers can bypass it with --no-verify
No CI round trip neededDoes not replace CI (CI is authoritative)

Rule: pre-commit is defense in depth, not the only defense. CI must still scan independently (because --no-verify can 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 typeExampleWhy it matters
AuthenticationLogin success/fail, MFA challenge, password resetBrute force, credential stuffing detection
AuthorizationAccess denied, role assumption, privilege escalationDetects horizontal/vertical privilege abuse
Privileged actionsudo, admin user creating an IAM key, modifying a firewall ruleInsider threat, post-compromise activity
Data accessDatabase query, S3 GetObject on PII, report exportGDPR audit, data exfiltration detection
Configuration changeIAM policy modified, SG rule added, production deployChange tracking, blame-free root cause
Security tool eventWAF block, IDS alert, EDR detection, AV quarantineActive attack indicator
Application error5xx, exception stack trace with security contextVulnerability 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

┌──────────┐┌──────────┐┌──────────┐│App1││App2││AppN│└─────┬────┘└─────┬────┘└─────┬────┘│││└────►LogAgent(Fluentd/Vector/CloudWatchAgent)──►Ship│▼┌──────────────────────────┐│CentralizedPlatform││ELK/Splunk/││Datadog/CloudWatch/││Loki/OpenSearch│└─────────┬────────────────┘│┌─────────────┼──────────────┐▼▼▼Search/UIAlertingLong-term(Kibana)(PagerDuty)Archive(S3Glacier)

Choosing a platform

PlatformCharacteristicsUse case
ELK / Elastic StackOSS, self-hosted, powerfulTeams with DevOps capacity
SplunkEnterprise, strong SIEM/SOARCompliance, regulated industries
Datadog LogsSaaS, integrated with APM/metricsCloud-native, no desire to run ops
AWS CloudWatch LogsAWS-native, Logs Insights queriesAWS service integration, low volume
Grafana LokiOSS, label-based, cheapLarge log volume, metric-style queries
OpenSearchAWS fork of ElasticAvoiding the Elastic license, AWS native

Retention requirements

StandardRetention
PCI-DSS1 year online, 3 months immediately accessible
HIPAA6 years
SOX7 years
GDPR"Storage limitation" — no longer than necessary, typically 6-24 months
ISO 27001Defined in policy (typically 1-3 years)

Hot/Warm/Cold tier

Hottier(0-30day)─►SSDindex,fastquery,expensiveWarmtier(30-90day)─►Slowerdisk,infrequentqueryColdtier(90day-1year)─►S3/Glacier,archive,slowrestore
# 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

Logs──►Normalize──►Enrich──►Correlate──►Alert──►Investigate│││││├──"5failedlogin+1success│││fromsameIPin1min"││├──"IAMroleassumedfrom│││unusualIP"││└──"S3GetObject10000obj/min││byuserwithnohistory"│││├──GeoIP,threatintelfeed,assetDB│└──Usercontext(role,department)│└──Maptoschema:ECS,CIM,OCSF

Tools

SIEMCharacteristics
Splunk Enterprise SecurityIndustry leader, expensive
Microsoft SentinelCloud-native, Azure-integrated, pay-per-GB
Elastic SecurityFree tier, OSS base
Datadog Cloud SIEMSaaS, tied to the observability stack
AWS Security Lake + AthenaCheap storage + ad-hoc queries, no real-time alerting
WazuhOSS 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)

┌────────────────────────────────────────────────────────────────┐│││1.Preparation││└──Runbook,training,on-call,tools,commchannel││││▼││2.Detection&Analysis││└──Alerttriage,scopeassessment,severityrating││││▼││3.Containment││├──Short-term:isolatehost,revokesession││└──Long-term:patch,rotatecred,fixrootcause││││▼││4.Eradication││└──Removemalware,closelateralmovement,killC2││││▼││5.Recovery││└──Restoreservice,monitorforre-infection││││▼││6.Post-Incident(LessonsLearned)││└──Blamelesspost-mortem,actionitems,updaterunbook││││└────►loopbacktoPreparation│└────────────────────────────────────────────────────────────────┘

Severity matrix (example)

SeverityDefinitionResponse SLA
SEV-1 CriticalProduction down, data breach, active ransomware< 15 minutes, all-hands
SEV-2 HighPartial outage, suspicious activity confirmed< 1 hour
SEV-3 MediumSingle component degraded, possible threat< 4 hours
SEV-4 LowCosmetic, FYINext business day

Roles during an incident

RoleResponsibility
Incident Commander (IC)Makes decisions, does not fix things personally — coordinates
Tech LeadHands-on debugging, proposes the fix
Communications LeadUpdates the status page, notifies stakeholders and customers
ScribeRecords the timeline, decisions, commands run
Subject Matter ExpertsOn 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 --policy-name DenyAll --policy-document file://deny-all.json

- 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:

  1. Facilitator: "At 3AM on Sunday, CloudTrail detects IAM user ci-deploy creating 50 EC2 instances in region eu-central-1 (a region you do not use). You get paged. What do you do?"
  2. Team discusses step by step: who does what, which commands run, who to escalate to
  3. Facilitator injects new developments ("the EC2 instances are running a crypto miner", "the AWS bill is already +$5000")
  4. 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

┌─────────────────────────────────────────────────────────────────┐│Timeline(UTC)││││14:23:01CloudTrail:GetCallerIdentityfrom203.0.113.42││14:23:15IAM:AccessKeyAKIA...createdforuserbob││14:24:02S3:GetObjectfromnewkey,1000obj/minspike││14:25:30GuardDutyalert:anomalousdataaccess││14:26:00On-callpaged││14:28:14IAM:Disableaccesskey(containment)││14:30:45Log:50000objdownloaded(10GBtotal)│└─────────────────────────────────────────────────────────────────┘│▼Reconstruct:"Bob'slaptoppwnedat14:20viaphishing,attackerstoleAWScredentials,creatednewkeyat14:23topersist..."

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

  1. 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) but x is 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.id goes straight into raw SQL.

    That is why you need both layers + SCA for deps to cover the different surfaces.

  2. 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 when eval only 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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).

  7. 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.

  8. 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.

  9. 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.

  10. 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


Next lesson →