A dew-covered spider web strung between bare branches against a dark forest, with the article title about generating Google SecOps YARA-L rules with an LLM
Cover based on a photo by Courtney Celley, U.S. Fish and Wildlife Service, via Wikimedia Commons, Public domain

You can generate YARA-L rules with an LLM quickly, and the draft usually looks right: an events block, a match window, a condition with a count. YARA-L 2.0 is Google Security Operations' own detection language (the Chronicle rule language), and models have seen far less of it than SPL, KQL or Sigma. The result is a draft that borrows field names that don't exist in UDM, enum values that aren't in the schema, and windows the engine won't accept. Some of those mistakes stop the rule from compiling. Others compile and quietly change what the rule matches. An LLM YARA-L rule is a draft until it fires on the event you planted and stays quiet on the one you didn't.

Not to be confused with YARA: YARA-L shares the name and little else. If you want malware signatures for files, see our guide to Sigma and YARA rules with an LLM. This post is about SecOps detection rules over UDM events.

What we tested, and what we didn't

Google's YARA-L compiler is closed. The authoritative check is inside a SecOps instance: the Rules Editor (Detections > Rules & detections > Rules Editor) and its Test button, or the verifyRuleText API method, which compiles a rule without creating it and returns success and compilationDiagnostics.

We didn't have a SecOps tenant for this guide, so we split the work in two. First, every rule below went through yl2lint, an open-source (Apache-2.0) YARA-L 2.0 linter written in Go that parses rules with its own lexer and parser. The linter output shown is real. Second, we checked each rule against Google's YARA-L reference pages for the things a linter can't know. Where we say what Google's compiler will do, we link the page that says so. We don't show Google compiler output, because we didn't run it.

The drafts were written for this guide to reproduce mistakes models commonly make in YARA-L. They are not a captured model transcript, and no model was called in the lab.

The setup was two commands:

git clone https://github.com/RanDev-Sec/yl2lint && cd yl2lint
go build -o yl2lint ./cmd/yl2lint   # README: Go 1.26+

yl2lint exits 0 when there are no error-severity findings, 1 when there is at least one error, and 2 on usage or file errors, so it drops into CI cleanly.

How to generate YARA-L rules with an LLM

Diagram of the loop to generate YARA-L rules with an LLM for Google SecOps: UDM fields and the detection goal go into the prompt, the model drafts a YARA-L 2.0 rule, an offline linter catches syntax and schema mistakes, a docs check catches what the linter cannot see, the Rules Editor or verifyRuleText compiles it, and a test run against a planted event decides whether the Chronicle rule is enabled
The linter and the docs check catch different mistakes; the SecOps compile and test steps come last. We did not run those two steps. Image: RedRouter, Original

Step 1: Give the model UDM, not your log format

YARA-L rules run over Unified Data Model events, not raw vendor logs. A Windows 4625 becomes a USER_LOGIN event with security_result.action = "FAIL". If you prompt with raw Windows field names, the model writes rules for a schema SecOps doesn't have.

Give the model three things:

  • The UDM fields you actually populate, copied from the UDM field list and checked against a real event in your instance. The user entity has userid, user_display_name and email_addresses. It has no username field, which is exactly what models reach for.
  • The enum values you'll filter on. metadata.event_type values include USER_LOGIN, PROCESS_LAUNCH and NETWORK_CONNECTION. SecurityResult.Action is ALLOW, ALLOW_WITH_MODIFICATION, BLOCK, QUARANTINE, FAIL, CHALLENGE or UNKNOWN_ACTION.
  • The detection goal in plain words, with a number: "one source IP fails logins for more than 20 distinct accounts within an hour."

Step 2: Lint the first draft

Here's a typical first draft for a password spray detection (MITRE ATT&CK T1110.003):

rule password_spray_single_source {
  events:
    $e.metadata.event_type = "USER_LOGIN"
    $e.security_result.action = "FAILURE"
    $e.principal.ip = $ip
    $e.target.user.username = $user

  match:
    $ip over 72h

  outcome:
    $targeted_users = $e.target.user.userid

  condition:
    #user > 20
}

The linter's output:

$ yl2lint lint draft1_password_spray.yaral
draft1_password_spray.yaral
  1:1  error    YL002  rule "password_spray_single_source" has no meta section (policy requires keys: author, description, severity)
  6:8  warning  YL004  unknown UDM field "target.user.username" on $e

✖ 2 problems (1 error, 1 warning, 0 info) in 1 file
exit=1

Both findings are right. Google's meta section reference says meta is required in rules and must come first, and target.user.username isn't a UDM field.

Now look at what the linter didn't report. The draft has three more problems, and each one is in Google's docs:

  1. "FAILURE" isn't a SecurityResult.Action value. The enum value is FAIL. The linter's UDM dictionary checks field paths, not enum strings.
  2. over 72h is outside the allowed window. The match section reference lists a minimum of 1m and a maximum of 48h for match windows. yl2lint's temporal check only flags windows over 14 days.
  3. The outcome isn't aggregated. This rule has a match section, so it's a multi-event rule, and outcome values must go through an aggregation function such as count(), max() or array_distinct(). The outcome section reference shows the single-event and multi-event forms side by side.

That's the main lesson: a clean lint is a floor. It catches the cheap mistakes in seconds, which saves you round trips to the Rules Editor, but it is an approximation of a closed compiler.

Step 3: The rule that compiles and matches the wrong events

The second draft fixes all five problems and adds an exclusion for a VPN concentrator, a normal tuning step:

rule password_spray_single_source {
  meta:
    author = "detection-engineering"
    description = "One source IP fails logins for more than 20 distinct accounts within 1 hour"
    severity = "HIGH"

  events:
    $e.metadata.event_type = "USER_LOGIN"
    $e.security_result.action = "FAIL"
    $e.principal.ip = $ip
    $e.target.user.userid = $user
    // skip the VPN concentrator
    $e.principal.ip != "10.20.0.5"

  match:
    $ip over 1h

  outcome:
    $targeted_users = array_distinct($e.target.user.userid)
    $failed_attempts = count($e.metadata.id)

  condition:
    #user > 20
}
$ yl2lint lint draft2_password_spray.yaral
draft2_password_spray.yaral
  13:8  warning  YL010  $e.principal.ip is a repeated field; `!=` without a quantifier means ANY element satisfies it, which is almost always true — use `all $e.principal.ip != ...` to exclude every element

✖ 1 problem (0 errors, 1 warning, 0 info) in 1 file
exit=0

Exit code 0. A CI gate that only checks errors passes this rule, and the bug is real. principal.ip is a repeated field. Google's repeated fields reference says an unmodified expression evaluates to true if any element satisfies it. An event whose principal.ip holds both the concentrator address and another address still passes != "10.20.0.5", because the other element isn't the concentrator. The exclusion leaks.

The fix is the all modifier, which the same page documents for exactly this case:

    all $e.principal.ip != "10.20.0.5"

Read the negation carefully. Google's page spells out that not all $e.principal.ip = "..." means "at least one IP doesn't match," while all $e.principal.ip != "..." means "no IP matches." Models swap these. If your instance logs multiple IPs per login, test the exclusion with a planted event that carries both addresses.

Two more traps in the same family:

  • Case. String comparisons are case-sensitive unless you append nocase, per the expressions reference. $e.target.user.userid = "administrator" won't match Administrator.
  • Empty values. Omitted fields default to zero values, such as "". Google's YARA-L best practices warn that joining two fields that are both empty can produce matches you didn't mean. Add explicit != "" filters on join fields that aren't in match.

The final spray rule:

rule password_spray_single_source {
  meta:
    author = "detection-engineering"
    description = "One source IP fails logins for more than 20 distinct accounts within 1 hour"
    severity = "HIGH"
    mitre_attack_technique = "T1110.003"

  events:
    $e.metadata.event_type = "USER_LOGIN"
    $e.security_result.action = "FAIL"
    $e.principal.ip = $ip
    $e.target.user.userid = $user
    // skip events that carry the VPN concentrator address in any principal.ip slot
    all $e.principal.ip != "10.20.0.5"

  match:
    $ip over 1h

  outcome:
    $risk_score = max(70)
    $targeted_users = array_distinct($e.target.user.userid)
    $failed_attempts = count($e.metadata.id)

  condition:
    #user > 20
}
$ yl2lint lint final_password_spray.yaral
✔ no problems found (1 file linted)

#user > 20 counts distinct values of the $user placeholder in each match window, per the condition section reference, which is what a spray detection needs: many accounts, one source. $risk_score is the special outcome variable SecOps uses for the detection's risk score; it's wrapped in max() because this is a multi-event rule.

Multi-event YARA-L: brute force, then a successful login

Correlation rules are where LLM drafts drift furthest. A typical draft for "five failures, then a success" (T1110.001):

rule brute_force_then_success {
  meta:
    author = "detection-engineering"
    description = "Five or more failed logins followed by a success for the same account"
    severity = "HIGH"

  events:
    $fail.metadata.event_type = "USER_LOGIN"
    $fail.security_result.action = "FAIL"
    $fail.target.user.userid = $user

    $ok.metadata.event_type = "USER_LOGIN"
    $ok.security_result.action = "ALLOW"
    $ok.target.user.userid = "Administrator"

  condition:
    #fail >= 5 and $ok
}
$ yl2lint lint draft1_bruteforce_success.yaral
draft1_bruteforce_success.yaral
  10:32  warning  YL003  placeholder $user is assigned in the events block but never used; remove it or reference it in outcome

✖ 1 problem (0 errors, 1 warning, 0 info) in 1 file
exit=0

One warning, exit 0. The warning points at the symptom, and the docs name the disease: the events section reference says every event variable in a rule must be joined with every other event variable, and Google's Get started with YARA-L page says a match section is required for multi-event correlation. This draft has two event variables, no join between them, and no window. The model also hardcoded "Administrator" on the success side, so even a joined version would only see one account.

The fixed rule joins both events on user and host, orders them, and sets a window:

rule brute_force_then_success {
  meta:
    author = "detection-engineering"
    description = "Five or more failed logins followed by a success for the same account and host within 30 minutes"
    severity = "HIGH"
    mitre_attack_technique = "T1110.001"

  events:
    $fail.metadata.event_type = "USER_LOGIN"
    $fail.security_result.action = "FAIL"
    $fail.target.user.userid = $user
    $fail.principal.hostname = $host

    $ok.metadata.event_type = "USER_LOGIN"
    $ok.security_result.action = "ALLOW"
    $ok.target.user.userid = $user
    $ok.principal.hostname = $host

    $fail.metadata.event_timestamp.seconds < $ok.metadata.event_timestamp.seconds

  match:
    $user, $host over 30m

  outcome:
    $risk_score = max(80)
    $failed_count = count($fail.metadata.id)
    $first_success = min($ok.metadata.event_timestamp.seconds)

  condition:
    #fail >= 5 and $ok
}
$ yl2lint lint final_bruteforce_success.yaral
✔ no problems found (1 file linted)

In the condition, $ok is shorthand for #ok > 0. Google's own YARA-L examples page has a similar brute-force-then-success rule; compare against it when a model's correlation logic looks off.

Step 4: Compile and test in SecOps

Everything above runs offline. The next two checks need your instance.

Compile. Paste the rule into the Rules Editor, or send it to verifyRuleText from a pipeline. The v1 REST reference documents the request body as {"ruleText": "..."} and the response as success plus compilationDiagnostics, with allowedRunFrequencies and nearRealTimeLiveRuleEligible. Treat any diagnostic as feedback for the model, verbatim.

Test against a planted event. In an authorized test window, generate the activity yourself: a lab account with 25 failed logins from one test host, or five failures and a success against a test user. Then click Test in the Rules Editor over that time range. Google's docs note that test detections aren't saved, don't generate alerts, and may differ from live rules or retrohunts because evaluation windows can align differently. A rule passes when it fires on your planted activity and stays quiet on a look-alike, such as the brute force for the spray rule.

Automate the loop: draft, lint, verify

The model drafts, the linter and compiler 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 SecOps instance 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 Google SecOps YARA-L 2.0 detection rules over UDM. Use only the UDM fields "
          "and enum values listed. Always include meta (author, description, severity). "
          "Match windows are 1m to 48h. In rules with a match section, every outcome uses an "
          "aggregation function. Join every event variable to every other one. Use all/any on "
          "repeated fields such as principal.ip. Return one rule and nothing else.")

FIELDS = "UDM: metadata.event_type (USER_LOGIN), security_result.action (FAIL|ALLOW), principal.ip (repeated), target.user.userid, principal.hostname"
GOAL = "One source IP fails logins for more than 20 distinct accounts within 1 hour. Exclude 10.20.0.5."

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(rule):
    with tempfile.NamedTemporaryFile("w", suffix=".yaral", delete=False) as f:
        f.write(rule)
    p = subprocess.run(["./yl2lint", "lint", f.name], capture_output=True, text=True)
    return p.returncode, p.stdout

rule = draft()
for _ in range(4):
    code, out = lint(rule)
    if code == 0 and "warning" not in out:
        break
    rule = draft(f"Your rule:\n{rule}\n\nyl2lint returned:\n{out}\nFix every finding.")
print(rule)  # next: verifyRuleText, then a Test run against planted activity

Two details matter. The stop condition treats warnings as failures, because the leaky VPN exclusion was only a warning. And the loop ends at the linter on purpose: the system prompt carries the rules the linter misses (window limits, aggregation, joins), and verifyRuleText plus a test run are the real gate.

One calibration note on the linter itself. We ran yl2lint's default configuration over the 948 rules in Google's public chronicle/detection-rules repo. It reported 682 errors, 538 of them for meta keys its default policy requires and Google's rules don't always set, plus function-signature and parser findings on rules Google publishes. Tune the config (yl2lint config init) to your team's meta policy before you gate merges on it, and don't treat its parser as the final word.

What to send the model

Detection rules are written from production telemetry, so be deliberate about prompts.

  • Send UDM field paths, enum values and the goal. That's usually enough to draft a rule.
  • Send the linter's or compiler's exact output back, not a paraphrase.
  • If the model needs an example event, send its shape with placeholder values: test accounts, documentation IP ranges and fake hostnames. Don't paste real usernames, internal IPs or hostnames from your SecOps instance.

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 drafting YARA-L, 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 detection work 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 YARA-L mistakes

Mistake in the draftWhat caught itFix
No meta sectionyl2lint YL002 error; required per Google's meta referenceAdd meta first, with author, description, severity
target.user.usernameyl2lint YL004 warningtarget.user.userid
security_result.action = "FAILURE"Not caught by the linter; not in the SecurityResult.Action enum"FAIL"
match: $ip over 72hNot caught by the linter; match windows are 1m to 48hover 1h, or split the logic
Unaggregated outcome in a rule with matchNot caught by the linter; outcome reference requires aggregationarray_distinct(), count(), max()
$e.principal.ip != "10.20.0.5"yl2lint YL010 warning (exit 0)all $e.principal.ip != "10.20.0.5"
Two event variables, no join, no matchyl2lint YL003 warning only; events and match referencesJoin on placeholders, add match: $user, $host over 30m
Hardcoded "Administrator" on one sideCode reviewUse the shared $user placeholder
Case-sensitive string matchCode reviewAppend nocase

Validation checklist

  • Every field path is in the UDM field list and populated in your instance.
  • Every enum string is a real enum value.
  • meta is first and matches your team's required keys.
  • Match windows are between 1m and 48h.
  • Multi-event rules join every event variable and aggregate every outcome.
  • Repeated fields such as principal.ip use any or all where it matters.
  • yl2lint shows no errors and no warnings you haven't read.
  • verifyRuleText or the Rules Editor compiles it.
  • A Test run fires on your planted activity and stays quiet on a look-alike.

FAQ

Can an LLM generate YARA-L rules that work the first time?

Sometimes, but plan on checking. In this guide, the first spray draft had five problems: the linter caught two and Google's docs explained the other three. The second draft passed the linter's error gate with a leaky exclusion. Each fix was small once something showed the exact problem. Treat the model as a fast drafter and the linter, compiler and a planted test as the judges.

Is YARA-L the same as YARA?

No. YARA matches patterns in files and memory for malware analysis. YARA-L 2.0 is Google SecOps' detection language for correlating UDM events over time windows. Our Sigma and YARA guide covers YARA.

How do I validate a YARA-L rule without a SecOps instance?

Only partly. An offline linter such as yl2lint catches syntax, missing meta, unknown UDM fields and repeated-field mistakes. It can't confirm enum values, Google's window limits or every compiler rule, and it can't tell you whether the rule fires on your data. For that you need verifyRuleText or the Rules Editor, plus a test run.

How does YARA-L compare with KQL or SPL?

KQL and SPL are query languages you run over tables or indexes; a YARA-L rule declares event variables, joins them and evaluates a condition per match window. If your team also hunts in Sentinel or Splunk, see KQL hunting queries with an LLM and Splunk SPL searches with an LLM.

What should I not paste into the prompt?

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

Related guides

Only write and test detection rules against telemetry you own or are authorized to use, and generate planted attack activity only in environments you're allowed to test.