Compare commits

..
6 Commits
Author SHA1 Message Date
Richard Gomez 4451b455f3 feat(config): define multiple global allowlists (#1777) 2025-04-29 08:49:04 -05:00
7fb21a4e61 feat(rules): Add Perplexity AI API key detection (#1825)
* feat(rules): Add Perplexity AI API key detection

* Fix generation

* Fix imports

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Update cmd/generate/config/rules/perplexity.go

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>

* Adjust regex, add imports

* Generate config

---------

Co-authored-by: vno <vno@serity.io>
Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-04-28 14:06:48 -05:00
Richard Gomez f6193bc92c feat(gcp): increase rule entropy (#1840) 2025-04-26 19:28:32 -05:00
San Tran 9bc725786d Adding clickhouse scanner (#1826)
* Adding clickhouse scanner

* removing mention of aws as i used it as template
2025-04-16 16:10:47 -05:00
Richard Gomez b6cc71aa3a fix(baseline): work with --redact (#1741) 2025-04-13 09:40:15 -05:00
Richard Gomez cfdeb0d7e0 feat(rule): validate & sort rule when generating (#1817) 2025-04-12 10:09:19 -05:00
74 changed files with 1552 additions and 989 deletions

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
go-version: 1.23 go-version: 1.23
- name: Build - name: Build
run: go build -v ./... run: go build ./...
- name: Set up gotestsum - name: Set up gotestsum
run: | run: |
+15 -6
View File
@@ -290,11 +290,10 @@ disabledRules = [ "generic-api-key"]
# An array of tables that contain information that define instructions # An array of tables that contain information that define instructions
# on how to detect secrets # on how to detect secrets
[[rules]] [[rules]]
# Unique identifier for this rule # Unique identifier for this rule
id = "awesome-rule-1" id = "awesome-rule-1"
# Short human readable description of the rule. # Short human-readable description of the rule.
description = "awesome rule 1" description = "awesome rule 1"
# Golang regular expression used to detect secrets. Note Golang's regex engine # Golang regular expression used to detect secrets. Note Golang's regex engine
@@ -368,19 +367,20 @@ id = "gitlab-pat"
regexTarget = "line" regexTarget = "line"
regexes = [ '''MY-glpat-''' ] regexes = [ '''MY-glpat-''' ]
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# ⚠️ In v8.25.0 `[allowlist]` was replaced with `[[allowlists]]`.
#
# Global allowlists have a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no # If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
# secrets will be detected for said commit. The same logic applies for regexes and paths. # secrets will be detected for said commit. The same logic applies for regexes and paths.
[allowlist] [[allowlists]]
description = "global allow list" description = "global allow list"
commits = [ "commit-A", "commit-B", "commit-C"] commits = [ "commit-A", "commit-B", "commit-C"]
paths = [ paths = [
'''gitleaks\.toml''', '''gitleaks\.toml''',
'''(.*?)(jpg|gif|doc)''' '''(.*?)(jpg|gif|doc)'''
] ]
# note: (global) regexTarget defaults to check the _Secret_ in the finding. # note: (global) regexTarget defaults to check the _Secret_ in the finding.
# if regexTarget is not specified then _Secret_ will be used.
# Acceptable values for regexTarget are "match" and "line" # Acceptable values for regexTarget are "match" and "line"
regexTarget = "match" regexTarget = "match"
regexes = [ regexes = [
@@ -394,6 +394,15 @@ stopwords = [
'''client''', '''client''',
'''endpoint''', '''endpoint''',
] ]
# ⚠️ In v8.25.0, `[[allowlists]]` have a new field called |targetRules|.
#
# Common allowlists can be defined once and assigned to multiple rules using |targetRules|.
# This will only run on the specified rules, not globally.
[[allowlists]]
targetRules = ["awesome-rule-1", "awesome-rule-2"]
description = "Our test assets trigger false-positives in a couple rules."
paths = ['''tests/expected/._\.json$''']
``` ```
Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) for examples or follow the [contributing guidelines](https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md) if you would like to contribute to the default configuration. Additionally, you can check out [this gitleaks blog post](https://blog.gitleaks.io/stop-leaking-secrets-configuration-2-3-aeed293b1fbf) which covers advanced configuration setups. Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml) for examples or follow the [contributing guidelines](https://github.com/gitleaks/gitleaks/blob/master/CONTRIBUTING.md) if you would like to contribute to the default configuration. Additionally, you can check out [this gitleaks blog post](https://blog.gitleaks.io/stop-leaking-secrets-configuration-2-3-aeed293b1fbf) which covers advanced configuration setups.
+1 -1
View File
@@ -78,7 +78,7 @@ func runDetect(cmd *cobra.Command, args []string) {
source, source,
detector.Sema, detector.Sema,
detector.FollowSymlinks, detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed, detector.Config.Allowlists,
) )
if err != nil { if err != nil {
logging.Fatal().Err(err).Send() logging.Fatal().Err(err).Send()
+1 -1
View File
@@ -60,7 +60,7 @@ func runDirectory(cmd *cobra.Command, args []string) {
source, source,
detector.Sema, detector.Sema,
detector.FollowSymlinks, detector.FollowSymlinks,
detector.Config.Allowlist.PathAllowed, detector.Config.Allowlists,
) )
if err != nil { if err != nil {
logging.Fatal().Err(err) logging.Fatal().Err(err)
+91 -89
View File
@@ -11,106 +11,108 @@ import (
func CreateGlobalConfig() config.Config { func CreateGlobalConfig() config.Config {
return config.Config{ return config.Config{
Title: "gitleaks config", Title: "gitleaks config",
Allowlist: config.Allowlist{ Allowlists: []*config.Allowlist{
Description: "global allow lists", {
Regexes: []*regexp.Regexp{ Description: "global allow lists",
// ----------- General placeholders ----------- Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)^true|false|null$`), // ----------- General placeholders -----------
// Awkward workaround to detect repeated characters. regexp.MustCompile(`(?i)^true|false|null$`),
func() *regexp.Regexp { // Awkward workaround to detect repeated characters.
var ( func() *regexp.Regexp {
letters = "abcdefghijklmnopqrstuvwxyz*." var (
patterns []string letters = "abcdefghijklmnopqrstuvwxyz*."
) patterns []string
for _, char := range letters { )
if char == '*' || char == '.' { for _, char := range letters {
patterns = append(patterns, fmt.Sprintf("\\%c+", char)) if char == '*' || char == '.' {
} else { patterns = append(patterns, fmt.Sprintf("\\%c+", char))
patterns = append(patterns, fmt.Sprintf("%c+", char)) } else {
patterns = append(patterns, fmt.Sprintf("%c+", char))
}
} }
} return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$")
return regexp.MustCompile("^(?i:" + strings.Join(patterns, "|") + ")$") }(),
}(),
// ----------- Environment Variables ----------- // ----------- Environment Variables -----------
regexp.MustCompile(`^\$(?:\d+|{\d+})$`), regexp.MustCompile(`^\$(?:\d+|{\d+})$`),
regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`), regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`),
regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`), regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`),
// ----------- Interpolated Variables ----------- // ----------- Interpolated Variables -----------
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html) // Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`), regexp.MustCompile(`^\{\{[ \t]*[\w ().|]+[ \t]*}}$`),
// GitHub Actions // GitHub Actions
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables // https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions // https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`), regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables) // NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`), regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`),
// String formatting. // String formatting.
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt) regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html) regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables) // Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`), regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`),
// ----------- Miscellaneous ----------- // ----------- Miscellaneous -----------
// File paths // File paths
regexp.MustCompile(`^/Users/(?i)[a-z0-9]+/[\w .-/]+$`), // MacOS regexp.MustCompile(`^/Users/(?i)[a-z0-9]+/[\w .-/]+$`), // MacOS
regexp.MustCompile(`^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$`), // Linux regexp.MustCompile(`^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$`), // Linux
// 11980 Jps -Dapplication.home=D:\develop_tools\jdk\jdk1.8.0_131 -Xms8m // 11980 Jps -Dapplication.home=D:\develop_tools\jdk\jdk1.8.0_131 -Xms8m
//regexp.MustCompile(`^$`), // Windows //regexp.MustCompile(`^$`), // Windows
}, },
Paths: []*regexp.Regexp{ Paths: []*regexp.Regexp{
regexp.MustCompile(`gitleaks\.toml`), regexp.MustCompile(`gitleaks\.toml`),
// ----------- Documents and media ----------- // ----------- Documents and media -----------
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$`), regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$`),
// ----------- Golang files ----------- // ----------- Golang files -----------
regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`), regexp.MustCompile(`go\.(?:mod|sum|work(?:\.sum)?)$`),
regexp.MustCompile(`(?:^|/)vendor/modules\.txt$`), regexp.MustCompile(`(?:^|/)vendor/modules\.txt$`),
regexp.MustCompile(`(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$`), regexp.MustCompile(`(?:^|/)vendor/(?:github\.com|golang\.org/x|google\.golang\.org|gopkg\.in|istio\.io|k8s\.io|sigs\.k8s\.io)(?:/.*)?$`),
// ----------- Java files ----------- // ----------- Java files -----------
// Gradle // Gradle
regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`), regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`),
regexp.MustCompile(`(?:^|/)gradle\.lockfile$`), regexp.MustCompile(`(?:^|/)gradle\.lockfile$`),
regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`), regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`),
regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`), regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
// ----------- JavaScript files ----------- // ----------- JavaScript files -----------
// Dependencies and lock files. // Dependencies and lock files.
regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`), regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`),
regexp.MustCompile(`(?:^|/)(?:deno\.lock|npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`), regexp.MustCompile(`(?:^|/)(?:deno\.lock|npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`), regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`),
// TODO: Add more common static assets, such as swagger-ui. // TODO: Add more common static assets, such as swagger-ui.
regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`), regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`),
regexp.MustCompile(`(?:^|/)javascript\.json$`), regexp.MustCompile(`(?:^|/)javascript\.json$`),
// ----------- Python files ----------- // ----------- Python files -----------
// Dependencies and lock files. // Dependencies and lock files.
regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`), regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`),
// Virtual environments // Virtual environments
regexp.MustCompile(`(?i)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`), regexp.MustCompile(`(?i)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`),
regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`), regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`),
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels) // dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`), regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`),
// ----------- Ruby files ----------- // ----------- Ruby files -----------
regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`), regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`),
regexp.MustCompile(`\.gem$`), // tar archive regexp.MustCompile(`\.gem$`), // tar archive
// Misc // Misc
regexp.MustCompile(`verification-metadata\.xml`), regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`), regexp.MustCompile(`Database.refactorlog`),
// regexp.MustCompile(`vendor`), // regexp.MustCompile(`vendor`),
}, },
StopWords: []string{ StopWords: []string{
"abcdefghijklmnopqrstuvwxyz", // character range "abcdefghijklmnopqrstuvwxyz", // character range
// ----------- Secrets ----------- // ----------- Secrets -----------
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56) // Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
"014df517-39d1-4453-b7b3-9930c563627c", "014df517-39d1-4453-b7b3-9930c563627c",
},
}, },
}, },
} }
+32 -16
View File
@@ -75,18 +75,22 @@ var allowlistRegexTests = map[string]struct {
func TestConfigAllowlistRegexes(t *testing.T) { func TestConfigAllowlistRegexes(t *testing.T) {
cfg := CreateGlobalConfig() cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist allowlists := cfg.Allowlists
for name, cases := range allowlistRegexTests { for name, cases := range allowlistRegexTests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid { for _, c := range cases.invalid {
if !allowlist.RegexAllowed(c) { for _, a := range allowlists {
t.Errorf("invalid value not marked as allowed: %s", c) if !a.RegexAllowed(c) {
t.Errorf("invalid value not marked as allowed: %s", c)
}
} }
} }
for _, c := range cases.valid { for _, c := range cases.valid {
if allowlist.RegexAllowed(c) { for _, a := range allowlists {
t.Errorf("valid value marked as allowed: %s", c) if a.RegexAllowed(c) {
t.Errorf("valid value marked as allowed: %s", c)
}
} }
} }
}) })
@@ -95,15 +99,19 @@ func TestConfigAllowlistRegexes(t *testing.T) {
func BenchmarkConfigAllowlistRegexes(b *testing.B) { func BenchmarkConfigAllowlistRegexes(b *testing.B) {
cfg := CreateGlobalConfig() cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist allowlists := cfg.Allowlists
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
for _, cases := range allowlistRegexTests { for _, cases := range allowlistRegexTests {
for _, c := range cases.invalid { for _, c := range cases.invalid {
allowlist.RegexAllowed(c) for _, a := range allowlists {
a.RegexAllowed(c)
}
} }
for _, c := range cases.valid { for _, c := range cases.valid {
allowlist.RegexAllowed(c) for _, a := range allowlists {
a.RegexAllowed(c)
}
} }
} }
} }
@@ -152,18 +160,22 @@ var allowlistPathsTests = map[string]struct {
func TestConfigAllowlistPaths(t *testing.T) { func TestConfigAllowlistPaths(t *testing.T) {
cfg := CreateGlobalConfig() cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist allowlists := cfg.Allowlists
for name, cases := range allowlistPathsTests { for name, cases := range allowlistPathsTests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
for _, c := range cases.invalid { for _, c := range cases.invalid {
if !allowlist.PathAllowed(c) { for _, a := range allowlists {
t.Errorf("invalid path not marked as allowed: %s", c) if !a.PathAllowed(c) {
t.Errorf("invalid path not marked as allowed: %s", c)
}
} }
} }
for _, c := range cases.valid { for _, c := range cases.valid {
if allowlist.PathAllowed(c) { for _, a := range allowlists {
t.Errorf("valid path marked as allowed: %s", c) if a.PathAllowed(c) {
t.Errorf("valid path marked as allowed: %s", c)
}
} }
} }
}) })
@@ -172,15 +184,19 @@ func TestConfigAllowlistPaths(t *testing.T) {
func BenchmarkConfigAllowlistPaths(b *testing.B) { func BenchmarkConfigAllowlistPaths(b *testing.B) {
cfg := CreateGlobalConfig() cfg := CreateGlobalConfig()
allowlist := cfg.Allowlist allowlists := cfg.Allowlists
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
for _, cases := range allowlistPathsTests { for _, cases := range allowlistPathsTests {
for _, c := range cases.invalid { for _, c := range cases.invalid {
allowlist.PathAllowed(c) for _, a := range allowlists {
a.PathAllowed(c)
}
} }
for _, c := range cases.valid { for _, c := range cases.valid {
allowlist.PathAllowed(c) for _, a := range allowlists {
a.PathAllowed(c)
}
} }
} }
} }
+23 -2
View File
@@ -4,6 +4,8 @@ import (
"os" "os"
"text/template" "text/template"
"golang.org/x/exp/slices"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base" "github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules" "github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
@@ -18,7 +20,7 @@ const (
func main() { func main() {
if len(os.Args) < 2 { if len(os.Args) < 2 {
os.Stderr.WriteString("Specify path to the gitleaks.toml config\n") _, _ = os.Stderr.WriteString("Specify path to the gitleaks.toml config\n")
os.Exit(2) os.Exit(2)
} }
gitleaksConfigPath := os.Args[1] gitleaksConfigPath := os.Args[1]
@@ -46,6 +48,7 @@ func main() {
rules.Beamer(), rules.Beamer(),
rules.CodecovAccessToken(), rules.CodecovAccessToken(),
rules.CoinbaseAccessToken(), rules.CoinbaseAccessToken(),
rules.ClickHouseCloud(),
rules.Clojars(), rules.Clojars(),
rules.CloudflareAPIKey(), rules.CloudflareAPIKey(),
rules.CloudflareGlobalAPIKey(), rules.CloudflareGlobalAPIKey(),
@@ -164,6 +167,7 @@ func main() {
rules.OktaAccessToken(), rules.OktaAccessToken(),
rules.OpenAI(), rules.OpenAI(),
rules.OpenshiftUserToken(), rules.OpenshiftUserToken(),
rules.PerplexityAPIKey(),
rules.PlaidAccessID(), rules.PlaidAccessID(),
rules.PlaidSecretKey(), rules.PlaidSecretKey(),
rules.PlaidAccessToken(), rules.PlaidAccessToken(),
@@ -239,9 +243,18 @@ func main() {
// ensure rules have unique ids // ensure rules have unique ids
ruleLookUp := make(map[string]config.Rule, len(configRules)) ruleLookUp := make(map[string]config.Rule, len(configRules))
for _, rule := range configRules { for _, rule := range configRules {
if err := rule.Validate(); err != nil {
logging.Fatal().Err(err).
Str("rule-id", rule.RuleID).
Msg("Failed to validate rule")
}
sortRule(rule)
// check if rule is in ruleLookUp // check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok { if _, ok := ruleLookUp[rule.RuleID]; ok {
logging.Fatal().Msgf("rule id %s is not unique", rule.RuleID) logging.Fatal().
Str("rule-id", rule.RuleID).
Msg("rule id is not unique")
} }
// TODO: eventually change all the signatures to get ride of this // TODO: eventually change all the signatures to get ride of this
// nasty dereferencing. // nasty dereferencing.
@@ -257,6 +270,7 @@ func main() {
if err != nil { if err != nil {
logging.Fatal().Err(err).Msg("Failed to create rules.toml") logging.Fatal().Err(err).Msg("Failed to create rules.toml")
} }
defer f.Close()
cfg := base.CreateGlobalConfig() cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp cfg.Rules = ruleLookUp
@@ -264,3 +278,10 @@ func main() {
logging.Fatal().Err(err).Msg("could not execute template") logging.Fatal().Err(err).Msg("could not execute template")
} }
} }
// sortRule makes the generated config deterministic.
func sortRule(r *config.Rule) {
for _, a := range r.Allowlists {
slices.Sort(a.StopWords)
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ func AWS() *config.Rule {
"ABIA", // AWS STS service bearer token "ABIA", // AWS STS service bearer token
"ACCA", // Context-specific credential "ACCA", // Context-specific credential
}, },
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`.+EXAMPLE$`), regexp.MustCompile(`.+EXAMPLE$`),
+30
View File
@@ -0,0 +1,30 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/regexp"
)
func ClickHouseCloud() *config.Rule {
// define rule
r := config.Rule{
RuleID: "clickhouse-cloud-api-secret-key",
Description: "Identified a pattern that may indicate clickhouse cloud API secret key, risking unauthorized clickhouse cloud api access and data breaches on ClickHouse Cloud platforms.",
Regex: regexp.MustCompile(`\b(4b1d[A-Za-z0-9]{38})\b`),
Entropy: 3,
Keywords: []string{
"4b1d", // Prefix
},
}
// validate
tps := utils.GenerateSampleSecrets("ClickHouse", "4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z")
tps = append(tps, utils.GenerateSampleSecrets("ClickHouse", "4b1d"+secrets.NewSecret("[A-Za-z0-9]{38}"))...)
fps := []string{
`key = 4b1dXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`, // Low entropy
`key = adf4b1dbRdW3rOcB7xLthrM4BTBGK1qPLkHigpN1bXD6z`, // Not start of a word
}
return utils.Validate(r, tps, fps)
}
+13 -11
View File
@@ -13,21 +13,22 @@
title = "{{.Title}}" title = "{{.Title}}"
[allowlist] {{ with .Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}# TODO: change to [[allowlists]]{{println}}[allowlist]
description = "{{.Allowlist.Description}}" {{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
{{- with .Allowlist.RegexTarget }} {{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
regexTarget = "{{ . }}"{{ end -}} {{- with .Commits -}}{{println}}commits = [
{{- with .Allowlist.Regexes }} {{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }} ]{{ end }}
{{- with .Allowlist.Paths }} {{- with .Paths }}{{println}}paths = [{{ range $j, $path := . }}
paths = [{{ range $i, $path := . }}
'''{{ $path }}''',{{ end }} '''{{ $path }}''',{{ end }}
]{{ end }} ]{{ end }}
{{- with .Allowlist.StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }} {{- if and .RegexTarget .Regexes }}{{println}}regexTarget = "{{ .RegexTarget }}"{{ end -}}
{{- with .Regexes }}{{println}}regexes = [{{ range $i, $regex := . }}
'''{{ $regex }}''',{{ end }}
]{{ end }}
{{- with .StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
"{{ $stopword }}",{{ end }} "{{ $stopword }}",{{ end }}
]{{ end }}{{println}} ]{{ end }}{{ end }}{{ end }}{{ end }}{{println}}
{{- range $i, $rule := .Rules }}{{println}}[[rules]] {{- range $i, $rule := .Rules }}{{println}}[[rules]]
id = "{{$rule.RuleID}}" id = "{{$rule.RuleID}}"
@@ -51,6 +52,7 @@ tags = [
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }} {{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
]{{ end }} ]{{ end }}
{{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]] {{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]]
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }} {{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
{{- with .Commits -}}{{println}}commits = [ {{- with .Commits -}}{{println}}commits = [
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }} {{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
+2 -2
View File
@@ -16,7 +16,7 @@ func CurlBasicAuth() *config.Rule {
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`), Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
Keywords: []string{"curl"}, Keywords: []string{"curl"},
Entropy: 2, Entropy: 2,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
@@ -109,7 +109,7 @@ func CurlHeaderAuth() *config.Rule {
fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)), fmt.Sprintf(`\bcurl\b(?:.*?|.*?(?:[\r\n]{1,2}.*?){1,5})[ \t\n\r](?:-H|--header)(?:=|[ \t]{0,5})(?:"%s"|'%s')(?:\B|\s|\z)`, authPat, authPat)),
Entropy: 2.75, Entropy: 2.75,
Keywords: []string{"curl"}, Keywords: []string{"curl"},
//Allowlists: []config.Allowlist{ //Allowlists: []*config.Allowlist{
// { // {
// Regexes: []*regexp.Regexp{}, // Regexes: []*regexp.Regexp{},
// }, // },
+3 -5
View File
@@ -30,11 +30,9 @@ func GCPAPIKey() *config.Rule {
RuleID: "gcp-api-key", RuleID: "gcp-api-key",
Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.", Description: "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches.",
Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false), Regex: utils.GenerateUniqueTokenRegex(`AIza[\w-]{35}`, false),
Entropy: 3.0, Entropy: 4,
Keywords: []string{ Keywords: []string{"AIza"},
"AIza", Allowlists: []*config.Allowlist{
},
Allowlists: []config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// example keys from https://github.com/firebase/firebase-android-sdk // example keys from https://github.com/firebase/firebase-android-sdk
+2 -2
View File
@@ -36,7 +36,7 @@ func GenericCredential() *config.Rule {
"token", "token",
}, },
Entropy: 3.5, Entropy: 3.5,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads. // NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters. // Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
@@ -281,7 +281,7 @@ jdbc.snowflake.url=`,
} }
func newPlausibleSecret(regex string) string { func newPlausibleSecret(regex string) string {
allowList := config.Allowlist{StopWords: DefaultStopWords} allowList := &config.Allowlist{StopWords: DefaultStopWords}
// attempt to generate a random secret, // attempt to generate a random secret,
// retrying until it contains at least one digit and no stop words // retrying until it contains at least one digit and no stop words
// TODO: currently the DefaultStopWords list contains many short words, // TODO: currently the DefaultStopWords list contains many short words,
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/zricethezav/gitleaks/v8/regexp" "github.com/zricethezav/gitleaks/v8/regexp"
) )
var githubAllowlist = []config.Allowlist{ var githubAllowlist = []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{ Paths: []*regexp.Regexp{
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options // https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
+1 -1
View File
@@ -15,7 +15,7 @@ func VaultServiceToken() *config.Rule {
Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false), Regex: utils.GenerateUniqueTokenRegex(`(?:hvs\.[\w-]{90,120}|s\.(?i:[a-z0-9]{24}))`, false),
Entropy: 3.5, Entropy: 3.5,
Keywords: []string{"hvs.", "s."}, Keywords: []string{"hvs.", "s."},
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357 // https://github.com/gitleaks/gitleaks/issues/1490#issuecomment-2334166357
+1 -1
View File
@@ -31,7 +31,7 @@ func KubernetesSecret() *config.Rule {
}, },
// Kubernetes secrets are usually yaml files. // Kubernetes secrets are usually yaml files.
Path: regexp.MustCompile(`(?i)\.ya?ml$`), Path: regexp.MustCompile(`(?i)\.ya?ml$`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// Ignore empty or placeholder values. // Ignore empty or placeholder values.
+1 -1
View File
@@ -14,7 +14,7 @@ func NugetConfigPassword() *config.Rule {
Path: regexp.MustCompile(`(?i)nuget\.config$`), Path: regexp.MustCompile(`(?i)nuget\.config$`),
Keywords: []string{"<add key="}, Keywords: []string{"<add key="},
Entropy: 1, Entropy: 1,
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
// samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file // samples from https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func PerplexityAPIKey() *config.Rule {
// Define Rule
r := config.Rule{
RuleID: "perplexity-api-key",
Description: "Detected a Perplexity API key, which could lead to unauthorized access to Perplexity AI services and data exposure.",
Regex: regexp.MustCompile(`\b(pplx-[a-zA-Z0-9]{48})(?:[\x60'"\s;]|\\[nr]|$|\b)`),
Keywords: []string{"pplx-"},
Entropy: 4.0,
}
// validate
tps := utils.GenerateSampleSecrets("perplexity", "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'")
fps := []string{
"PERPLEXITY_API_KEY=pplx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
}
return utils.Validate(r, tps, fps)
}
+50 -33
View File
@@ -38,9 +38,6 @@ type Allowlist struct {
// Paths is a slice of path regular expressions that are allowed to be ignored. // Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp Paths []*regexp.Regexp
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// Can be `match` or `line`. // Can be `match` or `line`.
// //
// If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_. // If `match` the _Regexes_ will be tested against the match of the _Rule.Regex_.
@@ -50,15 +47,54 @@ type Allowlist struct {
// If RegexTarget is empty, it will be tested against the found secret. // If RegexTarget is empty, it will be tested against the found secret.
RegexTarget string RegexTarget string
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// StopWords is a slice of stop words that are allowed to be ignored. // StopWords is a slice of stop words that are allowed to be ignored.
// This targets the _secret_, not the content of the regex match like the // This targets the _secret_, not the content of the regex match like the
// Regexes slice. // Regexes slice.
StopWords []string StopWords []string
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
}
func (a *Allowlist) Validate() error {
if a.validated {
return nil
}
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return fmt.Errorf("must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
uniqueCommits[commit] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[stopWord] = struct{}{}
}
a.StopWords = maps.Keys(uniqueStopwords)
}
a.validated = true
return nil
} }
// CommitAllowed returns true if the commit is allowed to be ignored. // CommitAllowed returns true if the commit is allowed to be ignored.
func (a *Allowlist) CommitAllowed(c string) (bool, string) { func (a *Allowlist) CommitAllowed(c string) (bool, string) {
if c == "" { if a == nil || c == "" {
return false, "" return false, ""
} }
@@ -72,15 +108,25 @@ func (a *Allowlist) CommitAllowed(c string) (bool, string) {
// PathAllowed returns true if the path is allowed to be ignored. // PathAllowed returns true if the path is allowed to be ignored.
func (a *Allowlist) PathAllowed(path string) bool { func (a *Allowlist) PathAllowed(path string) bool {
if a == nil || path == "" {
return false
}
return anyRegexMatch(path, a.Paths) return anyRegexMatch(path, a.Paths)
} }
// RegexAllowed returns true if the regex is allowed to be ignored. // RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(secret string) bool { func (a *Allowlist) RegexAllowed(secret string) bool {
if a == nil || secret == "" {
return false
}
return anyRegexMatch(secret, a.Regexes) return anyRegexMatch(secret, a.Regexes)
} }
func (a *Allowlist) ContainsStopWord(s string) (bool, string) { func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
if a == nil || s == "" {
return false, ""
}
s = strings.ToLower(s) s = strings.ToLower(s)
for _, stopWord := range a.StopWords { for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) { if strings.Contains(s, strings.ToLower(stopWord)) {
@@ -89,32 +135,3 @@ func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
} }
return false, "" return false, ""
} }
func (a *Allowlist) Validate() error {
// Disallow empty allowlists.
if len(a.Commits) == 0 &&
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return fmt.Errorf("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
uniqueCommits[commit] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[stopWord] = struct{}{}
}
a.StopWords = maps.Keys(uniqueStopwords)
}
return nil
}
+2 -1
View File
@@ -105,7 +105,7 @@ func TestValidate(t *testing.T) {
}{ }{
"empty conditions": { "empty conditions": {
input: Allowlist{}, input: Allowlist{},
wantErr: errors.New("[[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"), wantErr: errors.New("must contain at least one check for: commits, paths, regexes, or stopwords"),
}, },
"deduplicated commits and stopwords": { "deduplicated commits and stopwords": {
input: Allowlist{ input: Allowlist{
@@ -148,6 +148,7 @@ func TestValidate(t *testing.T) {
opts = cmp.Options{ opts = cmp.Options{
cmp.Comparer(regexComparer), cmp.Comparer(regexComparer),
cmpopts.SortSlices(arrayComparer), cmpopts.SortSlices(arrayComparer),
cmpopts.IgnoreUnexported(Allowlist{}),
} }
) )
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" { if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
+153 -118
View File
@@ -2,6 +2,7 @@ package config
import ( import (
_ "embed" _ "embed"
"errors"
"fmt" "fmt"
"sort" "sort"
"strings" "strings"
@@ -12,12 +13,14 @@ import (
"github.com/zricethezav/gitleaks/v8/regexp" "github.com/zricethezav/gitleaks/v8/regexp"
) )
//go:embed gitleaks.toml var (
var DefaultConfig string //go:embed gitleaks.toml
DefaultConfig string
// use to keep track of how many configs we can extend // use to keep track of how many configs we can extend
// yea I know, globals bad // yea I know, globals bad
var extendDepth int extendDepth int
)
const maxExtendDepth = 2 const maxExtendDepth = 2
@@ -25,29 +28,28 @@ const maxExtendDepth = 2
// to parse the config file. This struct does not include regular expressions. // to parse the config file. This struct does not include regular expressions.
// It is used as an intermediary to convert the Viper config to the Config struct. // It is used as an intermediary to convert the Viper config to the Config struct.
type ViperConfig struct { type ViperConfig struct {
Title string
Description string Description string
Extend Extend Extend Extend
Rules []struct { Rules []struct {
ID string ID string
Description string Description string
Path string
Regex string Regex string
SecretGroup int SecretGroup int
Entropy float64 Entropy float64
Keywords []string Keywords []string
Path string
Tags []string Tags []string
// Deprecated: this is a shim for backwards-compatibility. It should be removed in 9.x. // Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist AllowList *viperRuleAllowlist
Allowlists []viperRuleAllowlist Allowlists []*viperRuleAllowlist
}
Allowlist struct {
Commits []string
Paths []string
RegexTarget string
Regexes []string
StopWords []string
} }
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperGlobalAllowlist
Allowlists []*viperGlobalAllowlist
} }
type viperRuleAllowlist struct { type viperRuleAllowlist struct {
@@ -60,6 +62,11 @@ type viperRuleAllowlist struct {
StopWords []string StopWords []string
} }
type viperGlobalAllowlist struct {
TargetRules []string
viperRuleAllowlist `mapstructure:",squash"`
}
// Config is a configuration struct that contains rules and an allowlist if present. // Config is a configuration struct that contains rules and an allowlist if present.
type Config struct { type Config struct {
Title string Title string
@@ -67,11 +74,10 @@ type Config struct {
Path string Path string
Description string Description string
Rules map[string]Rule Rules map[string]Rule
Allowlist Allowlist
Keywords map[string]struct{} Keywords map[string]struct{}
// used to keep sarif results consistent // used to keep sarif results consistent
OrderedRules []string OrderedRules []string
Allowlists []*Allowlist
} }
// Extend is a struct that allows users to define how they want their // Extend is a struct that allows users to define how they want their
@@ -85,13 +91,24 @@ type Extend struct {
func (vc *ViperConfig) Translate() (Config, error) { func (vc *ViperConfig) Translate() (Config, error) {
var ( var (
keywords = make(map[string]struct{}) keywords = make(map[string]struct{})
orderedRules []string orderedRules []string
rulesMap = make(map[string]Rule) rulesMap = make(map[string]Rule)
ruleAllowlists = make(map[string][]*Allowlist)
) )
// Validate individual rules. // Validate individual rules.
for _, vr := range vc.Rules { for _, vr := range vc.Rules {
var (
pathPat *regexp.Regexp
regexPat *regexp.Regexp
)
if vr.Path != "" {
pathPat = regexp.MustCompile(vr.Path)
}
if vr.Regex != "" {
regexPat = regexp.MustCompile(vr.Regex)
}
if vr.Keywords == nil { if vr.Keywords == nil {
vr.Keywords = []string{} vr.Keywords = []string{}
} else { } else {
@@ -101,117 +118,85 @@ func (vc *ViperConfig) Translate() (Config, error) {
vr.Keywords[i] = keyword vr.Keywords[i] = keyword
} }
} }
if vr.Tags == nil { if vr.Tags == nil {
vr.Tags = []string{} vr.Tags = []string{}
} }
var configRegex *regexp.Regexp
var configPathRegex *regexp.Regexp
if vr.Regex != "" {
configRegex = regexp.MustCompile(vr.Regex)
}
if vr.Path != "" {
configPathRegex = regexp.MustCompile(vr.Path)
}
cr := Rule{ cr := Rule{
RuleID: vr.ID, RuleID: vr.ID,
Description: vr.Description, Description: vr.Description,
Regex: configRegex, Regex: regexPat,
SecretGroup: vr.SecretGroup, SecretGroup: vr.SecretGroup,
Entropy: vr.Entropy, Entropy: vr.Entropy,
Path: configPathRegex, Path: pathPat,
Keywords: vr.Keywords, Keywords: vr.Keywords,
Tags: vr.Tags, Tags: vr.Tags,
} }
// Parse the allowlist, including the older format for backwards compatibility.
// Parse the rule allowlists, including the older format for backwards compatibility.
if vr.AllowList != nil { if vr.AllowList != nil {
// TODO: Remove this in v9.
if len(vr.Allowlists) > 0 { if len(vr.Allowlists) > 0 {
return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID) return Config{}, fmt.Errorf("%s: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]", cr.RuleID)
} }
vr.Allowlists = append(vr.Allowlists, *vr.AllowList) vr.Allowlists = append(vr.Allowlists, vr.AllowList)
} }
for _, a := range vr.Allowlists { for _, a := range vr.Allowlists {
var condition AllowlistMatchCondition allowlist, err := parseAllowlist(a)
c := strings.ToUpper(a.Condition) if err != nil {
switch c { return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
case "AND", "&&":
condition = AllowlistMatchAnd
case "", "OR", "||":
condition = AllowlistMatchOr
default:
return Config{}, fmt.Errorf("%s: unknown allowlist condition '%s' (expected 'and', 'or')", cr.RuleID, c)
}
// Validate the target.
if a.RegexTarget != "" {
switch a.RegexTarget {
case "secret":
a.RegexTarget = ""
case "match", "line":
// do nothing
default:
return Config{}, fmt.Errorf("%s: unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", cr.RuleID, a.RegexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
for _, a := range a.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range a.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
allowlist := Allowlist{
MatchCondition: condition,
RegexTarget: a.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: a.Commits,
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return Config{}, fmt.Errorf("%s: %w", cr.RuleID, err)
} }
cr.Allowlists = append(cr.Allowlists, allowlist) cr.Allowlists = append(cr.Allowlists, allowlist)
} }
orderedRules = append(orderedRules, cr.RuleID) orderedRules = append(orderedRules, cr.RuleID)
rulesMap[cr.RuleID] = cr rulesMap[cr.RuleID] = cr
} }
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes { // Assemble the config.
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range vc.Allowlist.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
c := Config{ c := Config{
Description: vc.Description, Title: vc.Title,
Extend: vc.Extend, Description: vc.Description,
Rules: rulesMap, Extend: vc.Extend,
Allowlist: Allowlist{ Rules: rulesMap,
RegexTarget: vc.Allowlist.RegexTarget,
Regexes: allowlistRegexes,
Paths: allowlistPaths,
Commits: vc.Allowlist.Commits,
StopWords: vc.Allowlist.StopWords,
},
Keywords: keywords, Keywords: keywords,
OrderedRules: orderedRules, OrderedRules: orderedRules,
} }
// Parse the config allowlists, including the older format for backwards compatibility.
if vc.AllowList != nil {
// TODO: Remove this in v9.
if len(vc.Allowlists) > 0 {
return Config{}, errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]")
}
vc.Allowlists = append(vc.Allowlists, vc.AllowList)
}
for _, a := range vc.Allowlists {
allowlist, err := parseAllowlist(&a.viperRuleAllowlist)
if err != nil {
return Config{}, fmt.Errorf("[[allowlists]] %w", err)
}
// Allowlists with |targetRules| aren't added to the global list.
if len(a.TargetRules) > 0 {
for _, ruleID := range a.TargetRules {
// It's not possible to validate |ruleID| until after extend.
ruleAllowlists[ruleID] = append(ruleAllowlists[ruleID], allowlist)
}
} else {
c.Allowlists = append(c.Allowlists, allowlist)
}
}
if maxExtendDepth != extendDepth { if maxExtendDepth != extendDepth {
// disallow both usedefault and path from being set // disallow both usedefault and path from being set
if c.Extend.Path != "" && c.Extend.UseDefault { if c.Extend.Path != "" && c.Extend.UseDefault {
logging.Fatal().Msg("unable to load config due to extend.path and extend.useDefault being set") return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
} }
if c.Extend.UseDefault { if c.Extend.UseDefault {
c.extendDefault() if err := c.extendDefault(); err != nil {
return Config{}, err
}
} else if c.Extend.Path != "" { } else if c.Extend.Path != "" {
c.extendPath() if err := c.extendPath(); err != nil {
return Config{}, err
}
} }
} }
@@ -222,11 +207,68 @@ func (vc *ViperConfig) Translate() (Config, error) {
return Config{}, err return Config{}, err
} }
} }
// Populate targeted configs.
for ruleID, allowlists := range ruleAllowlists {
rule, ok := c.Rules[ruleID]
if !ok {
return Config{}, fmt.Errorf("[[allowlists]] target rule ID '%s' does not exist", ruleID)
}
rule.Allowlists = append(rule.Allowlists, allowlists...)
c.Rules[ruleID] = rule
}
} }
return c, nil return c, nil
} }
func parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
var matchCondition AllowlistMatchCondition
switch strings.ToUpper(a.Condition) {
case "AND", "&&":
matchCondition = AllowlistMatchAnd
case "", "OR", "||":
matchCondition = AllowlistMatchOr
default:
return nil, fmt.Errorf("unknown allowlist |condition| '%s' (expected 'and', 'or')", a.Condition)
}
// Validate the target.
regexTarget := a.RegexTarget
if regexTarget != "" {
switch regexTarget {
case "secret":
regexTarget = ""
case "match", "line":
// do nothing
default:
return nil, fmt.Errorf("unknown allowlist |regexTarget| '%s' (expected 'match', 'line')", regexTarget)
}
}
var allowlistRegexes []*regexp.Regexp
for _, a := range a.Regexes {
allowlistRegexes = append(allowlistRegexes, regexp.MustCompile(a))
}
var allowlistPaths []*regexp.Regexp
for _, a := range a.Paths {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
allowlist := &Allowlist{
Description: a.Description,
MatchCondition: matchCondition,
Commits: a.Commits,
Paths: allowlistPaths,
RegexTarget: regexTarget,
Regexes: allowlistRegexes,
StopWords: a.StopWords,
}
if err := allowlist.Validate(); err != nil {
return nil, err
}
return allowlist, nil
}
func (c *Config) GetOrderedRules() []Rule { func (c *Config) GetOrderedRules() []Rule {
var orderedRules []Rule var orderedRules []Rule
for _, id := range c.OrderedRules { for _, id := range c.OrderedRules {
@@ -237,47 +279,43 @@ func (c *Config) GetOrderedRules() []Rule {
return orderedRules return orderedRules
} }
func (c *Config) extendDefault() { func (c *Config) extendDefault() error {
extendDepth++ extendDepth++
viper.SetConfigType("toml") viper.SetConfigType("toml")
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil { if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended default config, err: %w", err)
return
} }
defaultViperConfig := ViperConfig{} defaultViperConfig := ViperConfig{}
if err := viper.Unmarshal(&defaultViperConfig); err != nil { if err := viper.Unmarshal(&defaultViperConfig); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended default config, err: %w", err)
return
} }
cfg, err := defaultViperConfig.Translate() cfg, err := defaultViperConfig.Translate()
if err != nil { if err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended default config, err: %w", err)
return
} }
logging.Debug().Msg("extending config with default config") logging.Debug().Msg("extending config with default config")
c.extend(cfg) c.extend(cfg)
return nil
} }
func (c *Config) extendPath() { func (c *Config) extendPath() error {
extendDepth++ extendDepth++
viper.SetConfigFile(c.Extend.Path) viper.SetConfigFile(c.Extend.Path)
if err := viper.ReadInConfig(); err != nil { if err := viper.ReadInConfig(); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended config, err: %w", err)
return
} }
extensionViperConfig := ViperConfig{} extensionViperConfig := ViperConfig{}
if err := viper.Unmarshal(&extensionViperConfig); err != nil { if err := viper.Unmarshal(&extensionViperConfig); err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended config, err: %w", err)
return
} }
cfg, err := extensionViperConfig.Translate() cfg, err := extensionViperConfig.Translate()
if err != nil { if err != nil {
logging.Fatal().Msgf("failed to load extended config, err: %s", err) return fmt.Errorf("failed to load extended config, err: %w", err)
return
} }
logging.Debug().Msgf("extending config with %s", c.Extend.Path) logging.Debug().Msgf("extending config with %s", c.Extend.Path)
c.extend(cfg) c.extend(cfg)
return nil
} }
func (c *Config) extendURL() { func (c *Config) extendURL() {
@@ -353,12 +391,9 @@ func (c *Config) extend(extensionConfig Config) {
} }
// append allowlists, not attempting to merge // append allowlists, not attempting to merge
c.Allowlist.Commits = append(c.Allowlist.Commits, for _, a := range extensionConfig.Allowlists {
extensionConfig.Allowlist.Commits...) c.Allowlists = append(c.Allowlists, a)
c.Allowlist.Paths = append(c.Allowlist.Paths, }
extensionConfig.Allowlist.Paths...)
c.Allowlist.Regexes = append(c.Allowlist.Regexes,
extensionConfig.Allowlist.Regexes...)
// sort to keep extended rules in order // sort to keep extended rules in order
sort.Strings(c.OrderedRules) sort.Strings(c.OrderedRules)
+474 -267
View File
@@ -5,6 +5,7 @@ import (
"testing" "testing"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@@ -14,105 +15,67 @@ import (
const configPath = "../testdata/config/" const configPath = "../testdata/config/"
var regexComparer = func(x, y *regexp.Regexp) bool {
if x == nil || y == nil {
return x == y
}
return x.String() == y.String()
}
type translateCase struct {
// Configuration file basename to load, from `../testdata/config/`.
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}
func TestTranslate(t *testing.T) { func TestTranslate(t *testing.T) {
tests := []struct { tests := []translateCase{
// Configuration file basename to load, from `../testdata/config/`. // Valid
cfgName string
// Expected result.
cfg Config
// Rules to compare.
rules []string
// Error to expect.
wantError error
}{
{ {
cfgName: "allowlist_old_compat", cfgName: "generic",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{"example": { Title: "gitleaks config",
RuleID: "example", Rules: map[string]Rule{"generic-api-key": {
Regex: regexp.MustCompile(`example\d+`), RuleID: "generic-api-key",
Tags: []string{}, Description: "Generic API Key",
Keywords: []string{}, Regex: regexp.MustCompile(`(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)`),
Allowlists: []Allowlist{ Entropy: 3.5,
{ Keywords: []string{"key", "api", "token", "secret", "client", "passwd", "password", "auth", "access"},
MatchCondition: AllowlistMatchOr, Tags: []string{},
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
}}, }},
}, },
}, },
{ {
cfgName: "allowlist_invalid_empty", cfgName: "valid/rule_path_only",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "allowlist_invalid_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "allowlist_invalid_regextarget",
cfg: Config{},
wantError: fmt.Errorf("example: unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
{
cfgName: "allow_aws_re",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{"aws-access-key": { Rules: map[string]Rule{"python-files-only": {
RuleID: "aws-access-key", RuleID: "python-files-only",
Description: "AWS Access Key", Description: "Python Files",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"), Path: regexp.MustCompile(`.py`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
}}, }},
}, },
}, },
{ {
cfgName: "allow_commit", cfgName: "valid/rule_regex_escaped_character_group",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{"aws-access-key": { Rules: map[string]Rule{"pypi-upload-token": {
RuleID: "aws-access-key", RuleID: "pypi-upload-token",
Description: "AWS Access Key", Description: "PyPI upload token",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"), Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "pypi"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"},
},
},
}}, }},
}, },
}, },
{ {
cfgName: "allow_path", cfgName: "valid/rule_entropy_group",
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
}},
},
},
{
cfgName: "entropy_group",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{"discord-api-key": { Rules: map[string]Rule{"discord-api-key": {
RuleID: "discord-api-key", RuleID: "discord-api-key",
@@ -125,23 +88,246 @@ func TestTranslate(t *testing.T) {
}}, }},
}, },
}, },
// Invalid
{ {
cfgName: "missing_id", cfgName: "invalid/rule_missing_id",
cfg: Config{}, cfg: Config{},
wantError: fmt.Errorf("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"), wantError: fmt.Errorf("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
}, },
{ {
cfgName: "no_regex_or_path", cfgName: "invalid/rule_no_regex_or_path",
cfg: Config{}, cfg: Config{},
wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"), wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
}, },
{ {
cfgName: "bad_entropy_group", cfgName: "invalid/rule_bad_entropy_group",
cfg: Config{}, cfg: Config{},
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"), wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
}, },
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
testTranslate(t, tt)
})
}
}
func TestTranslateAllowlists(t *testing.T) {
tests := []translateCase{
// Global
{ {
cfgName: "base", cfgName: "valid/allowlist_global_old_compat",
cfg: Config{
Rules: map[string]Rule{},
Allowlists: []*Allowlist{
{
StopWords: []string{"0989c462-69c9-49fa-b7d2-30dc5c576a97"},
},
},
},
},
{
cfgName: "valid/allowlist_global_multiple",
cfg: Config{
Rules: map[string]Rule{
"test": {
RuleID: "test",
Regex: regexp.MustCompile(`token = "(.+)"`),
Keywords: []string{},
Tags: []string{},
},
},
Allowlists: []*Allowlist{
{
Regexes: []*regexp.Regexp{regexp.MustCompile("^changeit$")},
},
{
MatchCondition: AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile("^node_modules/.*")},
StopWords: []string{"mock"},
},
},
},
},
{
cfgName: "valid/allowlist_global_target_rules",
cfg: Config{
Rules: map[string]Rule{
"github-app-token": {
RuleID: "github-app-token",
Regex: regexp.MustCompile(`(?:ghu|ghs)_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
},
},
},
"github-oauth": {
RuleID: "github-oauth",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: nil,
},
"github-pat": {
RuleID: "github-pat",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
Paths: []*regexp.Regexp{regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`)},
},
},
},
},
Allowlists: []*Allowlist{
{
Regexes: []*regexp.Regexp{regexp.MustCompile(".*fake.*")},
},
},
},
},
{
cfgName: "valid/allowlist_global_regex",
cfg: Config{
Rules: map[string]Rule{},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEM.L33243OLIA")},
},
},
},
},
{
cfgName: "invalid/allowlist_global_empty",
cfg: Config{},
wantError: fmt.Errorf("[[allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_global_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]"),
},
{
cfgName: "invalid/allowlist_global_target_rule_id",
cfg: Config{},
wantError: fmt.Errorf("[[allowlists]] target rule ID 'github-pat' does not exist"),
},
{
cfgName: "invalid/allowlist_global_regextarget",
cfg: Config{},
wantError: fmt.Errorf("[[allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
// Rule
{
cfgName: "valid/allowlist_rule_old_compat",
cfg: Config{
Rules: map[string]Rule{"example": {
RuleID: "example",
Regex: regexp.MustCompile(`example\d+`),
Tags: []string{},
Keywords: []string{},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_regex",
cfg: Config{
Title: "simple config with allowlist for aws",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_commit",
cfg: Config{
Title: "simple config with allowlist for a specific commit",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Commits: []string{"allowthiscommit"},
},
},
}},
},
},
{
cfgName: "valid/allowlist_rule_path",
cfg: Config{
Title: "simple config with allowlist for .go files",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
},
},
}},
},
},
{
cfgName: "invalid/allowlist_rule_empty",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_rule_old_and_new",
cfg: Config{},
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "invalid/allowlist_rule_regextarget",
cfg: Config{},
wantError: fmt.Errorf("example: [[rules.allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
}
for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) {
testTranslate(t, tt)
})
}
}
func TestTranslateExtend(t *testing.T) {
tests := []translateCase{
// Valid
{
cfgName: "valid/extend",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{ Rules: map[string]Rule{
"aws-access-key": { "aws-access-key": {
@@ -169,7 +355,27 @@ func TestTranslate(t *testing.T) {
}, },
}, },
{ {
cfgName: "extend_rule_allowlist_or", cfgName: "valid/extend_disabled",
cfg: Config{
Title: "gitleaks extend disable",
Rules: map[string]Rule{
"aws-secret-key": {
RuleID: "aws-secret-key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
},
"pypi-upload-token": {
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Tags: []string{},
Keywords: []string{},
},
},
},
},
{
cfgName: "valid/extend_rule_no_regexpath",
cfg: Config{ cfg: Config{
Rules: map[string]Rule{ Rules: map[string]Rule{
"aws-secret-key-again-again": { "aws-secret-key-again-again": {
@@ -178,7 +384,137 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`), Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{
Description: "False positive. Keys used for colors match the rule, and should be excluded.",
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
},
},
},
},
},
},
{
cfgName: "valid/extend_rule_override_description",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's description",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "Puppy Doggy",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_path",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's path",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Path: regexp.MustCompile("(?:puppy)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_regex",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's regex",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_secret_group",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's secretGroup",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)(?:a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_entropy",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's entropy",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Entropy: 999.0,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_keywords",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's keywords",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{"puppy"},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "valid/extend_rule_override_tags",
rules: []string{"aws-access-key"},
cfg: Config{
Title: "override a built-in rule's tags",
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS", "puppy"},
},
},
},
},
{
cfgName: "valid/extend_rule_allowlist_or",
cfg: Config{
Title: "gitleaks extended 3",
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"}, StopWords: []string{"fake"},
@@ -197,8 +533,9 @@ func TestTranslate(t *testing.T) {
}, },
}, },
{ {
cfgName: "extend_rule_allowlist_and", cfgName: "valid/extend_rule_allowlist_and",
cfg: Config{ cfg: Config{
Title: "gitleaks extended 3",
Rules: map[string]Rule{ Rules: map[string]Rule{
"aws-secret-key-again-again": { "aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again", RuleID: "aws-secret-key-again-again",
@@ -206,7 +543,7 @@ func TestTranslate(t *testing.T) {
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`), Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{}, Keywords: []string{},
Tags: []string{"key", "AWS"}, Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{ Allowlists: []*Allowlist{
{ {
MatchCondition: AllowlistMatchOr, MatchCondition: AllowlistMatchOr,
StopWords: []string{"fake"}, StopWords: []string{"fake"},
@@ -224,191 +561,61 @@ func TestTranslate(t *testing.T) {
}, },
}, },
}, },
{
cfgName: "extend_empty_regexpath", // Invalid
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key-again-again": {
RuleID: "aws-secret-key-again-again",
Description: "AWS Secret Key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Keywords: []string{},
Tags: []string{"key", "AWS"},
Allowlists: []Allowlist{
{
MatchCondition: AllowlistMatchOr,
Paths: []*regexp.Regexp{regexp.MustCompile(`something.py`)},
},
},
},
},
},
},
{
cfgName: "override_description",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "Puppy Doggy",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_entropy",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Entropy: 999.0,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_secret_group",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)(?:a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_regex",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:a)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_path",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Path: regexp.MustCompile("(?:puppy)"),
Keywords: []string{},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "override_tags",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{},
Tags: []string{"key", "AWS", "puppy"},
},
},
},
},
{
cfgName: "override_keywords",
rules: []string{"aws-access-key"},
cfg: Config{
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}"),
Keywords: []string{"puppy"},
Tags: []string{"key", "AWS"},
},
},
},
},
{
cfgName: "extend_disabled",
cfg: Config{
Rules: map[string]Rule{
"aws-secret-key": {
RuleID: "aws-secret-key",
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
Tags: []string{"key", "AWS"},
Keywords: []string{},
},
"pypi-upload-token": {
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Tags: []string{},
Keywords: []string{},
},
},
},
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.cfgName, func(t *testing.T) { t.Run(tt.cfgName, func(t *testing.T) {
t.Cleanup(func() { testTranslate(t, tt)
extendDepth = 0
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil && !assert.EqualError(t, tt.wantError, err.Error()) {
return
}
if len(tt.rules) > 0 {
rules := make(map[string]Rule)
for _, name := range tt.rules {
rules[name] = cfg.Rules[name]
}
cfg.Rules = rules
}
var regexComparer = func(x, y *regexp.Regexp) bool {
if x == nil || y == nil {
return x == y
}
return x.String() == y.String()
}
opts := cmp.Options{cmp.Comparer(regexComparer)}
if diff := cmp.Diff(tt.cfg.Rules, cfg.Rules, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", tt.cfgName, diff)
}
}) })
} }
} }
func testTranslate(t *testing.T, test translateCase) {
t.Helper()
t.Cleanup(func() {
extendDepth = 0
viper.Reset()
})
viper.AddConfigPath(configPath)
viper.SetConfigName(test.cfgName)
viper.SetConfigType("toml")
err := viper.ReadInConfig()
require.NoError(t, err)
var vc ViperConfig
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil && !assert.EqualError(t, err, test.wantError.Error()) {
return
}
if len(test.rules) > 0 {
rules := make(map[string]Rule)
for _, name := range test.rules {
rules[name] = cfg.Rules[name]
}
cfg.Rules = rules
}
opts := cmp.Options{
cmp.Comparer(regexComparer),
cmpopts.IgnoreUnexported(Rule{}, Allowlist{}),
}
if diff := cmp.Diff(test.cfg.Title, cfg.Title); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
if diff := cmp.Diff(test.cfg.Rules, cfg.Rules, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
if diff := cmp.Diff(test.cfg.Allowlists, cfg.Allowlists, opts); diff != "" {
t.Errorf("%s diff: (-want +got)\n%s", test.cfgName, diff)
}
}
func TestExtendedRuleKeywordsAreDowncase(t *testing.T) { func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -417,12 +624,12 @@ func TestExtendedRuleKeywordsAreDowncase(t *testing.T) {
}{ }{
{ {
name: "Extend base rule that includes AWS keyword with new attribute", name: "Extend base rule that includes AWS keyword with new attribute",
cfgName: "extend_base_rule_including_keysword_with_attribute", cfgName: "valid/extend_base_rule_including_keywords_with_attribute",
expectedKeywords: "aws", expectedKeywords: "aws",
}, },
{ {
name: "Extend base with a new rule with CMS keyword", name: "Extend base with a new rule with CMS keyword",
cfgName: "extend_with_new_rule", cfgName: "valid/extend_rule_new",
expectedKeywords: "cms", expectedKeywords: "cms",
}, },
} }
+37 -52
View File
@@ -13,23 +13,9 @@
title = "gitleaks config" title = "gitleaks config"
# TODO: change to [[allowlists]]
[allowlist] [allowlist]
description = "global allow lists" description = "global allow lists"
regexes = [
'''(?i)^true|false|null$''',
'''^(?i:a+|b+|c+|d+|e+|f+|g+|h+|i+|j+|k+|l+|m+|n+|o+|p+|q+|r+|s+|t+|u+|v+|w+|x+|y+|z+|\*+|\.+)$''',
'''^\$(?:\d+|{\d+})$''',
'''^\$(?:[A-Z_]+|[a-z_]+)$''',
'''^\${(?:[A-Z_]+|[a-z_]+)}$''',
'''^\{\{[ \t]*[\w ().|]+[ \t]*}}$''',
'''^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$''',
'''^%(?:[A-Z_]+|[a-z_]+)%$''',
'''^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$''',
'''^\{\d{0,2}}$''',
'''^@(?:[A-Z_]+|[a-z_]+)@$''',
'''^/Users/(?i)[a-z0-9]+/[\w .-/]+$''',
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
paths = [ paths = [
'''gitleaks\.toml''', '''gitleaks\.toml''',
'''(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$''', '''(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$''',
@@ -56,6 +42,21 @@ paths = [
'''verification-metadata\.xml''', '''verification-metadata\.xml''',
'''Database.refactorlog''', '''Database.refactorlog''',
] ]
regexes = [
'''(?i)^true|false|null$''',
'''^(?i:a+|b+|c+|d+|e+|f+|g+|h+|i+|j+|k+|l+|m+|n+|o+|p+|q+|r+|s+|t+|u+|v+|w+|x+|y+|z+|\*+|\.+)$''',
'''^\$(?:\d+|{\d+})$''',
'''^\$(?:[A-Z_]+|[a-z_]+)$''',
'''^\${(?:[A-Z_]+|[a-z_]+)}$''',
'''^\{\{[ \t]*[\w ().|]+[ \t]*}}$''',
'''^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$''',
'''^%(?:[A-Z_]+|[a-z_]+)%$''',
'''^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$''',
'''^\{\d{0,2}}$''',
'''^@(?:[A-Z_]+|[a-z_]+)@$''',
'''^/Users/(?i)[a-z0-9]+/[\w .-/]+$''',
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
stopwords = [ stopwords = [
"abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz",
"014df517-39d1-4453-b7b3-9930c563627c", "014df517-39d1-4453-b7b3-9930c563627c",
@@ -217,6 +218,13 @@ regex = '''[\w.-]{0,50}?(?i:[\w.-]{0,50}?(?:(?-i:[Mm]eraki|MERAKI))(?:[ \t\w.-]{
entropy = 3 entropy = 3
keywords = ["meraki"] keywords = ["meraki"]
[[rules]]
id = "clickhouse-cloud-api-secret-key"
description = "Identified a pattern that may indicate clickhouse cloud API secret key, risking unauthorized clickhouse cloud api access and data breaches on ClickHouse Cloud platforms."
regex = '''\b(4b1d[A-Za-z0-9]{38})\b'''
entropy = 3
keywords = ["4b1d"]
[[rules]] [[rules]]
id = "clojars-api-token" id = "clojars-api-token"
description = "Uncovered a possible Clojars API token, risking unauthorized access to Clojure libraries and potential code manipulation." description = "Uncovered a possible Clojars API token, risking unauthorized access to Clojure libraries and potential code manipulation."
@@ -545,7 +553,7 @@ keywords = ["freshbooks"]
id = "gcp-api-key" id = "gcp-api-key"
description = "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches." description = "Uncovered a GCP API key, which could lead to unauthorized access to Google Cloud services and data breaches."
regex = '''\b(AIza[\w-]{35})(?:[\x60'"\s;]|\\[nr]|$)''' regex = '''\b(AIza[\w-]{35})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3 entropy = 4
keywords = ["aiza"] keywords = ["aiza"]
[[rules.allowlists]] [[rules.allowlists]]
regexes = [ regexes = [
@@ -589,12 +597,15 @@ regexes = [
'''^[a-zA-Z_.-]+$''', '''^[a-zA-Z_.-]+$''',
] ]
[[rules.allowlists]] [[rules.allowlists]]
description = "Allowlist for Generic API Keys"
regexTarget = "match" regexTarget = "match"
regexes = [ regexes = [
'''(?i)(?:access(?:ibility|or)|access[_.-]?id|random[_.-]?access|api[_.-]?(?:id|name|version)|rapid|capital|[a-z0-9-]*?api[a-z0-9-]*?:jar:|author|X-MS-Exchange-Organization-Auth|Authentication-Results|(?:credentials?[_.-]?id|withCredentials)|(?:bucket|foreign|hot|idx|natural|primary|pub(?:lic)?|schema|sequence)[_.-]?key|(?:turkey)|key[_.-]?(?:alias|board|code|frame|id|length|mesh|name|pair|press(?:ed)?|ring|selector|signature|size|stone|storetype|word|up|down|left|right)|key[_.-]?vault[_.-]?(?:id|name)|keyVaultToStoreSecrets|key(?:store|tab)[_.-]?(?:file|path)|issuerkeyhash|(?-i:[DdMm]onkey|[DM]ONKEY)|keying|(?:secret)[_.-]?(?:length|name|size)|UserSecretsId|(?:csrf)[_.-]?token|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])|public[_.-]?token|(?:key|token)[_.-]?file|(?-i:(?:[A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(?:\n|\z))|(?-i:(?:[A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(?:\n|\z)))''', '''(?i)(?:access(?:ibility|or)|access[_.-]?id|random[_.-]?access|api[_.-]?(?:id|name|version)|rapid|capital|[a-z0-9-]*?api[a-z0-9-]*?:jar:|author|X-MS-Exchange-Organization-Auth|Authentication-Results|(?:credentials?[_.-]?id|withCredentials)|(?:bucket|foreign|hot|idx|natural|primary|pub(?:lic)?|schema|sequence)[_.-]?key|(?:turkey)|key[_.-]?(?:alias|board|code|frame|id|length|mesh|name|pair|press(?:ed)?|ring|selector|signature|size|stone|storetype|word|up|down|left|right)|key[_.-]?vault[_.-]?(?:id|name)|keyVaultToStoreSecrets|key(?:store|tab)[_.-]?(?:file|path)|issuerkeyhash|(?-i:[DdMm]onkey|[DM]ONKEY)|keying|(?:secret)[_.-]?(?:length|name|size)|UserSecretsId|(?:csrf)[_.-]?token|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])|public[_.-]?token|(?:key|token)[_.-]?file|(?-i:(?:[A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(?:\n|\z))|(?-i:(?:[A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(?:\n|\z)))''',
] ]
stopwords = [ stopwords = [
"000000", "000000",
"6fe4476ee5a1832882e326b506d14126",
"_ec2_",
"aaaaaa", "aaaaaa",
"about", "about",
"abstract", "abstract",
@@ -610,9 +621,9 @@ stopwords = [
"activity", "activity",
"adapter", "adapter",
"add-", "add-",
"add-on",
"add.", "add.",
"add_", "add_",
"add-on",
"addon", "addon",
"addres", "addres",
"admin", "admin",
@@ -655,10 +666,7 @@ stopwords = [
"any_", "any_",
"apache", "apache",
"app-", "app-",
"app-",
"app.", "app.",
"app.",
"app_",
"app_", "app_",
"apple", "apple",
"arch", "arch",
@@ -682,7 +690,6 @@ stopwords = [
"aura", "aura",
"auth", "auth",
"author", "author",
"author",
"authorize", "authorize",
"auto", "auto",
"automated", "automated",
@@ -803,7 +810,6 @@ stopwords = [
"cli.", "cli.",
"cli_", "cli_",
"client", "client",
"client",
"clojure", "clojure",
"clone", "clone",
"closure", "closure",
@@ -838,7 +844,6 @@ stopwords = [
"concept", "concept",
"conf", "conf",
"config", "config",
"config",
"connect", "connect",
"connector", "connector",
"console", "console",
@@ -897,7 +902,6 @@ stopwords = [
"dead", "dead",
"debian", "debian",
"debug", "debug",
"debug",
"debugger", "debugger",
"deck", "deck",
"define", "define",
@@ -929,10 +933,7 @@ stopwords = [
"dns-", "dns-",
"dns_", "dns_",
"doc-", "doc-",
"doc-",
"doc.", "doc.",
"doc.",
"doc_",
"doc_", "doc_",
"docker", "docker",
"docpad", "docpad",
@@ -946,8 +947,8 @@ stopwords = [
"dom.", "dom.",
"dom_", "dom_",
"domain", "domain",
"done",
"don't", "don't",
"done",
"dot-", "dot-",
"dot.", "dot.",
"dot_", "dot_",
@@ -967,7 +968,6 @@ stopwords = [
"dsl_", "dsl_",
"dynamic", "dynamic",
"easy", "easy",
"_ec2_",
"ecdsa", "ecdsa",
"eclipse", "eclipse",
"edit", "edit",
@@ -997,7 +997,6 @@ stopwords = [
"event", "event",
"evented", "evented",
"example", "example",
"example",
"exchange", "exchange",
"exercise", "exercise",
"experiment", "experiment",
@@ -1245,10 +1244,7 @@ stopwords = [
"koan", "koan",
"kohana", "kohana",
"lab-", "lab-",
"lab-",
"lab.", "lab.",
"lab.",
"lab_",
"lab_", "lab_",
"lambda", "lambda",
"lamp", "lamp",
@@ -1333,10 +1329,7 @@ stopwords = [
"manifest", "manifest",
"manual", "manual",
"map-", "map-",
"map-",
"map.", "map.",
"map.",
"map_",
"map_", "map_",
"mapper", "mapper",
"mapping", "mapping",
@@ -1422,10 +1415,7 @@ stopwords = [
"nette", "nette",
"network", "network",
"new-", "new-",
"new-",
"new.", "new.",
"new.",
"new_",
"new_", "new_",
"next", "next",
"nginx", "nginx",
@@ -1494,7 +1484,6 @@ stopwords = [
"package", "package",
"packet", "packet",
"page", "page",
"page",
"panel", "panel",
"paper", "paper",
"paperclip", "paperclip",
@@ -1611,8 +1600,8 @@ stopwords = [
"readme", "readme",
"ready", "ready",
"real", "real",
"reality",
"real-time", "real-time",
"reality",
"realtime", "realtime",
"recipe", "recipe",
"recorder", "recorder",
@@ -1678,7 +1667,6 @@ stopwords = [
"rvm_", "rvm_",
"salt", "salt",
"sample", "sample",
"sample",
"sandbox", "sandbox",
"sas-", "sas-",
"sas.", "sas.",
@@ -1729,7 +1717,6 @@ stopwords = [
"set.", "set.",
"set_", "set_",
"setting", "setting",
"setting",
"setup", "setup",
"sha1", "sha1",
"sha2", "sha2",
@@ -1852,19 +1839,12 @@ stopwords = [
"synopsi", "synopsi",
"syntax", "syntax",
"system", "system",
"system",
"tab-",
"tab-", "tab-",
"tab.", "tab.",
"tab.",
"tab_",
"tab_", "tab_",
"table", "table",
"tag-", "tag-",
"tag-",
"tag.", "tag.",
"tag.",
"tag_",
"tag_", "tag_",
"talk", "talk",
"target", "target",
@@ -2003,7 +1983,6 @@ stopwords = [
"website", "website",
"websocket", "websocket",
"welcome", "welcome",
"welcome",
"what", "what",
"what'", "what'",
"when", "when",
@@ -2070,7 +2049,6 @@ stopwords = [
"zsh-", "zsh-",
"zsh.", "zsh.",
"zsh_", "zsh_",
"6fe4476ee5a1832882e326b506d14126",
] ]
[[rules.allowlists]] [[rules.allowlists]]
regexTarget = "line" regexTarget = "line"
@@ -2651,6 +2629,13 @@ regex = '''\b(sha256~[\w-]{43})(?:[^\w-]|\z)'''
entropy = 3.5 entropy = 3.5
keywords = ["sha256~"] keywords = ["sha256~"]
[[rules]]
id = "perplexity-api-key"
description = "Detected a Perplexity API key, which could lead to unauthorized access to Perplexity AI services and data exposure."
regex = '''\b(pplx-[a-zA-Z0-9]{48})(?:[\x60'"\s;]|\\[nr]|$|\b)'''
entropy = 4
keywords = ["pplx-"]
[[rules]] [[rules]]
id = "pkcs12-file" id = "pkcs12-file"
description = "Found a PKCS #12 file, which commonly contain bundled private keys." description = "Found a PKCS #12 file, which commonly contain bundled private keys."
+20 -2
View File
@@ -41,11 +41,18 @@ type Rule struct {
Keywords []string Keywords []string
// Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords. // Allowlists allows a rule to be ignored for specific commits, paths, regexes, and/or stopwords.
Allowlists []Allowlist Allowlists []*Allowlist
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
} }
// Validate guards against common misconfigurations. // Validate guards against common misconfigurations.
func (r Rule) Validate() error { func (r *Rule) Validate() error {
if r.validated {
return nil
}
// Ensure |id| is present. // Ensure |id| is present.
if strings.TrimSpace(r.RuleID) == "" { if strings.TrimSpace(r.RuleID) == "" {
// Try to provide helpful context, since |id| is empty. // Try to provide helpful context, since |id| is empty.
@@ -70,5 +77,16 @@ func (r Rule) Validate() error {
return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp()) return fmt.Errorf("%s: invalid regex secret group %d, max regex secret group %d", r.RuleID, r.SecretGroup, r.Regex.NumSubexp())
} }
for _, allowlist := range r.Allowlists {
// This will probably never happen.
if allowlist == nil {
continue
}
if err := allowlist.Validate(); err != nil {
return fmt.Errorf("%s: %w", r.RuleID, err)
}
}
r.validated = true
return nil return nil
} }
+13 -15
View File
@@ -9,27 +9,25 @@ import (
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
) )
func IsNew(finding report.Finding, baseline []report.Finding) bool { func IsNew(finding report.Finding, redact uint, baseline []report.Finding) bool {
// Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that // Explicitly testing each property as it gives significantly better performance in comparison to cmp.Equal(). Drawback is that
// the code requires maintenance if/when the Finding struct changes // the code requires maintenance if/when the Finding struct changes
for _, b := range baseline { for _, b := range baseline {
if finding.RuleID == b.RuleID &&
if finding.Author == b.Author &&
finding.Commit == b.Commit &&
finding.Date == b.Date &&
finding.Description == b.Description && finding.Description == b.Description &&
finding.Email == b.Email && finding.StartLine == b.StartLine &&
finding.EndColumn == b.EndColumn &&
finding.EndLine == b.EndLine && finding.EndLine == b.EndLine &&
finding.Entropy == b.Entropy &&
finding.File == b.File &&
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
finding.Match == b.Match &&
finding.Message == b.Message &&
finding.RuleID == b.RuleID &&
finding.Secret == b.Secret &&
finding.StartColumn == b.StartColumn && finding.StartColumn == b.StartColumn &&
finding.StartLine == b.StartLine { finding.EndColumn == b.EndColumn &&
(redact > 0 || (finding.Match == b.Match && finding.Secret == b.Secret)) &&
finding.File == b.File &&
finding.Commit == b.Commit &&
finding.Author == b.Author &&
finding.Email == b.Email &&
finding.Date == b.Date &&
finding.Message == b.Message &&
// Omit checking finding.Fingerprint - if the format of the fingerprint changes, the users will see unexpected behaviour
finding.Entropy == b.Entropy {
return false return false
} }
} }
+114 -22
View File
@@ -11,59 +11,150 @@ import (
) )
func TestIsNew(t *testing.T) { func TestIsNew(t *testing.T) {
tests := []struct { t.Parallel()
tests := map[string]struct {
findings report.Finding findings report.Finding
redact uint
baseline []report.Finding baseline []report.Finding
expect bool expect bool
}{ }{
{ // new
"new - commit doesn't match baseline": {
findings: report.Finding{ findings: report.Finding{
Author: "a",
Commit: "0000", Commit: "0000",
Author: "a",
}, },
baseline: []report.Finding{ baseline: []report.Finding{
{ {
Author: "a",
Commit: "0000",
},
},
expect: false,
},
{
findings: report.Finding{
Author: "a",
Commit: "0000",
},
baseline: []report.Finding{
{
Author: "a",
Commit: "0002", Commit: "0002",
Author: "a",
}, },
}, },
expect: true, expect: true,
}, },
{ "new - redacted, different baseline": {
findings: report.Finding{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "REDACTED",
Secret: "REDACTED",
File: "key.txt",
Commit: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-03-02T15:10:40Z",
Message: "init",
Fingerprint: "6d3ba1f7653822c0f8ac9a9af56daaa2cd8bbcad:key.txt:private-key:1",
},
baseline: []report.Finding{
{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
},
expect: true,
},
// not new
"not new - commit+author matches": {
findings: report.Finding{ findings: report.Finding{
Author: "a",
Commit: "0000", Commit: "0000",
Author: "a",
},
baseline: []report.Finding{
{
Commit: "0000",
Author: "a",
},
},
expect: false,
},
"not new - commit+author matches, tags ignored": {
findings: report.Finding{
Commit: "0000",
Author: "a",
Tags: []string{"a", "b"}, Tags: []string{"a", "b"},
}, },
baseline: []report.Finding{ baseline: []report.Finding{
{ {
Author: "a",
Commit: "0000", Commit: "0000",
Author: "a",
Tags: []string{"a", "c"}, Tags: []string{"a", "c"},
}, },
}, },
expect: false, // Updated tags doesn't make it a new finding expect: false, // Updated tags doesn't make it a new finding
}, },
"not new - redacted, everything else matches": {
findings: report.Finding{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "REDACTED",
Secret: "REDACTED",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
redact: 100,
baseline: []report.Finding{
{
RuleID: "private-key",
Description: "Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.",
StartLine: 1,
EndLine: 15,
StartColumn: 1,
EndColumn: 30,
Match: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
Secret: "-----BEGIN RSA PRIVATE KEY-----\nMIICWgIBAAKBgFIckgeuo80H6skLd1FKYfJC75/tnmtDWO4Rf2AFqrYZdu71VKGR\noGfEVl7AmvxTd9u6tnPtWjAeu9k2VMQcOtXEwgU0A6H09EBcS1EVN/I8pcNw1qjO\nkJ7ZA8AhZk/OpVAK7665CEny7ISRNZnx1nPaHjlb8lebPzlWOvxX9wjbAgMBAAEC\ngYBN6wqv+4s4juC/cwAAxeL4L4iQbL497yS+lSAYEIiUUMnJrEhpIXXjwi5rr73i\n35oHisCEdaF1tFRxpNr/VgKFsM1KqQUZvCVRE9Rokfe23QkQDvcxh9CI/Ah9Eofp\nx/m5DjSsRKrbIpOOAC3J3B/s02HRmxy8tRYnQVqWXzAH8QJBAJdBgXi62KI1eytU\n7l3Q8ymkS1OHzSOGBEYPpZZQ7WRpZlv/06cKfJBT/dGgA4z9i9ySs8cWUoh+FGYX\nlkDB4c0CQQCK+TwfAFvrkSWorZ9Gjb6y2LZQPUufTzJNhzhK5XObCDbwyMXEM/Vs\newiyUFljlI/A9PjcrmkgrDLUMD4+og1HAkAs2t01W1uhBvEm0YH6yltCDxnThKM+\nFKEx0bQOVqN/so4LXFt83uw/tNjBkI1dA1e1qr+rm6AQICuWdwo03ApFAkBktes4\nuCTk2GHHFFM5aN0KdHviOBlGULkub9B+jjsx3UkbQxP2dITlYV/TAOFWhcGLXru+\nCPKMR93p4TAqaXtfAkA+ZZDb0mA9rtaetJlSoo6XgwI/+kqltADch9dcyqYBHwjr\nAEkzUKvmCxNAK4GEPA79FZFp30kDx+buysyeX9qY\n-----END RSA PRIVATE KEY-----",
File: "key.txt",
Commit: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4",
Entropy: 5.9834013,
Author: "James Bond",
Email: "jbond@gov.co.uk",
Date: "2025-02-02T17:45:30Z",
Message: "init",
Fingerprint: "e55e00ca1690a6b5b612d28b3d9ada3fd1775ac4:key.txt:private-key:1",
},
},
expect: false,
},
} }
for _, test := range tests { for name, test := range tests {
assert.Equal(t, test.expect, IsNew(test.findings, test.baseline)) t.Run(name, func(t *testing.T) {
assert.Equal(t, test.expect, IsNew(test.findings, test.redact, test.baseline))
})
} }
} }
func TestFileLoadBaseline(t *testing.T) { func TestFileLoadBaseline(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
Filename string Filename string
ExpectedError error ExpectedError error
@@ -89,6 +180,7 @@ func TestFileLoadBaseline(t *testing.T) {
} }
func TestIgnoreIssuesInBaseline(t *testing.T) { func TestIgnoreIssuesInBaseline(t *testing.T) {
t.Parallel()
tests := []struct { tests := []struct {
findings []report.Finding findings []report.Finding
baseline []report.Finding baseline []report.Finding
+168 -137
View File
@@ -212,17 +212,30 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
} }
d.TotalBytes.Add(uint64(len(fragment.Bytes))) d.TotalBytes.Add(uint64(len(fragment.Bytes)))
var findings []report.Finding var (
findings []report.Finding
logger = func() zerolog.Logger {
l := logging.With().Str("path", fragment.FilePath)
if fragment.CommitSHA != "" {
l = l.Str("commit", fragment.CommitSHA)
}
return l.Logger()
}()
)
// check if filepath is allowed // check if filepath is allowed
if fragment.FilePath != "" { if fragment.FilePath != "" {
// is the path our config or baseline file? // is the path our config or baseline file?
if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) || if fragment.FilePath == d.Config.Path || (d.baselinePath != "" && fragment.FilePath == d.baselinePath) {
// is the path excluded by the global allowlist? logging.Trace().Msg("skipping file: matches config or baseline path")
(d.Config.Allowlist.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && d.Config.Allowlist.PathAllowed(fragment.WindowsFilePath))) {
return findings return findings
} }
} }
// check if commit or filepath is allowed.
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, d.Config.Allowlists); isAllowed {
event.Msg("skipping file: global allowlist")
return findings
}
// add newline indices for location calculation in detectRule // add newline indices for location calculation in detectRule
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1) fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
@@ -292,46 +305,10 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}() }()
) )
// check if filepath or commit is allowed for this rule // check if commit or file is allowed for this rule.
for _, a := range r.Allowlists { if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
var ( event.Msg("skipping file: rule allowlist")
isAllowed bool return findings
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
)
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, false)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
event := logger.Trace().Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
event.Msg("skipping file: rule allowlist")
return findings
}
} }
if r.Path != nil { if r.Path != nil {
@@ -377,7 +354,6 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// use currentRaw instead of fragment.Raw since this represents the current // use currentRaw instead of fragment.Raw since this represents the current
// decoding pass on the text // decoding pass on the text
MatchLoop:
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) { for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
// Extract secret from match // Extract secret from match
secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n") secret := strings.Trim(currentRaw[matchIndex[0]:matchIndex[1]], "\n")
@@ -473,107 +449,23 @@ MatchLoop:
continue continue
} }
} }
// check if the regexTarget is defined in the allowlist "regexes" entry
// or if the secret is in the list of stopwords // check if the result matches any of the global allowlists.
globalAllowlistTarget := finding.Secret if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, d.Config.Allowlists); isAllowed {
switch d.Config.Allowlist.RegexTarget { event.Msg("skipping finding: global allowlist")
case "match":
globalAllowlistTarget = finding.Match
case "line":
globalAllowlistTarget = currentLine
}
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
logger.Trace().
Str("finding", globalAllowlistTarget).
Msg("skipping finding: global allowlist regex")
continue
} else if ok, word := d.Config.Allowlist.ContainsStopWord(finding.Secret); ok {
logger.Trace().
Str("finding", finding.Secret).
Str("allowed-stopword", word).
Msg("skipping finding: global allowlist stopword")
continue continue
} }
// check if the result matches any of the rule allowlists. // check if the result matches any of the rule allowlists.
for _, a := range r.Allowlists { if isAllowed, event := checkFindingAllowed(logger, finding, fragment, currentLine, r.Allowlists); isAllowed {
allowlistTarget := finding.Secret event.Msg("skipping finding: rule allowlist")
switch a.RegexTarget { continue
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = currentLine
}
var (
isAllowed bool
commitAllowed bool
commit string
pathAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword, word = a.ContainsStopWord(finding.Secret)
)
// check if the secret is in the list of stopwords
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
var allowlistChecks []bool
if len(a.Commits) > 0 {
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
allowlistChecks = append(allowlistChecks, pathAllowed)
}
if len(a.Regexes) > 0 {
allowlistChecks = append(allowlistChecks, regexAllowed)
}
if len(a.StopWords) > 0 {
allowlistChecks = append(allowlistChecks, containsStopword)
}
// Check if allowed.
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
event := logger.Trace().
Str("finding", finding.Secret).
Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
if regexAllowed {
event.Bool("allowed-regex", regexAllowed)
}
if containsStopword {
event.Str("allowed-stopword", word)
}
event.Msg("skipping finding: rule allowlist")
continue MatchLoop
}
} }
findings = append(findings, finding) findings = append(findings, finding)
} }
return findings return findings
} }
func allTrue(bools []bool) bool {
allMatch := true
for _, check := range bools {
if !check {
allMatch = false
break
}
}
return allMatch
}
// AddFinding synchronously adds a finding to the findings slice // AddFinding synchronously adds a finding to the findings slice
func (d *Detector) AddFinding(finding report.Finding) { func (d *Detector) AddFinding(finding report.Finding) {
globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine) globalFingerprint := fmt.Sprintf("%s:%s:%d", finding.File, finding.RuleID, finding.StartLine)
@@ -600,7 +492,7 @@ func (d *Detector) AddFinding(finding report.Finding) {
} }
} }
if d.baseline != nil && !IsNew(finding, d.baseline) { if d.baseline != nil && !IsNew(finding, d.Redact, d.baseline) {
logger.Debug(). logger.Debug().
Str("fingerprint", finding.Fingerprint). Str("fingerprint", finding.Fingerprint).
Msgf("skipping finding: baseline") Msgf("skipping finding: baseline")
@@ -624,3 +516,142 @@ func (d *Detector) Findings() []report.Finding {
func (d *Detector) addCommit(commit string) { func (d *Detector) addCommit(commit string) {
d.commitMap[commit] = true d.commitMap[commit] = true
} }
// checkCommitOrPathAllowed evaluates |fragment| against all provided |allowlists|.
//
// If the match condition is "OR", only commit and path are checked.
// Otherwise, if regexes or stopwords are defined this will fail.
func checkCommitOrPathAllowed(
logger zerolog.Logger,
fragment Fragment,
allowlists []*config.Allowlist,
) (bool, *zerolog.Event) {
if fragment.FilePath == "" && fragment.CommitSHA == "" {
return false, nil
}
for _, a := range allowlists {
var (
isAllowed bool
allowlistChecks []bool
commitAllowed, _ = a.CommitAllowed(fragment.CommitSHA)
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
)
// If the condition is "AND" we need to check all conditions.
if a.MatchCondition == config.AllowlistMatchAnd {
if len(a.Commits) > 0 {
allowlistChecks = append(allowlistChecks, commitAllowed)
}
if len(a.Paths) > 0 {
allowlistChecks = append(allowlistChecks, pathAllowed)
}
// These will be checked later.
if len(a.Regexes) > 0 {
return false, nil
}
if len(a.StopWords) > 0 {
return false, nil
}
isAllowed = allTrue(allowlistChecks)
} else {
isAllowed = commitAllowed || pathAllowed
}
if isAllowed {
event := logger.Trace().Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Bool("allowed-commit", commitAllowed)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
return true, event
}
}
return false, nil
}
// checkFindingAllowed evaluates |finding| against all provided |allowlists|.
//
// If the match condition is "OR", only regex and stopwords are run. (Commit and path should be handled separately).
// Otherwise, all conditions are checked.
//
// TODO: The method signature is awkward. I can't think of a better way to log helpful info.
func checkFindingAllowed(
logger zerolog.Logger,
finding report.Finding,
fragment Fragment,
currentLine string,
allowlists []*config.Allowlist,
) (bool, *zerolog.Event) {
for _, a := range allowlists {
allowlistTarget := finding.Secret
switch a.RegexTarget {
case "match":
allowlistTarget = finding.Match
case "line":
allowlistTarget = currentLine
}
var (
checks []bool
isAllowed bool
commitAllowed bool
commit string
pathAllowed bool
regexAllowed = a.RegexAllowed(allowlistTarget)
containsStopword, word = a.ContainsStopWord(finding.Secret)
)
// If the condition is "AND" we need to check all conditions.
if a.MatchCondition == config.AllowlistMatchAnd {
// Determine applicable checks.
if len(a.Commits) > 0 {
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
checks = append(checks, commitAllowed)
}
if len(a.Paths) > 0 {
pathAllowed = a.PathAllowed(fragment.FilePath) || (fragment.WindowsFilePath != "" && a.PathAllowed(fragment.WindowsFilePath))
checks = append(checks, pathAllowed)
}
if len(a.Regexes) > 0 {
checks = append(checks, regexAllowed)
}
if len(a.StopWords) > 0 {
checks = append(checks, containsStopword)
}
isAllowed = allTrue(checks)
} else {
isAllowed = regexAllowed || containsStopword
}
if isAllowed {
event := logger.Trace().
Str("finding", finding.Secret).
Str("condition", a.MatchCondition.String())
if commitAllowed {
event.Str("allowed-commit", commit)
}
if pathAllowed {
event.Bool("allowed-path", pathAllowed)
}
if regexAllowed {
event.Bool("allowed-regex", regexAllowed)
}
if containsStopword {
event.Str("allowed-stopword", word)
}
return true, event
}
}
return false, nil
}
func allTrue(bools []bool) bool {
for _, check := range bools {
if !check {
return false
}
}
return true
}
+184 -153
View File
@@ -53,7 +53,8 @@ password="bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw=="
` `
func TestDetect(t *testing.T) { func TestDetect(t *testing.T) {
tests := []struct { logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
tests := map[string]struct {
cfgName string cfgName string
baselinePath string baselinePath string
fragment Fragment fragment Fragment
@@ -65,14 +66,15 @@ func TestDetect(t *testing.T) {
expectedFindings []report.Finding expectedFindings []report.Finding
wantError error wantError error
}{ }{
{ // General
"valid allow comment (1)": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`, Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
}, },
{ "valid allow comment (2)": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `awsToken := \ Raw: `awsToken := \
@@ -83,7 +85,7 @@ func TestDetect(t *testing.T) {
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
}, },
{ "invalid allow comment": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\" Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
@@ -110,30 +112,7 @@ func TestDetect(t *testing.T) {
}, },
}, },
}, },
{ "detect finding - aws": {
cfgName: "escaped_character_group",
fragment: Fragment{
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "PyPI upload token",
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
Line: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
File: "tmp.go",
RuleID: "pypi-upload-token",
Tags: []string{"key", "pypi"},
StartLine: 0,
EndLine: 0,
StartColumn: 1,
EndColumn: 86,
Entropy: 1.9606875,
},
},
},
{
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
@@ -141,22 +120,22 @@ func TestDetect(t *testing.T) {
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
{ {
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
Line: `awsToken := \"AKIALALEMEL33243OLIA\"`,
File: "tmp.go",
RuleID: "aws-access-key", RuleID: "aws-access-key",
Tags: []string{"key", "AWS"}, Description: "AWS Access Key",
File: "tmp.go",
Line: `awsToken := \"AKIALALEMEL33243OLIA\"`,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
Entropy: 3.0841837,
StartLine: 0, StartLine: 0,
EndLine: 0, EndLine: 0,
StartColumn: 15, StartColumn: 15,
EndColumn: 34, EndColumn: 34,
Entropy: 3.0841837, Tags: []string{"key", "AWS"},
}, },
}, },
}, },
{ "detect finding - sidekiq env var": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`, Raw: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
@@ -164,22 +143,22 @@ func TestDetect(t *testing.T) {
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
{ {
RuleID: "sidekiq-secret",
Description: "Sidekiq Secret", Description: "Sidekiq Secret",
File: "tmp.sh",
Line: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;", Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;",
Secret: "cafebabe:deadbeef", Secret: "cafebabe:deadbeef",
Line: `export BUNDLE_ENTERPRISE__CONTRIBSYS__COM=cafebabe:deadbeef;`,
File: "tmp.sh",
RuleID: "sidekiq-secret",
Tags: []string{},
Entropy: 2.6098502, Entropy: 2.6098502,
StartLine: 0, StartLine: 0,
EndLine: 0, EndLine: 0,
StartColumn: 8, StartColumn: 8,
EndColumn: 60, EndColumn: 60,
Tags: []string{},
}, },
}, },
}, },
{ "detect finding - sidekiq env var, semicolon": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`, Raw: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
@@ -187,22 +166,22 @@ func TestDetect(t *testing.T) {
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
{ {
RuleID: "sidekiq-secret",
Description: "Sidekiq Secret", Description: "Sidekiq Secret",
Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=\"cafebabe:deadbeef\"",
Secret: "cafebabe:deadbeef",
File: "tmp.sh", File: "tmp.sh",
Line: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`, Line: `echo hello1; export BUNDLE_ENTERPRISE__CONTRIBSYS__COM="cafebabe:deadbeef" && echo hello2`,
RuleID: "sidekiq-secret", Match: "BUNDLE_ENTERPRISE__CONTRIBSYS__COM=\"cafebabe:deadbeef\"",
Tags: []string{}, Secret: "cafebabe:deadbeef",
Entropy: 2.6098502, Entropy: 2.6098502,
StartLine: 0, StartLine: 0,
EndLine: 0, EndLine: 0,
StartColumn: 21, StartColumn: 21,
EndColumn: 74, EndColumn: 74,
Tags: []string{},
}, },
}, },
}, },
{ "detect finding - sidekiq url": {
cfgName: "simple", cfgName: "simple",
fragment: Fragment{ fragment: Fragment{
Raw: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`, Raw: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`,
@@ -210,74 +189,36 @@ func TestDetect(t *testing.T) {
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
{ {
RuleID: "sidekiq-sensitive-url",
Description: "Sidekiq Sensitive URL", Description: "Sidekiq Sensitive URL",
Match: "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:",
Secret: "cafeb4b3:d3adb33f",
File: "tmp.sh", File: "tmp.sh",
Line: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`, Line: `url = "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:80/path?param1=true&param2=false#heading1"`,
RuleID: "sidekiq-sensitive-url", Match: "http://cafeb4b3:d3adb33f@enterprise.contribsys.com:",
Tags: []string{}, Secret: "cafeb4b3:d3adb33f",
Entropy: 2.984234, Entropy: 2.984234,
StartLine: 0, StartLine: 0,
EndLine: 0, EndLine: 0,
StartColumn: 8, StartColumn: 8,
EndColumn: 58, EndColumn: 58,
},
},
},
{
cfgName: "allow_aws_re",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
},
{
cfgName: "allow_path",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
},
{
cfgName: "allow_commit",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
},
{
cfgName: "entropy_group",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "Discord API key",
Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
File: "tmp.go",
RuleID: "discord-api-key",
Tags: []string{}, Tags: []string{},
Entropy: 3.7906237,
StartLine: 0,
EndLine: 0,
StartColumn: 7,
EndColumn: 93,
}, },
}, },
}, },
{ "ignore finding - our config file": {
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: filepath.Join(configPath, "simple.toml"),
},
},
"ignore finding - doesn't match path": {
cfgName: "generic_with_py_path", cfgName: "generic_with_py_path",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
}, },
{ "detect finding - matches path,regex,entropy": {
cfgName: "generic_with_py_path", cfgName: "generic_with_py_path",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
@@ -285,23 +226,40 @@ func TestDetect(t *testing.T) {
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
{ {
RuleID: "generic-api-key",
Description: "Generic API Key", Description: "Generic API Key",
File: "tmp.py",
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"", Match: "Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5", Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
File: "tmp.py",
RuleID: "generic-api-key",
Tags: []string{},
Entropy: 3.7906237, Entropy: 3.7906237,
StartLine: 0, StartLine: 0,
EndLine: 0, EndLine: 0,
StartColumn: 22, StartColumn: 22,
EndColumn: 93, EndColumn: 93,
Tags: []string{},
}, },
}, },
}, },
{ "ignore finding - allowlist regex": {
cfgName: "path_only", cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
},
// Rule
"rule - ignore path": {
cfgName: "valid/rule_path_only",
baselinePath: ".baseline.json",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: ".baseline.json",
},
},
"rule - detect path ": {
cfgName: "valid/rule_path_only",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py", FilePath: "tmp.py",
@@ -316,44 +274,118 @@ func TestDetect(t *testing.T) {
}, },
}, },
}, },
{ "rule - match based on entropy": {
cfgName: "bad_entropy_group", cfgName: "valid/rule_entropy_group",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"
//const Discord_Public_Key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
`,
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"), expectedFindings: []report.Finding{
}, {
{ RuleID: "discord-api-key",
cfgName: "simple", Description: "Discord API key",
fragment: Fragment{ File: "tmp.go",
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, Line: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: filepath.Join(configPath, "simple.toml"), Match: "Discord_Public_Key = \"e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5\"",
Secret: "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5",
Entropy: 3.7906237,
StartLine: 0,
EndLine: 0,
StartColumn: 7,
EndColumn: 93,
Tags: []string{},
},
}, },
}, },
{
cfgName: "allow_global_aws_re", // Allowlists
"global allowlist - ignore regex": {
cfgName: "valid/allowlist_global_regex",
fragment: Fragment{ fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`, Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
}, },
{ "global allowlist - detect, doesn't match all conditions": {
cfgName: "generic_with_py_path", cfgName: "valid/allowlist_global_multiple",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `
FilePath: "tmp.py", const token = "mockSecret";
// const token = "changeit";`,
FilePath: "config.txt",
},
expectedFindings: []report.Finding{
{
RuleID: "test",
File: "config.txt",
Line: "\nconst token = \"mockSecret\";",
Match: `token = "mockSecret"`,
Secret: "mockSecret",
Entropy: 2.9219282,
StartLine: 1,
EndLine: 1,
StartColumn: 8,
EndColumn: 27,
Tags: []string{},
},
}, },
}, },
{ "global allowlist - ignore, matches all conditions": {
cfgName: "path_only", cfgName: "valid/allowlist_global_multiple",
baselinePath: ".baseline.json",
fragment: Fragment{ fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`, Raw: `token := "mockSecret";`,
FilePath: ".baseline.json", FilePath: "node_modules/config.txt",
}, },
}, },
{ "global allowlist - detect path, doesn't match all conditions": {
cfgName: "valid/allowlist_global_multiple",
fragment: Fragment{
Raw: `var token = "fakeSecret";`,
FilePath: "node_modules/config.txt",
},
expectedFindings: []report.Finding{
{
RuleID: "test",
File: "node_modules/config.txt",
Line: "var token = \"fakeSecret\";",
Match: `token = "fakeSecret"`,
Secret: "fakeSecret",
Entropy: 2.8464394,
StartLine: 0,
EndLine: 0,
StartColumn: 5,
EndColumn: 24,
Tags: []string{},
},
},
},
"allowlist - ignore commit": {
cfgName: "valid/allowlist_rule_commit",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
},
"allowlist - ignore path": {
cfgName: "valid/allowlist_rule_path",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
},
"allowlist - ignore regex": {
cfgName: "valid/allowlist_rule_regex",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
},
// Base64-decoding
"detect base64": {
cfgName: "base64_encoded", cfgName: "base64_encoded",
fragment: Fragment{ fragment: Fragment{
Raw: b64TestValues, Raw: b64TestValues,
@@ -490,8 +522,8 @@ func TestDetect(t *testing.T) {
}, },
} }
for _, tt := range tests { for name, tt := range tests {
t.Run(fmt.Sprintf("%s - %s", tt.cfgName, tt.fragment.FilePath), func(t *testing.T) { t.Run(name, func(t *testing.T) {
viper.Reset() viper.Reset()
viper.AddConfigPath(configPath) viper.AddConfigPath(configPath)
viper.SetConfigName(tt.cfgName) viper.SetConfigName(tt.cfgName)
@@ -829,7 +861,7 @@ func TestFromFiles(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
detector.FollowSymlinks = true detector.FollowSymlinks = true
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed) paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
require.NoError(t, err) require.NoError(t, err)
findings, err := detector.DetectFiles(paths) findings, err := detector.DetectFiles(paths)
@@ -903,7 +935,7 @@ func TestDetectWithSymlinks(t *testing.T) {
cfg, _ := vc.Translate() cfg, _ := vc.Translate()
detector := NewDetector(cfg) detector := NewDetector(cfg)
detector.FollowSymlinks = true detector.FollowSymlinks = true
paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlist.PathAllowed) paths, err := sources.DirectoryTargets(tt.source, detector.Sema, true, cfg.Allowlists)
require.NoError(t, err) require.NoError(t, err)
findings, err := detector.DetectFiles(paths) findings, err := detector.DetectFiles(paths)
@@ -915,7 +947,7 @@ func TestDetectWithSymlinks(t *testing.T) {
func TestDetectRuleAllowlist(t *testing.T) { func TestDetectRuleAllowlist(t *testing.T) {
cases := map[string]struct { cases := map[string]struct {
fragment Fragment fragment Fragment
allowlist config.Allowlist allowlist *config.Allowlist
expected []report.Finding expected []report.Finding
}{ }{
// Commit / path // Commit / path
@@ -923,7 +955,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
}, },
}, },
@@ -931,7 +963,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
}, },
}, },
@@ -940,7 +972,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -951,7 +983,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package.json", FilePath: "package.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -974,7 +1006,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -998,7 +1030,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "package-lock.json", FilePath: "package-lock.json",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchOr, MatchCondition: config.AllowlistMatchOr,
Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"}, Commits: []string{"704178e7dca77ff143778a31cff0fc192d59b030"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -1008,19 +1040,19 @@ func TestDetectRuleAllowlist(t *testing.T) {
// Regex / stopwords // Regex / stopwords
"regex allowed": { "regex allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
}, },
}, },
"stopwords allowed": { "stopwords allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
StopWords: []string{"summer"}, StopWords: []string{"summer"},
}, },
}, },
"regex AND stopword allowed": { "regex AND stopword allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"2024"}, StopWords: []string{"2024"},
@@ -1031,7 +1063,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48", CommitSHA: "41edf1f7f612199f401ccfc3144c2ebd0d7aeb48",
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
@@ -1043,7 +1075,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
fragment: Fragment{ fragment: Fragment{
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`config.js`)},
@@ -1065,7 +1097,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
}, },
"regex AND stopword NOT allowed": { "regex AND stopword NOT allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`(?i)winter.+`), regexp.MustCompile(`(?i)winter.+`),
@@ -1089,7 +1121,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b", CommitSHA: "a060c9d2d5e90c992763f1bd4c3cd2a6f121241b",
FilePath: "config.js", FilePath: "config.js",
}, },
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"}, Commits: []string{"41edf1f7f612199f401ccfc3144c2ebd0d7aeb48"},
Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`package-lock.json`)},
@@ -1111,7 +1143,7 @@ func TestDetectRuleAllowlist(t *testing.T) {
}, },
"regex OR stopword allowed": { "regex OR stopword allowed": {
fragment: Fragment{}, fragment: Fragment{},
allowlist: config.Allowlist{ allowlist: &config.Allowlist{
MatchCondition: config.AllowlistMatchOr, MatchCondition: config.AllowlistMatchOr,
Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)}, Regexes: []*regexp.Regexp{regexp.MustCompile(`(?i)summer.+`)},
StopWords: []string{"winter"}, StopWords: []string{"winter"},
@@ -1126,7 +1158,7 @@ let password = 'Summer2024!';`
rule := config.Rule{ rule := config.Rule{
RuleID: "test-rule", RuleID: "test-rule",
Regex: regexp.MustCompile(`Summer2024!`), Regex: regexp.MustCompile(`Summer2024!`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
tc.allowlist, tc.allowlist,
}, },
} }
@@ -1189,7 +1221,6 @@ func TestNormalizeGitleaksIgnorePaths(t *testing.T) {
} }
func TestWindowsFileSeparator_RulePath(t *testing.T) { func TestWindowsFileSeparator_RulePath(t *testing.T) {
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
unixRule := config.Rule{ unixRule := config.Rule{
RuleID: "test-rule", RuleID: "test-rule",
Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`), Path: regexp.MustCompile(`(^|/)\.m2/settings\.xml`),
@@ -1320,7 +1351,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
}, },
@@ -1336,7 +1367,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
}, },
@@ -1364,7 +1395,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
@@ -1382,7 +1413,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
@@ -1414,7 +1445,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
}, },
@@ -1431,7 +1462,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`s3cr3t`), Regex: regexp.MustCompile(`s3cr3t`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
}, },
@@ -1448,7 +1479,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "unix-rule", RuleID: "unix-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|/)ignoreme(/.*)?$`)},
@@ -1467,7 +1498,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
rule: config.Rule{ rule: config.Rule{
RuleID: "windows-rule", RuleID: "windows-rule",
Regex: regexp.MustCompile(`value: "[^"]+"`), Regex: regexp.MustCompile(`value: "[^"]+"`),
Allowlists: []config.Allowlist{ Allowlists: []*config.Allowlist{
{ {
MatchCondition: config.AllowlistMatchAnd, MatchCondition: config.AllowlistMatchAnd,
Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)}, Paths: []*regexp.Regexp{regexp.MustCompile(`(^|\\)ignoreme(\\.*)?$`)},
+5 -3
View File
@@ -42,9 +42,11 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
commitSHA := "" commitSHA := ""
if gitdiffFile.PatchHeader != nil { if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA commitSHA = gitdiffFile.PatchHeader.SHA
if ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok { for _, a := range d.Config.Allowlists {
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist") if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
continue logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
continue
}
} }
} }
d.addCommit(commitSHA) d.addCommit(commitSHA)
+12 -5
View File
@@ -8,6 +8,7 @@ import (
"github.com/fatih/semgroup" "github.com/fatih/semgroup"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging" "github.com/zricethezav/gitleaks/v8/logging"
) )
@@ -18,7 +19,7 @@ type ScanTarget struct {
var isWindows = runtime.GOOS == "windows" var isWindows = runtime.GOOS == "windows"
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, shouldSkip func(string) bool) (<-chan ScanTarget, error) { func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget) paths := make(chan ScanTarget)
s.Go(func() error { s.Go(func() error {
defer close(paths) defer close(paths)
@@ -66,10 +67,16 @@ func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, sho
} }
// TODO: Also run this check against the resolved symlink? // TODO: Also run this check against the resolved symlink?
skip := shouldSkip(path) || var skip bool
// TODO: Remove this in v9. for _, a := range allowlists {
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641. skip = a.PathAllowed(path) ||
(isWindows && shouldSkip(filepath.ToSlash(path))) // TODO: Remove this in v9.
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
(isWindows && a.PathAllowed(filepath.ToSlash(path)))
if skip {
break
}
}
if fInfo.IsDir() { if fInfo.IsDir() {
// Directory // Directory
if skip { if skip {
+2 -2
View File
@@ -1,10 +1,10 @@
title = "gitleaks config" title = "gitleaks config"
[[rules]] [[rules]]
description = "Generic API Key"
id = "generic-api-key" id = "generic-api-key"
description = "Generic API Key"
regex = '''(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)''' regex = '''(?i)(?:key|api|token|secret|client|passwd|password|auth|access)(?:[0-9a-z\-_\t .]{0,20})(?:[\s|']|[\s|"]){0,3}(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)(?:'|\"|\s|=|\x60){0,5}([0-9a-z\-_.=]{10,150})(?:['|\"|\n|\r|\s|\x60|;]|$)'''
entropy = 3.5 entropy = 3.5
keywords = [ keywords = [
"key","api","token","secret","client","passwd","password","auth","access", "key","api","token","secret","client","passwd","password","auth","access",
] ]
+8 -9
View File
@@ -1,15 +1,20 @@
title = "gitleaks config" title = "gitleaks config"
[[rules]] [[rules]]
description = "Generic API Key"
id = "generic-api-key" id = "generic-api-key"
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]''' description = "Generic API Key"
path = '''.py''' path = '''.py'''
entropy = 3.7 regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
secretGroup = 4 secretGroup = 4
entropy = 3.7
[allowlist] [allowlist]
description = "global allow lists" description = "global allow lists"
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
'''(go.mod|go.sum)$'''
]
regexes = [ regexes = [
'''219-09-9999''', '''219-09-9999''',
'''078-05-1120''', '''078-05-1120''',
@@ -27,10 +32,4 @@ regexes = [
'''api\_key''', '''api\_key''',
'''apikey''', '''apikey''',
'''api\-key''', '''api\-key''',
]
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
'''(go.mod|go.sum)$'''
] ]
+2
View File
@@ -0,0 +1,2 @@
[[allowlists]]
@@ -0,0 +1,4 @@
[allowlist]
regexes = ['''123''']
[[allowlists]]
regexes = ['''456''']
@@ -0,0 +1,3 @@
[[allowlists]]
regexTarget = "mtach"
regexes = ['''456''']
@@ -0,0 +1,7 @@
[[rules]]
id = "github-app-token"
regex = '''(?:ghu|ghs)_[0-9a-zA-Z]{36}'''
[[allowlists]]
targetRules = ["github-app-token", "github-pat"]
regexes = ['''.*fake.*''']
@@ -1,5 +1,3 @@
title = "simple config with allowlist for aws"
[[rules]] [[rules]]
id = "example" id = "example"
regex = '''example\d+''' regex = '''example\d+'''
@@ -1,5 +1,3 @@
title = "simple config with allowlist for aws"
[[rules]] [[rules]]
id = "example" id = "example"
regex = '''example\d+''' regex = '''example\d+'''
@@ -1,5 +1,3 @@
title = "simple config with allowlist for aws"
[[rules]] [[rules]]
id = "example" id = "example"
regex = '''example\d+''' regex = '''example\d+'''
@@ -1,8 +1,10 @@
title = "gitleaks extended 1"
[extend]
path="../testdata/config/invalid/does_not_exist.toml"
[[rules]] [[rules]]
description = "AWS Access Key" description = "AWS Access Key"
id = "aws-access-key" id = "aws-access-key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}''' regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"] tags = ["key", "AWS"]
[allowlist]
regexes = ['''AKIALALEMEL33243OLIA''']
File renamed without changes.
File renamed without changes.
File renamed without changes.
+10
View File
@@ -0,0 +1,10 @@
[[rules]]
id = "test"
regex = '''token = "(.+)"'''
[[allowlists]]
regexes = ["^changeit$"]
[[allowlists]]
condition = "AND"
paths = ["^node_modules/.*"]
stopwords = ["mock"]
@@ -0,0 +1,2 @@
[allowlist]
stopwords = ["0989c462-69c9-49fa-b7d2-30dc5c576a97"]
+2
View File
@@ -0,0 +1,2 @@
[allowlist]
regexes = ['''AKIALALEM.L33243OLIA''']
@@ -0,0 +1,20 @@
[[rules]]
id = "github-app-token"
regex = '''(?:ghu|ghs)_[0-9a-zA-Z]{36}'''
[[rules]]
id = "github-oauth"
regex = '''gho_[0-9a-zA-Z]{36}'''
[[rules]]
id = "github-pat"
regex = '''ghp_[0-9a-zA-Z]{36}'''
[[allowlists]]
regexes = ['''.*fake.*''']
[[allowlists]]
targetRules = ["github-app-token", "github-pat"]
paths = [
'''(?:^|/)@octokit/auth-token/README\.md$''',
]
File renamed without changes.
@@ -1,5 +1,3 @@
title = "simple config with allowlist for aws"
[[rules]] [[rules]]
id = "example" id = "example"
regex = '''example\d+''' regex = '''example\d+'''
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,5 @@
title = "gitleaks config"
[extend] [extend]
path="../testdata/config/extend_1.toml" path="../testdata/config/valid/extend_base_1.toml"
[[rules]] [[rules]]
description = "AWS Secret Key" description = "AWS Secret Key"
@@ -1,7 +1,7 @@
title = "gitleaks extended 1" title = "gitleaks extended 1"
[extend] [extend]
path="../testdata/config/extend_2.toml" path="../testdata/config/valid/extend_base_2.toml"
[[rules]] [[rules]]
description = "AWS Access Key" description = "AWS Access Key"
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
title = "gitleaks extended 3" title = "gitleaks extended 3"
[extend] [extend]
path="../testdata/config/extend_rule_keywords_base.toml" path="../testdata/config/valid/extend_rule_keywords_base.toml"
[[rules]] [[rules]]
id = "aws-secret-key-again-again" id = "aws-secret-key-again-again"
@@ -1,7 +1,7 @@
title = "gitleaks extend disable" title = "gitleaks extend disable"
[extend] [extend]
path = "../testdata/config/extend_disabled_base.toml" path = "../testdata/config/valid/extend_disabled_base.toml"
disabledRules = [ disabledRules = [
'custom-rule1' 'custom-rule1'
] ]
File renamed without changes.
@@ -1,7 +1,7 @@
title = "gitleaks extended 3" title = "gitleaks extended 3"
[extend] [extend]
path="../testdata/config/extend_rule_allowlist_base.toml" path="../testdata/config/valid/extend_rule_allowlist_base.toml"
[[rules]] [[rules]]
id = "aws-secret-key-again-again" id = "aws-secret-key-again-again"
@@ -1,7 +1,7 @@
title = "gitleaks extended 3" title = "gitleaks extended 3"
[extend] [extend]
path="../testdata/config/extend_rule_allowlist_base.toml" path="../testdata/config/valid/extend_rule_allowlist_base.toml"
[[rules]] [[rules]]
id = "aws-secret-key-again-again" id = "aws-secret-key-again-again"
@@ -1,7 +1,7 @@
title = "gitleaks extended 3" title = "gitleaks extended 3"
[extend] [extend]
path="../testdata/config/extend_rule_keywords_base.toml" path="../testdata/config/valid/extend_rule_keywords_base.toml"
[[rules]] [[rules]]
id = "aws-rule-that-is-not-in-base" id = "aws-rule-that-is-not-in-base"
@@ -1,5 +1,5 @@
[extend] [extend]
path="../testdata/config/extend_3.toml" path="../testdata/config/valid/extend_base_3.toml"
[[rules]] [[rules]]
id = "aws-secret-key-again-again" id = "aws-secret-key-again-again"
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,3 @@
title = "gitleaks config"
[[rules]] [[rules]]
id = "discord-api-key" id = "discord-api-key"
description = "Discord API key" description = "Discord API key"
@@ -1,5 +1,3 @@
title = "gitleaks config"
[[rules]] [[rules]]
description = "Python Files" description = "Python Files"
id = "python-files-only" id = "python-files-only"
@@ -1,8 +1,5 @@
title = "gitleaks config"
# https://learnxinyminutes.com/docs/toml/ for toml reference
[[rules]] [[rules]]
id = "pypi-upload-token" id = "pypi-upload-token"
description = "PyPI upload token" description = "PyPI upload token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}''' regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
tags = ["key", "pypi"] tags = ["key", "pypi"]