Tag: Windows event logs

  • Threat hunting with ATT&CK: from a technique to a hypothesis to a query

    Threat hunting with ATT&CK: from a technique to a hypothesis to a query

    Why most hunts go nowhere

    Flowchart of a threat hunting loop: ATT&CK technique, hypothesis, telemetry check, query, triage, then either a detection or a periodic hunt, and finally a hunt log entry that feeds back to the start

    The hunt loop as a flowchart, drawn by me (not a screenshot).

    The usual failed hunt starts with “let’s look for anything weird in the logs.” Three hours later someone has a pivot table of 40,000 rare process names, none of them malicious, and the hunt gets written up as “no findings.” That isn’t a hunt. It’s browsing.

    A hunt is a falsifiable question about your own environment. “Has an attacker established persistence through scheduled tasks on a server that never creates them?” can be answered yes or no with data you already collect. MITRE ATT&CK is useful here for one reason: it gives you a catalog of behaviors to turn into those questions, so you don’t start from a blank page.

    ATT&CK isn’t a detection strategy on its own. It’s a vocabulary, and the work is translating it.

    Start from a technique, then add a constraint

    Pick one technique and one place it would matter. Scheduled task persistence is T1053.005, and it’s a good teaching case because it is both common in real intrusions and common in legitimate software, which forces you to deal with noise.

    The hypothesis needs three parts: the behavior, the population it applies to, and what normal looks like there. Mine:

    “On our Windows servers, schtasks.exe creating a task that runs a binary from a user-writable path (Temp, ProgramData, Users\Public) is rare, and nearly all of it is explained by a short list of installers and management tools.”

    That sentence tells you the telemetry (process creation with command lines), the filter (create plus a writable path), and the success condition (a short, explainable list). If the data comes back with 900 distinct parents, the hypothesis was wrong and you’ve learned something about your estate, which is a legitimate outcome.

    Check that the data exists before you write the query

    This is the step people skip. Process creation events with full command lines are Sysmon event ID 1, or Windows Security event 4688 with the “Include command line in process creation events” policy enabled. Without that policy 4688 records the image but not the arguments, and a hunt for /create flags is impossible. Scheduled task creation is also logged directly as Security event 4698, but only if the “Audit Other Object Access Events” subcategory is on, and many baselines leave it off.

    Before hunting, count the events per host per day. A server that reports zero process events is not clean. It’s blind. I’ve seen hunts conclude “no activity” on a host where the agent had been dead for three weeks.

    A first query

    Here is the hypothesis as KQL against the Microsoft Defender for Endpoint DeviceProcessEvents table. The table and column names are real. Adapt the path list to your environment.

    DeviceProcessEvents
    | where Timestamp > ago(30d)
    | where FileName =~ "schtasks.exe"
    | where ProcessCommandLine has "/create"
    | where ProcessCommandLine has_any (@"\Temp\", @"\ProgramData\", @"\Users\Public\", @"\AppData\")
    | summarize runs = count(),
                hosts = dcount(DeviceName),
                first = min(Timestamp),
                last = max(Timestamp)
        by InitiatingProcessFileName, InitiatingProcessParentFileName
    | order by hosts asc, runs asc

    Sort ascending on hosts. The interesting rows are parents that appear on one or two machines, not the ones appearing on 300. A software deployment tool hits everything. An intruder hits what they can reach.

    Then look at the rows that survive and read the actual command lines. Don’t trust the summary. A parent of cmd.exe launched from w3wp.exe on a web server is a very different story from cmd.exe launched by your patching agent, and both would collapse into the same “cmd.exe” row if you stopped at the first column.

    Triage the results like an investigator

    For each unexplained hit, answer four things and write them down:

    1. What launched it, and what launched that? Walk the process tree up at least two levels.
    2. What does the task execute, and does that file exist, and who wrote it?
    3. What else did that host do in the ten minutes around it: new services, new outbound connections, credential access?
    4. Is the account that did it one that ever does admin work?

    Most hits will be benign, and that’s fine, as long as you record why. “Backup agent vendor X creates this task on install” becomes an allowlist entry with an owner and a date. Next quarter that entry is what keeps the hunt from re-triaging the same 30 rows.

    Turn the hunt into a detection

    A hunt that finds nothing still produced something: a query with a known false-positive profile. If the allowlist is short and stable, promote it into a scheduled detection. If it’s long and churns every month, don’t. Keep it as a periodic hunt, because an alert nobody trusts is worse than no alert (the previous posts on alert fatigue and Sigma rules cover that tradeoff).

    Writing it up as Sigma makes the logic portable. The process_creation category and fields like Image and CommandLine are standard Sigma taxonomy:

    title: Scheduled task created pointing at user-writable path
    status: experimental
    logsource:
      category: process_creation
      product: windows
    detection:
      selection_img:
        Image|endswith: '\schtasks.exe'
        CommandLine|contains: '/create'
      selection_path:
        CommandLine|contains:
          - '\Temp\'
          - '\ProgramData\'
          - '\Users\Public\'
      condition: selection_img and selection_path
    falsepositives:
      - Software installers and management agents (maintain an allowlist)
    level: medium
    tags:
      - attack.persistence
      - attack.t1053.005

    Keep a hunt log

    Each hunt gets a short record: hypothesis, ATT&CK ID, data source, date range, query, results, disposition, and what changed afterward (new detection, new logging, or nothing). It takes ten minutes and it’s the difference between a program and a series of afternoons. It also shows your coverage gaps. If you can’t write the data source line because the telemetry doesn’t exist, the first deliverable of that hunt is a logging change.

    I’d rather run six well-scoped hunts a quarter than one sprawling exercise. Pick techniques that your actual intrusions or your peers’ public incident reports use, not the ones that look good on a heatmap. A fully green ATT&CK coverage matrix tells you which boxes someone ticked, and says nothing about whether the detections fire.

    What this doesn't do

    A hunt of this kind finds behavior that reuses a known technique through a known tool. It won’t find an operator who creates the task through the Task Scheduler COM API, never touching schtasks.exe, which is exactly what several public tools do. That’s why the next iteration of the hypothesis should target the outcome (a new task registered, event 4698 or the task XML files under C:\Windows\System32\Tasks) rather than one binary. Hunting the artifact rather than the tool is slower to write and survives much longer.

  • Writing detections as code: Sigma rules tested against real logs

    Writing detections as code: Sigma rules tested against real logs

    Part 2 of 3 in the Detection engineering series. Part 1: Logging that actually helps an investigation.

    Detection logic that lives only inside a SIEM’s web console has the same problems as server config edited by hand over SSH. Nobody reviews the change, nobody knows why a condition was added, and when a rule silently stops matching after a log format change, nobody notices for months. Treating detections as code fixes most of that, and Sigma is the most practical way I know to do it without tying yourself to one vendor.

    In part 1 we covered which events to collect. This part is about turning them into rules you can review, version and, most importantly, test.

    What Sigma actually is

    Detection-as-code pipeline: lint, convert, positive and negative fixtures, volume estimate, deploy, production feedback

    Sigma is an open, YAML-based format for describing log detections, maintained by the SigmaHQ project along with a large public rule repository. A rule describes the log source in abstract terms (process creation on Windows, say) and the matching logic as field conditions. A converter then translates it into your backend’s query language: Splunk SPL, Elasticsearch, Microsoft Sentinel’s KQL and many others through pySigma backends.

    The abstraction is the point. The same rule can run against Sysmon data in one environment and against an EDR’s process events in another, as long as a processing pipeline maps the field names.

    A rule worth having

    Here’s a rule for a pattern that turns up in a lot of web server compromises: the IIS worker process starting a command shell. Web applications rarely have a legitimate reason to do that, and a web shell almost always does.

    title: Command shell spawned by IIS worker process
    id: 6b1f3c52-8f0e-4b8a-9d3e-2c7a5e1f9b40
    status: experimental
    description: >
      Detects cmd.exe or PowerShell started by w3wp.exe, which usually
      indicates a web shell or command injection in a hosted application.
    references:
      - https://attack.mitre.org/techniques/T1505/003/
    author: canutethegreat
    date: 2026-10-14
    tags:
      - attack.persistence
      - attack.t1505.003
    logsource:
      category: process_creation
      product: windows
    detection:
      selection:
        ParentImage|endswith: '\w3wp.exe'
        Image|endswith:
          - '\cmd.exe'
          - '\powershell.exe'
          - '\pwsh.exe'
      filter_health_check:
        CommandLine|contains: '\inetpub\scripts\healthcheck.cmd'
      condition: selection and not filter_health_check
    falsepositives:
      - Application pools that deliberately shell out (document them in a filter)
    level: high

    Notice the filter. Real environments always have the one legacy app that shells out for a reason, and the right place to record that exception is in the rule, in version control, with a commit message saying who asked for it. Part 3 goes deeper on how to keep exceptions from eating your coverage.

    Converting and linting in CI

    The sigma-cli tool wraps pySigma. A minimal CI step that validates and converts every rule looks like this:

    pip install sigma-cli
    sigma plugin install splunk
    sigma plugin install sysmon
    
    # Fail the build on structural problems
    sigma check rules/
    
    # Produce backend queries as a build artifact
    sigma convert -t splunk -p sysmon rules/ -o build/splunk.conf

    sigma check catches malformed YAML, missing fields and duplicate IDs. Conversion failures matter too, because a modifier or field that your backend can’t express means the rule never runs where you think it does. I’ve seen rule sets where a quarter of the rules failed conversion and the failures were simply ignored.

    Testing against real logs

    Linting proves a rule is well formed. It says nothing about whether the rule fires on the activity you care about, or whether it fires on a Tuesday-morning patch run. For that you need recorded events.

    Keep two fixture directories next to each rule set. The positive fixtures contain events that must match, ideally captured from a lab machine where you reproduced the behaviour, or taken from public datasets such as the OTRF Security-Datasets project or the EVTX-ATTACK-SAMPLES collection. The negative fixtures contain normal activity from your own estate that must not match: a day of process events from a busy web server is a good start.

    To evaluate Sigma directly against EVTX files without a SIEM, WithSecure’s open source Chainsaw works well:

    chainsaw hunt tests/positive/ -s rules/ \
      --mapping mappings/sigma-event-logs-all.yml --json > out/positive.json
    chainsaw hunt tests/negative/ -s rules/ \
      --mapping mappings/sigma-event-logs-all.yml --json > out/negative.json

    Then a short script turns those results into pass or fail. The exact JSON layout varies between Chainsaw versions, so treat this as a sketch you adapt to the output you get:

    import json, sys
    
    def hits(path):
        with open(path) as f:
            return {d["name"] for doc in json.load(f) for d in doc.get("detections", [])}
    
    expected = {"Command shell spawned by IIS worker process"}
    pos, neg = hits("out/positive.json"), hits("out/negative.json")
    
    missing = expected - pos
    noisy = expected & neg
    if missing or noisy:
        print("did not fire:", sorted(missing))
        print("fired on benign data:", sorted(noisy))
        sys.exit(1)

    Now a rule change that breaks detection fails the build, and so does a change that would page someone on ordinary traffic. Most teams skip that second check, and it’s the one that stops analysts from muting your rules.

    Keep production honest too

    Fixtures drift away from reality. Log schemas change when an agent is upgraded, a field gets renamed, or Sysmon’s config stops collecting the event you depended on. Fixture tests won’t catch any of that, because the fixtures still have the old shape.

    The fix is a scheduled end-to-end check. On a dedicated test host, run a harmless action that a specific rule should catch (for the rule above, a test IIS site whose handler starts cmd.exe /c echo detection-test), then query the SIEM a few minutes later and confirm the alert exists. If it doesn’t, that is itself an alert, routed to whoever owns the pipeline. Frameworks like Atomic Red Team provide catalogued, benign test procedures mapped to ATT&CK techniques, which saves you writing your own for common cases.

    Review like you mean it

    A pull request for a detection should answer the same questions as any code review, plus a few of its own. What behaviour does it catch, and what’s the evidence? Which fixtures prove it? What’s the expected alert volume, measured by running the converted query over the last 30 days of real data? Who triages it, and what does the runbook say they should do first?

    That last question gets skipped constantly. A rule without a response plan just moves the problem from “we didn’t see it” to “we saw it and didn’t know what to do”.

    Once you have dozens of tested rules, the next problem shows up fast: too many alerts. That’s the subject of part 3.

    Other parts: Part 1: Logging that actually helps an investigation. Part 3: Alert fatigue: tuning detections without going blind.