mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-29 20:54:22 +01:00
Composite rules (#1905)
* composite rules * add test config * tests * taking care of some pr comments * naming
This commit is contained in:
1 parent
72977e41b6
commit
b1c9c7ecbe
9 files changed
+473
-21
No files matched your search
+143
-1
@@ -357,6 +357,10 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
}()
|
||||
)
|
||||
|
||||
if r.SkipReport == true && !fragment.InheritedFromFinding {
|
||||
return findings
|
||||
}
|
||||
|
||||
// check if commit or file is allowed for this rule.
|
||||
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
|
||||
event.Msg("skipping file: rule allowlist")
|
||||
@@ -539,7 +543,145 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
}
|
||||
findings = append(findings, finding)
|
||||
}
|
||||
return findings
|
||||
|
||||
// Handle required rules (multi-part rules)
|
||||
if fragment.InheritedFromFinding || len(r.RequiredRules) == 0 {
|
||||
return findings
|
||||
}
|
||||
|
||||
// Process required rules and create findings with auxiliary findings
|
||||
return d.processRequiredRules(fragment, currentRaw, r, encodedSegments, findings, logger)
|
||||
}
|
||||
|
||||
// processRequiredRules handles the logic for multi-part rules with auxiliary findings
|
||||
func (d *Detector) processRequiredRules(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment, primaryFindings []report.Finding, logger zerolog.Logger) []report.Finding {
|
||||
if len(primaryFindings) == 0 {
|
||||
logger.Debug().Msg("no primary findings to process for required rules")
|
||||
return primaryFindings
|
||||
}
|
||||
|
||||
// Pre-collect all required rule findings once
|
||||
allRequiredFindings := make(map[string][]report.Finding)
|
||||
|
||||
for _, requiredRule := range r.RequiredRules {
|
||||
rule, ok := d.Config.Rules[requiredRule.RuleID]
|
||||
if !ok {
|
||||
logger.Error().Str("rule-id", requiredRule.RuleID).Msg("required rule not found in config")
|
||||
continue
|
||||
}
|
||||
|
||||
// Mark fragment as inherited to prevent infinite recursion
|
||||
inheritedFragment := fragment
|
||||
inheritedFragment.InheritedFromFinding = true
|
||||
|
||||
// Call detectRule once for each required rule
|
||||
requiredFindings := d.detectRule(inheritedFragment, currentRaw, rule, encodedSegments)
|
||||
allRequiredFindings[requiredRule.RuleID] = requiredFindings
|
||||
|
||||
logger.Debug().
|
||||
Str("rule-id", requiredRule.RuleID).
|
||||
Int("findings", len(requiredFindings)).
|
||||
Msg("collected required rule findings")
|
||||
}
|
||||
|
||||
var finalFindings []report.Finding
|
||||
|
||||
// Now process each primary finding against the pre-collected required findings
|
||||
for _, primaryFinding := range primaryFindings {
|
||||
var requiredFindings []*report.RequiredFinding
|
||||
|
||||
for _, requiredRule := range r.RequiredRules {
|
||||
foundRequiredFindings, exists := allRequiredFindings[requiredRule.RuleID]
|
||||
if !exists {
|
||||
continue // Rule wasn't found earlier, skip
|
||||
}
|
||||
|
||||
// Filter findings that are within proximity of the primary finding
|
||||
for _, requiredFinding := range foundRequiredFindings {
|
||||
if d.withinProximity(primaryFinding, requiredFinding, requiredRule) {
|
||||
req := &report.RequiredFinding{
|
||||
RuleID: requiredFinding.RuleID,
|
||||
StartLine: requiredFinding.StartLine,
|
||||
EndLine: requiredFinding.EndLine,
|
||||
StartColumn: requiredFinding.StartColumn,
|
||||
EndColumn: requiredFinding.EndColumn,
|
||||
Line: requiredFinding.Line,
|
||||
Match: requiredFinding.Match,
|
||||
Secret: requiredFinding.Secret,
|
||||
}
|
||||
requiredFindings = append(requiredFindings, req)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we have at least one auxiliary finding for each required rule
|
||||
if len(requiredFindings) > 0 && d.hasAllRequiredRules(requiredFindings, r.RequiredRules) {
|
||||
// Create a finding with auxiliary findings
|
||||
newFinding := primaryFinding // Copy the primary finding
|
||||
newFinding.AddRequiredFindings(requiredFindings)
|
||||
finalFindings = append(finalFindings, newFinding)
|
||||
|
||||
logger.Debug().
|
||||
Str("primary-rule", r.RuleID).
|
||||
Int("primary-line", primaryFinding.StartLine).
|
||||
Int("auxiliary-count", len(requiredFindings)).
|
||||
Msg("multi-part rule satisfied")
|
||||
}
|
||||
}
|
||||
|
||||
return finalFindings
|
||||
}
|
||||
|
||||
// hasAllRequiredRules checks if we have at least one auxiliary finding for each required rule
|
||||
func (d *Detector) hasAllRequiredRules(auxiliaryFindings []*report.RequiredFinding, requiredRules []*config.Required) bool {
|
||||
foundRules := make(map[string]bool)
|
||||
// AuxiliaryFinding
|
||||
for _, aux := range auxiliaryFindings {
|
||||
foundRules[aux.RuleID] = true
|
||||
}
|
||||
|
||||
for _, required := range requiredRules {
|
||||
if !foundRules[required.RuleID] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *Detector) withinProximity(primary, required report.Finding, requiredRule *config.Required) bool {
|
||||
// fmt.Println(requiredRule.WithinLines)
|
||||
// If neither within_lines nor within_columns is set, findings just need to be in the same fragment
|
||||
if requiredRule.WithinLines == nil && requiredRule.WithinColumns == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check line proximity (vertical distance)
|
||||
if requiredRule.WithinLines != nil {
|
||||
lineDiff := abs(primary.StartLine - required.StartLine)
|
||||
if lineDiff > *requiredRule.WithinLines {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Check column proximity (horizontal distance)
|
||||
if requiredRule.WithinColumns != nil {
|
||||
// Use the start column of each finding for proximity calculation
|
||||
colDiff := abs(primary.StartColumn - required.StartColumn)
|
||||
if colDiff > *requiredRule.WithinColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// abs returns the absolute value of an integer
|
||||
func abs(x int) int {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// AddFinding synchronously adds a finding to the findings slice
|
||||
|
||||
+112
-14
@@ -1,8 +1,10 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -10,6 +12,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -86,6 +89,46 @@ secret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%
|
||||
secret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
|
||||
`
|
||||
|
||||
var multili = `
|
||||
username = "admin"
|
||||
|
||||
|
||||
|
||||
password = "secret123"
|
||||
`
|
||||
|
||||
func compare(t *testing.T, a, b []report.Finding) {
|
||||
if diff := cmp.Diff(a, b,
|
||||
cmpopts.SortSlices(func(a, b report.Finding) bool {
|
||||
if a.File != b.File {
|
||||
return a.File < b.File
|
||||
}
|
||||
if a.StartLine != b.StartLine {
|
||||
return a.StartLine < b.StartLine
|
||||
}
|
||||
if a.StartColumn != b.StartColumn {
|
||||
return a.StartColumn < b.StartColumn
|
||||
}
|
||||
if a.EndLine != b.EndLine {
|
||||
return a.EndLine < b.EndLine
|
||||
}
|
||||
if a.EndColumn != b.EndColumn {
|
||||
return a.EndColumn < b.EndColumn
|
||||
}
|
||||
if a.RuleID != b.RuleID {
|
||||
return a.RuleID < b.RuleID
|
||||
}
|
||||
return a.Secret < b.Secret
|
||||
}),
|
||||
cmpopts.IgnoreFields(report.Finding{},
|
||||
"Fingerprint", "Author", "Email", "Date", "Message", "Commit", "requiredFindings"),
|
||||
cmpopts.EquateApprox(0.0001, 0), // For floating point Entropy comparison
|
||||
); diff != "" {
|
||||
t.Errorf("findings mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestDetect(t *testing.T) {
|
||||
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
|
||||
tests := map[string]struct {
|
||||
@@ -97,8 +140,9 @@ func TestDetect(t *testing.T) {
|
||||
// I.e., if the finding is from a --no-git file, the line number will be
|
||||
// increase by 1 in DetectFromFiles(). If the finding is from git,
|
||||
// the line number will be increased by the patch delta.
|
||||
expectedFindings []report.Finding
|
||||
wantError error
|
||||
expectedFindings []report.Finding
|
||||
wantError error
|
||||
expectedAuxOutput string
|
||||
}{
|
||||
// General
|
||||
"valid allow comment (1)": {
|
||||
@@ -424,6 +468,28 @@ const token = "mockSecret";
|
||||
FilePath: "tmp.go",
|
||||
},
|
||||
},
|
||||
"fragment level composite": {
|
||||
cfgName: "composite",
|
||||
fragment: Fragment{
|
||||
Raw: multili,
|
||||
},
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
Description: "Primary rule",
|
||||
RuleID: "primary-rule",
|
||||
StartLine: 5,
|
||||
EndLine: 5,
|
||||
StartColumn: 5,
|
||||
EndColumn: 26,
|
||||
Line: "\n\t\t\tpassword = \"secret123\"",
|
||||
Match: `password = "secret123"`,
|
||||
Secret: "secret123",
|
||||
Entropy: 2.9477028846740723,
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
expectedAuxOutput: "Required: username-rule:1:admin\n",
|
||||
},
|
||||
// Decoding
|
||||
"detect encoded": {
|
||||
cfgName: "encoded",
|
||||
@@ -736,11 +802,50 @@ const token = "mockSecret";
|
||||
d.baselinePath = tt.baselinePath
|
||||
|
||||
findings := d.Detect(tt.fragment)
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
|
||||
compare(t, findings, tt.expectedFindings)
|
||||
|
||||
// extremely goofy way to test auxiliary findings
|
||||
// capture stdout and print that sonabitch
|
||||
// TODO
|
||||
if tt.expectedAuxOutput != "" {
|
||||
capturedOutput := captureStdout(func() {
|
||||
for _, finding := range findings {
|
||||
finding.PrintRequiredFindings()
|
||||
}
|
||||
})
|
||||
|
||||
// Clean up the output for comparison (remove ANSI color codes)
|
||||
cleanOutput := stripANSI(capturedOutput)
|
||||
expectedClean := stripANSI(tt.expectedAuxOutput)
|
||||
|
||||
assert.Equal(t, expectedClean, cleanOutput, "Auxiliary output should match")
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func stripANSI(s string) string {
|
||||
ansiRegex := regexp.MustCompile(`\x1b\[[0-9;]*m`)
|
||||
return ansiRegex.ReplaceAllString(s, "")
|
||||
}
|
||||
|
||||
func captureStdout(f func()) string {
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
f()
|
||||
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// TestFromGit tests the FromGit function
|
||||
func TestFromGit(t *testing.T) {
|
||||
// TODO: Fix this test on windows.
|
||||
@@ -2300,10 +2405,9 @@ let password = 'Summer2024!';`
|
||||
|
||||
f := tc.fragment
|
||||
f.Raw = raw
|
||||
|
||||
actual := d.detectRule(f, raw, rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(tc.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
compare(t, tc.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2462,9 +2566,7 @@ func TestWindowsFileSeparator_RulePath(t *testing.T) {
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(test.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
compare(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2648,11 +2750,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
|
||||
for name, test := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
|
||||
if diff := cmp.Diff(test.expected, actual); diff != "" {
|
||||
t.Errorf("diff: (-want +got)\n%s", diff)
|
||||
}
|
||||
compare(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//endregion
|
||||
@@ -232,7 +232,9 @@ func printFinding(f report.Finding, noColor bool) {
|
||||
|
||||
fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID)
|
||||
fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy)
|
||||
|
||||
if f.File == "" {
|
||||
f.PrintRequiredFindings()
|
||||
fmt.Println("")
|
||||
return
|
||||
}
|
||||
@@ -243,6 +245,7 @@ func printFinding(f report.Finding, noColor bool) {
|
||||
fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
|
||||
if f.Commit == "" {
|
||||
fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
|
||||
f.PrintRequiredFindings()
|
||||
fmt.Println("")
|
||||
return
|
||||
}
|
||||
@@ -254,5 +257,7 @@ func printFinding(f report.Finding, noColor bool) {
|
||||
if f.Link != "" {
|
||||
fmt.Printf("%-12s %s\n", "Link:", f.Link)
|
||||
}
|
||||
|
||||
f.PrintRequiredFindings()
|
||||
fmt.Println("")
|
||||
}
|
||||
Reference in new issue
Block a user