A single thin pipeline line crossing a vast blue-gray snowfield seen from an aircraft at dusk, with the article title about generating Cortex XQL queries with an LLM
Cover based on a photo by BLM Alaska, via Wikimedia Commons, Public domain

You can generate Cortex XQL queries with an LLM in seconds, and the first draft usually looks plausible: a dataset = xdr_data, a couple of filter stages, a comp count(). The trouble is that XQL, the query language in Palo Alto Networks Cortex XDR and XSIAM, has seen far less training data than SPL or KQL. Models fill the gaps with habits from those languages: where, stats, ==, project. Some of those mistakes fail loudly in the query builder. Others run fine and return the wrong rows. In our lab, a "working" XQL query for encoded PowerShell caught 4 of 7 encoded command lines and flagged 3 harmless ones. A query an LLM wrote is a draft until it returns the activity you planted and leaves the look-alikes out.

XQL isn't the same language as Velociraptor's VQL, Splunk's SPL or Microsoft's KQL, though it borrows pipes and some vocabulary. If you hunt in those tools, see our guides to KQL hunting queries, Splunk SPL searches and Velociraptor VQL. This post is about Cortex.

What we tested, and what we didn't

The real judge of an XQL query is a Cortex tenant: the query builder runs it against your data or returns an error. We didn't have a tenant for this guide, so we split the work into three checks we could actually run, plus a documentation check:

  1. A local XQL linter. XQLibur is an MIT-licensed, independent VS Code extension that parses XQL locally and flags unknown stages, unknown functions, wrong argument counts and fields removed by an earlier stage. Its core has no editor dependency, so we bundled it into a 20-line Node CLI at commit 28683c0 (release 0.3.2). It's a young project, and its own README says a clean result doesn't prove a query will run in Cortex. We treat it as a fast first filter, nothing more. As a calibration run, it reported no findings on the sample query in Palo Alto's public cortex-xql-queries repo.
  2. A regex test bench. The ~= pattern is where hunting logic lives, so we tested every pattern against 14 command lines with Go's regexp package (Go 1.27.3), which implements RE2 syntax. Palo Alto's current reference pages don't name XQL's regex engine, so treat this as a check on your logic, and confirm unusual constructs in your tenant.
  3. The official reference. For everything a linter can't know, we checked the Cortex XQL Command Reference and the XQL query best practices page, and we link the page for each claim.

The drafts below were written for this guide to reproduce mistakes models commonly make in XQL. They aren't a captured model transcript, and no model was called in the lab. We don't show Cortex output, because we didn't run Cortex.

How to generate Cortex XQL queries with an LLM

The hunt: find endpoints where PowerShell ran with an encoded command in the last seven days, and show the host, the users, the parent processes, a count, and first and last seen. Encoded commands are a common way to hide what a script does (MITRE ATT&CK T1059.001 lists many groups that use them), and the goal is easy to state, which makes it a good test.

Diagram of the loop to generate Cortex XQL queries with an LLM: the stage list, real xdr_data field names and the hunting goal go into the prompt, the model drafts an XQL query, a local XQL linter flags unknown stages and fields dropped by comp, a regex test bench checks the ~= pattern against encoded and look-alike PowerShell command lines, and a run in the Cortex XDR or XSIAM query builder against planted lab activity decides whether the query is kept
Lint and the regex bench return their exact output to the model before the query reaches Cortex. We did not run the Cortex step. Image: RedRouter, Original

Step 1: Give the model XQL stages and real field names

Models write better XQL when the prompt pins down three things:

  • The stages you allow. XQL queries are a pipeline: config first, then dataset or preset, then stages such as filter, alter, fields, comp, sort and limit. Paste the stages list or a short version of it, and say "no SPL or KQL syntax."
  • Field names copied from your tenant. For process events in xdr_data, Palo Alto's own examples use event_type = ENUM.PROCESS, event_sub_type = ENUM.PROCESS_START, action_process_image_name, action_process_image_command_line, actor_process_image_name, actor_effective_username and agent_hostname (see the best practices page and the getrole example). Check them against a real event in your schema before you trust them, because a model will invent plausible ones.
  • The goal with numbers. "PowerShell or pwsh with -EncodedCommand or any of its short forms, last 7 days, grouped by host."

Step 2: Lint the first Cortex XQL draft

Here's a typical first draft. It reads like XQL, but half of it is borrowed:

dataset = xdr_data
| config timeframe = 7d
| where event_type = ENUM.PROCESS
| filter action_process_image_name = "powershell.exe" and action_process_image_command_line contains "-enc"
| stats count() as runs by agent_hostname
| sort runs desc

The linter's output:

$ node xqlcheck.cjs draft1_encoded_ps.xql
draft1_encoded_ps.xql
  3:3  warning  XQL201  Stage 'where' is not in the bundled reference; newer syntax may be supported by Cortex.
  5:3  warning  XQL201  Stage 'stats' is not in the bundled reference; newer syntax may be supported by Cortex.
0 error(s), 2 other finding(s)

Both findings are right. XQL filters rows with filter and aggregates with comp; where and stats are Splunk and KQL habits.

Two more problems went through without a warning:

  1. config isn't first. The config reference says the stage "must always be the first stage in your XQL query." The linter doesn't check stage order.
  2. sort runs desc has the direction in the wrong place. The sort syntax is sort asc|desc <field>, so it's sort desc runs.

The linter is quiet about the worst problem of all, the contains "-enc" logic. We come back to that in Step 4.

Step 3: Watch what comp throws away

Fix the stage names, feed the findings back, and a typical second draft looks like this:

config timeframe = 7d
| dataset = xdr_data
| filter event_type = ENUM.PROCESS and action_process_image_name = "powershell.exe"
| filter action_process_image_command_line contains "-enc"
| alter user = actor_effective_username, parent = actor_process_image_name
| comp count() as runs, min(_time) as first_seen, max(_time) as last_seen by agent_hostname
| filter user != "SYSTEM"
| fields agent_hostname, user, parent, runs, first_seen, last_seen
| sort desc runs
$ node xqlcheck.cjs draft2_encoded_ps.xql
draft2_encoded_ps.xql
  7:10  warning  XQL301  Local binding 'user' was removed by an earlier supported projection. This is local scope evidence, not tenant validation.
  8:26  warning  XQL301  Local binding 'user' was removed by an earlier supported projection. This is local scope evidence, not tenant validation.
  8:32  warning  XQL301  Local binding 'parent' was removed by an earlier supported projection. This is local scope evidence, not tenant validation.
0 error(s), 3 other finding(s)

This is the most useful thing the linter caught. comp returns one row per group, and the comp reference says "all other original fields are discarded." After the comp, user and parent no longer exist, so the SYSTEM filter and the two columns refer to nothing. Move row filters above comp, and carry anything you want to keep through the aggregation with values().

One honest limit: XQLibur only proves this for names the query itself creates, such as the alter above. If the draft had read actor_effective_username straight from xdr_data after the comp, the linter couldn't prove the field was gone, because it doesn't load tenant schemas. Read every line after a comp yourself.

Step 4: Test the XQL regex before you trust it

The second draft is now clean enough to run, and it would return rows. That's the risk. contains "-enc" looks like a reasonable encoded-command filter, but PowerShell accepts the parameter in several forms. The pwsh documentation lists -EncodedCommand | -e | -ec, attack tooling commonly uses prefixes like -enc and -enco (the public Sigma rule for Base64 PowerShell matches -e, -en, -enc, -enco and -ec), and the Windows PowerShell docs note that from cmd.exe you can use a forward slash instead of a hyphen. Windows PowerShell 5.1 also has a separate -EncodedArguments parameter.

We built 14 test lines: 7 encoded launches and 7 look-alikes, including a -Command that passes -enc ascii to Add-Content (its -Encoding parameter, abbreviated), the pattern Unit 42 shows in its EncodedCommand write-up. The Base64 is Write-Output 'lab' in UTF-16LE. We scored four filters:

label  draft   noCase  regex1  final   command line
ENC    hit     hit     hit     hit     powershell.exe -NoProfile -enc VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGw...
ENC    hit     MISS    hit     hit     powershell.exe -EncodedCommand VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGw...
ENC    MISS    hit     hit     hit     "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -nop -w hi...
ENC    MISS    hit     hit     hit     pwsh.exe -ec VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGwAYQBiACcA
ENC    MISS    hit     hit     hit     powershell.exe /enc VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGwAYQBiACcA
ENC    hit     MISS    hit     hit     powershell.exe -NonInteractive -EnCoDeDcOmMaNd VwByAGkAdABlAC0ATwB1AHQ...
ENC    hit     hit     hit     hit     powershell.exe -enco VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGwAYQBiACcA
CLEAN  -       -       -       -       powershell.exe -ExecutionPolicy Bypass -File C:\lab\inventory.ps1
CLEAN  -       -       -       -       powershell.exe -ep bypass -Command Get-Service
CLEAN  FALSE+  -       -       -       powershell.exe -EncodedArguments VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnA...
CLEAN  -       -       -       -       pwsh.exe -Command "Get-ChildItem -Exclude *.enc"
CLEAN  FALSE+  -       -       -       powershell.exe -Command "Get-Content C:\lab\notes-enc.txt"
CLEAN  -       -       -       -       powershell.exe -File C:\lab\backup.ps1 -env prod
CLEAN  FALSE+  FALSE+  FALSE+  -       powershell.exe -nop -c "ac C:\lab\ftp.txt -val 'open lab-ftp' -enc asc...
draft contains "-enc"    caught 4/7 encoded, 3 false positives on 7 other lines
regex without (?i)       caught 5/7 encoded, 1 false positives on 7 other lines
regex1 (prefixes, (?i))  caught 7/7 encoded, 1 false positives on 7 other lines
final (+ Base64 argument) caught 7/7 encoded, 0 false positives on 7 other lines

We emulated contains as a case-insensitive substring match, because the config reference says case_sensitive defaults to false. Four lessons came out of it:

  • contains "-enc" missed -e, -ec and /enc, and flagged a file name. Three of seven encoded launches were invisible, and notes-enc.txt showed up as a hit.
  • Add (?i) to the regex. The regextract reference says regular expression matching is case-sensitive by default, so don't rely on config case_sensitive to cover your pattern. Without (?i), -EncodedCommand slipped through.
  • Require the Base64 argument. Matching the parameter alone still flagged -enc ascii. Requiring at least 20 Base64 characters after it removed the last false positive.
  • Skip lookaheads. A model trying to exclude -ExecutionPolicy will often write -e(?!xecutionpolicy). Go rejected it outright: error parsing regexp: invalid or unsupported Perl syntax: (?!. RE2-style engines don't support lookarounds, so list the forms you want instead of excluding the ones you don't.

There's one escaping trap to watch for. The filter reference says that inside a normal double-quoted XQL string, a backslash is a plain character. So write \s, not \\s. A model used to JSON or Java will double the backslash, and the pattern then looks for a literal backslash. In our bench, the double-escaped version of the final regex caught 0 of 7.

-EncodedArguments is labeled "clean" here because it's a different parameter. If you want it too, add it as its own alternative. This is a hunting decision, not a regex fix.

Step 5: The Cortex XQL query we'd run

config timeframe = 7d
| dataset = xdr_data
| filter event_type = ENUM.PROCESS and event_sub_type = ENUM.PROCESS_START
| filter action_process_image_name in ("powershell.exe", "pwsh.exe")
| filter action_process_image_command_line ~= "(?i)\s[-/](ec|e|en|enc|enco|encod|encode|encoded|encodedc|encodedco|encodedcom|encodedcomm|encodedcomma|encodedcomman|encodedcommand)\s+[A-Za-z0-9+/=]{20,}"
| fields agent_hostname, actor_effective_username, actor_process_image_name, _time
| comp count() as runs, min(_time) as first_seen, max(_time) as last_seen, values(actor_effective_username) as users, values(actor_process_image_name) as parents by agent_hostname
| sort desc runs
| limit 100

XQLibur: no findings. Why it's shaped this way:

  • config comes first, and timeframe = 7d uses a documented unit.
  • event_type is filtered first. The best practices page says xdr_data is clustered on event_type and agent_id, so that filter lets the engine skip data. PROCESS_START counts each launch once.
  • in ("powershell.exe", "pwsh.exe") covers both shells. With case_sensitive at its default of false, PowerShell.exe matches too.
  • fields before comp narrows the columns early, which is another best-practice recommendation, and values() keeps the users and parents that the second draft lost.

What it still misses: renamed copies of powershell.exe (the image-name filter won't see them), caret obfuscation such as -e^nc typed in cmd.exe, and encoded content passed some other way. Treat those as separate hunts.

Step 6: Validate the query in Cortex

Run it. Paste the query into the XQL query builder in your Cortex XDR or XSIAM tenant. Any error goes back to the model verbatim, along with the query.

Plant the activity. On a lab endpoint you own that runs the Cortex agent, launch a harmless encoded command, the same one we used in the bench:

powershell.exe -NoProfile -EncodedCommand VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGwAYQBiACcA

It prints lab. Run the -e and -ec forms too, plus a look-alike such as Get-Content notes-enc.txt. The query passes when the lab host shows up with the planted runs and the look-alike doesn't. If you plan to turn the hunt into a BIOC or correlation rule, check the stage support notes for that rule type first, since some stages aren't supported everywhere.

KQL and SPL habits that don't carry over to XQL

A second draft we linted, a "hosts talking to the most external IPs" hunt, shows how far a model's Sentinel habits leak:

config timeframe = 24h
| dataset = xdr_data
| filter event_type == ENUM.NETWORK and action_remote_ip not incidr "10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16"
| comp dcount(action_remote_ip) as dests by agent_hostname
| project agent_hostname, dests
| top 20 by dests
$ node xqlcheck.cjs draft5_kql_habits.xql
draft5_kql_habits.xql
  4:8  warning  XQL202  Function 'dcount' is not in the bundled reference; this does not establish a Cortex error.
  5:3  warning  XQL201  Stage 'project' is not in the bundled reference; newer syntax may be supported by Cortex.
0 error(s), 2 other finding(s)

The linter caught dcount (use count_distinct) and project (use fields). It didn't catch ==, which isn't in the supported operators (equality is =). It also missed top 20 by dests, which is the trickiest one because top is a real XQL stage. The top reference defines it as top <integer> <field>, which returns the most frequent values of a field with approximate counts. That's not KQL's "top N rows by a column". For that, write sort desc dests | limit 20.

Automate the loop: draft, lint, test

The model drafts, the linter and your regex bench judge, and the exact output goes back. The drafting side calls RedRouter's OpenAI-compatible endpoint: base URL https://redrouter.org/v1 and a Bearer key, per the RedRouter quickstart. We didn't call a model or a Cortex tenant in the lab, so treat this as a sketch:

import os, subprocess, tempfile
from openai import OpenAI

client = OpenAI(base_url="https://redrouter.org/v1",
                api_key=os.environ["REDROUTER_API_KEY"])

SYSTEM = ("You write Cortex XQL for xdr_data. config is always the first stage. Use only these "
          "stages: config, dataset, filter, alter, fields, comp, sort, limit, dedup. No SPL or KQL "
          "(no where, stats, project, ==). Put every row filter before comp; comp drops all other "
          "fields, so carry columns with values(). Regexes use ~=, start with (?i), use single "
          "backslashes and no lookarounds. Return one query and nothing else.")

FIELDS = ("xdr_data fields: event_type (ENUM.PROCESS), event_sub_type (ENUM.PROCESS_START), "
          "action_process_image_name, action_process_image_command_line, actor_process_image_name, "
          "actor_effective_username, agent_hostname, _time")
GOAL = ("PowerShell or pwsh launched with -EncodedCommand or a short form (-e, -ec, -enc, /enc) "
        "followed by Base64, last 7 days, per host: count, first/last seen, users, parents.")

def draft(feedback=""):
    r = client.chat.completions.create(
        model="glm-5.3-flash-red", temperature=0,
        messages=[{"role": "system", "content": SYSTEM},
                  {"role": "user", "content": f"{FIELDS}\n\nGoal: {GOAL}\n\n{feedback}"}])
    return r.choices[0].message.content.strip().strip("`")

def lint(query):
    with tempfile.NamedTemporaryFile("w", suffix=".xql", delete=False) as f:
        f.write(query)
    p = subprocess.run(["node", "xqlcheck.cjs", f.name], capture_output=True, text=True)
    return p.stdout

query = draft()
for _ in range(4):
    out = lint(query)
    if "no findings" in out and query.lstrip().lower().startswith("config"):
        break
    query = draft(f"Your query:\n{query}\n\nThe linter returned:\n{out}\nFix every finding.")
print(query)  # next: regex bench, then a tenant run against planted activity

The stop condition adds the config-first check the linter doesn't make. The loop ends at the linter on purpose. The system prompt carries the rules the linter can't check, and the regex bench plus a tenant run are the real gate.

What to send the model

Hunting queries are written from production telemetry, so be deliberate about prompts.

  • Send stage names, field names and the goal. That's usually enough to draft a query.
  • Send the linter's or query builder's exact output back, not a paraphrase.
  • If the model needs example rows, send their shape with placeholder values: test hosts, documentation IP ranges, made-up usernames. Don't paste real hostnames, usernames or internal IPs from your tenant.

On RedRouter, Zero Data Retention is an opt-in setting and off by default. The data handling docs explain what's stored and how to turn it on, and what RedRouter keeps is the short version. Our security page covers how we handle security workloads.

Which model to use for XQL

For drafting XQL, we'd start with GLM 5.3 Flash Red (glm-5.3-flash-red). On docs.redrouter.org/models it lists at $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. A draft-and-fix round like the one above is a few thousand tokens. For hunting inside a broader authorized red-team or purple-team engagement, red-cyber-1 (Beta) lists at $0.28 / $0.13 / $1.10 per 1M. Plans are on /pricing.

Common LLM mistakes in Cortex XQL

Mistake in the draftWhat caught itFix
where, statsXQLibur XQL201 warningfilter, comp
config after datasetNot caught by the linter; config reference says firstMove config to line 1
sort runs descNot caught by the linter; sort syntaxsort desc runs
Fields used after compXQLibur XQL301 (for names the query created)Filter before comp; carry columns with values()
contains "-enc"Regex bench: 4/7 caught, 3 false positivesAnchored prefix list with (?i) and a Base64 argument
No (?i) in ~=Regex bench: missed -EncodedCommandStart the pattern with (?i)
Lookahead (?!...)Go regexp compile errorList the allowed forms instead
\\s in a regexRegex bench: 0/7 caughtSingle backslash: \s
dcount, projectXQLibur XQL202 / XQL201 warningscount_distinct, fields
==Not caught by the linter; supported operators=
top 20 by xNot caught; top is a different real stagesort desc x | limit 20

Validation checklist

  • config is the first stage.
  • Every stage and function is in the Cortex XQL reference.
  • Every field name exists in your tenant's xdr_data schema.
  • Row filters come before comp, and nothing after comp reads a dropped field.
  • Every ~= pattern starts with (?i), uses single backslashes, has no lookarounds and passed a bench of hits and look-alikes.
  • XQLibur shows no findings you haven't read.
  • The query builder runs it without errors.
  • It returns your planted lab activity and leaves out the look-alike.

FAQ

Can an LLM write Cortex XQL queries that work the first time?

Sometimes, but plan on checking. In this guide, the first draft had five problems: the linter caught two, the reference explained two more, and the fifth, the contains "-enc" logic, only showed up in a regex test. The second draft would have run and returned rows while missing three of seven encoded launches. Use the model as a fast drafter and the linter, a regex bench and a tenant run as the judges.

Is Cortex XQL case-sensitive?

Field value comparisons aren't by default. The config reference says case_sensitive defaults to false, and you can set config case_sensitive = true. Regex is different: the regextract reference says regular expression matching is case-sensitive by default, so add (?i) to patterns.

How do I validate XQL without a Cortex tenant?

Only partly. A local linter such as XQLibur catches unknown stages and functions, wrong argument counts and some dropped fields, and a regex bench tests your matching logic. Neither knows your schema or proves the query runs. For that you need the query builder and planted activity.

How does XQL compare with KQL or SPL?

All three are pipe languages, but the stage names differ: XQL uses filter, alter, fields and comp where KQL uses where, extend, project and summarize. If your team also hunts in Sentinel or Splunk, see KQL hunting queries with an LLM and Splunk SPL searches with an LLM. For detection rules in a portable format, see Sigma and YARA rules with an LLM.

What should I not paste into the prompt?

Real hostnames, usernames, internal IPs and raw events from production. The model needs stage names, field names and the goal, and placeholders work for examples.

Related guides

Only run hunting queries against telemetry you own or are authorized to use, and run planted test activity only on endpoints you're allowed to test.