VirusTotal / yara

The pattern matching swiss knife
https://virustotal.github.io/yara/
BSD 3-Clause "New" or "Revised" License
8.29k stars 1.45k forks source link

Iterating over constant strings in yara conditions block #1765

Open nikhilh-20 opened 2 years ago

nikhilh-20 commented 2 years ago

Hello,

I recently had a use-case where I wanted to have a list of strings in the conditions block in a yara rule. I'm using yara v4.0.5. A minimal example is: comparing the SHA1 of a file with a known set of hashes. This is a working yara rule:

test.yar:

import "hash"

rule test {
    condition:
        hash.sha1(0,filesize) == "0a9fbc6dacd8887bd9d9065bc7d9a4905d7ea687" or
        hash.sha1(0,filesize) == "90cf88f9f3326d2616232d73e5adc1e85d28097f"
}

$ yara test.yar test.txt 
test test.txt

For readability, this is alright when there are, say, 5 hashes. But if there are 100 hashes, then the rule file becomes messy. Is there a way in yara to have non-search strings in one variable? And I'm not referring to the strings block because those strings are searched in the file. I'm referring to a string variable (containing a list of strings) which is not searched in the file and can purely be used in the conditions block. Also, I assume hash.sha1 will be computed only once? (caching: https://github.com/VirusTotal/yara/issues/592)

Something like:

import "hash"

rule test {
    condition:
        for any i in ("90cf88f9f3326d2616232d73e5adc1e85d28097f","0a9fbc6dacd8887bd9d9065bc7d9a4905d7ea687"):
            ( i == hash.sha1(0,filesize) )
}

The above doesn't work:

$ yara test.yar test.txt 
test.yar(5): error in rule "test": wrong type for enumeration item

Thanks for the help!

wxsBSD commented 2 years ago

I've had a need for this in the past and just ended up doing a long or chain. If @plusvic agrees with this or has a better idea I'd be happy to take a shot at making it work.

plusvic commented 2 years ago

I think it makes sense that iterators work on lists of strings too. It's more intuitive than a long sequence of or statements.

wxsBSD commented 2 years ago

OK, I'll take a shot at implementing this in the coming weeks.

wxsBSD commented 2 years ago

I've taken a shot at this and am having a hard time getting it to work correctly in the grammar. It seems there is a conflict with the way integer sets are built.

Also there is https://github.com/VirusTotal/yara/pull/1338, which might make this issue obsolete. As such, I'm going to put this on hold until I can come up with a way to make it work or someone with more knowledge than me can do it.

wxsBSD commented 2 years ago

After being shown the path by @plusvic I've got this implemented and up for review now.

Thanks, again, Victor!