Skip to content

About

Go parser for Elasticsearch EQL (Event Query Language) - extracts conditions & correlations, with bidirectional Sigma interop

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

88 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EQL Parser

Go Reference Go Report Card License: AGPL-3.0

A production-ready Go parser for EQL (Event Query Language), the correlation language used by Elastic Security detection rules. It extracts conditions, fields, correlation structure, and pipes from EQL queries used in Elasticsearch, Kibana, and the legacy Endgame ecosystem.

Hand-written lexer and recursive-descent parser, zero dependencies, and tested against a large corpus of real-world detection rules plus millions of fuzzed and mutated inputs.

Features

  • Full EQL grammar: event queries, sequence, join, and sample correlations, by join keys, with maxspan, with runs, until, and ![...] missing-event clauses.
  • Every operator: == != < <= > >=, the case-insensitive :, like / like~, regex / regex~, in / in~ / not in, arithmetic, and boolean and / or / not.
  • Condition extraction: field, operator, value, negation (De Morgan-aware), case-sensitivity, alternatives for list operators, event category, sequence step, and pipe stage.
  • Field discovery: optional ?fields, backtick-escaped `field names`, dotted paths, and array indices (process.args[0]).
  • Functions: wildcard, cidrMatch, endsWith, startsWith, stringContains, length, match, and the ~ case-insensitive variants.
  • Pipes: head, tail, plus the legacy count, unique, unique_count, sort, and filter.
  • Permissive legacy acceptance: single-quoted strings, = equality, child of / descendant of / event of lineage, and ?"raw" strings from Endgame-era rules.
  • Bounded processing: synchronous parsing with per-call input, token, node, work, condition, output, and nesting limits, cooperative deadlines, and recovery that still extracts what it can.
  • Input normalization: smart quotes, zero-width characters, markdown code fences, and JSON-escaped newlines from copy-pasted or extracted rules.

Literal spellings true, false, and null are case-sensitive, as in Elastic EQL. Other spellings such as TRUE or Null name fields; backticks can also quote literal-named fields. The parser retains case-insensitive operator aliases such as WHERE, AND, and NOT for legacy input.

Installation

go get github.com/craftedsignal/eql-parser

Usage

Condition extraction

package main

import (
	"fmt"

	eql "github.com/craftedsignal/eql-parser"
)

func main() {
	result := eql.ExtractConditions(
		`process where process.name : "cmd.exe" and process.parent.name : "explorer.exe"`,
	)

	for _, c := range result.Conditions {
		fmt.Printf("%s %s %q (category=%s)\n", c.Field, c.Operator, c.Value, c.EventCategory)
	}
	// process.name : "cmd.exe" (category=process)
	// process.parent.name : "explorer.exe" (category=process)
}

Correlation (sequence / join / sample)

Parse preserves authored term placement and with runs=N counts. ExtractConditions and AnalyzeQuery expose normalized correlation terms: for a recognized, nonmissing sequence until C with runs=N with N in 2..100, one independent positive C term has Runs=N-1, followed by an independent final until C with Runs=1. This follows Elastic's repeated-term expansion before its final until filter is selected, without allocating N copies. Absent or explicit runs=1 retains the existing Until.Runs=0 convention. The AST remains unchanged; malformed/unknown modifiers keep existing errors. Queries with existing parse errors retain their prior partial term structure.

For correlations, ParseResult.Expression retains its existing filter-pipe projection (and is absent without filters); term trees live in Sequence. SemanticQuery.Expression combines the positive term trees with every filter pipe tree, preserving each term's Boolean grouping. Missing-event and final until trees remain in Sequence and are excluded from that root.

Filter leaves of all kinds (condition, scalar, and value) carry PipeStage, the 1-based index in ordered Pipes; zero means a body predicate. Conditions also retain their existing Condition.PipeStage. A filter after head, unique, or count operates on that pipe's output. The combined root is a cross-stage predicate projection, not an executable pre-pipe event predicate. Consumers must honor ordered Pipes and leaf stages; moving downstream filters before a limit, deduplication, or aggregation can change results. See the upstream pipe guide.

The semantic root projects positive terms' predicates. Steps[].Runs retains correlation multiplicity; the Boolean tree alone does not express repetitions, ordering, absence or expiration. This metadata does not execute EQL or certify all backend correlation limits. The added term/subquery and semantic copies share existing request budgets; resource/cancellation failures remain atomic.

result := eql.ExtractConditions(`
sequence by process.entity_id with maxspan=5m
  [process where event.type == "start" and process.name : "msxsl.exe"]
  [network where event.type == "connection" and network.direction : "egress"]`)

seq := result.Sequence
fmt.Println(seq.Kind)        // "sequence"
fmt.Println(seq.MaxSpanMS)   // 300000
fmt.Println(seq.ByFields)    // [process.entity_id]
fmt.Println(seq.ByKeys[0].Syntax) // process.entity_id
fmt.Println(len(seq.Steps))  // 2

ByKeys is the authoritative ordered list of authored by expressions on the sequence, each step, and until. Each entry keeps complete canonical Syntax. Direct fields also have Field.Name and Field.Optional; computed expressions keep their syntax with no Field summary. The syntax is preserved for inspection and does not imply that an Elasticsearch backend can execute the expression. Global and term keys stay in their own scopes, including duplicates. Local join-key counts must agree across correlation terms, including an authored until term; with runs changes repetition, not key arity. ByFields, JoinKeys, and field discovery remain compatibility projections and can omit optional markers or flatten fields from computed keys. Older serialized results without ByKeys do not establish that keys were required; do not reconstruct descriptors from ByFields.

ConditionCount is the number of flat condition records emitted for a term before OR-alternative merging. It is not the number of final Subquery.Conditions entries, semantic leaves, events, or runs, and must not be used to slice the final root Conditions array. Use each nested Subquery for the returned event predicate, or the step and until tags for root condition provenance.

AST access

q, err := eql.Parse(`process where process.name in ("a.exe", "b.exe")`)
if err != nil {
	// err is non-nil for malformed input, but q still holds the partial AST.
}
fmt.Println(q.String()) // canonical re-rendering (round-trips)

API

Function Description
ExtractConditions(query) *ParseResult Full extraction: conditions, sequence info, pipes, fields, errors. Never panics.
ExtractConditionsContext(ctx, query) *ParseResult Extraction with caller cancellation and a cooperative deadline.
AnalyzeQueryContext(ctx, query) *SemanticQuery Semantic analysis under the same extraction/conversion budget.
ParseContext(ctx, query) (*Query, error) AST parsing with cancellation and resource bounds.
ParseExpressionContext(ctx, input) (Expr, error) Standalone expression parsing with cancellation and resource bounds.
Parse(query) (*Query, error) Parse to an AST with round-trippable String().
ParseExpression(input) (Expr, error) Parse a standalone boolean expression.
NormalizeQuery(query) string Clean up pasted/extracted query text.
ClassifyFieldUsage(result, field) FieldUsage Structured field role: join key, sequence steps, pipes, until.
ClassifyFieldProvenance(result, field) FieldProvenance Field role as a main/joined/join_key/ambiguous string (sibling-parser vocabulary).
DeduplicateConditions(conditions) []Condition Remove exact-duplicate conditions, preserving context.
IsStatisticalQuery(result) bool Query aggregates/correlates (count/unique pipe, or sequence/sample).
HasComplexWhereConditions(result) bool Pattern/list/function predicates, including either operand and scalar/value expressions; uncertain metadata is conservatively complex.
GetEventTypeFromConditions(result) string Scope-aware first-event-code heuristic (e.g. windows_4688); not a proof of a unique event type.

The complexity helper inspects complete event predicates, correlation terms (including missing/until terms), and legacy filter pipe arguments. It does not treat other pipe arguments such as sort as filters or execute predicates. Functions on either side of a comparison, nested list/pattern predicates, and opaque scalar/value predicates are included. Nil/empty results remain simple; extraction errors, malformed/shared/cyclic trees, unknown predicates, or exhausted inspection budgets are conservatively complex. Inspection shares one time/work budget across the whole result, with at most 4,096 structural items/tokens, depth 64, and 128 KiB of inspected text.

The event-type helper preserves the historical first non-negated event-code/list value and case-insensitive event-code aliases. Boolean alternatives do not make this a unique-event classifier. A Sysmon family hint now requires a positive literal/glob or entirely Sysmon-valued list on the exact case-sensitive fields event.provider, winlog.provider_name, provider, or event.module. Negative, regex, computed, field-valued, or mixed-list provider predicates do not supply a hint; unrelated text such as process.name == "Sysmon.exe" does not either. Provider evidence must match the selected code's pipe stage, sequence step, missing/until status, event category, and relationship lineage. This deliberately omits hints across stages even where a backend might preserve event identity. Malformed provider operands supply no hint; exhausted inspection budgets return an empty type. These helpers do not change extraction, ordered pipe execution, or Boolean query semantics.

The field distinction follows the ECS event provider definition and process name definition. Function expressions can occur as comparison operands; legacy filter pipes operate at their authored position in the pipeline.

| MaxSpanDuration(span) (int64, bool) | Convert a maxspan value to milliseconds. |

All-digit durations with explicit ms, s, m, h, or d units (including existing case-insensitive aliases) are converted exactly when their millisecond value fits the signed 64-bit range. Decimal durations, sub-millisecond units, and unitless helper inputs retain their existing conversion behavior. Parsed queries report a semantic error when the authored maxspan number is zero, decimal, or exponent notation: Elasticsearch requires a positive integer literal. Best-effort metadata and helper conversion remain available. The authored MaxSpan text remains available when the numeric projection does not fit. This is a local metadata conversion, not a backend acceptance guarantee.

ExtractConditions and AnalyzeQuery use MaxParseTime (default 5 seconds) as a cooperative deadline. No parsing goroutine continues after they return. Cancellation is checked during lexing, parsing, extraction, and semantic conversion, and before/after bounded normalization and expression rendering; these checkpoints do not provide hard wall-clock preemption.

The 1 MiB input limit is supplemented by per-call limits of 32,768 tokens, 32,768 AST/expression nodes, 4,096 emitted conditions (including step subqueries), 4 MiB of accounted output text/structure, and 4,194,304 work units. Extraction and semantic conversion share these budgets. Resource or cancellation failure returns an error with no partial conditions or semantic tree. Ordinary syntax errors still support best-effort extraction.

ParseResult carries Conditions, EventCategories, Sequence, Pipes, Commands, Fields, BodyFields, JoinKeys (also via GroupByFields()), and Errors. Pipe-field classification uses private AST-derived metadata bound to the extracted pipe descriptors. Manually constructed or JSON-restored Pipes, or descriptors changed after extraction, do not establish pipe roles; independent structured conditions and join keys still contribute to the classification. Public Args remain canonical syntax, not a field-name inventory. Conditions is a flat, best-effort field projection. For event filters, use Expression as the complete boolean tree: a condition leaf refers to a condition index, while a scalar leaf carries canonical EQL syntax and any enclosing NOT parity. A scalar can represent a constant, a field-free predicate, or a computed/function predicate. Consumers must preserve it or explicitly reject it; dropping it or treating it as true changes the filter. The corresponding SemanticQuery.Expression carries owned condition, scalar, and structured value leaves. Scalar syntax is canonical rendering, not the original source substring or an evaluated truth value. For a sequence, join, or sample it is the AND of the positive steps' own trees; missing events and until appear only under Sequence. EventCategoryAny distinguishes the unrestricted any keyword from the literal category "any". Only exact lowercase any is unrestricted; ANY and Any are literal category identifiers (and retain their spelling as field names). It is present on root event-filter results, correlation steps, their recursive subqueries, and conditions (including the semantic API). Sequence roots do not aggregate this flag. Existing category strings remain unchanged; JSON adds event_category_any: true only for wildcard event filters. Older JSON without this flag remains readable but cannot resolve the former ambiguity.

Each Condition records the Field, Operator, Value, Negated, CaseInsensitive, LogicalOp, Alternatives, EventCategory, SequenceStep, FromUntil, FromMissing, PipeStage, IsOptional, Function, ValueIsField, CoFields, and Lineage. Sequence/join/sample steps additionally expose a recursive Subquery *ParseResult — a self-contained extraction of that correlation term, the EQL analog of a join subsearch.

Newly extracted field conditions also carry RHS and PredicateSyntax. RHS identifies string, number, bool, null, field, list, or expression operands; list items retain their kinds, order, and repetitions. Number text keeps its original notation, and a null operand has no sentinel text. PredicateSyntax is the full atomic predicate in canonical EQL, including function arguments and their order. For a safely merged OR condition, it is the canonical OR of its source atoms. Computed predicates remain scalar leaves in the complete expression even when flat extraction reports a field, except for the structured value family below. Quoted and indexed field paths that collide after flattening also remain scalar leaves; their PredicateSyntax keeps the exact path structure. Ambiguous RHS field references use an expression operand with canonical EQL text. Older serialized conditions without RHS are untyped: Value alone does not establish whether null, true, or 1 was a literal or a string. These metadata fields are additive in JSON, but adding exported Go struct fields can break unkeyed struct literals. Consumers should use Expression for boolean meaning and either support scalar/value leaves and typed RHS explicitly or reject unsupported predicates.

Membership and pattern predicates bind before unary arithmetic, multiplication, addition and comparisons. A comparison such as x in (1) == true compares the membership result; it is not reduced to an event-field equality. Nested membership/pattern atoms and root predicates with compound operands carry BooleanValue with a ValuePredicate and recursive ValueExpression. Ordered children retain literal kinds, exact numeric text, decoded strings, optional field paths, grouping, calls, operators, predicate flags and legacy relationship events. Contextual NOT is separate from internal NOT and NOT-IN. These atoms emit no best-effort flat Conditions; the complete AST field inventory remains. Consumers must support this unevaluated value tree or reject it explicitly. It does not certify backend type compatibility or impose two-valued/null logic.

Parsing is intentionally permissive: field-to-field comparisons such as x == y can be represented locally, although modern Elasticsearch EQL does not support them. Parser acceptance alone does not establish service support.

For sequence, join and sample event terms, both field-role helpers also read that term's self-contained Subquery.Fields inventory. This includes field references inside compound pattern/membership value predicates that emit no flat conditions. It does not evaluate the predicate or infer backend support. The inventory excludes the surrounding join keys and downstream pipes; until retains its separate role and shared fields can have multiple roles. Opaque syntax is never reparsed.

For a single event query, BodyFields (body_fields in JSON) records the same case-sensitive canonical field-name projection as Fields, limited to the event body before any pipes. Optional markers and quoted/indexed path identity remain in the complete expressions; this string inventory is not a typed path-identity proof. Fields continues to include references anywhere, including pipes. Both helpers use the body inventory for step-zero/main roles even when a compound predicate emits no flat conditions. A field used in both the body and a pipe retains both usage roles; pipe-only fields do not acquire a body role. Array callback locals remain excluded by the existing free-event-field collector. Term subqueries also carry their own independently owned body inventory; a correlation root has none. SemanticQuery clones the inventory. Predicates and pipe execution are unchanged. Older serialized results without body_fields retain existing flat-condition fallbacks; their global Fields inventory is not treated as body evidence. JSON-restored Pipes alone still do not establish pipe roles. The additive Go struct field can break unkeyed ParseResult/SemanticQuery literals; use keyed literals.

Both helpers bound inspected condition, key, pipe and term-field metadata to 4,096 items and 128 KiB of text in total, including body fields; exhaustion returns no positive roles. They inspect only shallow event-filter inventories, not recursive expression or subquery graphs. Nested correlations, pipes or errors inside a manually supplied term Subquery do not establish these additional event roles. Nor do term inventories carrying join keys or condition tags from another step, an until clause, a missing event, or a pipe. Caller-supplied inventories are metadata, not authenticated query evidence. Single-event body inventories are ignored on correlations, join-key/error results, or contradictory sequence/until/missing condition tags and impossible pipe stage indexes.

ClassifyFieldUsage includes exact, case-sensitive references in each condition's CoFields, including secondary operands of functions and arithmetic. Standalone Boolean calls also retain all secondary field references in source order, with exact-case duplicates removed. Their legacy Value remains the first literal argument and ValueIsField remains false; the complete call stays an opaque scalar expression rather than an executable flat comparison. Compound membership/pattern value predicates continue to emit no flat conditions. Pipe-filter roles take precedence over until, which takes precedence over sequence-step roles; repeated step references are reported once in first-seen order. Negated predicates still reference their fields. Existing non-filter pipe roles require trusted extraction metadata; serialized pipe descriptors alone do not establish those roles. The helper does not traverse operand or expression graphs.

Legacy arraySearch(array, variable, predicate) and arrayCount bind their second argument only within the third argument. Event-field discovery, CoFields, primary fields, pipe inventories and computed join-key inventories exclude that declaration and references rooted in its local name. The array argument is inspected in the outer scope, nested bindings shadow only their body, and later siblings regain the outer scope. Base path segments match exactly and case-sensitively: itemized and the single escaped name `item.user` remain event fields under a local item binding. Complete call syntax and structured/opaque expressions remain unchanged; local paths are not rewritten into fabricated event-column names.

Scope recognition uses the exact legacy names arraySearch/arrayCount, three arguments, and a simple, unoptional, unindexed declaration. Other function spellings and unsupported declaration shapes retain the existing permissive syntactic interpretation; they do not establish a proven local binding or backend validity. This changes field inventories and usage conclusions for valid legacy array callbacks, not their predicate meaning.

For nil results, empty field names, or metadata exceeding its shared limit of 4,096 inspected items or 128 KiB of inspected text, it returns an empty usage. That conservative result is not proof that the field is absent. Limits include flat conditions, secondary fields, join keys, and public/private pipe metadata.

Sigma interoperability

Offline Sigma ↔ EQL corpus tooling lives in cmd/generated-corpus, outside the dependency-free core. make sigma-corpus and make rules-corpus exercise translation and structural round-trip checks under a shared canonical vocabulary. Shape equality is a regression check, not proof of equivalent live-backend behavior.

The Sigma token path supports escaped literal wildcards and Unicode literals with independent language fixtures. Unsupported authored regex, binary operands, and nonrepresentable rule or pipeline constructs are explicitly excluded with reasons. EQL correlations and Sigma free-text searches do not have a general faithful translation in this tooling. See the supported contract and exclusions for details, including optional pinned Java/Lucene native checks and backend limitations. These checks complement the real EQL rule corpus; they do not execute queries against a live backend.

Testing

make test        # full suite with coverage, then short suite with race detection
make fuzz        # native Go fuzzing (FuzzExtractConditions, FuzzParse)
make corpus      # regenerate the differential test corpus
make benchmark   # lexer / parser / extractor benchmarks

CI and make test run go test -v -count=1 -timeout=10m -coverprofile=coverage.out ./... followed by go test -short -race -count=1 -timeout=5m ./.... The full run retains every corpus and stress test and produces the coverage report. The short race run includes a bounded concurrent test of parsing, extraction, semantic analysis, and cancellation/resource-failure isolation. Separating the runs avoids the combined cost of race detection and atomic coverage on the large corpora. CI checks out the corpus files with Git LFS and uploads coverage.out to Codecov.

The suite includes unit tests for the lexer, parser, and extractor; a round-trip property test (parse → render → parse is a fixpoint); real detection-rule corpora; curated valid and adversarial inputs; bounded-AST differential testing with an independent oracle; Sigma ↔ EQL translation checks; native fuzzing; and structured stress and adversarial mutation runs. Generated differential and stress inputs supplement these checks but are not counted as real-world query coverage. The real-rule coverage includes sequences, joins, samples, predicates, typed values, nested expressions, correlation clauses, functions, and pipes.

head and tail accept constant integer arithmetic whose folded value is between 0 and 2147483647, including parentheses and unary signs. Folding follows Elasticsearch's integer widths: intermediate overflow and division by zero are errors, and decimal/exponent values retain their noninteger type. The authored argument remains in the AST and Pipes.Args; validation does not rewrite it. Fields, calls and other nonconstant arguments remain invalid for these pipes.

Dialect notes

The canonical dialect is modern Elasticsearch EQL. Legacy Endgame syntax is accepted permissively (and flagged where it is invalid in modern EQL) because real-world rule corpora mix both. The parser reports semantic problems (sequence needing two events, missing-event clauses needing maxspan, comparison chaining, unknown pipes) in ParseResult.Errors while still extracting everything it can — extraction is best-effort by design.

Samples report errors for pipes and repeated join-key names within each term's combined global and local by keys, matching Elasticsearch. Names compare case-sensitively after decoding identifier quotes; ?host.id and host.id name the same key. Reusing a key across different sample terms is valid. The AST, conditions, keys and pipe metadata remain available for inspection even when these diagnostics are present.

Limitations

  • EQL functions are recognized structurally; their return types are not evaluated. length(x) > 2 extracts x with the length function recorded, not a computed value.
  • Regex and wildcard values are extracted as literal strings; patterns are not compiled or matched.
  • The parser targets extraction and structural analysis, not execution. It does not query Elasticsearch.

License

AGPL-3.0 — see LICENSE.

About

Go parser for Elasticsearch EQL (Event Query Language) - extracts conditions & correlations, with bidirectional Sigma interop

Topics

Resources

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages