Skip to content

Built-in and host modules

Docs for v0.11.1 · Go 1.27.0+ · Go API

Modules make functions and typed data available to rule conditions. Import a built-in module by name, or register a host module when creating the compiler.

Signatures from the release’s hash, math, string, and time module registry:

FunctionAccepted arguments → result
hash.checksum32
(string) → integer
(integer, integer) → integer
hash.crc32
(string) → integer
(integer, integer) → integer
hash.md5
(string) → string
(integer, integer) → string
hash.sha1
(string) → string
(integer, integer) → string
hash.sha256
(string) → string
(integer, integer) → string
hash.sha512
(string) → string
(integer, integer) → string
math.abs
(integer) → integer
math.count
(integer) → integer
(integer, integer, integer) → integer
math.deviation
(integer, integer) → float
(integer, integer, float) → float
(string, float) → float
math.entropy
(string) → float
(integer, integer) → float
math.in_range
(float, float, float) → integer
math.max
(integer, integer) → integer
(float, float) → float
(integer, float) → float
(float, integer) → float
math.mean
(string) → float
(integer, integer) → float
math.min
(integer, integer) → integer
(float, float) → float
(integer, float) → float
(float, integer) → float
math.mode
() → integer
(integer, integer) → integer
math.monte_carlo_pi
(string) → float
(integer, integer) → float
math.percentage
(integer) → float
(integer, integer, integer) → float
math.serial_correlation
(string) → float
(integer, integer) → float
math.to_number
(boolean) → integer
math.to_string
(integer) → string
(integer, integer) → string
string.length
(string) → integer
string.to_int
(string) → integer
(string, integer) → integer
time.now
() → integer

Starting in v0.10.0, the built-in pure-Go pe module adds PE32/PE32+ header, section, RVA/overlay, declared_extent/input_truncated, is_dotnet(), is_dll(), is_32bit()/is_64bit(), full-file checksum, standard import/export and regex query, imphash(), resource, version_info, Rich header, CodeView pdb_path, and Authenticode metadata/offline verification fields without CGO; non-PE rules incur zero PE allocation or parse overhead. See PE module coverage and limits for all signatures, host snapshot rules, and the pe.number_of_imports > 0 guard recommended with pe.imphash().

Use the built-in pcap module for TLS certificate-name comparisons. For DNS and HTTP fields, the Go examples decode records with go-pcap and pass the selected fields to YARA while retaining packet and flow evidence.

The checked-in rules compare each flow’s ClientHello SNI with the server leaf certificate’s DNS names:

examples/pcap/tls.yar
import "pcap"
rule tls_name_mismatch {
condition:
for any row in pcap.tls : (
defined row.server_name_match and not row.server_name_match
)
}
rule tls_name_evidence_missing {
condition:
for any row in pcap.tls : (not defined row.server_name_match)
}
Terminal window
go mod download github.com/cawalch/go-pcap
fixtures="$(go list -m -f '{{.Dir}}' github.com/cawalch/go-pcap)/testdata/deployments"
go run ./cmd examples/pcap/tls.yar "$fixtures/proxy.pcapng"

The synthetic proxy capture matches only tls_name_evidence_missing: its TLS 1.3 handshakes have no keys to recover the leaf certificates. A defined false comparison indicates a name mismatch; undefined means the comparison lacks evidence, including missing SNI, a missing leaf, or a potentially omitted SAN at the parser limit. Neither result establishes certificate trust or malicious activity.

TLS extraction runs on first evaluated access to pcap.tls and is reused within the scan. Invalid captures, parser errors, or inputs larger than 64 MiB make the array undefined. For streaming, use an io.ReaderAt and io.Seeker, such as an open file; sequential-only inputs must fit completely in the retained 64 KiB header. See capture limits and flow indices.

These rules operate directly on pcap.tls, without a Go adapter. They combine outcomes across parsed TLS flows rather than search the raw capture for certificate strings:

examples/pcap/tls-triage.yar
import "pcap"
// Count flows with positive mismatch evidence; missing evidence does not count.
rule tls_multiple_name_mismatches {
condition:
for 2 row in pcap.tls : (
defined row.server_name_match and not row.server_name_match
)
}
// Useful after a proxy/certificate rollout: both outcomes occur in this capture.
// This does not establish that the flows used the same listener or hostname.
rule tls_mixed_name_results {
condition:
for any row in pcap.tls : (row.server_name_match) and
for any row in pcap.tls : (
defined row.server_name_match and not row.server_name_match
)
}
// Preserve an observed mismatch while flagging incomplete comparison coverage.
rule tls_mismatch_with_evidence_gaps {
condition:
for any row in pcap.tls : (
defined row.server_name_match and not row.server_name_match
) and
for any row in pcap.tls : (not defined row.server_name_match)
}
// Require at least one row: "all" alone also succeeds for an empty collection.
// This asserts name agreement only, not certificate trust or capture completeness.
rule tls_all_observed_names_match {
condition:
defined pcap.tls[0].flow_index and
for all row in pcap.tls : (
defined row.server_name_match and row.server_name_match
)
}
Terminal window
go run ./cmd examples/pcap/tls-triage.yar "$fixtures/proxy.pcapng"

The proxy fixture produces no triage matches because every name comparison is undefined. Missing evidence never counts as a mismatch or an agreement. The integration tests supply the positive and negative controls:

Observed comparisons Matching triage rules
Two mismatches tls_multiple_name_mismatches
An agreement and a mismatch tls_mixed_name_results
A mismatch and an undefined comparison tls_mismatch_with_evidence_gaps
One or more agreements, with no other outcomes tls_all_observed_names_match
No TLS rows, invalid capture, or only undefined comparisons None
Terminal window
go test ./compiler -run '^TestPCAPTriageRules$' -v

for 2 requires at least two matching rows. The existence guard before for all prevents an empty capture from passing. A mixed result can guide a certificate-rollout investigation, but the current schema cannot establish that those flows share a hostname, listener, or time window. All-agreement means only that every observed TLS row has a defined matching name; it does not establish certificate trust or capture completeness.

The useful composition here is a YARA condition over go-pcap’s parsed, flow-scoped evidence in an offline capture. Other network tools also inspect protocol fields: Suricata supports raw and normalized HTTP URI buffers, Zeek supports signatures, and Sigma supports event correlations. These examples demonstrate module collections, count thresholds, and undefined handling; they do not establish detection coverage unavailable in those tools. The built-in module currently exposes only TLS flow indices and name-comparison results. DNS and HTTP below use Go adapters.

Run the DNS watch adapter against the synthetic IoT capture using the fixtures variable above:

Terminal window
go run ./examples/pcap/dns-watch "$fixtures/iot.pcapng"
watched_dns_question packet=2 flow=2 name="collector.example"

Packet and flow indices are zero-based; inspect frame 3 in a packet viewer. This finding establishes a DNS question, not a completed connection.

The required-service adapter pairs questions and replies, then scans the complete question name with the response code as an external integer:

Terminal window
go run ./examples/pcap/dns-failure ./examples/pcap/dns-failure/testdata/service.pcap
required_service_dns_failure name="api.example" resolver=192.0.2.53:53 rcode=3 query_frame=1 reply_frame=2
required_service_dns_failure name="api.example" resolver=192.0.2.53:53 rcode=2 query_frame=3 reply_frame=4

Inspect frame 2 for NXDOMAIN and frame 4 for SERVFAIL. Edit $service in the required-service rule to watch another name. Pairing requires ordinary single-question DNS on port 53 from one observation point; repeated identical outstanding questions make the pairing key ambiguous for the rest of the capture. See the Go adapter and DNS examples.

The HTTP adapter applies inventory and approval policies to decoded HTTP/1 and HTTP/2 requests:

Terminal window
go run ./examples/pcap/http-hunts ./examples/pcap/http-hunts/testdata/hunts.pcap
unexpected_server_webhook_post frame=2 time_ns=1700000000002469134 flow=0 stream=0 source=192.0.2.10 POST webhook.site
unapproved_decoy_route_access frame=11 time_ns=1700000000013580237 flow=5 stream=3 source=192.0.2.12 GET app.example

Frames identify the start of each request, even when it spans packets; stream zero denotes HTTP/1. Replace the fixture’s source inventory, webhook approvals, and private decoy route before using a real capture. Unknown sources produce no findings. Encrypted-only traffic cannot establish an HTTP method or route from SNI. A webhook POST establishes an attempted transfer; acceptance and contents require separate evidence. See HTTP rules, benign controls, and packet attribution.

Hash functions accept either a string or an (offset, size) range in the scanned input. They return a digest string, except crc32 and checksum32, which return integers.

The statistical functions accept strings or input ranges. math.count and math.percentage take a byte value, optionally followed by an offset and size. math.mode accepts an optional offset and size. math.in_range(value, lower, upper) takes three floats and returns an integer truth value.

math.deviation(offset, size, mean) and math.deviation(string, mean) calculate mean absolute deviation. The two-integer form is the go-yara standard-deviation extension. math.to_string accepts an optional base of 8, 10, or 16. string.to_int accepts an optional integer base; invalid conversions produce undefined.

Invalid ranges also produce undefined. Ranges starting inside the input are truncated at EOF. See numeric and string differences for unsigned comparisons, float overloads, and high-byte statistics.

Declare the shape of application data with Module.Schema. The compiler checks member names and types; each scanner receives its own data snapshot.

At compilation
  1. Module schematelemetry.score: float
  2. Rule conditiontelemetry.score > 0.9
  3. Type checkVerify the field and comparison types
At scanning
  1. Application datascore = 0.95
  2. Scanner bindingValidate and copy a data snapshot
  3. Condition result0.95 > 0.9 → true
The application produces the data. A schema describes its shape; it does not parse a file or calculate a score.

This example exposes a floating-point score to a rule and prints true:

Typed host data
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
telemetry := compiler.Module{
Name: "telemetry",
Schema: &compiler.ModuleSchema{Fields: map[string]compiler.ModuleField{
"score": {Kind: compiler.ModuleFloat},
}},
}
program, err := compiler.NewCompiler(compiler.WithModule(telemetry)).CompileSourceWithContext(context.Background(), `
import "telemetry"
rule elevated { condition: telemetry.score > 0.9 }`)
if err != nil {
return err
}
scanner := program.NewScanner(compiler.WithModuleData("telemetry", map[string]any{"score": 0.95}))
defer scanner.Close()
result, err := scanner.Scan(nil)
if err != nil {
return err
}
fmt.Println(result.RuleResults["elevated"])
return nil
}

Schemas can contain nested structures, arrays, string-keyed dictionaries, and scalar constants. Bind exported Go struct fields, string-keyed maps, slices, or arrays. Field names are case-insensitive for Go structs unless an exact yara:"name" tag is provided. Values must match the declared schema.

Missing fields, missing dictionary keys, and out-of-range array indices evaluate as undefined. Use defined when the condition requires a value. Missing collections iterate as empty collections: any is false, while all and none are true.

WithModuleData reports binding errors through scan methods. To replace data between scans and receive an error immediately, call scanner.SetModuleData(name, data). Binding copies the data; setters must not run concurrently with scans.

Register scalar callbacks through Module.Functions. Declare their accepted signatures and return type, and keep callbacks deterministic and safe for concurrent use. The Module API reference describes the callback types.

This byte-lookup callback returns undefined when the offset is outside its input. The example serializes the program, demonstrates the missing-callback load error, reloads with the handler, and binds an external variable on the new scanner.

Complete Go example: register a function and restore it after loading
main.go
package main
import (
"context"
"fmt"
"log"
"github.com/cawalch/go-yara/compiler"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
// A pure byte lookup. Undefined is a valid return for an absent offset.
module := compiler.Module{Name: "sample", Functions: map[string]compiler.ModuleFunction{
"byte_at": {
Signatures: []compiler.ModuleSignature{{Arguments: []compiler.ModuleValueType{compiler.ModuleInteger}}},
ReturnType: compiler.ModuleInteger,
Evaluate: func(ctx compiler.ModuleContext, args []compiler.ModuleValue) (compiler.ModuleValue, error) {
offset := args[0].Integer
if offset < 0 || offset >= int64(len(ctx.Data)) {
return compiler.ModuleValue{}, nil
}
return compiler.IntegerValue(int64(ctx.Data[offset])), nil
},
},
}}
program, err := compiler.NewCompiler(compiler.WithModule(module)).CompileSourceWithContext(context.Background(), `
import "sample"
external enabled
rule magic { condition: enabled and defined sample.byte_at(0) and sample.byte_at(0) == 0x4d }`)
if err != nil {
return err
}
blob, err := program.MarshalBinary()
if err != nil {
return err
}
_, err = compiler.UnmarshalCompiledProgram(blob)
fmt.Printf("load without callback fails: %t\n", err != nil)
// Supply compatible callbacks while loading, then bind runtime values.
loaded, err := compiler.UnmarshalCompiledProgram(blob, module)
if err != nil {
return err
}
scanner := loaded.NewScanner(compiler.WithExternalVariables(map[string]any{"enabled": true}))
defer scanner.Close()
for _, input := range [][]byte{nil, []byte("MZ")} {
matched, err := scanner.Matches(input)
if err != nil {
return err
}
fmt.Printf("input=%q matched=%t\n", input, matched)
}
return nil
}
Output
load without callback fails: true
input="" matched=false
input="MZ" matched=true

ModuleContext supplies scan data, blocks, and the current rule name; it is not a context.Context. This example operates on ordinary byte-slice scans. A callback intended for sparse block scans must implement the address semantics it needs using the supplied blocks. Keep callbacks bounded and avoid blocking I/O: scanner cancellation cannot preempt Go code that is blocked inside your callback.

Return ModuleValue{} for undefined. An undefined argument propagates without invoking the callback; a non-nil callback error fails the scan. For cache opt-in, results must depend only on input data, blocks, and arguments, never the rule name, time, external state, or side effects. String arguments are not eligible for this cache.

Deterministic built-in numeric and range calls share a bounded cache within each scan. String arguments and time.now() are not cached. Custom callbacks are uncached unless they opt in with ModuleFunction.Cacheable and satisfy its purity contract. A digest calculation can still allocate on a cache miss; see performance.

Pass custom handlers to UnmarshalCompiledProgram while loading, then bind host data again. Schemas survive serialization; runtime data does not.