SecurityPart 5: Detection and response
Chapter 17Logging and telemetry
In June 2023 a US State Department analyst caught a China-based actor reading government email in Microsoft's cloud, thanks to one audit event, MailItemsAccessed, that customers on cheaper licences did not receive at all. This chapter teaches you to pick, collect, normalize and protect the telemetry that makes detection possible in the first place.
After this chapter you can
- Explain what endpoint, network, identity and cloud telemetry can and cannot see
- Design a log pipeline that parses, normalizes and stores events with trustworthy timestamps
- Compare SIEM, EDR, XDR and security data lakes, and estimate what retention costs
- Recognize how attackers tamper with logs and design collection that survives it
- Build a local Elasticsearch stack, ship real logs into it and query your own activity
Telemetry is a set of vantage points
Telemetry is the stream of machine-generated records that tells you what happened on a system. Each source sees one slice of an attack from one position. A process launch is invisible to the network, and an encrypted HTTPS session is opaque to a host that only logs process names. No single source sees everything, so coverage comes from combining vantage points.
| Source | Sees well | Blind to |
|---|---|---|
| Endpoint (Sysmon, auditd, eBPF, EDR) | Processes, command lines, file and registry changes, which process opened which connection | Hosts without an agent, activity inside a process's memory, network devices |
| Network (flow logs, Zeek) | Who talked to whom, when, how much; DNS, TLS names, HTTP metadata | Payload of encrypted traffic, which process made the connection |
| Identity provider (Entra ID, Okta) | Sign-ins, MFA results, token issuance, app consents | What the user did after authenticating to a third-party app |
| Cloud audit (CloudTrail, Azure Activity, GCP Audit Logs) | Control-plane API calls, who called them, from where | Data reads unless you opt in and pay, activity inside a VM |
Endpoint telemetry: Sysmon, auditd and eBPF
The endpoint is where attackers run code, so it is the richest source. On Windows, the built-in Security log records logons (Event ID 4624, failures 4625) and process creation (4688). Process command lines only appear in 4688 if you enable the "Include command line in process creation events" policy, and that one setting decides whether living-off-the-land activity is visible at all.
Sysmon (System Monitor) is a free Microsoft driver that writes far richer events to its own log channel. It was a separate Sysinternals download for years. Windows 11 and Windows Server 2025 now include it as an optional feature that is off by default. Its value comes from a configuration file that says what to keep and what to drop.
| Sysmon event ID | Records | Why defenders care |
|---|---|---|
| 1 | Process created, with command line, parent and hashes | The backbone of most endpoint detections |
| 3 | Network connection, with the process that made it | Ties traffic to a binary |
| 10 | One process opened another (ProcessAccess) | Credential dumping touches LSASS this way |
| 11 | File created | Dropped payloads, staged archives |
| 13 | Registry value set | Run keys and other persistence |
| 22 | DNS query, with the requesting process | Finds beaconing and odd domains per process |
On Linux, the kernel audit subsystem (auditd) logs system calls that match rules you write. eBPF (extended Berkeley Packet Filter) lets small verified programs run inside the kernel. Tools such as Falco, Tetragon and Sysmon for Linux use it to watch process, file and network events with less overhead and richer context than auditd.
# Log every program execution on 64-bit syscalls, tagged for searching
-a always,exit -F arch=b64 -S execve -k exec
# Watch for changes to SSH authorized keys (persistence)
-w /root/.ssh/authorized_keys -p wa -k ssh_keysNetwork, identity and cloud telemetry
Network telemetry comes in two depths. Flow logs (VPC Flow Logs in AWS, NetFlow/IPFIX on routers) record the 5-tuple: source and destination address, ports and protocol, plus byte counts and timing. Zeek is an open-source network monitor that turns a packet feed into structured logs per protocol: conn.log, dns.log, http.log, ssl.log and more. It still cannot read inside TLS, but the server name, certificate and timing are often enough to spot beaconing.
ts uid id.orig_h id.orig_p id.resp_h id.resp_p proto service duration orig_bytes resp_bytes
1733047201.3 CuJx1a2b 10.0.4.17 51544 203.0.113.50 443 tcp ssl 0.42 517 3120Identity provider logs record every sign-in, the MFA method used, the device and location, and grants such as an OAuth app consent. Since most modern intrusions start with a stolen session or password, these logs often hold the first sign of trouble. Default retention is short (days to a month depending on licence), so export them to your own storage.
Cloud audit logs record control-plane API calls. In AWS, CloudTrail management events (such as CreateUser or StopLogging) are recorded by default and kept 90 days in Event history. Data events, such as each S3 object read, are off by default and billed separately. Google Cloud splits the same idea into Admin Activity logs (always on) and Data Access logs (mostly off by default).
Pipelines and normalization
A log pipeline moves events from where they are produced to where you can search them. Along the way it parses raw text into fields, enriches events (adding asset owner, geolocation or threat-intel matches) and normalizes field names so one query works across sources.
Normalization matters because every vendor names the same thing differently. Without it, a rule for "suspicious command line" must know that one source says CommandLine, another cmdline and a third process.args. Two open schemas dominate:
| Concept | ECS (Elastic Common Schema) | OCSF (Open Cybersecurity Schema Framework) |
|---|---|---|
| Full command line | process.command_line | process.cmd_line |
| User | user.name | actor.user.name |
| Host | host.name | device.hostname |
| Source IP | source.ip | src_endpoint.ip |
| Event kind | event.category: process | class_uid: 1007 (Process Activity) |
ECS grew out of Elastic and has been contributed to OpenTelemetry's semantic conventions. OCSF is a vendor-neutral project used by AWS Security Lake and many SIEM vendors. Pick one per platform and map everything to it at ingest.
Where telemetry lives and what it costs
Four product categories overlap and get confused in interviews.
| Category | What it is | Strength | Limit |
|---|---|---|---|
| SIEM (Security Information and Event Management) | Central search, correlation and alerting over many log sources | Cross-source detection, compliance reporting | Expensive per GB ingested; only as good as what you send |
| EDR (Endpoint Detection and Response) | Agent on each host that records activity and can act on it | Deep endpoint visibility, isolate host, kill process | Sees only endpoints with the agent |
| XDR (Extended Detection and Response) | A vendor's EDR plus its own network, email and identity telemetry, correlated | Integrated story across one vendor's tools | Weaker with other vendors' data |
| Security data lake | Cheap object storage (Parquet, Iceberg) queried with SQL engines | Long retention at low cost | Slower queries, you build detection on top |
A common pattern is to route high-value, detection-relevant events to the SIEM and send everything else to the lake for hunting and investigations. Retention is the other big lever. Attackers often go undetected for weeks or months, so a 30-day window can delete the start of an intrusion before anyone looks. Compliance can also set a floor: PCI DSS, for example, requires a year of audit logs with the last three months immediately available.
Estimate cost before you switch a source on. The arithmetic is simple, and the inputs are what you must measure in your own environment:
2,000 endpoints x 5,000 events/day x 800 bytes = 8 GB/day raw
x 90 days hot retention = 720 GB
x ~0.3 after index compression (varies widely) = ~216 GB on disk
Raw ingest of 8 GB/day is what most SIEMs bill on.Time is evidence
An investigation is a timeline, and a timeline is only as good as its clocks. Every host should sync to the same time source with NTP (Network Time Protocol, for example via chrony) and every pipeline should store UTC. Three different timestamps describe one event, and they disagree more often than you would think.
Here is a real example from a public attack dataset you will load in the lab. The same Sysmon process event carries UtcTime: 2020-10-18 23:50:05.910 and TimeCreated: 2020-10-18 07:50:05.917. The second field appears to be local time (US Eastern, 19:50) written in 12-hour format with no AM/PM marker and no zone, so naive parsing places it 16 hours earlier. Your pipeline must decide which field is the event time, convert it to UTC, and record how much it trusts that decision.
What attackers do to logs
Attackers know you watch logs, so tampering is a documented set of MITRE ATT&CK techniques. MITRE ATT&CK is a public catalogue of adversary techniques, each with an ID such as T1070. In 2026 (ATT&CK v19) the old Defense Evasion tactic was split into Stealth and Defense Impairment, so older reports cite the log-tampering techniques below as T1070.001 and T1562.x.
| Technique | What it looks like | What still catches it |
|---|---|---|
| Clear Windows event logs (T1685.005) | wevtutil cl Security | Event 1102 "audit log was cleared", events already forwarded off-host |
| Disable or modify Windows event log (T1685.001) | Stopping the EventLog service, changing audit policy | Heartbeat gap from that host, policy-change events |
| Disable or modify tools (T1685) | Unloading Sysmon, stopping the EDR agent | Agent health alerts, last-seen time per host |
| Disable or modify cloud log (T1685.002) | CloudTrail StopLogging, DeleteTrail | Alert on those API calls; organization-level trails the account cannot touch |
| Clear command history (T1070.003) | unset HISTFILE, history -c | Process telemetry from auditd or eBPF |
| Timestomp (T1070.006) | Changing file timestamps to blend in | NTFS $FILE_NAME times and the USN journal, which are harder to edit |
The defenses follow one principle: get events off the host fast, onto storage the attacker cannot reach. Forward in near real time, write archives to immutable storage such as S3 Object Lock, and alert when a source goes silent. A host that stops sending logs is itself an alert.
Key terms
- Telemetry
- Machine-generated records of activity on systems, networks, identities and cloud services.
- Sysmon
- A free Microsoft driver that logs detailed process, network, file and registry events on Windows.
- eBPF
- A Linux mechanism for running small verified programs in the kernel, used by modern sensors to observe system activity.
- Zeek
- An open-source network monitor that turns traffic into structured per-protocol logs.
- Normalization
- Mapping fields from different sources onto one schema so a single query works across them.
- ECS and OCSF
- Two open schemas for security events: Elastic Common Schema and the Open Cybersecurity Schema Framework.
- SIEM
- A platform that centralizes logs for search, correlation and alerting.
- EDR
- An endpoint agent that records host activity and can take response actions such as isolating the machine.
- Ingest time
- When the pipeline received an event, as opposed to when the event happened.
Build a home SIEM and find your own footprints
Goal: run Elasticsearch and Kibana locally, ship live SSH logs and a recorded Windows attack dataset into them, normalize both, and find specific events with queries. You will reuse this stack in the next three chapters, so keep the folder.
You need: Docker Desktop (give it at least 4 GB of memory) or Docker Engine with Compose v2, curl, jq (preinstalled on recent macOS; sudo apt install jq on Debian/Ubuntu), Python 3.10 or newer, and about 3 GB of disk. On a Linux host, Elasticsearch also needs sudo sysctl -w vm.max_map_count=262144. Everything runs on your machine and listens only on 127.0.0.1; the "victim" is a container you build.
- Create the project folder and the compose file.
mkdir -p ~/seclab/data ~/seclab/hunts && cd ~/seclabname: seclab
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:9.5.7
environment:
- discovery.type=single-node
- xpack.security.enabled=false # lab only, never on a reachable host
- ES_JAVA_OPTS=-Xms1g -Xmx1g
ports: ["127.0.0.1:9200:9200"]
volumes: [esdata:/usr/share/elasticsearch/data]
kibana:
image: docker.elastic.co/kibana/kibana:9.5.7
environment:
- ELASTICSEARCH_HOSTS=http://elasticsearch:9200
ports: ["127.0.0.1:5601:5601"]
depends_on: [elasticsearch]
victim:
build:
context: .
dockerfile_inline: |
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y --no-install-recommends openssh-server \
&& mkdir -p /run/sshd /var/log/sshd \
&& useradd -m -s /bin/bash analyst \
&& echo 'analyst:lab-only-password' | chpasswd
CMD ["/usr/sbin/sshd", "-D", "-E", "/var/log/sshd/sshd.log"]
hostname: victim
ports: ["127.0.0.1:2222:22"]
volumes: [victimlogs:/var/log/sshd]
fluent-bit:
image: fluent/fluent-bit:5.2.1
user: "0"
command: ["/fluent-bit/bin/fluent-bit", "-c", "/fluent-bit/etc/fluent-bit.yaml"]
volumes:
- ./fluent-bit.yaml:/fluent-bit/etc/fluent-bit.yaml:ro
- victimlogs:/victim-logs:ro
depends_on: [elasticsearch, victim]
volumes:
esdata:
victimlogs:Newer patch versions of Elasticsearch, Kibana and Fluent Bit work too; keep Elasticsearch and Kibana on the same version.
- Add the shipper configuration. Fluent Bit tails the SSH log file and sends each line to Elasticsearch.
service:
flush: 1
log_level: info
pipeline:
inputs:
- name: tail
path: /victim-logs/sshd.log
tag: victim.sshd
read_from_head: true
refresh_interval: 5
outputs:
- name: es
match: 'victim.*'
host: elasticsearch
port: 9200
index: linux-sshd
suppress_type_name: on
retry_limit: no_limits- Start only Elasticsearch and Kibana first, and wait until the cluster reports
green. Kibana takes a minute or two longer.
docker compose up -d elasticsearch kibana
until curl -s localhost:9200/_cluster/health | grep -q '"status":"green"'; do sleep 5; done; echo ready- Create the normalization rules before any data arrives. The ingest pipeline turns raw sshd lines into ECS fields. The two index templates set mappings: Linux strings stay case-sensitive, while Windows strings are stored lowercased because Windows paths are case-insensitive. Templates only apply to new indices, which is why the order matters.
#!/usr/bin/env bash
set -euo pipefail
ES=http://127.0.0.1:9200
put() { curl -s -X PUT "$ES/$1" -H 'Content-Type: application/json' -d @-; echo; }
put _ingest/pipeline/sshd-parse <<'JSON'
{
"description": "Normalize OpenSSH log lines to ECS",
"processors": [
{ "rename": { "field": "log", "target_field": "message", "ignore_missing": true } },
{ "gsub": { "field": "message", "pattern": "\\r$", "replacement": "", "ignore_missing": true } },
{ "grok": {
"field": "message",
"patterns": ["%{SSHD_ACTION:event.action} %{USERNAME:user.name} from %{IP:source.ip} port %{NUMBER:source.port:int}"],
"pattern_definitions": {
"SSHD_ACTION": "Invalid user|Failed password for invalid user|Failed password for|Accepted password for|Accepted publickey for"
},
"ignore_failure": true } },
{ "set": { "if": "ctx.event?.action != null && ctx.event.action.startsWith('Accepted')", "field": "event.outcome", "value": "success" } },
{ "set": { "if": "ctx.event?.action != null && !ctx.event.action.startsWith('Accepted')", "field": "event.outcome", "value": "failure" } },
{ "set": { "field": "host.name", "value": "victim" } },
{ "set": { "field": "event.dataset", "value": "sshd" } },
{ "set": { "field": "event.ingested", "value": "{{{_ingest.timestamp}}}" } }
]
}
JSON
put _index_template/lab-linux <<'JSON'
{
"index_patterns": ["linux-*"],
"template": {
"settings": { "number_of_replicas": 0, "index.default_pipeline": "sshd-parse" },
"mappings": {
"dynamic_templates": [
{ "strings": { "match_mapping_type": "string",
"mapping": { "type": "keyword", "ignore_above": 8191 } } }
],
"properties": { "source": { "properties": { "ip": { "type": "ip" } } } }
}
}
}
JSON
put _index_template/lab-winlogs <<'JSON'
{
"index_patterns": ["winlogs-*"],
"template": {
"settings": {
"number_of_replicas": 0,
"analysis": { "normalizer": { "lc": { "type": "custom", "filter": ["lowercase"] } } }
},
"mappings": {
"dynamic_templates": [
{ "strings": { "match_mapping_type": "string",
"mapping": { "type": "keyword", "normalizer": "lc", "ignore_above": 8191 } } }
],
"properties": { "@timestamp": { "type": "date" }, "EventID": { "type": "integer" } }
}
}
}
JSONchmod +x setup-es.sh && ./setup-es.shExpect three lines of {"acknowledged":true}.
- Start the victim and the shipper, then generate activity: a burst of logins for usernames that do not exist, one wrong password, and one real login.
docker compose up -d --build victim fluent-bit
for u in admin oracle test ubuntu pi postgres; do
ssh -p 2222 -o BatchMode=yes -o StrictHostKeyChecking=no \
-o UserKnownHostsFile=/dev/null "$u@127.0.0.1" true 2>/dev/null
done
ssh -p 2222 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null analyst@127.0.0.1At the password prompt type something wrong once, then lab-only-password. Run id and exit. Confirm the raw log exists with docker compose exec victim tail -n 5 /var/log/sshd/sshd.log.
- Save a small helper that sends ES|QL (Elasticsearch's piped query language) from a file, then find your footprints.
#!/usr/bin/env bash
# usage: ./esql.sh hunts/query.esql
jq -n --rawfile q "$1" '{query: $q}' |
curl -s -H 'Content-Type: application/json' \
'http://127.0.0.1:9200/_query?format=txt' -d @-FROM linux-sshd
| WHERE event.outcome IS NOT NULL
| STATS attempts = COUNT(*) BY source.ip, event.outcome, user.name
| SORT attempts DESCchmod +x esql.sh && ./esql.sh hunts/ssh-footprints.esqlYou should see one failure row per fake username, a failure and a success for analyst, all from one source IP. That IP is your Docker gateway (often 192.168.65.1 on Docker Desktop or 172.x.0.1 on Linux), not your laptop's address: NAT already hid the true source.
- Load a recorded Windows attack. The OTRF Security-Datasets project publishes real Sysmon and Security logs captured while attacks ran in a lab. Download two, then load them with a script that picks a trustworthy timestamp for each event.
cd ~/seclab/data
B=https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows
curl -sSLO $B/credential_access/host/psh_lsass_memory_dump_comsvcs.zip
curl -sSLO $B/discovery/host/empire_shell_net_local_users.zip
unzip -o -q '*.zip' && ls *.json && cd ..#!/usr/bin/env python3
"""Load a Security-Datasets JSON-lines file into Elasticsearch.
Usage: python3 load_dataset.py data/<file>.json
"""
import json
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
ES = "http://127.0.0.1:9200"
INDEX = "winlogs-lab"
def to_utc(text):
stamp = datetime.strptime(text, "%Y-%m-%d %H:%M:%S.%f")
return stamp.replace(tzinfo=timezone.utc).isoformat()
def pick_time(event):
"""Return (timestamp, how far to trust it)."""
try:
if event.get("@timestamp"):
return event["@timestamp"], "collector"
if event.get("UtcTime"): # Sysmon always writes UTC here
return to_utc(event["UtcTime"]), "sysmon_utc"
if event.get("TimeCreated"): # local clock, zone unknown
return to_utc(event["TimeCreated"]), "untrusted_local"
except ValueError:
pass
return None, "missing"
def normalize(event, source):
# Store every scalar as a string so mixed types across files never clash
doc = {k: (v if isinstance(v, (dict, list)) else str(v))
for k, v in event.items() if v is not None}
doc["EventID"] = int(event.get("EventID", 0))
stamp, trust = pick_time(event)
if stamp:
doc["@timestamp"] = stamp
doc["lab"] = {"time_source": trust, "dataset": source}
return doc
def send(lines):
body = ("\n".join(lines) + "\n").encode()
req = urllib.request.Request(f"{ES}/_bulk", data=body, method="POST",
headers={"Content-Type": "application/x-ndjson"})
with urllib.request.urlopen(req) as resp:
result = json.load(resp)
if result["errors"]:
bad = next(i["index"] for i in result["items"] if "error" in i["index"])
sys.exit(f"bulk error: {bad['error']}")
def main(path):
source = Path(path).stem
batch, total = [], 0
with open(path, encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
batch.append(json.dumps({"index": {"_index": INDEX}}))
batch.append(json.dumps(normalize(json.loads(line), source)))
total += 1
if len(batch) >= 1000:
send(batch)
batch = []
if batch:
send(batch)
print(f"indexed {total} events from {source} into {INDEX}")
if __name__ == "__main__":
main(sys.argv[1])for f in data/*.json; do python3 load_dataset.py "$f"; doneExpect indexed 184 events ... and indexed 1907 events ....
- Find the credential dump and see the clock problem for yourself.
FROM winlogs-lab
| WHERE EventID == 1 AND CommandLine LIKE "*minidump*"
| KEEP @timestamp, Hostname, User, ParentImage, CommandLineFROM winlogs-lab
| WHERE lab.dataset LIKE "psh_lsass*"
| STATS events = COUNT(*), first = MIN(@timestamp), last = MAX(@timestamp) BY lab.time_sourceThe first query returns one rundll32.exe launch at 2020-10-18T23:50:05.910Z whose command line calls comsvcs.dll with minidump (values appear lowercased because of the Windows template). The second shows 148 sysmon_utc events around 23:50 and 36 untrusted_local Security events around 07:50, 16 hours apart, though they describe the same few seconds.
- Open Kibana at
http://localhost:5601, go to Discover, and create a data view forlinux-*and another forwinlogs-*, both with@timestampas the time field. Set the time picker wide enough to include October 2020 for the Windows data.
Check your work: curl -s localhost:9200/linux-sshd/_count returns a count of at least 8, the footprints query shows your fake usernames with failure, and the LSASS query returns exactly one event.
Stretch: fix the untrusted timestamps properly. Compute the offset between TimeCreated and UtcTime from Sysmon events in the same file, apply it to the Security events in load_dataset.py, reload into a new index (winlogs-fixed), and show that both sources now line up within a second.
Check yourself
An attacker runs living-off-the-land commands such as wmic and netsh on a Windows server. You have Security event 4688 enabled but nothing else. What is most likely missing?
Your SIEM shows a host's events arriving with an ingest time six hours after their event time, for that host only. What is the best first hypothesis?
Which control best protects audit evidence against an attacker who gains admin rights on a server?
A teammate proposes sending every VPC flow log and every S3 data event straight into the SIEM. What is the strongest objection?
Recap
- Each telemetry source is a vantage point with blind spots; coverage comes from combining endpoint, network, identity and cloud logs.
- Defaults decide visibility: command-line auditing, cloud data events and IdP retention often need switching on.
- Pipelines parse, enrich and normalize; a schema such as ECS or OCSF lets one query span many sources.
- SIEM, EDR, XDR and data lakes solve different problems, and volume times retention drives cost.
- Store UTC, keep event and ingest time, and record how much you trust each timestamp.
- Forward logs off-host quickly to storage attackers cannot alter, and treat silence as a signal.
Go deeper
- Sysmon documentation (Microsoft Sysinternals): event IDs, configuration schema and install options.
- Elastic Common Schema reference: field definitions you will meet in Elastic, Sigma pipelines and many shippers.
- OCSF schema browser: explore event classes and objects in the vendor-neutral schema.
- Zeek documentation: what each Zeek log contains and how to run it on a packet capture.
- OTRF Security-Datasets: recorded attack telemetry for practising detection without running malware.
- CISA advisory AA23-144A: a real advisory whose detection guidance depends on command-line logging.