Skip to content

Commit

Permalink
Add InferFileType helper function (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
bradleyjkemp authored May 14, 2021
1 parent 8ee67d2 commit 5122d62
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
35 changes: 35 additions & 0 deletions rule_or_config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package sigma

import (
"gopkg.in/yaml.v3"
)

func InferFileType(contents []byte) FileType {
var fileType FileType
yaml.Unmarshal(contents, &fileType)
return fileType
}

type FileType string

const (
UnknownFile FileType = ""
RuleFile FileType = "rule"
ConfigFile FileType = "config"
)

func (f *FileType) UnmarshalYAML(node *yaml.Node) error {
// Check if there's a key called "detection".
// This is a required field in a Sigma rule but doesn't exist in a config
for _, node := range node.Content {
if node.Kind == yaml.ScalarNode && node.Value == "detection" {
*f = RuleFile
return nil
}
if node.Kind == yaml.ScalarNode && node.Value == "logsources" {
*f = ConfigFile
return nil
}
}
return nil
}
44 changes: 44 additions & 0 deletions rule_or_config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package sigma

import (
"testing"

"gopkg.in/yaml.v3"
)

func Test_isSigmaRule(t *testing.T) {
tests := []struct {
file string
expectedType FileType
}{
{
`title: foo
logsources:
foo:
category: process_creation
index: bar
`,
ConfigFile,
},
{
`title: foo
detection:
foo:
- bar
- baz
selection: foo
`,
RuleFile,
},
}
for _, tt := range tests {
var fileType FileType
err := yaml.Unmarshal([]byte(tt.file), &fileType)
if err != nil {
t.Fatal(err)
}
if fileType != tt.expectedType {
t.Errorf("Expected\n%s to be detected as a rule", tt.file)
}
}
}

0 comments on commit 5122d62

Please sign in to comment.