Skip to content

Commit

Permalink
Add more regex unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
stevemk14ebr committed Aug 19, 2024
1 parent d7d9a98 commit 784db2d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions objfile/patterns.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ func FindRegex(data []byte, regexInfo *RegexAndNeedle) []int {
if len(subMatches) == 0 {
break
}

for _, match := range subMatches {
matches = append(matches, match[0]+subStart)
}
Expand Down
44 changes: 44 additions & 0 deletions objfile/patterns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,4 +171,48 @@ func TestRegexpPatternFromYaraPattern(t *testing.T) {
t.Errorf("incorrect needle")
}
})

t.Run("AllSubMatches", func(t *testing.T) {
reg, err := RegexpPatternFromYaraPattern("{ AA [0-1] BB CC }")
if err != nil {
t.Errorf("pattern errored")
}

if !bytes.Equal(reg.needle, []byte{0xBB, 0xCC}) {
t.Errorf("incorrect needle")
}

matches := FindRegex([]byte{0xAA, 0xAA, 0xBB, 0xCC}, reg)
if len(matches) != 2 {
t.Errorf("Wrong sub match count")
}

matches2 := FindRegex([]byte{0xAA, 0xBB, 0xCC}, reg)
if len(matches2) != 1 {
t.Errorf("Wrong sub match count")
}

matches3 := FindRegex([]byte{0x00, 0x00, 0x11, 0xAA, 0xBB, 0xCC, 0xAA, 0xAA, 0xBB, 0xCC}, reg)
if len(matches3) != 3 {
t.Errorf("Wrong sub match count")
}

matches4 := FindRegex([]byte{0xFF, 0xAA, 0xFF, 0xBB, 0xCC, 0x00, 0x00, 0x11, 0xAA, 0xBB, 0xCC, 0xAA, 0xAA, 0xBB, 0xCC}, reg)
if len(matches4) != 4 {
t.Errorf("Wrong sub match count")
}
})

t.Run("NewLineByte", func(t *testing.T) {
// ensure ?? (dot) matches \n (0x0A)
reg, err := RegexpPatternFromYaraPattern("{ ?? AA BB CC }")
if err != nil {
t.Errorf("pattern errored")
}

matches := FindRegex([]byte{0x0A, 0xAA, 0xBB, 0xCC, 0x0A, 0xAA, 0xBB, 0x00, 0xAA, 0xBB, 0xCC, 0x0A}, reg)
if len(matches) != 2 {
t.Errorf("Wrong match count")
}
})
}

0 comments on commit 784db2d

Please sign in to comment.