01 BitsOfBinary
Search

Days 38–45 · 10 min read

The YARA Math Module & Entropy

Measuring randomness and obfuscation with entropy, Monte Carlo Pi, and serial correlation, plus bounding loops safely for performance.

On this page (8)

Day 38 - Math Module - Intro

So far we’ve discussed a few different types of YARA modules, mostly around file parsing. However, there are several modules that can be used on any file type, the math module being one of them.

It is described as such in the docs:

The Math module allows you to calculate certain values from portions of your file and create signatures based on those results.

Personally I’ve found it trickier to write rules using these functions, as it may be quite circumstantial how you want to use them. Regardless, let’s see what we can do with some of the available functions.

To start with, I’d recommend reading Wesley Shields’ (@wxs) intro guide to the math module which gives some great examples and explanations: https://gist.github.com/wxsBSD/019740e83faa7a7206f4

Day 39 - Math Module - Entropy

The function that I’ve seen used (and which I’ve used) the most from the math module, is math.entropy(). This returns the entropy of the input, which is described as “information density of the contents of the file”. The higher number returned out (which goes up to a maximum of 8), this means the more dense it is with information, i.e. it is closer to being “random”.

As such, a high entropy can indicate “random” data, which in some scenarios could indicate that the data itself is encrypted (i.e. good encryption algorithms will make the ciphertext look as random as possible).

Threat actors use encryption to obfuscate sections of malware (e.g. strings, configuration, next stages, etc.), meaning we can use entropy to try and find these. How you decide which parts of a file to scan for encrypted data is up to you. A rule that I’ve written before looking for possible samples possibly abusing MS13-098 can be found here: https://github.com/PwCUK-CTO/TheSAS2021-Red-Kelpie/blob/main/yara/ms13_098.yar

In this case, I’m looking for extra data at the end of a Microsoft digital signature, and checking to see if the entropy is high; that is, there is potentially an encrypted payload at the end of it.

Looking for anomalies like this (i.e. high entropy in unexpected places) can lead to some good heuristic rules!

Day 40 - Math Module - Entropy of PE sections

Some success of using the entropy function can be found in targeting specific sections of PE files. For example, as Tony Lambert points out in a blog, he uses a rule looking for encrypted resources in PE files: https://forensicitguy.github.io/adventures-in-yara-hashing-entropy/#matching-on-resource-entropy

Something that may help us to use the entropy function successfully is understanding the expected entropy of PE sections, to give us a rough idea of what is “normal”.

So, for example, using YARA itself I could run the following rule to print the entropy value of the .text section (i.e. the code section) of a PE file:

import "math"
import "console"
import "pe"
rule PE_Entropy_dottext_Section {
condition:
for any section in pe.sections : (
section.name == ".text" and
console.log(math.entropy(section.raw_data_offset, section.raw_data_size))
)
}

On windows, if I run this rule across C:\Windows\system32, I can print out each .text entropy and save off the values. I can copy and paste the results from this straight into CyberChef, and using these formulas get the average entropy of a PE in this folder.

For my Windows installation, this mean value comes to 5.80 (with standard deviation 1.27). This makes sense, as code itself can appear “quite” random, but will have some structure to it based on consistent use of specific assembly instructions.

If I do the same for the .rdata section (i.e. the read-only data section which usually stores things like strings), the average is 3.54 (with standard deviation 1.46). This value is a lot lower than the .text section, which is to be expected as strings are generally “less random” than code.

Day 41 - Math Module - Entropy Performance

If you use the entropy function in your YARA rules, you may notice that the performance of these rules are slower in general compared to string only rules. This gets worse the bigger the data is that you are computing the entropy for. As such, it is undesirable to perform blind entropy checks against arbitrary files.

Instead, it is better to be smarter with your entropy checks. Florian Roth recommends using the fact that functions like math.entropy will only be evaluated in the condition if/when they need to reorder your conditions to not run them in every instance.

Another suggestion I remember seeing was that if you needed to compute entropy of a large amount of data, consider only checking the entropy of small chunks of the data instead. This may not give as accurate results, may give a performance boost! If you need more accurate results, you could first compute the entropy of a smaller chunk, and only then compute the entropy of the rest of the file.

For example, here is the same rule from the previous post, but only computing entropy of the first 2048 bytes of the .text section (if the section is smaller than this it will just compute the whole thing):

import "math"
import "console"
import "pe"
rule PE_Entropy_dottext_Section {
condition:
for any section in pe.sections : (
section.name == ".text" and
console.log(math.entropy(section.raw_data_offset, math.min(2048, section.raw_data_size)))
)
}

Day 42 - Math Module - Monte Carlo Pi

The entropy function is the only measure of “randomness” in the math module (as an aside, see this Twitter thread started by @notareverser that gives a more nuanced look on what the entropy is measuring: https://twitter.com/notareverser/status/1623842328044527616). Another one to consider is the math.monte_carlo_pi function.

This function will use a Monte Carlo method of estimating the value of pi (3.14159265359...). This is done by taking the values which are input into the function, scaling them and placing them on a graph of a circle. By comparing the number of points that are inside vs. outside the circle, the value of pi can be estimated. The idea is that the more random points there are plotted in/out of the circle, the more accurate the estimation of pi will be. If the data isn’t very “random” though, the estimation won’t be as good.

Estimation of pi using Monte Carlo method

The output of math.monte_carlo_pi is not the estimated value of pi, but rather the percentage difference between the true value of pi compared to the estimated one. As such, the lower the output of the function, the closer the estimation to pi was, and the more “random” the data was. The higher the number, the further away from pi the estimation, so the less random it was.

If I take a string that has no randomness, then we can see what a bad estimation looks like:

import "math"
import "console"
rule Bad_Monte_Carlo_Pi_Estimate {
condition:
console.log(math.monte_carlo_pi("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"))
}

In this case, the result is 0.273240, which is approximately (4 - pi) / pi (i.e. the estimated value of pi with this data is the value 4 - maybe good enough for engineering, not good enough for maths!). So this can be considered a bad estimation.

If I do the same test but instead of for null I use 0xFF:

import "math"
import "console"
rule Bad_Monte_Carlo_Pi_Estimate {
condition:
console.log(math.monte_carlo_pi("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"))
}

Then the output for this is 1.000000 (i.e. pi would be computed to be 0, and so is 100% off the true value).

Alternatively, if I take some random data (10,000 bytes worth) and repeat this test against a file with the random data in it:

import "math"
import "console"
rule Monte_Carlo_Pi_Estimate {
condition:
console.log(math.monte_carlo_pi(0, filesize))
}

I get 0.019468, i.e. much closer to zero. For context, on the same data I get the entropy result of 7.981289.

So in short, data the appears random/compressed etc. is going to have a low value from this function as it better estimates pi, whereas as very ordered data is going to be higher in value. More experimentation is need to figure out what kind of outputs are good at “predicting” certain types of data!

Day 43 - Math Module - Serial Correlation

There’s still one more function used to determine “randomness” in the math module! And that is math.serial_correlation. This computation compares how much each byte depends upon the previous byte(s).

Whereas entropy and Monte Carlo pi had somewhat arbitrary upper and lower limits, the serial correlation will be between 0.0 and 1.0 (note: like with most of the math module output, it will be a floating point number), with closer to zero corresponding to more “random” data, and closer to one being more ordered data.

I’ve found in practice that this value will be negative sometimes, so that is something that might need to be considered in calculations. E.g., applying the following rule to the same random data as in the previous post using the following rule:

import "math"
import "console"
rule Serial_Correlation {
condition:
console.log(math.serial_correlation(0, filesize))
}

I got -0.019990, which feels like it’s too big to be a floating point rounding error! So it’s potentially worth applying two ranges checks to make sure you’re not missing negative numbers.

Day 44 - Math Module - Randomness Functions Efficiency Comparison

So we’ve got three different measures of “randomness” in the math module: entropy, Monte Carlo pi, and serial correlation. So, which one should you use?

Disregarding the mathematical nuances of each function, a potential way of answering this is by determing which is the most efficient function to use. Using Florian Roth and Arnim Rupp’s tool for measuring YARA performance, Panopticon, I ran each function against a bunch of files I grabbed from C:\Windows\system32 to get the following output:

[WARNING] Rule "entropy" slows down a search with 50 rules by 12.8011 % (Measured by best of 3 runs)
[WARNING] Rule "monte_carlo" slows down a search with 50 rules by 35.2246 % (Measured by best of 3 runs)
[WARNING] Rule "serial_correlation" slows down a search with 50 rules by 20.0926 % (Measured by best of 3 runs)

While this is somewhat anectodal, and results will vary between the baseline rules you use/samples you target/general reruns, this run of the tool shows that entropy performs the best, followed by serial correlation then Monte Carlo pi.

This is quite a gratifying result, as I (and many others) have used entropy as the main way of measuring “randomness” in YARA, so to know this is likely the most efficient of the functions means we don’t have to change too much in our approach.

However, hopefully what these posts/discussion around them have shown is that there is value in looking at these functions more closely to figure out how best they can be used! I know I will personally be trying to find new ways to use Monte Carlo pi and serial correlation in my rules going forward.

Day 45 - Math Module - Using min to bound loops

The math module comes with several convenient functions, including math.max() and math.min(). While you could certainly use these for maths related operations, they can have some other uses within your conditions.

In particular, if you’re using loops in YARA, you may find your self in positions where performance may become an issue; especially if you have nested loops (note: in general, try to avoid nested loops). Take the following hypothetical, convoluted rule for instance:

rule Loop_Test {
strings:
$foo = "foo"
$bar = "bar"
condition:
for any i in (1 .. #foo) : (
for any j in (1 .. #bar) : (
@foo[i] ^ @bar[j] == 0xdeadbeef
)
)
}

This rule has a double for loop, looking for any instance where the addresses of two strings XOR to a specific value. The problem with this rule is that depending on how common the strings are, it may be searching for a long time! If you had say 500 occurances of $foo and 200 occurances of $bar, that’s up to 100,000 iterations in total to evaluate.

Instead, to ensure that the performance isn’t terrible for a loop like this, consider using math.min() to limit the number of iterations:

import "math"
rule Loop_Test {
strings:
$foo = "foo"
$bar = "bar"
condition:
for any i in (1 .. math.min(#foo, 10)) : (
for any j in (1 .. math.min(#bar, 10)) : (
@foo[i] ^ @bar[j] == 0xdeadbeef
)
)
}

This will ensure that only the first 10 instances of each string are compared, which is a max 100 iterations in comparison.

Note that using this approach has the chance of missing many checks, so bear that in mind. In practice, your circumstances will change a lot between rules, but considering that you should bound these loops should be a priority for the sake of performance!