0

I've recently been testing the Go bindings for YARA for local yara scans (https://github.com/hillu/go-yara). I am using yara v4.0.0. I have only one .go file which has 2 routines: CompileAllRules and main. I don't get any matches whenever I try to scan the malicious files which I know for a fact that the YARA rules have a hit on.

Code simply looks for YARA rules inside the current folder, compiles them and scans the /root directory with those rules. Below is the problematic code.

func CompileAllRules(compiler *yara.Compiler) (*yara.Compiler, error) {
    log.Info("Start")
    var rule_count = 0
    var invalid_rules = 0

    current_path, cerr := os.Executable()
    if(cerr != nil){
        log.Info(cerr)
        os.Exit(0)
    }
    rules_path := filepath.Dir(current_path)

    log.Info("[COMPILER] Looking for Rules in: ", rules_path)
    _ = filepath.Walk(rules_path, func(filePath string, fileObj os.FileInfo, ferr error) error {
        fileName := fileObj.Name()
        if (path.Ext(fileName) == ".yar") || (path.Ext(fileName) == ".yara") {
            rulesObj, _ := os.Open(filePath)
            defer rulesObj.Close()
            if(compiler.AddFile(rulesObj, "") != nil){
                compiler.Destroy()
                a, ferr := yara.NewCompiler()
                compiler = a
                invalid_rules+=1
                if ferr != nil {
                    log.Info(ferr)
                    os.Exit(0)
                }
            }else{
                rule_count+=1
            }
        }
            return nil
    })

    log.Info("[COMPILER] Compiled: ", rule_count, " Invalid: ", invalid_rules)
    return compiler, cerr
}

func main() {
    compiler, err := yara.NewCompiler()
    if err != nil {
        log.Info(err)
        os.Exit(0)
    }

    compiler, _ = CompileAllRules(compiler)
    rules, err := compiler.GetRules()

    if(err != nil || rules == nil){
        log.Info("Could not get the rules")
        os.Exit(0)
    }

    scanner, err := yara.NewScanner(rules)
    if(err != nil){
        log.Info("Could not generate a scanner")
        os.Exit(0)
    }

    var matches []yara.MatchRule
    _ = filepath.Walk("/root", func(filePath string, fileObj os.FileInfo, ferr error) error {
        fileName := fileObj.Name()
        if (path.Ext(fileName) == ".yar") || (path.Ext(fileName) == ".yara") {
            //log.Info("[scanner] Scanning file: ", fileName)
            matches, _ = scanner.ScanFile(fileName)
            if (len(matches) != 0) {
                log.Info("[SCANNER] Mathes found: ", len(matches))
            }
        }
            return nil
    })
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

1

I was deleting the old compiler and creating a new one without thinking the rules compiled up to that point would be discarded as well. I solved it by iterating through the rules first checking the validity, then compiling the valid ones.