Practice library / Security operations basics
Lab · Easy · 45 minutes
YARA & Sigma for Defenders
Write YARA malware signatures and Sigma detection rules for SIEM platforms.
On this page 13 sections
A detection rule is the sentence that tells a machine what suspicious looks like. YARA matches patterns in files and process memory, and Sigma writes one rule that converts to the query language of every major SIEM — the format behind most public threat-hunting rulesets, including SigmaHQ and the Elastic detection repository. Write one rule of each kind, tune it against a false positive, and convert the Sigma rule into a working SIEM query.
What You'll Learn
- Write a YARA rule with strings and a condition, and run it on files
- Show which strings matched, and where
- Find a false positive and tune the rule to remove it
- Write a Sigma rule for process-creation logs
- Test a Sigma rule against sample events and convert it for a SIEM
A detection rule is a sentence that a machine can check: "if a file or a log line looks like this, tell me." YARA checks files and memory. Sigma checks logs, and one Sigma rule converts to the query language of many SIEM products. In this lab you write one rule of each kind, run it, find where it is wrong, and fix it.
You work as a defender. The "malware" in this lab is plain text that contains the words a real downloader script contains. It does nothing when you run it, and you never run it.
Prerequisites
Read the Detection chapter of the SOC Operations & SIEM workbook. It explains log sources and why a rule must be tuned. For the Windows events that the Sigma part uses, see Windows Event Log Analysis.
Lab Setup
Use your own Kali machine.
- Install YARA:
sudo apt install yara. - Install
jq:sudo apt install jq. - For Steps 7 and 8, install
sigma-cliwithpipx install sigma-cli. Then add the Splunk backend:sigma plugin install splunk.
All files are in the folder ~/rules-lab. Every address is in the lab network 10.0.0.0/8.
Write and test rules only on your own lab files and on logs that you may read. A rule that fires on a real system is the start of an investigation, so ask the owner of the system before you scan it.
Step 1: Check the tools
Confirm that YARA runs
Check the version before you write a rule. YARA has changed its syntax over the years, so the version is part of your notes.
mkdir -p ~/rules-lab/samples && cd ~/rules-lab
yara --versionExample output:
4.5.2Your version can differ. The rules in this lab use syntax that works in all 4.x versions.
Step 2: Create the sample files
Make one bad sample and two good files
A rule needs a test set with both kinds of files. A rule that you test only on the bad file always looks perfect.
Create three files. dropper.ps1 is the bad sample: it holds the words of a downloader, but it is only text. admin-tool.ps1 is a normal script of an IT team. notes.txt has no script at all.
cat > samples/dropper.ps1 <<'EOF'
# LAB SAMPLE: harmless text, not a working script
$u = "http://10.0.0.50/stage2.txt"
$data = "SGVsbG8="
$bytes = [System.Convert]::FromBase64String($data)
Invoke-Expression ([System.Text.Encoding]::UTF8.GetString($bytes))
EOF
cat > samples/admin-tool.ps1 <<'EOF'
# Inventory helper written by the IT team
$token = [System.Convert]::FromBase64String($env:INV_TOKEN)
Invoke-Expression "Get-ChildItem C:\Inventory"
EOF
echo "Meeting notes. Nothing to see here." > samples/notes.txt
ls samplesExample output:
admin-tool.ps1 dropper.ps1 notes.txtStep 3: Write the first YARA rule
Describe the bad file with strings and a condition
A YARA rule has three parts. meta is for people. strings lists what to look for. condition is the logic that decides a match. Start with a broad rule and see what it finds.
Write the rule to a file.
cat > rules.yar <<'EOF'
rule Lab_Script_Downloader
{
meta:
author = "KaliRange labs"
description = "Script that decodes Base64 and runs the result"
strings:
$b64 = "FromBase64String" nocase
$exec = "Invoke-Expression" nocase
$url = /https?:\/\/10\.0\.0\.[0-9]{1,3}\//
condition:
filesize < 100KB and 2 of them
}
EOFRead the rule. $b64 and $exec are text strings, and nocase ignores capital letters. $url is a regular expression for a web address in the lab network. 2 of them means that at least 2 of the 3 strings must be present. filesize < 100KB skips big files, which makes the scan fast.
Scan the sample folder.
yara rules.yar samples/dropper.ps1Example output:
Lab_Script_Downloader samples/dropper.ps1Each match is one line: the rule name and the file. No line means no match.
Step 4: See which strings matched
Print the matching strings with their offsets
A match line does not say why the rule fired. Use -s to see each matching string and its position. An analyst reads this to judge the match.
yara -s rules.yar samples/dropper.ps1Example output:
Lab_Script_Downloader samples/dropper.ps1
0x83:$b64: FromBase64String
0x9b:$exec: Invoke-Expression
0x38:$url: http://10.0.0.50/The number is the offset in the file, in hexadecimal. All three strings matched. Check one offset by hand: the web address starts at byte 56, which is 0x38.
grep -bo 'http://10.0.0.50/' samples/dropper.ps1Example output:
56:http://10.0.0.50/Step 5: Find the false positive
Scan every file and read the extra match
Scan the whole folder with -r. This is the test that a rule must pass before it goes to production.
yara -r rules.yar samplesExample output:
Lab_Script_Downloader samples/admin-tool.ps1
Lab_Script_Downloader samples/dropper.ps1The rule also matched admin-tool.ps1, a normal IT script. Both files contain FromBase64String and Invoke-Expression, so "2 of them" is true for both. This is a false positive: the rule fires on a file that is not malicious.
On a real network, this rule would fire on many admin scripts, and the analysts would learn to ignore it. A noisy rule is almost as bad as no rule.
Step 6: Tune the rule
Change the condition, not the file list
Do not add the admin tool to an exception list. Find what is different in the bad file and require it. The bad file has the web address of the lab network. The admin tool has none.
Change the condition so that the address must be present, with at least one of the two other strings.
sed -i 's/filesize < 100KB and 2 of them/filesize < 100KB and $url and ($b64 or $exec)/' rules.yar
grep condition -A1 rules.yarExample output:
condition:
filesize < 100KB and $url and ($b64 or $exec)Scan the folder again.
yara -r rules.yar samplesExample output:
Lab_Script_Downloader samples/dropper.ps1Only the bad file matches. The false positive is gone.
The new rule has a weakness. It depends on one address. An attacker who changes the address avoids the rule. A better rule for a real case uses a string that is hard to change, for example a function name that the malware needs, and keeps the address as one more clue. Precision and durability pull in opposite directions, and you choose a balance for every rule.
Step 7: Write a Sigma rule
Describe an attack in a log source, not in a product
Sigma describes a detection in YAML, with the log source and the fields to check. It has no product syntax. Later a converter makes a Splunk or Elastic query from it.
Write a rule for process creation events. It finds PowerShell that runs with an encoded command, which is how attackers hide a script from simple log reading.
cat > ps-encoded.yml <<'EOF'
title: PowerShell with an encoded command
id: 3f0c6b1e-6a54-4f4d-9a6e-2f1d0c9e7a11
status: experimental
description: Finds powershell.exe that starts with -enc or -EncodedCommand
author: KaliRange labs
logsource:
category: process_creation
product: windows
detection:
selection_image:
Image|endswith: '\powershell.exe'
selection_cli:
CommandLine|contains:
- ' -enc '
- ' -EncodedCommand '
condition: selection_image and selection_cli
falsepositives:
- Admin scripts that use an encoded command
level: medium
EOFRead the rule. logsource says which events the rule needs: process creation on Windows. endswith and contains are modifiers on the field name. Matching in Sigma ignores case by default, so -ENC also matches. A list means "any of these". The condition joins the two selections with and.
Test the logic on sample events. Create four events and run the same checks with jq.
cat > proc.ndjson <<'EOF'
{"Image":"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe","CommandLine":"powershell.exe -enc UwB0AGEAcgB0AC0AUwBsAGUAZQBwAA==","Host":"WS-1002"}
{"Image":"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe","CommandLine":"powershell.exe -File C:\\Scripts\\inventory.ps1","Host":"WS-1002"}
{"Image":"C:\\Windows\\System32\\cmd.exe","CommandLine":"cmd.exe /c echo -enc test","Host":"WS-2210"}
{"Image":"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShell.exe","CommandLine":"PowerShell.exe -EncodedCommand UwB0AGEAcgB0AC0AUwBsAGUAZQBwAA==","Host":"WS-2210"}
EOF
jq -c 'select((.Image | ascii_downcase | endswith("\\powershell.exe"))
and (.CommandLine | ascii_downcase | (contains(" -enc ") or contains(" -encodedcommand "))))
| {Host, CommandLine}' proc.ndjsonExample output:
{"Host":"WS-1002","CommandLine":"powershell.exe -enc UwB0AGEAcgB0AC0AUwBsAGUAZQBwAA=="}
{"Host":"WS-2210","CommandLine":"PowerShell.exe -EncodedCommand UwB0AGEAcgB0AC0AUwBsAGUAZQBwAA=="}Two events match: events 1 and 4. Event 2 is PowerShell without an encoded command. Event 3 has the text -enc, but the program is cmd.exe, so the image selection fails. Both selections are needed, and the test shows why.
The rule has a gap. PowerShell accepts short forms such as -e and -ec, and this rule does not match them. A test set with such an event would show the gap. Adding ' -e ' as a pattern also matches other tools, so test any change first.
Step 8: Check and convert the Sigma rule
Validate the rule and make a SIEM query
sigma check finds errors in the rule file. sigma convert makes the query for one backend. Use the Splunk backend that you installed in the setup.
Check the rule.
sigma check ps-encoded.ymlA valid file ends with no errors and no issues. If the command reports one, fix the line it names.
Convert the rule for Splunk.
sigma convert -t splunk -p splunk_windows ps-encoded.ymlThe output is one Splunk search string. Read it and confirm that it has both conditions: the image name ends with \powershell.exe, and the command line contains -enc or -EncodedCommand. The exact text depends on the version of the backend. To see which pipelines your install has, run sigma list pipelines.
Paste the search into Splunk and run it on your lab data to see the matches, as in Threat Detection with Splunk.
Defence and Detection
- Test every rule on bad and good data. Step 5 found a false positive only because a normal script was in the test set. Keep a folder of normal files and logs and run each new rule on it.
- Prefer behaviour to indicators. An address, a hash or a file name changes in seconds. A behaviour, such as "decode, then run", is harder for an attacker to change.
- Keep rules in version control. Each YARA and Sigma rule is a text file. Review changes as you review code.
- Write the false positives in the rule. The
falsepositivesfield of Sigma tells the next analyst what to expect. - Measure. Count the matches per rule per week. A rule that never fires may be broken, and a rule that fires on every host needs tuning.
Check Your Work
Show these results from your own lab:
- The output of
yara -swith the three matching strings from Step 4. - The output of Step 5 with two matches, and the output of Step 6 with one match.
- The two matching events of Step 7 from
jq. - The result of
sigma checkand the converted Splunk search from Step 8.
For one extra task, write a second test event for the short form -ec. Show that the rule misses it and describe one way to cover it.
Clean-up
- Delete the folder:
rm -r ~/rules-lab. It holds only text samples and rules. - Keep the two rule files in your own notes if you want to use them as a template.
Lab complete. You wrote a YARA rule and a Sigma rule, found a false positive and removed it. Next: the Detection Engineering workbook shows how to build, test and maintain detections at scale.
Sign in to track progress and send feedback.
Related
This lab is extra practice for the course Security operations basics. Do the lessons first.Open the course