Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Security operations basics

Lab · Medium · 1.5 hoursFree account

Threat Hunting with Elastic

Hypothesis-driven hunting in Elastic/Kibana using KQL and EQL.

  • threat-hunting
  • elastic
  • kql
  • eql
  • detection
On this page 14 sections
  1. ·Prerequisites
  2. ·Lab Setup
  3. ·Build the target
  4. ·Build the data
  5. 1Load the data and check it
  6. 2Hunt 1: Office applications that start shells
  7. Locked: Hunt 2: Decode the encoded command
  8. Locked: Hunt 3: A sequence of events with EQL
  9. Locked: Hunt 4: Persistence with scheduled tasks
  10. Locked: Hunt 5: Find the rare process
  11. Locked: Turn the hunt into a detection
  12. Locked: Defence and Detection
  13. Locked: Check Your Work
  14. Locked: Clean-up

Detection rules fire on known bad patterns. Threat hunting asks a different question: what would an attacker do, and does the data show it yet? Many hunts find nothing, and that is still a valid result. Good hunts find attackers that no rule caught, and the best ones turn into new rules that catch them next time. In this lab, you run five hunts in Elastic against a lab dataset of Windows events.

What You'll Learn

  • Write a hunting hypothesis that you can prove or reject with one query
  • Check that the data in the Elastic Stack is complete before you hunt
  • Hunt with KQL in Kibana Discover and with EQL through the search API
  • Find an Office macro chain, an encoded PowerShell command, a scheduled task and a brute-force login
  • Decode a suspicious command and rate each finding as true positive or false positive
  • Turn a hunt query into a saved detection rule

A detection rule waits for a known bad pattern. A hunt does the opposite: you pick a behaviour an attacker must use, then you search the data for it. Many hunts find nothing, and that is a valid result. Some hunts find an attacker that no rule caught. In both cases the hunt ends with a better rule or a better data source.

Every hunt in this lab follows the same loop:

PhaseQuestionIn this lab
HypothesisWhat would the attacker do, and what would it leave in the logs?A sentence at the start of each step
DataWhich index and which fields show it?process and authentication events
AnalysisWhich query separates attacker from normal?KQL, EQL and one aggregation
OutcomeTrue positive, false positive, or no result?A line in your hunt notes
FeedbackCan a rule find it next time?Step 7

You work as a defender. Every query in this lab only reads data.

Prerequisites

Finish the SOC Operations and SIEM workbook first. It explains log sources, alerts and triage, which this lab applies.

For the same ideas in a different product, continue with Threat Detection with Splunk.

Lab Setup

Use your own Kali machine (a Kali Linux machine that you own: a virtual machine is fine). You need these items:

  1. Kibana in a browser at https://10.0.0.20:5601, and Elasticsearch at https://10.0.0.20:9200. You build this Elastic Stack yourself (see Build the target).
  2. The user elastic and its password. You set the password, or Elasticsearch prints it at the first start.
  3. The file hunt-sample.ndjson. You make it with the script in Build the data. It holds 1,240 fake Windows events from the host WS-FIN-07, in Elastic Common Schema (ECS) field names.
  4. curl and jq (both are in a default Kali install).

Store the address and the password in shell variables.

export ES=https://10.0.0.20:9200
export ELASTIC_PASSWORD='<password of the elastic user>'

The data is fake. All names, such as jdoe and WS-FIN-07, and all addresses in 10.0.0.0/8 belong to the lab. The commands use curl -k because the certificate of your own cluster is self-signed. Do not use -k on a real cluster.

Hunt only in data that you own or have written permission to search. On a real cluster, user and process names are personal data. Follow your company rules and do not copy them out of the SIEM.

Build the target

KaliRange hosts no targets, no virtual machines and no lab files. You run this lab on your own machine, against an Elastic Stack that you build. The 10.0.0.20 address is the example address of this lab. Replace it with the address of your own machine.

Your lab needs these parts:

  • One machine at 10.0.0.20 that runs Elasticsearch and Kibana 8.x as a single node, with security on: HTTPS with a self-signed certificate and the user elastic.
  • Kibana on port 5601 and Elasticsearch on port 9200, both reachable from your Kali machine.
  • The Kibana Security app, with detection rules and the rule type Event Correlation (EQL), for Step 7. The free Basic licence is enough for everything in this lab.
  • The index hunt-sample, with the field types and the data from Build the data. Steps 1 to 7 read this index and nothing else.

Build such a machine from free, legal parts. Install Elasticsearch and Kibana from Elastic on a virtual machine or a container on your own computer. Take a snapshot of the virtual machine, or note the state of the container, before Step 1.

Build the data

KaliRange gives no sample files. You make the file hunt-sample.ndjson with the script below. It uses a fixed seed, so it writes the same file each time. It writes 1,240 events of the host WS-FIN-07 on 12 November 2026: 1,018 process events and 222 authentication events. Most events are normal work. A few events are the attack that the five hunts find.

Save the script as make_hunt_sample.py and run it with python3 make_hunt_sample.py.

import base64, json, random, re

rnd = random.Random(1240)
HOST = "WS-FIN-07"
S32 = "C:\\Windows\\System32\\"
OFFICE = "C:\\Program Files\\Microsoft Office\\root\\Office16\\"
PS = S32 + "WindowsPowerShell\\v1.0\\powershell.exe"


def b64(text):
    return base64.b64encode(text.encode("utf-16-le")).decode()


def ts(sec):
    return "2026-11-12T%02d:%02d:%02d.000Z" % (sec // 3600, sec // 60 % 60, sec % 60)


def at(h, m, s):
    return ts(h * 3600 + m * 60 + s)


def proc(t, user, exe, parent, cmd):
    args = [a.strip('"') for a in re.findall(r'"[^"]*"|\S+', cmd)]
    return {"@timestamp": t, "host": {"name": HOST}, "user": {"name": user},
            "event": {"category": "process"},
            "process": {"name": exe.split("\\")[-1], "executable": exe,
                        "command_line": cmd, "args": args, "parent": {"name": parent}}}


def auth(t, user, ip, outcome):
    return {"@timestamp": t, "host": {"name": HOST}, "user": {"name": user},
            "source": {"ip": ip}, "event": {"category": "authentication", "outcome": outcome}}


enc = b64("whoami /all")
docs = [
    # the attack
    proc(at(9, 14, 5), "jdoe", S32 + "cmd.exe", "WINWORD.EXE", "cmd.exe /c powershell -nop -w hidden -enc " + enc),
    proc(at(9, 14, 6), "jdoe", PS, "cmd.exe", "powershell -nop -w hidden -enc " + enc),
    proc(at(9, 14, 8), "jdoe", S32 + "whoami.exe", "powershell.exe", "whoami /all"),
    proc(at(9, 21, 30), "jdoe", S32 + "schtasks.exe", "powershell.exe",
         'schtasks /create /tn "Updater" /tr "C:\\Users\\Public\\upd.exe" /sc minute /mo 30'),
    proc(at(9, 51, 30), "jdoe", "C:\\Users\\Public\\upd.exe", "taskeng.exe", "C:\\Users\\Public\\upd.exe"),
    # the backup job
    proc(at(11, 40, 0), "svc-backup", PS, "taskeng.exe",
         "powershell -nop -enc " + b64("& 'C:\\Scripts\\backup.ps1'")),
]
for i, s in enumerate((41, 43, 44, 46, 48)):
    docs.append(auth(at(3, 11, s), "admin", "10.0.0.77", "failure"))
docs.append(auth(at(3, 12, 2), "admin", "10.0.0.77", "success"))

# normal work: (user, executable, parent, command lines)
U = ["jdoe", "asmith", "mkhan", "lchen"]
pool = [
    (U, "C:\\Windows\\explorer.exe", "userinit.exe", ["explorer.exe"]),
    (U, "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "explorer.exe",
     ["chrome.exe", "chrome.exe --type=renderer", "chrome.exe --type=gpu-process", "chrome.exe --type=utility"]),
    (U, OFFICE + "EXCEL.EXE", "explorer.exe", ['EXCEL.EXE "C:\\Finance\\budget.xlsx"', 'EXCEL.EXE "C:\\Finance\\ledger.xlsx"']),
    (U, OFFICE + "WINWORD.EXE", "explorer.exe", ['WINWORD.EXE "C:\\Finance\\memo.docx"']),
    (U, OFFICE + "OUTLOOK.EXE", "explorer.exe", ["OUTLOOK.EXE"]),
    (U, "C:\\Windows\\splwow64.exe", "EXCEL.EXE", ["splwow64.exe 12288"]),
    (U, S32 + "cmd.exe", "explorer.exe", ["cmd.exe", "cmd.exe /c dir C:\\Finance"]),
    (U, S32 + "ipconfig.exe", "cmd.exe", ["ipconfig /all"]),
    (U, S32 + "ping.exe", "cmd.exe", ["ping 10.0.0.1"]),
    (U, S32 + "conhost.exe", "cmd.exe", ["conhost.exe 0xffffffff -ForceV1"]),
    (U, PS, "explorer.exe", ["powershell.exe -NoProfile -Command Get-Date", "powershell.exe -NoProfile -File C:\\Finance\\report.ps1"]),
    (U, "C:\\Windows\\notepad.exe", "explorer.exe", ["notepad.exe"]),
    (U, "C:\\Program Files\\Microsoft OneDrive\\OneDrive.exe", "explorer.exe", ["OneDrive.exe /background"]),
    (["SYSTEM"], S32 + "svchost.exe", "services.exe", ["svchost.exe -k netsvcs -p", "svchost.exe -k LocalService"]),
    (["SYSTEM"], S32 + "SearchIndexer.exe", "services.exe", ["SearchIndexer.exe /Embedding"]),
    (["SYSTEM"], S32 + "taskhostw.exe", "svchost.exe", ["taskhostw.exe"]),
]
weights = [10, 30, 12, 8, 10, 3, 6, 2, 2, 2, 5, 4, 4, 40, 6, 8]
for users, exe, parent, cmds in rnd.choices(pool, weights, k=1018 - 6):
    docs.append(proc(ts(rnd.randrange(6 * 3600, 19 * 3600)), rnd.choice(users), exe, parent, rnd.choice(cmds)))

# normal logons: one address for each user, about 6 in 100 fail
ips = {"jdoe": "10.0.0.31", "asmith": "10.0.0.32", "mkhan": "10.0.0.33", "lchen": "10.0.0.34"}
for _ in range(222 - 6):
    u = rnd.choice(U)
    docs.append(auth(ts(rnd.randrange(6 * 3600, 19 * 3600)), u, ips[u], "failure" if rnd.random() < 0.06 else "success"))

docs.sort(key=lambda d: d["@timestamp"])
with open("hunt-sample.ndjson", "w") as f:
    for d in docs:
        f.write('{"index":{}}\n' + json.dumps(d) + "\n")
print(len(docs), "events written to hunt-sample.ndjson")

Example output:

1240 events written to hunt-sample.ndjson

Check the file. Each event has an action line before it, so the file has 2,480 lines.

wc -l hunt-sample.ndjson

Example output:

2480 hunt-sample.ndjson

Create the index with keyword fields first. The hunts in this lab need exact values and aggregations on these fields. With the default field types, the terms and rare_terms aggregations fail.

curl -sk -u elastic:$ELASTIC_PASSWORD -H 'Content-Type: application/json' -XPUT "$ES/hunt-sample" -d '
{"mappings": {"properties": {
  "@timestamp": {"type": "date"},
  "host": {"properties": {"name": {"type": "keyword"}}},
  "user": {"properties": {"name": {"type": "keyword"}}},
  "source": {"properties": {"ip": {"type": "ip"}}},
  "event": {"properties": {"category": {"type": "keyword"}, "outcome": {"type": "keyword"}}},
  "process": {"properties": {
    "name": {"type": "keyword"}, "executable": {"type": "keyword"},
    "command_line": {"type": "keyword"}, "args": {"type": "keyword"},
    "parent": {"properties": {"name": {"type": "keyword"}}}}}}}}'

Example output:

{"acknowledged":true,"shards_acknowledged":true,"index":"hunt-sample"}

Step 1: Load the data and check it

1

Prove the data is complete before you hunt

A hunt that finds nothing in a broken data source is a false negative. Before every hunt, check that the events exist, that the fields are filled and that the time range is right.

Load the file into the index hunt-sample with the bulk API. The file already holds the action lines that _bulk needs.

curl -sk -u elastic:$ELASTIC_PASSWORD -H 'Content-Type: application/x-ndjson' \
  -XPOST "$ES/hunt-sample/_bulk?refresh=true" --data-binary @hunt-sample.ndjson \
  | jq '{errors, took, items: (.items | length)}'

Example output:

{
  "errors": false,
  "took": 212,
  "items": 1240
}

"errors": false means that Elasticsearch accepted every event. Count the events by category.

curl -sk -u elastic:$ELASTIC_PASSWORD -H 'Content-Type: application/json' \
  "$ES/hunt-sample/_search?size=0" \
  -d '{"aggs": {"cat": {"terms": {"field": "event.category"}}}}' \
  | jq -c '.aggregations.cat.buckets[]'

Example output:

{"key":"process","doc_count":1018}
{"key":"authentication","doc_count":222}

Now open Kibana. Select the menu, then Discover. Create a data view named hunt-sample with the index pattern hunt-sample and the timestamp field @timestamp. Set the time range to the date of the file: 12 November 2026, 00:00 to 23:59.

In the query bar, type this KQL query and press Enter.

event.category : "process"

Open one event. Look for process.name, process.command_line and process.parent.name. If these fields are empty, every hunt below fails without an error. Write in your hunt notes: data OK, 1,240 events, 2 categories.

Step 2: Hunt 1: Office applications that start shells

2

Hunt a macro chain with KQL

Hypothesis: an attacker sends a document with a macro. The macro makes WINWORD.EXE or EXCEL.EXE start a command shell. A normal user does not do this.

KQL (Kibana Query Language) is the query bar language of Discover. field : value matches a value. and, or and not join conditions. A value in a keyword field is case-sensitive, so use the spelling that the data uses.

Type this query in Discover.

process.parent.name : ("WINWORD.EXE" or "EXCEL.EXE" or "POWERPNT.EXE") and process.name : ("cmd.exe" or "powershell.exe" or "wscript.exe")

Add the columns @timestamp, user.name, process.parent.name, process.name and process.command_line with the field list on the left.

Example result:

@timestampuser.nameprocess.parent.nameprocess.nameprocess.command_line
2026-11-12 09:14:05jdoeWINWORD.EXEcmd.execmd.exe /c powershell -nop -w hidden -enc dwBoAG8AYQBtAGkAIAAvAGEAbABsAA==

The query returns one row: the macro chain. Word started cmd.exe, and the command line of the shell starts a hidden PowerShell window. The PowerShell process itself has cmd.exe as its parent, so this query does not match it. Step 3 finds it. A word processor has no good reason to start cmd.exe and then a hidden PowerShell window. Rate it: likely true positive. Verify it with the user and the mail gateway.

If your query returns nothing, check the spelling of the names. Run process.parent.name : * and look at how the data writes WINWORD.EXE. The EQL operator : in Step 4 ignores case. KQL on a keyword field does not.

Sign in to continue

8 more sections are for signed-in members. It is free: sign in with Google.

This lab is extra practice for the course Security operations basics. Do the lessons first.Open the course