Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install threat-hunting@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin threat-hunting v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install threat-hunting

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/security-threat-hunting/

Extract the ZIP to .github/skills/ in your repo. The folder name must match security-threat-hunting for Copilot to auto-discover it.

Skill Files (3)

SKILL.md 12.2 KB
---
name: security-threat-hunting
description: >
  Hypothesis-driven threat hunting in Elastic Security using iterative ES|QL exploration.
  Covers IOC search, anomaly identification, baseline comparison, lateral movement
  tracking, and turning hunt findings into cases and detection rules. Use when running
  a proactive hunt, investigating suspicious activity patterns, searching for indicators
  of compromise, or looking for rare events in security telemetry.
metadata:
  author: elastic
  version: 0.2.0
  universal: true
compatibility: Elasticsearch 8.x or 9.x — self-managed, Elastic Cloud Hosted, or Elastic
  Cloud Serverless — with endpoint or other security data indexed. Requires the `elastic`
  CLI with `es` support.
---

# Threat Hunting

Hunt proactively for threats that detection rules have not surfaced. Start from a specific hypothesis, explore security
data iteratively with ES|QL, separate anomalies from legitimate behavior, and document what you find.

<!-- begin-partial: preamble -->

## Environment Configuration

This skill executes Elasticsearch operations through the `elastic` CLI. If the
[`elastic` CLI](https://github.com/elastic/cli#configuration) is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.

This skill references operations in HTTP-shorthand form (e.g., `GET /`, `GET /_cat/indices`, `GET /{index}/_mapping`,
`GET /{index}/_settings/index.mode`, `POST /_query`). The [Operations](#operations) table at the end of this document
maps each shorthand to the equivalent `elastic` CLI command — always use the CLI rather than calling the HTTP API
directly.

<!-- end-partial: preamble -->

## Critical principles

- **Start with a hypothesis.** Do not explore without direction. Tie each hunt to a MITRE ATT&CK technique, a threat
  report, or a specific question about your environment.
- **Rare is not malicious.** A single-host, low-count result is a lead, not a finding. Corroborate it before escalating.
- **Zero rows does not mean clean.** It means the hypothesis is not confirmed in this window, data source, and field
  set. Say so explicitly.
- **Report tool output verbatim.** Copy hostnames, IPs, hashes, and counts exactly as returned. Do not invent details.

## Hunting approaches

| Method                | Description                                           | When to use                                                     |
| --------------------- | ----------------------------------------------------- | --------------------------------------------------------------- |
| **Hypothesis-driven** | Start with a specific theory about adversary behavior | New threat intel, emerging technique, "could this happen here?" |
| **CTI-driven**        | Search for known IOCs or TTPs from threat reports     | After reading a threat report, advisory, or news                |
| **Data-driven**       | Use frequency analysis and statistical outliers       | Baseline hunting, anomaly detection, "what's unusual?"          |

## Process

### Step 1 — Formulate a hypothesis

Every hunt starts with a question. Good hypotheses are **specific, testable, and scoped**:

- **Good**: "Are there LOLBin processes making DNS queries to rare external domains in our Windows fleet?"
- **Good**: "Has any process established persistence via Run keys on a single host in the last 7 days?"
- **Bad**: "Is there malware in our environment?" (too broad, not testable)

Define the expected data sources and the time window. Use 7–30 days for behavioral patterns and shorter windows for IOC
sweeps. Sources for hypotheses:

- MITRE ATT&CK techniques relevant to your environment
- Recent threat intelligence or advisories (CTI-driven)
- Alert triage patterns, such as recurring false positives that hint at coverage gaps
- [Elastic Security Labs](https://www.elastic.co/security-labs) research

Data needed: a one-sentence hypothesis, the technique or actor it maps to, the data sources, and the time window.

### Step 2 — Identify data sources

Discover which security indices exist with `GET /_cat/indices`, then confirm field availability before you query. Run
`POST /_query` with `FROM <pattern> | LIMIT 0` to list the available fields without returning documents. Use
`GET /{index}/_mapping` only for a single concrete index: on a wildcard pattern it returns the mapping of every backing
index, which can reach megabytes. Prefer ECS field names for cross-source portability.

Common sources are in the table under [Common indices for hunting](#common-indices-for-hunting). If an index the
hypothesis depends on is absent, say so and stop or adjust the hypothesis — do not query a pattern that matches nothing.

Data needed: confirmed index patterns and the fields available in each.

### Step 3 — Explore iteratively

Run each query with `POST /_query`. Use an existing template from
[references/query-templates.md](references/query-templates.md) (lateral movement, C2 beaconing, brute force, rare
process execution) or write a custom query.

Write custom ES|QL with these principles:

- **FROM**: use the narrowest index pattern, such as `logs-endpoint.events.process-*`.
- **WHERE**: scope every query with an `@timestamp` range, such as `WHERE @timestamp >= NOW() - 7 DAYS`, and filter
  early.
- **KEEP**: select only the fields you need.
- **STATS**: use `COUNT(*)`, `COUNT_DISTINCT(host.id)`, and `VALUES()` for frequency and outlier analysis. Aggregate
  before you pull raw events to understand data volume.
- **LIMIT**: cap output, including aggregations.

Start broad to establish a baseline, then chain `WHERE` clauses to narrow. Avoid one overly complex query.

Data needed: aggregate results that show the shape of the data and which entities to examine.

### Step 4 — Identify anomalies

Look for statistical outliers using the frequency pattern: aggregate by a field, count occurrences and distinct hosts,
then keep only the rare items.

```esql
FROM logs-endpoint.events.process-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.action == "start"
| STATS count = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.executable
| WHERE hosts == 1 AND count <= 3
| SORT count ASC
| LIMIT 50
```

Interpret results:

- **Zero rows**: the hypothesis is not confirmed in this window. Expand the lookback or adjust filters before you
  conclude anything.
- **Low count, single host**: a high-interest finding. Investigate that host.
- **High count, many hosts**: likely legitimate or systemic. Refine filters to reduce noise.
- **Aggregation outliers**: rows with `hosts == 1` or `cc == 1` in frequency hunts are the most interesting.

Use percentile and standard deviation analysis (`PERCENTILE()`, `STD_DEV()`) to find volumetric anomalies. Compare
current activity against a historical baseline before you escalate. Normalize user-specific paths and GUIDs with
`REPLACE()` before aggregating — see [references/hunting-guide.md](references/hunting-guide.md).

Data needed: a short list of anomalous entities, each with the count and host spread that made it stand out.

### Step 5 — Search for IOCs

For CTI-driven hunts, query for known-bad indicators: IP addresses, domains, file hashes, and registry keys. Use
`POST /{index}/_search` for exact-match lookups across indices, and check for related activity on the same entities
within a time window. Cross-reference findings against the threat intelligence you started from.

Data needed: which indicators matched, on which hosts, and when.

### Step 6 — Investigate findings

When a hunt returns an interesting result, pivot into deeper investigation. Query the process tree around the finding
with `POST /_query`, anchored on the finding's absolute timestamp:

```esql
FROM logs-endpoint.events.process-*
| WHERE agent.id == "<agent_id>"
  AND @timestamp >= "<finding_time - 5min>"
  AND @timestamp <= "<finding_time + 10min>"
| KEEP @timestamp, process.name, process.command_line, process.pid, process.parent.name, process.executable
| SORT @timestamp
| LIMIT 50
```

For network context, file lineage, related alerts, and entity risk pivots, see
[references/hunting-guide.md](references/hunting-guide.md). For triage of related alerts, use the
**security-alert-analysis** skill.

Data needed: enough context to classify the finding as a confirmed threat, suspicious (needs more data), or benign.

### Step 7 — Document and operationalize

Record the hypothesis, data explored, queries used, time range, and result. Then act on the finding:

- **Confirmed threat**: create a case with IOCs, MITRE techniques, and affected entities. Use the **kibana-cases** skill
  for the case-management operation. Do not leave hunt results undocumented.
- **New detection gap**: convert the hunting query into a detection rule so the coverage runs continuously. Validate the
  query against recent data before you enable the rule.
- **No findings**: record the hypothesis, query, time range, and the "no findings" result. Consider scheduling the query
  as a recurring hunt or converting it to a detection rule for continuous coverage.

Data needed: classification, evidence summary, and the chosen follow-up action.

## Common indices for hunting

| Data source        | Index pattern                     | Key fields                                                                          |
| ------------------ | --------------------------------- | ----------------------------------------------------------------------------------- |
| Endpoint processes | `logs-endpoint.events.process-*`  | `process.name`, `process.command_line`, `process.parent.name`, `process.executable` |
| Endpoint network   | `logs-endpoint.events.network-*`  | `destination.ip`, `destination.port`, `process.name`, `dns.question.name`           |
| Endpoint files     | `logs-endpoint.events.file-*`     | `file.path`, `file.name`, `event.action`                                            |
| Endpoint registry  | `logs-endpoint.events.registry-*` | `registry.path`, `registry.data.strings`, `process.name`                            |
| Security alerts    | `.alerts-security.alerts-*`       | `kibana.alert.rule.name`, `kibana.alert.severity`                                   |
| AWS CloudTrail     | `logs-aws.cloudtrail-*`           | `event.action`, `aws.cloudtrail.user_identity.type`                                 |

## Guidelines

- **Hunt with direction.** Every query serves the stated hypothesis. Stop and re-scope when it does not.
- **Aggregate before drilling down.** Use `STATS` to understand volume before you pull raw events.
- **Report only tool output.** Do not invent IDs, hostnames, IPs, or details not present in the tool response.
- **Preserve identifiers.** Use the exact values the analyst provides in queries and responses.
- **Distinguish facts from inference.** Label conclusions beyond tool output as your assessment.
- **Use absolute timestamps for pivots.** Anchor follow-up queries on the finding's `@timestamp`, not `NOW()`.
- **Validate before escalating.** Check findings against known-good baselines first.
- **Document the trail.** Future analysts need the hypothesis, queries, and results.

## Examples

- "Hunt for lateral movement using PsExec across all Windows hosts in the last 30 days."
- "Search for any signs of credential dumping or LSASS access."
- "Run a data-driven hunt for unusual outbound network connections."
- "Check whether this IP from a threat report appears anywhere in our endpoint network data."

## References

- [references/query-templates.md](references/query-templates.md) — starter ES|QL templates for lateral movement, C2
  beaconing, brute force, and rare process execution
- [references/hunting-guide.md](references/hunting-guide.md) — query design principles, hunting examples by MITRE
  tactic, and investigation pivots

## Operations

| HTTP API (shorthand)    | `elastic` CLI command                                             |
| ----------------------- | ----------------------------------------------------------------- |
| `GET /_cat/indices`     | `elastic es cat indices --index '<pattern>'`                      |
| `GET /{index}/_mapping` | `elastic es indices get-mapping --index '<index>'`                |
| `POST /_query`          | `elastic es esql query --format tsv --query '<esql>'`             |
| `POST /{index}/_search` | `elastic es search --index '<index>' --input-file '<query.json>'` |
references/
hunting-guide.md 9.5 KB
# Threat Hunting Guide

Detailed hunting patterns, examples, and reference material for proactive threat hunting with Elastic Security. For
ready-to-run starter queries, see [query-templates.md](query-templates.md).

## Hunting query design principles

### ES|QL best practices

1. **Narrow the index**: Use specific index patterns (`logs-endpoint.events.process-*`) instead of broad ones (`logs-*`)
2. **Filter first**: Put the most selective `WHERE` clauses first to reduce processing
3. **Use `KEEP`**: Select only fields needed for `STATS` or review
4. **Aggregate with `STATS`**: Use `COUNT(*)`, `COUNT_DISTINCT(host.id)`, `VALUES()` to find outliers
5. **Normalize paths**: Use `REPLACE()` to normalize user-specific paths and GUIDs for better aggregation
6. **Limit output**: Always include a `LIMIT` clause

### Frequency analysis pattern

The core data-driven hunting pattern: aggregate by a field, count occurrences and unique hosts, then filter for rare
items.

```esql
FROM <index>
| WHERE @timestamp > NOW() - <N> day
  AND <base_filters>
| KEEP <fields_for_aggregation>
| EVAL normalized_field = REPLACE(field, "<pattern>", "<replacement>")
| STATS count = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY <group_by_fields>
| WHERE hosts == 1 AND count <= <threshold>
| SORT count ASC
| LIMIT <N>
```

**Why `hosts == 1`?** If something appears on only one host, it's either unique legitimate software or a potential
indicator. Multi-host occurrence typically means fleet-wide software.

### Path normalization

User-specific paths and GUIDs create artificial uniqueness. Normalize before aggregating:

```esql
| EVAL normalized = REPLACE(process.executable,
    """[cC]:\\[uU][sS][eE][rR][sS]\\[a-zA-Z0-9._\-$~ ]+\\""",
    "C:\\users\\user\\"
  )
| EVAL normalized = REPLACE(normalized,
    """[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}""",
    "<GUID>"
  )
```

## Hunting examples by MITRE tactic

### Persistence (TA0003)

#### Run key persistence (T1547.001)

Hunt for rare programs adding themselves to registry Run keys:

```esql
FROM logs-endpoint.events.registry-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.category == "registry"
  AND event.action == "modification"
  AND ENDS_WITH(registry.key, "\\Microsoft\\Windows\\CurrentVersion\\Run")
  AND NOT registry.data.strings RLIKE """(.{1,2}[c-fC-F]:\\Program Files.+)"""
| KEEP registry.key, registry.data.strings, process.name, host.id
| EVAL registry_data = REPLACE(registry.data.strings,
    """[cC]:\\[uU][sS][eE][rR][sS]\\[a-zA-Z0-9._\-$~ ]+\\""",
    "C:\\users\\user\\"
  )
| STATS cc = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.name, registry_data
| WHERE hosts == 1 AND cc == 1
```

#### Scheduled task persistence (T1053.005)

Hunt for rare scheduled task actions:

```esql
FROM logs-endpoint.events.registry-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.category == "registry"
  AND event.action == "modification"
  AND registry.path LIKE """*\\Actions\\*"""
  AND registry.key LIKE """*\\Schedule\\TaskCache\\Tasks\\*"""
| KEEP registry.data.strings, process.name, host.id
| EVAL task_action = REPLACE(registry.data.strings,
    """[cC]:\\[uU][sS][eE][rR][sS]\\[a-zA-Z0-9._\-$~ ]+\\""",
    "C:\\users\\user\\"
  )
| STATS cc = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.name, task_action
| WHERE hosts <= 2 AND cc <= 5
| SORT cc ASC
| LIMIT 50
```

#### Linux cron persistence (T1053.003)

```esql
FROM logs-endpoint.events.file-*
| WHERE @timestamp > NOW() - 30 day
  AND host.os.type == "linux"
  AND event.type IN ("creation", "change")
  AND (
    file.path IN ("/etc/cron.allow", "/etc/cron.deny", "/etc/crontab")
    OR file.path LIKE "/etc/cron.*/*"
    OR file.path LIKE "/var/spool/cron/crontabs/*"
  )
  AND NOT process.name IN ("dpkg", "dockerd", "yum", "dnf", "snapd", "pacman")
| STATS count = COUNT(*), agent_count = COUNT_DISTINCT(agent.id) BY process.executable, file.path
| WHERE count <= 20 AND agent_count <= 3
| SORT count ASC
| LIMIT 100
```

### Defense Evasion (TA0005)

#### DLL sideloading (T1574.002)

Hunt for rare DLLs loaded by legitimate processes:

```esql
FROM logs-endpoint.events.library-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.action == "load"
  AND (dll.code_signature.exists == false OR dll.code_signature.trusted == false)
  AND process.code_signature.trusted == true
| KEEP dll.name, dll.path, process.name, host.id
| EVAL dll_path_norm = REPLACE(dll.path,
    """[cC]:\\[uU][sS][eE][rR][sS]\\[a-zA-Z0-9._\-$~ ]+\\""",
    "C:\\users\\user\\"
  )
| STATS cc = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.name, dll.name, dll_path_norm
| WHERE hosts == 1 AND cc <= 3
| SORT cc ASC
| LIMIT 50
```

#### Masquerading (T1036)

Hunt for processes pretending to be native Windows binaries but running from unusual paths:

```esql
FROM logs-endpoint.events.process-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.action == "start"
  AND process.name IN ("svchost.exe", "csrss.exe", "lsass.exe", "services.exe", "smss.exe", "wininit.exe", "winlogon.exe")
  AND NOT process.executable RLIKE """[cC]:\\Windows\\(System32|SysWOW64|WinSxS)\\.*"""
| KEEP @timestamp, process.name, process.executable, process.command_line, host.name, agent.id
| SORT @timestamp
| LIMIT 50
```

### Command and Control (TA0011)

#### Beaconing detection (T1071)

Hunt for processes with unusually regular network connections (potential C2 beaconing):

```esql
FROM logs-endpoint.events.network-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.action == "connection_attempted"
  AND NOT CIDR_MATCH(destination.ip, "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", "169.254.0.0/16")
| STATS conn_count = COUNT(*), unique_destinations = COUNT_DISTINCT(destination.ip) BY process.name, agent.id
| WHERE conn_count >= 100 AND unique_destinations <= 3
| SORT conn_count DESC
| LIMIT 50
```

#### DNS over LOLBins (T1071.004)

```esql
FROM logs-endpoint.events.network-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.category == "network"
  AND event.action IN ("lookup_requested", "DNSEvent (DNS query)")
  AND process.name IN ("powershell.exe", "rundll32.exe", "certutil.exe", "mshta.exe", "wscript.exe", "cscript.exe", "regsvr32.exe", "msbuild.exe")
  AND dns.question.name RLIKE """.+\.[a-zA-Z]{2,3}"""
| KEEP process.name, dns.question.name, host.id
| STATS occurrences = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.name, dns.question.name
| WHERE hosts == 1
| SORT occurrences ASC
| LIMIT 50
```

### Credential Access (TA0006)

#### LSASS access (T1003.001)

Hunt for unusual processes accessing LSASS memory:

```esql
FROM logs-endpoint.events.api-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND process.Ext.api.name IN ("OpenProcess", "OpenThread")
  AND Target.process.name == "lsass.exe"
| KEEP process.name, process.executable, host.id
| STATS cc = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY process.executable
| WHERE hosts <= 3
| SORT cc ASC
| LIMIT 50
```

### Lateral Movement (TA0008)

#### SMB file transfers (T1021.002)

```esql
FROM logs-endpoint.events.file-*
| WHERE @timestamp > NOW() - 7 day
  AND host.os.family == "windows"
  AND event.action == "creation"
  AND (file.Ext.header_bytes LIKE "4d5a*" OR file.extension IN ("exe", "dll", "sys", "bat", "cmd", "ps1", "vbs"))
  AND process.name == "System"
  AND file.path LIKE """C:\\Windows\\*"""
| KEEP @timestamp, file.name, file.path, host.id
| STATS cc = COUNT(*), hosts = COUNT_DISTINCT(host.id) BY file.name, file.path
| SORT cc ASC
| LIMIT 50
```

### Cloud Hunting (AWS)

#### Unusual IAM API calls

```esql
FROM logs-aws.cloudtrail-*
| WHERE @timestamp > NOW() - 7 day
  AND event.provider == "iam.amazonaws.com"
  AND event.outcome == "success"
| STATS action_count = COUNT(*), unique_users = COUNT_DISTINCT(aws.cloudtrail.user_identity.arn) BY event.action
| WHERE unique_users == 1 AND action_count <= 3
| SORT action_count ASC
| LIMIT 50
```

#### S3 data exfiltration indicators

```esql
FROM logs-aws.cloudtrail-*
| WHERE @timestamp > NOW() - 7 day
  AND event.provider == "s3.amazonaws.com"
  AND event.action IN ("GetObject", "ListBucket", "ListObjects")
| STATS object_count = COUNT(*), unique_buckets = COUNT_DISTINCT(aws.cloudtrail.request_parameters) BY aws.cloudtrail.user_identity.arn, source.ip
| WHERE object_count >= 50
| SORT object_count DESC
| LIMIT 50
```

## Investigation pivot patterns

When a hunt returns results, use these pivot queries to build the full picture.

### From process finding --> full process tree

```esql
FROM logs-endpoint.events.process-*
| WHERE agent.id == "<agent_id>"
  AND @timestamp >= "<time - 5min>"
  AND @timestamp <= "<time + 10min>"
  AND process.parent.name IS NOT NULL
| KEEP @timestamp, process.name, process.command_line, process.pid, process.parent.name, process.parent.pid
| SORT @timestamp
| LIMIT 80
```

### From network finding --> process + destination context

```esql
FROM logs-endpoint.events.network-*
| WHERE agent.id == "<agent_id>"
  AND process.name == "<process>"
  AND @timestamp >= "<time - 1hr>"
| KEEP @timestamp, destination.ip, destination.port, network.direction, dns.question.name
| SORT @timestamp
| LIMIT 50
```

### From file finding --> who wrote it and what happened next

```esql
FROM logs-endpoint.events.file-*
| WHERE agent.id == "<agent_id>"
  AND file.path == "<file_path>"
| KEEP @timestamp, event.action, process.name, process.executable, file.path
| SORT @timestamp
| LIMIT 20
```
query-templates.md 3.5 KB
# Hunting query templates

Starting-point ES|QL templates for common hunts. These mirror the templates in Kibana's Agent Builder threat-hunting
skill. Adjust index patterns, time windows, and thresholds to the data you have. Run `POST /_query` for each one.

## Lateral movement

### Remote service creation

```esql
FROM logs-endpoint.events.process-*, winlogbeat-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE event.action IN ("start", "Process Create")
  AND process.name IN ("psexec.exe", "psexesvc.exe", "wmic.exe", "mstsc.exe", "schtasks.exe")
| STATS host_count = COUNT_DISTINCT(host.name), exec_count = COUNT(*) BY process.name, user.name
| WHERE host_count > 1
| SORT host_count DESC
| LIMIT 50
```

### Suspicious logon types

```esql
FROM winlogbeat-*, logs-system.security-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE event.code IN ("4624", "4625")
  AND winlog.event_data.LogonType IN ("3", "10")
| STATS attempt_count = COUNT(*), unique_sources = COUNT_DISTINCT(source.ip) BY user.name, host.name
| WHERE unique_sources > 3
| SORT unique_sources DESC
| LIMIT 50
```

## C2 beaconing

### Periodic connection analysis

```esql
FROM logs-endpoint.events.network-*, packetbeat-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE event.action == "connection_attempted"
  AND NOT CIDR_MATCH(destination.ip, "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
| STATS conn_count = COUNT(*), first_seen = MIN(@timestamp), last_seen = MAX(@timestamp)
    BY process.name, destination.ip, host.name
| WHERE conn_count > 50
| SORT conn_count DESC
| LIMIT 50
```

### Low-frequency DNS to rare domains

```esql
FROM packetbeat-*, logs-endpoint.events.network-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE dns.question.name IS NOT NULL
| STATS query_count = COUNT(*), host_count = COUNT_DISTINCT(host.name) BY dns.question.name
| WHERE query_count < 5 AND host_count == 1
| SORT query_count ASC
| LIMIT 100
```

## Brute force and credential spraying

### Failed authentication spike

```esql
FROM winlogbeat-*, logs-system.security-*, filebeat-*
| WHERE @timestamp >= NOW() - 24 HOURS
| WHERE event.outcome == "failure" AND event.category == "authentication"
| STATS fail_count = COUNT(*), target_count = COUNT_DISTINCT(user.name) BY source.ip
| WHERE fail_count > 10
| SORT fail_count DESC
| LIMIT 50
```

### Credential spraying (many users, few attempts each)

```esql
FROM winlogbeat-*, logs-system.security-*
| WHERE @timestamp >= NOW() - 24 HOURS
| WHERE event.outcome == "failure" AND event.category == "authentication"
| STATS fail_count = COUNT(*), user_count = COUNT_DISTINCT(user.name) BY source.ip
| WHERE user_count > 5 AND fail_count / user_count < 3
| SORT user_count DESC
| LIMIT 50
```

## Rare process execution

### Statistically rare processes

```esql
FROM logs-endpoint.events.process-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE event.action == "start"
| STATS host_count = COUNT_DISTINCT(host.name), exec_count = COUNT(*) BY process.executable
| WHERE host_count == 1 AND exec_count < 3
| SORT exec_count ASC
| LIMIT 100
```

### Processes running from unusual directories

```esql
FROM logs-endpoint.events.process-*
| WHERE @timestamp >= NOW() - 7 DAYS
| WHERE event.action == "start"
  AND NOT STARTS_WITH(process.executable, "C:\\Windows\\")
  AND NOT STARTS_WITH(process.executable, "C:\\Program Files")
  AND NOT STARTS_WITH(process.executable, "/usr/")
  AND NOT STARTS_WITH(process.executable, "/bin/")
| STATS exec_count = COUNT(*), host_count = COUNT_DISTINCT(host.name) BY process.executable, process.name
| WHERE host_count == 1
| SORT exec_count ASC
| LIMIT 100
```

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE