NewScanner creates a new YARA scanner.
(psnap ps.Snapshotter, config config.Config)
| 78 | |
| 79 | // NewScanner creates a new YARA scanner. |
| 80 | func NewScanner(psnap ps.Snapshotter, config config.Config) (Scanner, error) { |
| 81 | c, err := yara.NewCompiler() |
| 82 | if err != nil { |
| 83 | return nil, fmt.Errorf("unable to create yara compiler: %v", err) |
| 84 | } |
| 85 | // add yara rules from file system paths by walking the dirs recursively |
| 86 | for _, dir := range config.Rule.Paths { |
| 87 | f, err := os.Stat(dir.Path) |
| 88 | if err != nil { |
| 89 | log.Warnf("cannot access %q rule path: %v", dir.Path, err) |
| 90 | continue |
| 91 | } |
| 92 | if !f.IsDir() { |
| 93 | continue |
| 94 | } |
| 95 | err = filepath.Walk(dir.Path, func(path string, fi os.FileInfo, err error) error { |
| 96 | if filepath.Ext(path) != ".yar" { |
| 97 | return nil |
| 98 | } |
| 99 | f, err := os.Open(path) |
| 100 | if err != nil { |
| 101 | log.Warnf("cannot open the rule %q: %v", path, err) |
| 102 | return nil |
| 103 | } |
| 104 | err = c.AddFile(f, dir.Namespace) |
| 105 | _ = f.Close() |
| 106 | if err != nil { |
| 107 | log.Warnf("couldn't add %s rule: %v", fi.Name(), err) |
| 108 | return nil |
| 109 | } |
| 110 | rulesInCompiler.Add(1) |
| 111 | log.Infof("loading yara rule(s) from %s", path) |
| 112 | |
| 113 | return nil |
| 114 | }) |
| 115 | if err != nil { |
| 116 | log.Warnf("couldn't walk %s path: %v", dir.Path, err) |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // add yara rules from config strings |
| 121 | for _, s := range config.Rule.Strings { |
| 122 | err := c.AddString(s.String, s.Namespace) |
| 123 | if err != nil { |
| 124 | log.Warnf("couldn't add %s rule string: %v", s.String, err) |
| 125 | continue |
| 126 | } |
| 127 | rulesInCompiler.Add(1) |
| 128 | } |
| 129 | |
| 130 | if len(c.Errors) > 0 { |
| 131 | return nil, parseCompilerErrors(c.Errors) |
| 132 | } |
| 133 | |
| 134 | rules, err := c.GetRules() |
| 135 | if err != nil { |
| 136 | return nil, fmt.Errorf("couldn't compile yara rules: %v", err) |
| 137 | } |