YARA-L best practices

This document describes Google Security Operations's recommended best practices for writing rules in YARA-L.

Filter out zero values

Fields might be automatically omitted in the events you run your rules against. When fields are omitted, they default to their zero values.

For example, an omitted string value defaults to "".

If you equate two fields that are both omitted, they might both default to their zero values. This might lead to unintended matches where two fields match because they both have zero values. You can avoid this behavior by explicitly specifying the zero value.

For example, if you have a rule that equates two events based on two fields, there is a chance that both of those fields are empty, causing a match:

$e1.field1 = $e2.field2

If both e1.field1 and e2.field2 are omitted in the data, "" = "" is true, causing a match.

The following comparison expressions ensure that you don't get a match because e1.field1 and e2.field2 don't include any data:

$e1.field1 = $e2.field2
$e1.field != ""

Add an event type filter

In the following example, the IP addresses for each UDM event are checked against the reference list, consuming a lot of resources:

  // For every UDM event, check if the target.ip is listed in
  // the suspicious_ip_addresses reference list.
  $e.target.ip in %suspicious_ip_addresses

If your YARA-L rule only detects on UDM events of a certain event type, adding an event type filter can help to optimize your rule by reducing the number of events the rule needs to evaluate.

  // For every UDM event of type NETWORK_DNS, check if the target.ip is
  // listed in the suspicious_ip_addresses reference list.
  $e.metadata.event_type = "NETWORK_DNS"
  $e.target.ip in %suspicious_ip_addresses

Add these filters to the beginning of the events section. You should also put equality filters before regex or other comparisons. Filters are applied in the order they appear in the rule.