Search code examples
pythonscanningyara

Scanning directory with YARA python


Stuck with this problem for some time now. I am scanning a directory with my own yara rules, it works when I tried my code for a single file, but when I use the same code on a for loop, it doesn't match anything.

I've tried searching my problem, but it always shows me the documentation of the basics of yara.

def scan_test(): // works
    file_source = 'index.php'
    match_list = []
    externals = {'filename': file_source}
    rules = yara.compile('rules.yar', externals=externals)
    with open('filepath') as f:
        matches = rules.match(data=f.read(), externals=externals)

    if len(matches) > 0:
        match_list.append(matches)

    return match_list
    
def scan_test3(dir_source): // not working
    match_list = []
    for folder,subfolders, files in os.walk(dir_source):
        for file in files:
            path = os.path.join(folder, file)
            try:
                file_name, file_extension = os.path.splitext(file)
                if (file_extension == '.txt' or file_extension == '.php'):
                    rules = yara.compile('rules.yar', externals={'filename': file})
                    with open(path) as f:
                        matches = rules.match(data=f.read(), externals={'filename': file})
                    if len(matches) > 0:
                        match_list.append(matches)
            except Exception as e:
                print(e)
                pass
    return match_list

Test yara rule:

    rule test_rule
    {
        meta:
            description = "This is a test rule"
        strings:
            $a = "<?php"
        condition:
            $a and (filename matches /index\.php/ or filename matches /login\.php/)
    }

Is my code even right? Can anyone help me on this?


Solution

  • Nothing wrong with the code. For some reason yara-python is not running properly on Windows. Tried this code on Linux and it works perfectly fine.