yara

package module
v4.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2023 License: BSD-2-Clause Imports: 10 Imported by: 42

README

Logo

go-yara

PkgGoDev buildtest Go Report Card

Go bindings for YARA, staying as close as sensible to the library's C-API while taking inspiration from the yara-python implementation.

Build/Installation

On Unix-like systems, libyara version 4.3, corresponding header files, and pkg-config must be installed. Adding go-yara v4 to a project with Go Modules enabled, simply add the proper dependency…

import "github.com/hillu/go-yara/v4"

…and rebuild your package.

If libyara has been installed to a custom location, the PKG_CONFIG_PATH environment variable can be used to point pkg-config at the right yara.pc file.

For anything more complicated, refer to the "Build Tags" section below. Instructions for cross-building go-yara for different operating systems or architectures can be found in README.cross-building.md.

To build go-yara on Windows, a GCC-based build environment is required, preferably one that includes pkg-config. The 32-bit and 64-bit MinGW environments provided by the MSYS2 provide such an environment.

Build Tags

Static builds

The build tag yara_static can be used to tell the Go toolchain to run pkg-config with the --static switch. This is not enough for a static build; the appropriate linker flags (e.g. -extldflags "-static") still need to be passed to the go tool.

Building without pkg-config

The build tag yara_no_pkg_config can be used to tell the Go toolchain not to use pkg-config's output. In this case, any compiler or linker flags have to be set via the CGO_CFLAGS and CGO_LDFLAGS environment variables, e.g.:

export CGO_CFLAGS="-I${YARA_SRC}/libyara/include"
export CGO_LDFLAGS="-L${YARA_SRC}/libyara/.libs -lyara"
go install -tags yara_no_pkg_config github.com/hillu/go-yara

If libyara has been linked against other libraries (e.g. libcrypto, libmagic) and a static build is performed, these libraries also need to be added to CGO_LDFLAGS.

YARA 4.1.x vs. earlier versions

This version of go-yara can only be used with YARA 4.3 or later.

Version of go-yara compatible with YARA 4.1.x are available via the v4.2.x branch or tagged v4.2.* releases.

Version of go-yara compatible with YARA 4.1.x are available via the v4.1.x branch or tagged v4.1.* releases.

Version of go-yara compatible with YARA 4.0.x are available via the v4.0.x branch or tagged v4.0.* releases.

Versions of go-yara compatible with YARA 3.11 are available via the v3.x branch or tagged v3.* releases.

Versions of go-yara compatible with earlier 3.x versions of YARA are available via the v1.x branch or tagged v1.* releases.

License

BSD 2-clause, see LICENSE file in the source distribution.

Author

Hilko Bengen <bengen@hilluzination.de>

Documentation

Overview

Package yara provides bindings to the YARA library.

Index

Constants

View Source
const (
	ConfigStackSize             ConfigName = C.YR_CONFIG_STACK_SIZE
	ConfigMaxMatchData                     = C.YR_CONFIG_MAX_MATCH_DATA
	ConfigMaxStringsPerRule                = C.YR_CONFIG_MAX_STRINGS_PER_RULE
	ConfigMaxProcessMemoryChunk            = C.YR_CONFIG_MAX_PROCESS_MEMORY_CHUNK
)
View Source
const (
	// ScanFlagsFastMode avoids multiple matches of the same string
	// when not necessary.
	ScanFlagsFastMode = C.SCAN_FLAGS_FAST_MODE
	// ScanFlagsProcessMemory causes the scanned data to be
	// interpreted like live, in-prcess memory rather than an on-disk
	// file.
	ScanFlagsProcessMemory = C.SCAN_FLAGS_PROCESS_MEMORY
)

Variables

This section is empty.

Functions

func Finalize

func Finalize() error

Finalize releases all the resources allocated by the YARA library. It should be called by the program when it no longer needs YARA, e.g. just before the program exits. It is not strictly necessary to call Finalize because the allocated memory will be freed on program exit; however, explicitly-freed resources will not show up as a leak in memory profiling tools.

A good practice is calling Finalize as a deferred function in the program's main function:

defer yara.Finalize()

func GetConfiguration

func GetConfiguration(name ConfigName) (interface{}, error)

GetConfiguration gets a global YARA configuration option.

func SetConfiguration

func SetConfiguration(name ConfigName, src interface{}) error

SetConfiguration sets a global YARA configuration option.

Types

type Compiler

type Compiler struct {
	Errors   []CompilerMessage
	Warnings []CompilerMessage
	// contains filtered or unexported fields
}

A Compiler encapsulates the YARA compiler that transforms rules into YARA's internal, binary form which in turn is used for scanning files or memory blocks.

Since this type contains a C pointer to a YR_COMPILER structure that may be automatically freed, it should not be copied.

func NewCompiler

func NewCompiler() (*Compiler, error)

NewCompiler creates a YARA compiler.

func (*Compiler) AddFile

func (c *Compiler) AddFile(file *os.File, namespace string) (err error)

AddFile compiles rules from a file. Rules are added to the specified namespace.

If this function returns an error, the Compiler object will become unusable.

func (*Compiler) AddString

func (c *Compiler) AddString(rules string, namespace string) (err error)

AddString compiles rules from a string. Rules are added to the specified namespace.

If this function returns an error, the Compiler object will become unusable.

func (*Compiler) DefineVariable

func (c *Compiler) DefineVariable(identifier string, value interface{}) (err error)

DefineVariable defines a named variable for use by the compiler. Boolean, int64, float64, and string types are supported.

func (*Compiler) Destroy

func (c *Compiler) Destroy()

Destroy destroys the YARA data structure representing a compiler.

It should not be necessary to call this method directly.

func (*Compiler) DisableIncludes

func (c *Compiler) DisableIncludes()

DisableIncludes disables all include statements in the compiler. See yr_compiler_set_include_callbacks.

func (*Compiler) GetRules

func (c *Compiler) GetRules() (*Rules, error)

GetRules returns the compiled ruleset.

func (*Compiler) SetIncludeCallback

func (c *Compiler) SetIncludeCallback(cb CompilerIncludeFunc)

SetIncludeCallback registers an include function that is called (through Go glue code) by the YARA compiler for every include statement.

type CompilerIncludeFunc

type CompilerIncludeFunc func(name, filename, namespace string) []byte

CompilerIncludeFunc is used with Compiler.SetIncludeCallback. Arguments are: name for the rule file to be included, filename for the file that contains the include statement, namespace for the rule namespace. The function returns a byte slice containing the contents of the included file. It must return a nil return value on error.

See also: yr_compiler_set_include_callback in the YARA C API documentation.

type CompilerMessage

type CompilerMessage struct {
	Filename string
	Line     int
	Text     string
	Rule     *Rule
}

A CompilerMessage contains an error or warning message produced while compiling sets of rules using AddString or AddFile.

type ConfigName

type ConfigName uint32

type Error

type Error int

Error encapsulates the C API error codes.

func (Error) Error

func (e Error) Error() string

type Match

type Match struct {
	// contains filtered or unexported fields
}

Match represents a string match.

func (*Match) Base

func (m *Match) Base() int64

Base returns the base offset of the memory block in which the string match occurred.

func (*Match) Data

func (m *Match) Data() []byte

Data returns the blob of data associated with the string match.

func (*Match) Offset

func (m *Match) Offset() int64

Offset returns the offset at which the string match occurred.

type MatchRule

type MatchRule struct {
	Rule      string
	Namespace string
	Tags      []string
	Metas     []Meta
	Strings   []MatchString
}

A MatchRule represents a rule successfully matched against a block of data.

type MatchRules

type MatchRules []MatchRule

MatchRules is used to collect matches that are returned by the simple (*Rules).Scan* methods.

func (*MatchRules) RuleMatching

func (mr *MatchRules) RuleMatching(sc *ScanContext, r *Rule) (abort bool, err error)

RuleMatching implements the ScanCallbackMatch interface for MatchRules.

type MatchString

type MatchString struct {
	Name   string
	Base   uint64
	Offset uint64
	Data   []byte
}

A MatchString represents a string declared and matched in a rule.

type MemoryBlock

type MemoryBlock struct {
	// Base contains the base address of the current block
	Base uint64
	// Size contains the size of the current block
	Size uint64
	// FetchData is used to read size bytes into a byte slice
	FetchData func([]byte)
}

MemoryBlock is returned by the MemoryBlockIterator's First and Next methods

type MemoryBlockIterator

type MemoryBlockIterator interface {
	First() *MemoryBlock
	Next() *MemoryBlock
}

MemoryBlockIterator is a Go representation of YARA's YR_MEMORY_BLOCK_ITERATOR mechanism that is used within yr_rules_mem_scan_blobs.

type MemoryBlockIteratorWithFilesize added in v4.1.0

type MemoryBlockIteratorWithFilesize interface {
	MemoryBlockIterator
	Filesize() uint64
}

type Meta

type Meta struct {
	Identifier string
	Value      interface{}
}

Meta represents a rule meta variable. Value can be of type string, int, boolean, or nil.

type Object

type Object struct {
	// contains filtered or unexported fields
}

type Rule

type Rule struct {
	// contains filtered or unexported fields
}

Rule represents a single rule as part of a ruleset.

func (*Rule) Disable

func (r *Rule) Disable()

Disable disables a single rule.

func (*Rule) Enable

func (r *Rule) Enable()

Enable enables a single rule.

func (*Rule) Identifier

func (r *Rule) Identifier() string

Identifier returns the rule's name.

func (*Rule) IsGlobal

func (r *Rule) IsGlobal() bool

IsGlobal returns true if the rule is marked as global.

func (*Rule) IsPrivate

func (r *Rule) IsPrivate() bool

IsPrivate returns true if the rule is marked as private.

func (*Rule) Metas

func (r *Rule) Metas() (metas []Meta)

Metas returns the rule's meta variables as a list of Meta objects.

func (*Rule) Namespace

func (r *Rule) Namespace() string

Namespace returns the rule's namespace.

func (*Rule) Strings

func (r *Rule) Strings() (strs []String)

Strings returns the rule's strings.

func (*Rule) Tags

func (r *Rule) Tags() (tags []string)

Tags returns the rule's tags.

type RuleProfilingInfo

type RuleProfilingInfo struct {
	Rule
	Cost uint64
}

type Rules

type Rules struct {
	// contains filtered or unexported fields
}

Rules contains a compiled YARA ruleset.

Since this type contains a C pointer to a YR_RULES structure that may be automatically freed, it should not be copied.

func Compile

func Compile(rules string, variables map[string]interface{}) (r *Rules, err error)

Compile compiles rules and an (optional) set of variables into a Rules object in a single step.

func LoadRules

func LoadRules(filename string) (*Rules, error)

LoadRules retrieves a compiled ruleset from filename.

func MustCompile

func MustCompile(rules string, variables map[string]interface{}) (r *Rules)

MustCompile is like Compile but panics if the rules and optional variables can't be compiled. Like regexp.MustCompile, it allows for simple, safe initialization of global or test data.

func ReadRules

func ReadRules(rd io.Reader) (*Rules, error)

ReadRules retrieves a compiled ruleset from an io.Reader.

func (*Rules) DefineVariable

func (r *Rules) DefineVariable(identifier string, value interface{}) (err error)

DefineVariable defines a named variable for use by the compiler. Boolean, int64, float64, and string types are supported.

func (*Rules) Destroy

func (r *Rules) Destroy()

Destroy destroys the YARA data structure representing a ruleset.

It should not be necessary to call this method directly.

func (*Rules) GetRules

func (r *Rules) GetRules() (rules []Rule)

GetRules returns a slice of rule objects that are part of the ruleset.

func (*Rules) Save

func (r *Rules) Save(filename string) (err error)

Save writes a compiled ruleset to filename.

func (*Rules) ScanFile

func (r *Rules) ScanFile(filename string, flags ScanFlags, timeout time.Duration, cb ScanCallback) (err error)

ScanFile scans a file using the ruleset. For every event emitted by libyara, the corresponding method on the ScanCallback object is called.

Note that the filename is passed as-is to the YARA library and may not be processed in a sensible way. It is recommended to avoid this function and to obtain an os.File handle f using os.Open() and use ScanFileDescriptor(f.Fd(), …) instead.

func (*Rules) ScanFileDescriptor

func (r *Rules) ScanFileDescriptor(fd uintptr, flags ScanFlags, timeout time.Duration, cb ScanCallback) (err error)

ScanFileDescriptor scans a file using the ruleset. For every event emitted by libyara, the corresponding method on the ScanCallback object is called.

func (*Rules) ScanMem

func (r *Rules) ScanMem(buf []byte, flags ScanFlags, timeout time.Duration, cb ScanCallback) (err error)

ScanMem scans an in-memory buffer using the ruleset. For every event emitted by libyara, the corresponding method on the ScanCallback object is called.

func (*Rules) ScanMemBlocks

func (r *Rules) ScanMemBlocks(mbi MemoryBlockIterator, flags ScanFlags, timeout time.Duration, cb ScanCallback) (err error)

ScanMemBlocks scans over a MemoryBlockIterator using the ruleset. For every event emitted by libyara, the corresponding method on the ScanCallback object is called.

func (*Rules) ScanProc

func (r *Rules) ScanProc(pid int, flags ScanFlags, timeout time.Duration, cb ScanCallback) (err error)

ScanProc scans a live process using the ruleset. For every event emitted by libyara, the corresponding method on the ScanCallback object is called.

func (*Rules) Write

func (r *Rules) Write(wr io.Writer) (err error)

Write writes a compiled ruleset to an io.Writer.

type ScanCallback

type ScanCallback interface {
	RuleMatching(*ScanContext, *Rule) (bool, error)
}

ScanCallback is a placeholder for different interfaces that may be implemented by the callback object that is passed to the (*Rules).ScanXxxx and (*Scanner).ScanXxxx methods.

The RuleMatching method corresponds to YARA's CALLBACK_MSG_RULE_MATCHING message.

type ScanCallbackConsoleLog added in v4.2.0

type ScanCallbackConsoleLog interface {
	ConsoleLog(*ScanContext, string)
}

ScanCallbackConsoleLog can be used to implement custom functions to handle the console.log feature introduced in YARA 4.2.

type ScanCallbackFinished

type ScanCallbackFinished interface {
	ScanFinished(*ScanContext) (bool, error)
}

ScanCallbackFinished is used to signal that a scan has finished. The ScanFinished method corresponds to YARA's CALLBACK_MSG_SCAN_FINISHED message.

type ScanCallbackModuleImport

type ScanCallbackModuleImport interface {
	ImportModule(*ScanContext, string) ([]byte, bool, error)
}

ScanCallbackModuleImport is used to provide data to a YARA module. The ImportModule method corresponds to YARA's CALLBACK_MSG_IMPORT_MODULE message.

type ScanCallbackModuleImportFinished

type ScanCallbackModuleImportFinished interface {
	ModuleImported(*ScanContext, *Object) (bool, error)
}

ScanCallbackModuleImportFinished can be used to free resources that have been used in the ScanCallbackModuleImport implementation. The ModuleImported method corresponds to YARA's CALLBACK_MSG_MODULE_IMPORTED message.

type ScanCallbackNoMatch

type ScanCallbackNoMatch interface {
	RuleNotMatching(*ScanContext, *Rule) (bool, error)
}

ScanCallbackNoMatch is used to record rules that did not match during a scan. The RuleNotMatching method corresponds to YARA's CALLBACK_MSG_RULE_NOT_MATCHING mssage.

type ScanCallbackTooManyMatches added in v4.3.0

type ScanCallbackTooManyMatches interface {
	TooManyMatches(*ScanContext, *Rule, string) (bool, error)
}

ScanCallbackTooManyMatches can be used to receive information about strings that match too many times.

type ScanContext

type ScanContext struct {
	// contains filtered or unexported fields
}

ScanContext contains the data passed to the ScanCallback methods.

Since this type contains a C pointer to a YR_SCAN_CONTEXT structure that may be automatically freed, it should not be copied.

type ScanFlags

type ScanFlags int

ScanFlags are used to tweak the behavior of Scan* functions.

type Scanner

type Scanner struct {

	// Current callback object, set by SetCallback
	Callback ScanCallback
	// contains filtered or unexported fields
}

Scanner contains a YARA scanner (YR_SCANNER). The main difference to Rules (YR_RULES) is that it is possible to set variables in a thread-safe manner (cf. https://github.com/VirusTotal/yara/issues/350).

Since this type contains a C pointer to a YR_SCANNER structure that may be automatically freed, it should not be copied.

func NewScanner

func NewScanner(r *Rules) (*Scanner, error)

NewScanner creates a YARA scanner.

func (*Scanner) DefineVariable

func (s *Scanner) DefineVariable(identifier string, value interface{}) (err error)

DefineVariable defines a named variable for use by the scanner. Boolean, int64, float64, and string types are supported.

func (*Scanner) Destroy

func (s *Scanner) Destroy()

Destroy destroys the YARA data structure representing a scanner.

It should not be necessary to call this method directly.

func (*Scanner) GetLastErrorRule

func (s *Scanner) GetLastErrorRule() (r *Rule)

GetLastErrorRule returns the Rule which caused the last error.

The result is nil, if scanner returned no rule

func (*Scanner) GetLastErrorString

func (s *Scanner) GetLastErrorString() (r *String)

GetLastErrorString returns the String which caused the last error.

The result is nil, if scanner returned no string

func (*Scanner) GetProfilingInfo

func (s *Scanner) GetProfilingInfo() (rpis []RuleProfilingInfo)

GetProfilingInfo retrieves profiling information from the Scanner.

func (*Scanner) ResetProfilingInfo

func (s *Scanner) ResetProfilingInfo()

ResetProfilingInfo resets the Scanner's profiling information

func (*Scanner) ScanFile

func (s *Scanner) ScanFile(filename string) (err error)

ScanFile scans a file using the scanner.

If no callback object has been set for the scanner using SetCAllback, it is initialized with an empty MatchRules object.

Note that the filename is passed as-is to the YARA library and may not be processed in a sensible way. It is recommended to avoid this function and to obtain an os.File handle f using os.Open() and use ScanFileDescriptor(f.Fd()) instead.

func (*Scanner) ScanFileDescriptor

func (s *Scanner) ScanFileDescriptor(fd uintptr) (err error)

ScanFileDescriptor scans a file using the scanner.

If no callback object has been set for the scanner using SetCAllback, it is initialized with an empty MatchRules object.

func (*Scanner) ScanMem

func (s *Scanner) ScanMem(buf []byte) (err error)

ScanMem scans an in-memory buffer using the scanner.

If no callback object has been set for the scanner using SetCAllback, it is initialized with an empty MatchRules object.

func (*Scanner) ScanMemBlocks

func (s *Scanner) ScanMemBlocks(mbi MemoryBlockIterator) (err error)

ScanMemBlocks scans over a MemoryBlockIterator using the scanner.

If no callback object has been set for the scanner using SetCAllback, it is initialized with an empty MatchRules object.

func (*Scanner) ScanProc

func (s *Scanner) ScanProc(pid int) (err error)

ScanProc scans a live process using the scanner.

If no callback object has been set for the scanner using SetCAllback, it is initialized with an empty MatchRules object.

func (*Scanner) SetCallback

func (s *Scanner) SetCallback(cb ScanCallback) *Scanner

SetCallback sets a callback object for the scanner. For every event emitted by libyara during subsequent scan, the appropriate method on the ScanCallback object is called.

For the common case where only a list of matched rules is relevant, setting a callback object is not necessary.

func (*Scanner) SetFlags

func (s *Scanner) SetFlags(flags ScanFlags) *Scanner

SetFlags sets flags for the scanner.

func (*Scanner) SetTimeout

func (s *Scanner) SetTimeout(timeout time.Duration) *Scanner

SetTimeout sets a timeout for the scanner.

type String

type String struct {
	// contains filtered or unexported fields
}

String represents a string as part of a rule.

func (*String) Identifier

func (s *String) Identifier() string

Identifier returns the string's name.

func (*String) Matches

func (s *String) Matches(sc *ScanContext) (matches []Match)

Matches returns all matches that have been recorded for the string.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL