Search code examples
pythonmalwareyara

Writing yara rules in Python


I've been reading the documentation and I've been having a hard time trying to figure this out. A translation would help a lot.

I came across this sample Perl rule online for Yara:

rule BadBoy
{
strings:
 $a = "win.exe"
 $b = "http://foo.com/badfile1.exe"
 $c = "http://bar.com/badfile2.exe"
condition:
 $a and ($b or $c)
}

How would you write and compile this rule in Python?


Solution

  • From python you first need to import yara

    Straight from the documentation:

    Then you will need to compile your YARA rules before applying them to your data, the rules can be compiled from a file path:

    rules = yara.compile()
    

    You can either pass a filename for formatted rules, or insert a string for compilation.

    For passing Strings, dictionary structures must be used, with the key being the namespace for the data, and the values being attributes.

    import yara
    rules = yara.compile(sources={
    'identifier_for_instance_of rule':'rule BadBoy { 
                           'strings': [('$a', 'win.exe'),('$b', 'http://foo.com/badfile1.exe') , ('$c', 'http://bar.com/badfile2.exe')],
                           'condition': '$a and ($b or $c)'
                          }'})