Writing YARA Rules
Reverse Engineering
Malware Analysis
May 27, 2024

Objectives
In this blog, we will learn how to write a YARA Rule to detect different samples from the same families and hunt for them on a scale.
Rule Header
This section defines the metadata for the rule such as (the description of the rule, the author’s name, the date of writing the rule, etc.)
example
Strings Section
This section contains the strings that the rule will search for
strings can be in (Ascii, Unicode, hexadecimal, and Regular expressions)
The strings should be unique in this malware family as much as you can to have fewer false positives.
If there are common bytes in a malware family we can add it in our rule. If there are differences in some hexadecimal digits we can replace the different hexadecimal digits with “?”
example
Conditions Section
This section contains the conditions that must be met for the rule to trigger
We can use these operators (<, <=, >, >=, ,==, !=, and, or, etc.)
Checking the imported functions
If the malware imports a suspicious function we can use “pe.imports(“dll name”, “function name”)” after importing “pe” at the beginning of the rule
example
Searching for sections
If we want the rule to search for a section we can use
(for any section in pe.sections : ( section.name == “.upx0” ))
we can also check for the number of section
(pe.number_of_sections >= 4)
Checking Sample size
If we observe that the sample size is less than 500KB, for example, we can add this to our rule’s conditions to make it more specific.
Checking bytes
We can check the first bytes of the sample by using (uint16(offset number) == hex value)
example
Writing a YARA Rule 1#
Now let’s practice what we have learned and write a YARA Rule.
I downloaded two samples of Stealc Stealer

We can observe that the two samples are less than 250KB
Let’s search for common strings

Let’s search for common bytes. I’ll use PEbear

This is our final YARA rule
Let’s test it

Writing a YARA Rule 2#
I downloaded Ryuk Ransomware sample, this sample has two stages, so we have to write a yara rule to detect both of them

Let’s see some common strings



After analyzing the two samples by IDA we can observe that the dropper uses ShellExecuteW function to execute the second stage.

ShellExecuteW is a function imported from Shell32.dll
Let’s test our rule in hybrid analysis

It worked!
This blog is authored by Mostafa Farghaly(M4lcode).
Frequently asked questions
Still have questions?
Can’t find the answer you’re looking for? Please chat to our friendly team.
