From bbc738e16f8b637afde58d65196374af98a5e0e2 Mon Sep 17 00:00:00 2001 From: Mathieu Deous Date: Sat, 30 Apr 2022 15:41:40 +0200 Subject: Compile rules from their location (#116) * handle errors while loading rules * move to rules folder for compiling--- php-malware-finder/phpmalwarefinder.go | 40 ++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/php-malware-finder/phpmalwarefinder.go b/php-malware-finder/phpmalwarefinder.go index 799df60..2a641b3 100644 --- a/php-malware-finder/phpmalwarefinder.go +++ b/php-malware-finder/phpmalwarefinder.go @@ -210,6 +210,42 @@ func scanDir(dirName string, targets chan<- string, ticker <-chan time.Time) { close(targets) } +// loadRulesFile reads YARA rules from specified `fileName` and returns +// them in their compiled form. +func loadRulesFile(fileName string) (*yara.Rules, error) { + var err error = nil + // record working directory and move to rules location + curDir, err := os.Getwd() + if err != nil { + return nil, fmt.Errorf("unable to determine working directory: %v", err) + } + ruleDir, ruleName := filepath.Split(fileName) + err = os.Chdir(ruleDir) + if err != nil { + return nil, fmt.Errorf("unable to move to rules directory: %v", err) + } + + // read file content + data, err := ioutil.ReadFile(ruleName) + if err != nil { + return nil, fmt.Errorf("unable to read rules file: %v", err) + } + + // compile rules + rules, err := yara.Compile(string(data), nil) + if err != nil { + return nil, fmt.Errorf("unable to load rules: %v", err) + } + + // move back to working directory + err = os.Chdir(curDir) + if err != nil { + return nil, fmt.Errorf("unable to move back to working directory: %v", err) + } + + return rules, nil +} + func main() { startTime := time.Now() _, err := flags.Parse(&args) @@ -265,8 +301,8 @@ func main() { // load YARA rules rulePath := path.Join(args.RulesDir, RulesFile) - data, _ := ioutil.ReadFile(rulePath) - rules, _ := yara.Compile(string(data), nil) + rules, err := loadRulesFile(rulePath) + handleError(err, true) if args.Verbose { log.Println("[DEBUG] ruleset loaded:", rulePath) } -- cgit v1.3