Tag: Incident Response

  • Memory forensics for responders: what Volatility finds that disk forensics misses

    Memory forensics for responders: what Volatility finds that disk forensics misses

    The first time I watched someone pull a memory image off a compromised box before pulling the plug, I thought it was overkill. The disk was right there. Then the disk turned out to be clean. The implant had never been written to it.

    That story is why I care about memory forensics. Disk forensics tells you what was stored. Memory tells you what was running, what it was talking to, and what it had decrypted. For modern intrusions those are often different answers.

    What lives only in RAM

    Comparison chart of what a disk image and a memory image usually contain: memory covers running processes, injected code, command lines, network connections and kernel modules, disk covers installed files.

    The chart above is a hand-built illustration of typical evidence coverage, not measured data.

    Fileless and reflectively loaded malware is the obvious case. A loader that allocates executable memory, copies a payload in and jumps to it leaves nothing for a disk scanner to hash. Process hollowing works the same way: the binary on disk is still a perfectly normal svchost.exe, but the code running under that name isn’t.

    Other things that exist mainly or only in memory:

    • Command lines and environment variables of running processes, including arguments the attacker passed to a tool before deleting the script.
    • Network connections and listening sockets at the moment of capture, with the owning process.
    • Decrypted content. Packed payloads are plaintext once they run, and encrypted volumes are mounted with keys held in RAM.
    • Credentials in use, such as cached tickets and, on older or unprotected Windows setups, secrets in LSASS.
    • Kernel state: loaded drivers and modules, hooked system call tables, hidden processes.

    None of this replaces disk or log evidence. It covers what those two miss, and for kernel state it is the only place to look.

    Capture first

    Memory is the most volatile evidence you have. Every minute the machine runs you lose some of it, and a reboot loses all of it. Capture before you shut anything down. Network isolation is fine and usually right, since it doesn’t touch RAM.

    On Windows, WinPmem writes a raw image. On Linux there are two common options: LiME, a kernel module that has to be built for the running kernel, and AVML, a static binary from Microsoft that reads /proc/kcore or /dev/crash and writes LiME format without a module build.

    # Linux, AVML (run as root, write to external media, not the suspect disk)
    ./avml /mnt/evidence/host01.lime
    
    # Linux, LiME (module must be built for this exact kernel)
    insmod ./lime-$(uname -r).ko "path=/mnt/evidence/host01.lime format=lime"
    
    # Hash it and record who, when and how
    sha256sum /mnt/evidence/host01.lime | tee host01.lime.sha256

    Capturing changes memory. Your tool is now in RAM too. That’s acceptable, but write down what you ran and when.

    First pass with Volatility 3

    Volatility 3 is the current generation, a Python tool you run as vol or python3 vol.py. Windows images pull symbols from Microsoft’s symbol server on first use. Linux images need a symbol table (ISF) matching the exact kernel build, and that is the step that trips people up. If you manage a fleet, build and store symbol files for your standard kernels ahead of time. Doing it during an incident is miserable.

    Start with the process list, and run two plugins that disagree on purpose.

    vol -f host01.raw windows.pslist
    vol -f host01.raw windows.psscan
    vol -f host01.raw windows.pstree
    vol -f host01.raw windows.cmdline

    pslist walks the kernel’s active process list. psscan scans memory for process structures, so it also finds processes that were unlinked from the list or that already exited. A process in psscan and not in pslist deserves a long look, though an exited process isn’t automatically suspicious, so check the exit time first.

    pstree and cmdline give you parentage and arguments. Word spawning PowerShell with an encoded command is the classic, and I still see it more than anything fancier.

    Hunting injected code

    The plugin I reach for next is malfind. It looks for memory regions that are executable and not backed by a file on disk, which is what injected code and reflectively loaded payloads look like.

    vol -f host01.raw windows.malfind
    vol -f host01.raw -o ./dumps windows.malfind --dump
    vol -f host01.raw linux.malfind

    Expect false positives. Just-in-time compilers (browsers, .NET, Java) legitimately create executable anonymous memory, and some security products inject into every process. I treat malfind output as a list of leads: the region’s protection, the first bytes (an MZ header in a private region is hard to explain), and which process owns it. Dump the region and analyze it rather than trusting the plugin’s verdict.

    Network and persistence in memory

    vol -f host01.raw windows.netscan
    vol -f host01.raw windows.svcscan
    vol -f host01.raw windows.registry.hivelist
    vol -f host01.raw linux.sockstat
    vol -f host01.raw linux.lsmod

    netscan can show closed connections as well as live ones that are still resident in memory. That gives you a partial timeline of outbound traffic that firewall logs may not have if the attacker used an allowed port. Matching a remote address to a process you already flagged in the tree is the moment an investigation stops being a hunch.

    On Linux, kernel rootkits are where memory pays for itself. A module hidden from lsmod output can still be found by scanning memory, and a hooked system call table can show up with plugins like check_syscall, depending on kernel version and symbol support. Check the plugin list for your Volatility version, because Linux coverage moves quickly.

    Where it falls short

    Memory images are as large as the machine’s RAM, so you need space and a way to move them, and the capture is a single moment. If the attacker ran something an hour earlier and cleaned up, memory may have been overwritten since. Pages swapped to disk aren’t in the image unless you also collect the pagefile, and Windows hibernation and crash dump files are worth grabbing for the same reason.

    Defenses reduce what you find, too. Credential Guard moves secrets out of the LSASS process into an isolated one. That’s good for defenders even though it makes the forensics less satisfying. Some malware encrypts its payload while idle. And a kernel-level rootkit can lie to your capture tool if you acquire from inside the live OS, which is why hypervisor snapshots of VMs are so valuable: you capture from outside the guest.

    The practical version: if your servers are virtual machines, learn how to take a memory snapshot from the hypervisor before you need one. It is quicker than any agent, and the guest can’t interfere with it.

    What I’d set up now

    Choose a capture tool for each OS and test it on a lab machine. Store Linux symbol files for the kernels you run. Write a one-page procedure covering where the image goes, how it is hashed, and who can authorize a capture on a production host. Then infect a lab VM on purpose, capture it, and run the plugins above. That way the first time you read malfind output isn’t during a real incident.

  • Designing an Incident Response Runbook That Actually Gets Used Under Pressure

    Designing an Incident Response Runbook That Actually Gets Used Under Pressure

    Most incident response docs die the same death. Someone writes them once, during a calm retrospective, optimizing for completeness instead of usability. Six months later it’s 3 a.m., PagerDuty is screaming, there’s a VP in the Slack channel, and nobody opens the doc, because reading five paragraphs of prose to figure out what to do first is cognitively impossible under stress. I’ve watched competent engineers abandon a 40-page “IR plan” in under 90 seconds and just start guessing. The plan wasn’t wrong. It was unusable.

    A runbook that documents your incident process and a runbook that gets followed when your hands are shaking are two different documents.

    Why prose-heavy runbooks fail

    Decision flow diagram for a credential-leak incident response runbook

    Under acute stress, working memory collapses. You lose the ability to parse nested conditionals, skim for relevance, or hold context across paragraphs. That’s neurology, not a discipline problem. A document that reads like a design doc (“In the event that database replication lag exceeds acceptable thresholds, engineers should first consider…”) demands exactly the kind of sustained reading comprehension that incident stress destroys.

    I keep seeing the same three failure modes.

    No entry point. The doc assumes you already know which section applies. There’s no triage step that gets you from “something’s wrong” to “page 14” in under 10 seconds.

    Decisions buried in narrative. The actual decision (“page the DBA if X, roll back if Y”) sits in sentence four of paragraph three, surrounded by justification nobody needs mid-incident.

    Root-cause bias. The doc walks you toward understanding why before it tells you how to stop the bleeding. In a live incident, causality is a luxury. Containment is not.

    Better prose won’t fix this. Build runbooks as flowcharts and checklists first, and demote prose to footnotes and postmortem material.

    What a usable structure looks like

    Every runbook entry should be scannable top to bottom in the order a responder actually needs it, not the order that’s intellectually tidy.

    1. Trigger conditions: the literal alert names, dashboard thresholds, or symptom descriptions that mean “this runbook applies.” Not “if the database seems slow,” the actual PromQL alert name or Datadog monitor ID. Ambiguity here is the single biggest cause of wasted minutes.

    2. Severity tiers, defined by observable impact, not by vibes:

    SEV1: customer-facing outage or data integrity risk, all hands, exec notified
    SEV2: degraded service, workaround exists, on-call + lead notified
    SEV3: internal-only or single-component failure, on-call handles solo

    Tie the tier directly to escalation and comms obligations below. Don’t make the responder infer what SEV2 implies.

    3. First-5-minutes checklist: literal checkboxes, imperative verbs, zero interpretation required. This is the part people actually execute, so it has to survive being read by someone operating at 60% cognitive capacity.

    4. Escalation path: who, in what order, by what channel, with what SLA for response. Include a fallback if the primary doesn’t ack in N minutes. Name the PagerDuty schedule, the phone number, the backup. “Escalate” can’t be a vague gesture.

    5. Communication templates: pre-written, fill-in-the-blank status updates for internal Slack, status page, and customer-facing comms if applicable. Nobody should be composing prose for stakeholders while also fighting the fire.

    6. Containment and rollback steps, before root-cause investigation. This is the part teams get backwards most often. The runbook should assume the goal is “stop customer impact,” not “understand the bug.” Rollback, failover, feature-flag kill, traffic shedding, whatever gets you back to a known-good state comes before anyone opens a debugger or starts reading logs line by line. Root cause is a postmortem activity, not an incident-response one, unless root cause is the fix (killing a single bad host, say).

    Everything else, architecture diagrams, why the system is built this way, historical context, belongs in a linked reference doc, not the runbook itself. If it’s not actionable in the first 15 minutes, it doesn’t belong above the fold.

    Concrete example: suspected credential leak

    Take a credential or API key suspected to be exposed (committed to a public repo, leaked in a log, found in a pastebin).

    RUNBOOK: Suspected Credential Leak
    
    TRIGGER CONDITIONS
    - GitHub secret-scanning alert fired
    - Credential found in public repo, log aggregator, or third-party report
    - Any employee reports pasting a secret into a public channel/tool
    
    SEVERITY
    SEV1 if: production DB creds, cloud provider root/admin keys, payment
             processor keys
    SEV2 if: scoped service credentials, internal-only API keys
    SEV3 if: already-rotated or non-functional/test credentials
    
    FIRST 5 MINUTES (do these in order, do not skip to investigation)
    [ ] 1. Identify exact credential(s) exposed (name, system, scope)
    [ ] 2. Revoke/rotate the credential at the source NOW
           - AWS: `aws iam update-access-key --access-key-id <id> --status Inactive`
           - DB: rotate password, update secrets manager, do not wait for
             app redeploy to confirm, deactivate first
    [ ] 3. Check access/audit logs for USE of the credential since exposure
           timestamp (not since discovery timestamp)
    [ ] 4. If evidence of use: treat as active compromise, escalate to SEV1,
           page security on-call immediately
    [ ] 5. Post initial status in #incidents using template below
    
    ESCALATION
    - Page: Security on-call (PagerDuty "sec-oncall"), ack SLA 5 min
    - If no ack in 5 min: page Security team lead directly (see contacts doc)
    - SEV1: notify Eng Director + CISO via phone, not Slack
    
    COMMUNICATION TEMPLATE (#incidents channel)
        INCIDENT: Credential exposure - [system/service]
        Severity: [SEV1/2/3]
        Status: [Contained / Investigating / Monitoring]
        Credential rotated: [Y/N, timestamp]
        Evidence of misuse: [Y/N, details]
        Next update: [time]
        IC: [name]
    
    CONTAINMENT (before root-cause)
    [ ] Credential rotated/revoked (confirmed, not assumed)
    [ ] Dependent services redeployed with new credential and confirmed healthy
    [ ] If public repo: force-push history rewrite or purge via GitHub support;
        assume cached copies exist regardless (CDN/scraper mirrors), rotation
        is the real fix, not deletion
    [ ] If evidence of use: lock down affected resource (IP allowlist, disable
        key entirely) even if it breaks a dependent system, customer data
        risk outweighs availability here
    
    ROOT CAUSE (postmortem, after containment confirmed)
    - How did the credential reach a public/exposed location?
    - Was secret-scanning in place on this repo/pipeline? If not, why not?
    - Time from exposure to detection, and detection to rotation

    The excerpt leaves things out on purpose. It doesn’t explain OAuth, doesn’t lecture on secrets-management philosophy, doesn’t walk through how secret scanners work under the hood. All of that lives elsewhere. This section has one job: get a half-asleep on-call engineer from “alert fired” to “credential is dead and we know if it was misused” in under ten minutes, with zero ambiguity about who to call next.

    Keeping it alive

    A runbook this terse goes stale fast if nobody exercises it. I’ve seen teams write a beautiful one and then watch it rot for two years because it never got touched. Two practices help.

    Run it in tabletop exercises quarterly, with someone unfamiliar with the specific system reading it cold. If they get stuck or have to ask what a step means, that’s a bug in the doc, not the reader.

    Update it in the postmortem of every real incident it was used for. If a step was ambiguous or missing during the actual event, fix it that week. Runbooks nobody touches after a real use are already decaying, whether anyone notices or not.

    I’d take an unimpressive document that a tired, stressed, possibly junior engineer can execute correctly without me in the room. Write for that person, not for the auditor who’ll read it later.

  • Alert fatigue: tuning detections without going blind

    Alert fatigue: tuning detections without going blind

    Part 3 of 3 in the Detection engineering series. Part 1: Logging that actually helps an investigation. Part 2: Writing detections as code: Sigma rules tested against real logs.

    In 2013, attackers inside Target’s network set off malware alerts from a detection tool the company had recently deployed. The alerts reached Target’s security team, and the US Senate Commerce Committee’s 2014 kill chain analysis of the breach concluded they weren’t acted on in time. Roughly 40 million payment cards were stolen. The detection tool did its job. The process around it didn’t.

    I’ve seen that pattern more than once. When a team gets hundreds of alerts a day and nearly all of them are benign, people learn, quite rationally, that alerts are probably nothing. Then the real one gets the same treatment.

    This is part 3 of the series. Part 1 covered collecting the right events and part 2 covered writing and testing detections as code. This one is about living with them.

    Measure before you tune

    Illustrative Pareto chart of 30-day alert volume by detection rule, coloured by precision

    You can’t tune what you don’t count. For every rule, track three numbers over a rolling 30 days: how many alerts it produced, how many were true positives after triage, and how long triage took. Precision per rule (true positives divided by total alerts) is the most useful single figure, and it’s almost never on the SIEM dashboard by default.

    That means analysts have to record a disposition when they close an alert. Keep the choices small and honest: true positive, benign true positive (the rule matched what it was meant to, but the activity was authorised), false positive, and needs tuning. The “benign true positive” bucket matters, because an admin running a scanner is not the rule being wrong, and conflating the two leads to deleting good rules.

    When you plot alert volume by rule, you’ll nearly always find that a handful of rules generate most of the noise. Good: you don’t have to fix everything, only the top few.

    Tune narrowly

    The lazy fix for a noisy rule is excluding the whole host, the whole service account, or the whole subnet. Each of those is a hole an intruder can stand in. If your backup server is excluded from the PowerShell rule because its jobs are noisy, then PowerShell on the backup server is now invisible, and backup servers are exactly what ransomware operators go looking for.

    Make exceptions as specific as the evidence allows: the exact parent process, the exact command line or script path, ideally the file hash and the expected account. In Sigma that’s a named filter in the rule itself:

    detection:
      selection:
        Image|endswith: '\powershell.exe'
        CommandLine|contains: ' -EncodedCommand '
      filter_backup_job:
        ParentImage: 'C:\Program Files\BackupAgent\scheduler.exe'
        User: 'CORP\svc-backup'
        CommandLine|contains: 'C:\BackupAgent\scripts\prejob.ps1'
      condition: selection and not filter_backup_job

    If the backup agent is compromised and starts running something else, the filter no longer matches and the alert fires.

    Give every exception an owner and an expiry

    Exceptions accumulate like firewall rules. Nobody remembers why half of them exist, and nobody dares remove them. Store them in the repository with metadata, and let CI enforce it:

    # exceptions/powershell-encoded.yml
    rule_id: 0c4b3a9e-71d2-4f5e-9b8a-6e2d1c7f3a10
    filter: filter_backup_job
    reason: Vendor pre-job script uses encoded commands (ticket SEC-1432)
    owner: infra-backup
    expires: 2027-01-31
    import datetime, glob, sys, yaml
    
    today = datetime.date.today()
    expired = []
    for path in glob.glob("exceptions/*.yml"):
        with open(path) as f:
            doc = yaml.safe_load(f)
        if doc["expires"] <= today:
            expired.append(f'{path}: owner {doc["owner"]}, expired {doc["expires"]}')
    
    if expired:
        print("\n".join(expired))
        sys.exit(1)

    When an exception expires, the owner either renews it with a fresh justification or it goes away. I default to ninety days. It’s a little annoying, and that annoyance is what keeps the list short.

    Change what happens, not just whether it fires

    Not every detection should page a human. A lot of useful signals are weak on their own: a new admin tool on a workstation, a login from an unusual country, a service account authenticating interactively. Individually each one is noisy. Together, on the same host or user within a few hours, they tell a story.

    This is risk-based alerting. Low-fidelity rules don’t create alerts; they add a risk score to the user or host they involve. A separate correlation rule fires when an entity’s accumulated score crosses a threshold, or when signals from several distinct ATT&CK tactics appear together. Splunk documents this approach as its RBA framework, but you can build the same thing in any SIEM that can aggregate by entity over a time window.

    Alongside that, route by confidence. High-precision rules page someone. Medium ones land in a queue that’s worked during business hours. The rest feed risk scores and dashboards. A rule that has never produced a true positive in a year and doesn’t feed anything is a candidate for retirement, but only after you’ve confirmed it can still fire (see the next section), because a rule that never fires might be a rule that’s broken.

    Prove you’re not blind

    Tuning removes alerts. The danger is that you can’t easily see the alerts you removed, or the ones that stopped firing because a log source died. So you need a positive signal that coverage still exists.

    Part 2 described scheduled end-to-end tests: a harmless, known action on a test host that a specific rule must catch within minutes. Run those continuously, track the pass rate per rule, and treat a failure as an incident in the detection pipeline. Combine it with a per-source volume monitor so that a domain controller going quiet raises its own alert.

    I also like a quarterly review of the top 20 noisiest rules and every rule with zero alerts. The noisy ones need tuning. The silent ones need a test proving they still work.

    Watch the humans

    The last metric is about the analysts. If one person is triaging 200 alerts per shift, median triage time drops to seconds and the quality goes with it. Track alerts per analyst-hour and the share of alerts closed in under a minute. When those climb, the fix is in the rules, not in telling people to try harder.

    A healthy detection program is one where an alert is rare enough that people still feel a small jolt when one arrives. Getting there is mostly dull bookkeeping, and every hour of it pays off.