Golang for infosec — Building an EDR #Part2 — YARA rules

Go, C, … cgo!

As the official Golang documentation says, cgo enables the creation of Go packages that call C code. To use cgo, write normal Go code that imports a pseudo-package “C”. The Go code can then refer to types such as C.size_t, variables such as C.stdout, or functions such as C.putchar.

// #include <stdio.h>
// #include <errno.h>
import “C”
  • Threads created by the Go runtime may not interact properly with libpthread’s thread local storage implementation.
  • Go reuses OS threads to run multiple Goroutines. If the C code called a blocking system call or otherwise monopolised the thread, it could be detrimental to other goroutines.
  • to compile YARA from GCC
  • to use pkg-config to allow yara to be linked to your programs

Compile your YARA rules

Now you’ve got mingw install, libyara correctly compiled and that you set-up your environmet variables and PATH to help the C linker, you’re ready to go. Start by installing go-yara:

go get github.com/hillu/go-yara
go install github.com/hillu/go-yara
// LoadYaraRules compile yara rules from specified paths and return a pointer to the yara compiler
func LoadYaraRules(path []string) (compiler *yara.Compiler, err error) {
compiler, err = yara.NewCompiler()
if err != nil {
return nil, errors.New("Failed to initialize YARA compiler")
}
for _, dir := range path {
f, err := os.Open(dir)
if err != nil{
log.Println("[ERROR]", "Could not open rule file ", dir, err)
}
namespace := filepath.Base(dir)[:len(filepath.Base(dir))-4] if err = compiler.AddFile(f, namespace); err != nil{
log.Println("[ERROR]", "Could not load rule file ", dir, err)
}
f.Close()
}
return compiler, nil}

Search for YARA match

From your compiled rules, it’s time to search for match:

// PerformYaraScan use provided YARA rules and search for match in the given byte slicefunc PerformYaraScan(data []byte, rules *yara.Rules) yara.MatchRules {
result, err := YaraScan(data, rules)
if err != nil{
log.Println("[ERROR]", err)
}
return result
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store