Compare commits

..
12 Commits
Author SHA1 Message Date
bplaxco 78eebaca9d Percent/URL Decoding Support (#1831)
* Add initial percent decoding support

* Refactor multi encoding support

* Add detect tests to confirm positions

* Avoid a few extra passes during decoding

* Do multiple passes for finding encodings re

* Fix issue with overlapping encodings when doing separate passes
2025-05-12 11:22:36 -05:00
Richard Gomez 6f967cad68 fix(kubernetes): remove slow element from pat (#1848) 2025-05-02 20:16:30 -05:00
Richard Gomez 88f56d3695 feat: identify slow file (#1479) 2025-05-01 07:39:13 -05:00
Zach 9609928c02 rm 1password detect test since we test it in cfg gen 2025-04-30 09:57:28 -05:00
Jordan BradfordandRichard Gomez 23cb69fba4 feat(rules): Add 1Password secret key detection (#1834)
* Add `1password-secret-key` detection

* Document key details

* Update cmd/generate/config/rules/1password.go

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

* Generate new `.toml`

* Use `GenerateSampleSecrets` to test more scenarios

* Comment lowercase `fps`

* Decrease entropy

---------

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-04-30 09:30:58 -05:00
Richard Gomez d1c77598da fix(detect): test all allowlists (#1845) 2025-04-30 08:29:57 -05:00
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
89 changed files with 2596 additions and 1365 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: |
+18 -7
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.
@@ -440,7 +449,9 @@ ways:
Currently supported encodings: Currently supported encodings:
- `base64` (both standard and base64url) - **percent** - Any printable ASCII percent encoded values
- **hex** - Any printable ASCII hex encoded values >= 32 characters
- **base64** - Any printable ASCII base64 encoded values >= 16 characters
#### Reporting #### Reporting
+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)
}
} }
} }
} }
+24 -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,12 +20,13 @@ 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]
configRules := []*config.Rule{ configRules := []*config.Rule{
rules.OnePasswordSecretKey(),
rules.OnePasswordServiceAccountToken(), rules.OnePasswordServiceAccountToken(),
rules.AdafruitAPIKey(), rules.AdafruitAPIKey(),
rules.AdobeClientID(), rules.AdobeClientID(),
@@ -46,6 +49,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 +168,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 +244,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 +271,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 +279,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)
}
}
+40 -1
View File
@@ -33,10 +33,49 @@ export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoibXkuMXBhc3N3b3JkLmNv
serviceAccountToken: serviceAccountToken:
fn::secret: ops_eyJzaWduSW5B..[Redacted]`, fn::secret: ops_eyJzaWduSW5B..[Redacted]`,
`: To start using this service account, run the following command: `: To start using this service account, run the following command:
: :
: export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`, : export OP_SERVICE_ACCOUNT_TOKEN=ops_eyJzaWduSW5BZGRyZXNzIjoiaHR0cHM6...`,
// Low entropy. // Low entropy.
`ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`, `ops_eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,
} }
return utils.Validate(r, tps, fps) return utils.Validate(r, tps, fps)
} }
// Reference:
// - https://1passwordstatic.com/files/security/1password-white-paper.pdf
func OnePasswordSecretKey() *config.Rule {
// 1Password secret keys include several hyphens but these are only for readability
// and are stripped during 1Password login. This means that the following are technically
// the same valid key:
// - A3ASWWYB798JRYLJVD423DC286TVMH43EB
// - A-3-A-S-W-W-Y-B-7-9-8-J-R-Y-L-J-V-D-4-2-3-D-C-2-8-6-T-V-M-H-4-3-E-B
// But in practice, when these keys are added to a vault, exported in an emergency kit, or
// copied, they have hyphens that follow one of two patterns I can find:
// - A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB (every key I've generated has this pattern)
// - A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB (the whitepaper includes this example, which could just be a typo)
// To avoid a complicated regex that checks for every possible situation it's probably best
// to scan for the these two patterns.
r := config.Rule{
Description: "Uncovered a possible 1Password secret key, potentially compromising access to secrets in vaults.",
RuleID: "1password-secret-key",
Regex: regexp.MustCompile(`\bA3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b`),
Entropy: 3.8,
Keywords: []string{"A3-"},
}
// validate
tps := utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{11}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))
tps = append(tps, utils.GenerateSampleSecrets("1password", secrets.NewSecret(`A3-[A-Z0-9]{6}-[A-Z0-9]{6}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}`))...)
tps = append(tps,
// from whitepaper
`A3-ASWWYB-798JRYLJVD4-23DC2-86TVM-H43EB`,
`A3-ASWWYB-798JRY-LJVD4-23DC2-86TVM-H43EB`,
)
fps := []string{
// low entropy
`A3-XXXXXX-XXXXXXXXXXX-XXXXX-XXXXX-XXXXX`,
// lowercase
`A3-xXXXXX-XXXXXX-XXXXX-XXXXX-XXXXX-XXXXX`,
}
return utils.Validate(r, tps, fps)
}
+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
+4 -4
View File
@@ -17,7 +17,7 @@ func KubernetesSecret() *config.Rule {
// - valid base64 characters // - valid base64 characters
// - longer than 10 characters (no "YmFyCg==") // - longer than 10 characters (no "YmFyCg==")
//language=regexp //language=regexp
dataPat := `\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))` dataPat := `\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))`
// define rule // define rule
r := config.Rule{ r := config.Rule{
@@ -25,13 +25,13 @@ func KubernetesSecret() *config.Rule {
Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments", Description: "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments",
Regex: regexp.MustCompile(fmt.Sprintf( Regex: regexp.MustCompile(fmt.Sprintf(
//language=regexp //language=regexp
`(?i)(?:%s(?:.|\s){0,200}?%s|%s(?:.|\s){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)), `(?i)(?:%s(?s:.){0,200}?%s|%s(?s:.){0,200}?%s)`, kindPat, dataPat, dataPat, kindPat)),
Keywords: []string{ Keywords: []string{
"secret", "secret",
}, },
// 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.
@@ -45,7 +45,7 @@ func KubernetesSecret() *config.Rule {
// Avoid overreach between directives. // Avoid overreach between directives.
RegexTarget: "match", RegexTarget: "match",
Regexes: []*regexp.Regexp{ Regexes: []*regexp.Regexp{
regexp.MustCompile(`(kind:(?:.|\s)+\n---\n(?:.|\s)+\bdata:|data:(?:.|\s)+\n---\n(?:.|\s)+\bkind:)`), regexp.MustCompile(`(kind:(?s:.)+\n---\n(?s:.)+\bdata:|data:(?s:.)+\n---\n(?s:.)+\bkind:)`),
}, },
}, },
}, },
+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",
}, },
} }
+46 -54
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,11 +42,33 @@ 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",
] ]
[[rules]]
id = "1password-secret-key"
description = "Uncovered a possible 1Password secret key, potentially compromising access to secrets in vaults."
regex = '''\bA3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b'''
entropy = 3.8
keywords = ["a3-"]
[[rules]] [[rules]]
id = "1password-service-account-token" id = "1password-service-account-token"
description = "Uncovered a possible 1Password service account token, potentially compromising access to secrets in vaults." description = "Uncovered a possible 1Password service account token, potentially compromising access to secrets in vaults."
@@ -217,6 +225,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 +560,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 +604,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 +628,9 @@ stopwords = [
"activity", "activity",
"adapter", "adapter",
"add-", "add-",
"add-on",
"add.", "add.",
"add_", "add_",
"add-on",
"addon", "addon",
"addres", "addres",
"admin", "admin",
@@ -655,10 +673,7 @@ stopwords = [
"any_", "any_",
"apache", "apache",
"app-", "app-",
"app-",
"app.", "app.",
"app.",
"app_",
"app_", "app_",
"apple", "apple",
"arch", "arch",
@@ -682,7 +697,6 @@ stopwords = [
"aura", "aura",
"auth", "auth",
"author", "author",
"author",
"authorize", "authorize",
"auto", "auto",
"automated", "automated",
@@ -803,7 +817,6 @@ stopwords = [
"cli.", "cli.",
"cli_", "cli_",
"client", "client",
"client",
"clojure", "clojure",
"clone", "clone",
"closure", "closure",
@@ -838,7 +851,6 @@ stopwords = [
"concept", "concept",
"conf", "conf",
"config", "config",
"config",
"connect", "connect",
"connector", "connector",
"console", "console",
@@ -897,7 +909,6 @@ stopwords = [
"dead", "dead",
"debian", "debian",
"debug", "debug",
"debug",
"debugger", "debugger",
"deck", "deck",
"define", "define",
@@ -929,10 +940,7 @@ stopwords = [
"dns-", "dns-",
"dns_", "dns_",
"doc-", "doc-",
"doc-",
"doc.", "doc.",
"doc.",
"doc_",
"doc_", "doc_",
"docker", "docker",
"docpad", "docpad",
@@ -946,8 +954,8 @@ stopwords = [
"dom.", "dom.",
"dom_", "dom_",
"domain", "domain",
"done",
"don't", "don't",
"done",
"dot-", "dot-",
"dot.", "dot.",
"dot_", "dot_",
@@ -967,7 +975,6 @@ stopwords = [
"dsl_", "dsl_",
"dynamic", "dynamic",
"easy", "easy",
"_ec2_",
"ecdsa", "ecdsa",
"eclipse", "eclipse",
"edit", "edit",
@@ -997,7 +1004,6 @@ stopwords = [
"event", "event",
"evented", "evented",
"example", "example",
"example",
"exchange", "exchange",
"exercise", "exercise",
"experiment", "experiment",
@@ -1245,10 +1251,7 @@ stopwords = [
"koan", "koan",
"kohana", "kohana",
"lab-", "lab-",
"lab-",
"lab.", "lab.",
"lab.",
"lab_",
"lab_", "lab_",
"lambda", "lambda",
"lamp", "lamp",
@@ -1333,10 +1336,7 @@ stopwords = [
"manifest", "manifest",
"manual", "manual",
"map-", "map-",
"map-",
"map.", "map.",
"map.",
"map_",
"map_", "map_",
"mapper", "mapper",
"mapping", "mapping",
@@ -1422,10 +1422,7 @@ stopwords = [
"nette", "nette",
"network", "network",
"new-", "new-",
"new-",
"new.", "new.",
"new.",
"new_",
"new_", "new_",
"next", "next",
"nginx", "nginx",
@@ -1494,7 +1491,6 @@ stopwords = [
"package", "package",
"packet", "packet",
"page", "page",
"page",
"panel", "panel",
"paper", "paper",
"paperclip", "paperclip",
@@ -1611,8 +1607,8 @@ stopwords = [
"readme", "readme",
"ready", "ready",
"real", "real",
"reality",
"real-time", "real-time",
"reality",
"realtime", "realtime",
"recipe", "recipe",
"recorder", "recorder",
@@ -1678,7 +1674,6 @@ stopwords = [
"rvm_", "rvm_",
"salt", "salt",
"sample", "sample",
"sample",
"sandbox", "sandbox",
"sas-", "sas-",
"sas.", "sas.",
@@ -1729,7 +1724,6 @@ stopwords = [
"set.", "set.",
"set_", "set_",
"setting", "setting",
"setting",
"setup", "setup",
"sha1", "sha1",
"sha2", "sha2",
@@ -1852,19 +1846,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 +1990,6 @@ stopwords = [
"website", "website",
"websocket", "websocket",
"welcome", "welcome",
"welcome",
"what", "what",
"what'", "what'",
"when", "when",
@@ -2070,7 +2056,6 @@ stopwords = [
"zsh-", "zsh-",
"zsh.", "zsh.",
"zsh_", "zsh_",
"6fe4476ee5a1832882e326b506d14126",
] ]
[[rules.allowlists]] [[rules.allowlists]]
regexTarget = "line" regexTarget = "line"
@@ -2399,7 +2384,7 @@ keywords = ["kraken"]
[[rules]] [[rules]]
id = "kubernetes-secret-yaml" id = "kubernetes-secret-yaml"
description = "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments" description = "Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments"
regex = '''(?i)(?:\bkind:[ \t]*["']?\bsecret\b["']?(?:.|\s){0,200}?\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?:.|\s){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?:.|\s){0,200}?\bkind:[ \t]*["']?\bsecret\b["']?)''' regex = '''(?i)(?:\bkind:[ \t]*["']?\bsecret\b["']?(?s:.){0,200}?\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))|\bdata:(?s:.){0,100}?\s+([\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:["']?[a-z0-9+/]{10,}={0,3}["']?|\{\{[ \t\w"|$:=,.-]+}}|""|''))(?s:.){0,200}?\bkind:[ \t]*["']?\bsecret\b["']?)'''
path = '''(?i)\.ya?ml$''' path = '''(?i)\.ya?ml$'''
keywords = ["secret"] keywords = ["secret"]
[[rules.allowlists]] [[rules.allowlists]]
@@ -2409,7 +2394,7 @@ regexes = [
[[rules.allowlists]] [[rules.allowlists]]
regexTarget = "match" regexTarget = "match"
regexes = [ regexes = [
'''(kind:(?:.|\s)+\n---\n(?:.|\s)+\bdata:|data:(?:.|\s)+\n---\n(?:.|\s)+\bkind:)''', '''(kind:(?s:.)+\n---\n(?s:.)+\bdata:|data:(?s:.)+\n---\n(?s:.)+\bkind:)''',
] ]
[[rules]] [[rules]]
@@ -2651,6 +2636,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
+34
View File
@@ -0,0 +1,34 @@
package codec
var printableASCII [256]bool
func init() {
for b := 0; b < len(printableASCII); b++ {
if '\x08' < b && b < '\x7f' {
printableASCII[b] = true
}
}
}
// isPrintableASCII returns true if all bytes are printable ASCII
func isPrintableASCII(b []byte) bool {
for _, c := range b {
if !printableASCII[c] {
return false
}
}
return true
}
// hasByte can be used to check if a string has at least one of the provided
// bytes. Note: make sure byteset is long enough to handle the largest byte in
// the string.
func hasByte(data string, byteset []bool) bool {
for i := 0; i < len(data); i++ {
if byteset[data[i]] {
return true
}
}
return false
}
+39
View File
@@ -0,0 +1,39 @@
package codec
import (
"encoding/base64"
)
// likelyBase64Chars is a set of characters that you would expect to find at
// least one of in base64 encoded data. This risks missing about 1% of
// base64 encoded data that doesn't contain these characters, but gives you
// the performance gain of not trying to decode a lot of long symbols in code.
var likelyBase64Chars = make([]bool, 256)
func init() {
for _, c := range `0123456789+/-_` {
likelyBase64Chars[c] = true
}
}
// decodeBase64 decodes base64 encoded printable ASCII characters
func decodeBase64(encodedValue string) string {
// Exit early if it doesn't seem like base64
if !hasByte(encodedValue, likelyBase64Chars) {
return ""
}
// Try standard base64 decoding
decodedValue, err := base64.StdEncoding.DecodeString(encodedValue)
if err == nil && isPrintableASCII(decodedValue) {
return string(decodedValue)
}
// Try base64url decoding
decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue)
if err == nil && isPrintableASCII(decodedValue) {
return string(decodedValue)
}
return ""
}
+102
View File
@@ -0,0 +1,102 @@
package codec
import (
"bytes"
"github.com/zricethezav/gitleaks/v8/logging"
)
// Decoder decodes various types of data in place
type Decoder struct {
decodedMap map[string]string
}
// NewDecoder creates a default decoder struct
func NewDecoder() *Decoder {
return &Decoder{
decodedMap: make(map[string]string),
}
}
// Decode returns the data with the values decoded in place along with the
// encoded segment meta data for the next pass of decoding
func (d *Decoder) Decode(data string, predecessors []*EncodedSegment) (string, []*EncodedSegment) {
segments := d.findEncodedSegments(data, predecessors)
if len(segments) > 0 {
result := bytes.NewBuffer(make([]byte, 0, len(data)))
encodedStart := 0
for _, segment := range segments {
result.WriteString(data[encodedStart:segment.encoded.start])
result.WriteString(segment.decodedValue)
encodedStart = segment.encoded.end
}
result.WriteString(data[encodedStart:])
return result.String(), segments
}
return data, segments
}
// findEncodedSegments finds the encoded segments in the data
func (d *Decoder) findEncodedSegments(data string, predecessors []*EncodedSegment) []*EncodedSegment {
if len(data) == 0 {
return []*EncodedSegment{}
}
decodedShift := 0
encodingMatches := findEncodingMatches(data)
segments := make([]*EncodedSegment, 0, len(encodingMatches))
for _, m := range encodingMatches {
encodedValue := data[m.start:m.end]
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
if !alreadyDecoded {
decodedValue = m.encoding.decode(encodedValue)
d.decodedMap[encodedValue] = decodedValue
}
if len(decodedValue) == 0 {
continue
}
segment := &EncodedSegment{
predecessors: predecessors,
original: toOriginal(predecessors, m.startEnd),
encoded: m.startEnd,
decoded: startEnd{
m.start + decodedShift,
m.start + decodedShift + len(decodedValue),
},
decodedValue: decodedValue,
encodings: m.encoding.kind,
depth: 1,
}
// Shift decoded start and ends based on size changes
decodedShift += len(decodedValue) - len(encodedValue)
// Adjust depth and encoding if applicable
if len(segment.predecessors) != 0 {
// Set the depth based on the predecessors' depth in the previous pass
segment.depth = 1 + segment.predecessors[0].depth
// Adjust encodings
for _, p := range segment.predecessors {
if segment.encoded.overlaps(p.decoded) {
segment.encodings |= p.encodings
}
}
}
segments = append(segments, segment)
logging.Debug().Msgf(
"segment found: original=%s pos=%s: %q -> %q",
segment.original,
segment.encoded,
encodedValue,
segment.decodedValue,
)
}
return segments
}
@@ -1,9 +1,10 @@
package detect package codec
import ( import (
"testing" "encoding/hex"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"net/url"
"testing"
) )
func TestDecode(t *testing.T) { func TestDecode(t *testing.T) {
@@ -66,8 +67,8 @@ func TestDecode(t *testing.T) {
}, },
{ {
name: "b64-url-safe: hyphen url b64", name: "b64-url-safe: hyphen url b64",
chunk: `dHJ1ZmZsZWhvZz4-ZmluZHMtc2VjcmV0cw`, chunk: `Z2l0bGVha3M-PmZpbmRzLXNlY3JldHM`,
expected: `trufflehog>>finds-secrets`, expected: `gitleaks>>finds-secrets`,
}, },
{ {
name: "b64-url-safe: underscore url b64", name: "b64-url-safe: underscore url b64",
@@ -79,13 +80,49 @@ func TestDecode(t *testing.T) {
chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`, chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`, expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`,
}, },
{
name: "url encoded value",
chunk: `secret%3D%22q%24%21%40%23%24%25%5E%26%2A%28%20asdf%22`,
expected: `secret="q$!@#$%^&*( asdf"`,
},
{
name: "hex encoded value",
chunk: `secret="466973684D617048756E6B79212121363334"`,
expected: `secret="FishMapHunky!!!634"`,
},
} }
decoder := NewDecoder() decoder := NewDecoder()
fullDecode := func(data string) string {
segments := []*EncodedSegment{}
for {
data, segments = decoder.Decode(data, segments)
if len(segments) == 0 {
return data
}
}
}
// Test value decoding
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
decoded, _ := decoder.decode(tt.chunk, []EncodedSegment{}) assert.Equal(t, tt.expected, fullDecode(tt.chunk))
assert.Equal(t, tt.expected, decoded) })
}
// Percent encode the values to test percent decoding
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encodedChunk := url.PathEscape(tt.chunk)
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
})
}
// Hex encode the values to test hex decoding
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
encodedChunk := hex.EncodeToString([]byte(tt.chunk))
assert.Equal(t, tt.expected, fullDecode(encodedChunk))
}) })
} }
} }
+153
View File
@@ -0,0 +1,153 @@
package codec
import (
"fmt"
"math"
"regexp"
"strings"
)
var (
// encodingsRe is a regex built by combining all the encoding patterns
// into named capture groups so that a single pass can detect multiple
// encodings
encodingsRe *regexp.Regexp
// encodings contains all the encoding configurations for the detector.
// The precedence is important. You want more specific encodings to
// have a higher precedence or encodings that partially encode the
// values (e.g. percent) unlike encodings that fully encode the string
// (e.g. base64). If two encoding matches overlap the decoder will use
// this order to determine which encoding should wait till the next pass.
encodings = []*encoding{
&encoding{
kind: percentKind,
pattern: `%[0-9A-Fa-f]{2}(?:.*%[0-9A-Fa-f]{2})?`,
decode: decodePercent,
},
&encoding{
kind: hexKind,
pattern: `[0-9A-Fa-f]{32,}`,
decode: decodeHex,
},
&encoding{
kind: base64Kind,
pattern: `[\w\/+-]{16,}={0,2}`,
decode: decodeBase64,
},
}
)
// encodingNames is used to map the encodingKinds to their name
var encodingNames = []string{
"percent",
"hex",
"base64",
}
// encodingKind can be or'd together to capture all of the unique encodings
// that were present in a segment
type encodingKind int
var (
// make sure these go up by powers of 2
percentKind = encodingKind(1)
hexKind = encodingKind(2)
base64Kind = encodingKind(4)
)
func (e encodingKind) String() string {
i := int(math.Log2(float64(e)))
if i >= len(encodingNames) {
return ""
}
return encodingNames[i]
}
// kinds returns a list of encodingKinds combined in this one
func (e encodingKind) kinds() []encodingKind {
kinds := []encodingKind{}
for i := 0; i < len(encodingNames); i++ {
if kind := int(e) & int(math.Pow(2, float64(i))); kind != 0 {
kinds = append(kinds, encodingKind(kind))
}
}
return kinds
}
// encodingMatch represents a match of an encoding in the text
type encodingMatch struct {
encoding *encoding
startEnd
}
// encoding represent a type of coding supported by the decoder.
type encoding struct {
// the kind of decoding (e.g. base64, etc)
kind encodingKind
// the regex pattern that matches the encoding format
pattern string
// take the match and return the decoded value
decode func(string) string
// determine which encoding should win out when two overlap
precedence int
}
func init() {
count := len(encodings)
namedPatterns := make([]string, count)
for i, encoding := range encodings {
encoding.precedence = count - i
namedPatterns[i] = fmt.Sprintf(
"(?P<%s>%s)",
encoding.kind,
encoding.pattern,
)
}
encodingsRe = regexp.MustCompile(strings.Join(namedPatterns, "|"))
}
// findEncodingMatches finds as many encodings as it can for this pass
func findEncodingMatches(data string) []encodingMatch {
var all []encodingMatch
for _, matchIndex := range encodingsRe.FindAllStringSubmatchIndex(data, -1) {
// Add the encodingMatch with its proper encoding
for i, j := 2, 0; i < len(matchIndex); i, j = i+2, j+1 {
if matchIndex[i] > -1 {
all = append(all, encodingMatch{
encoding: encodings[j],
startEnd: startEnd{
start: matchIndex[i],
end: matchIndex[i+1],
},
})
}
}
}
totalMatches := len(all)
if totalMatches == 1 {
return all
}
// filter out lower precedence ones that overlap their neigbors
filtered := make([]encodingMatch, 0, len(all))
for i, m := range all {
if i > 0 {
prev := all[i-1]
if m.overlaps(prev.startEnd) && prev.encoding.precedence > m.encoding.precedence {
continue // skip this one
}
}
if i+1 < totalMatches {
next := all[i+1]
if m.overlaps(next.startEnd) && next.encoding.precedence > m.encoding.precedence {
continue // skip this one
}
}
filtered = append(filtered, m)
}
return filtered
}
+60
View File
@@ -0,0 +1,60 @@
package codec
// hexMap is a precalculated map of hex nibbles
const hexMap = "" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" +
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
// likelyHexChars is a set of characters that you would expect to find at
// least one of in hex encoded data. This risks missing some hex data that
// doesn't contain these characters, but gives you the performance gain of not
// trying to decode a lot of long symbols in code.
var likelyHexChars = make([]bool, 256)
func init() {
for _, c := range `0123456789` {
likelyHexChars[c] = true
}
}
// decodeHex decodes hex data
func decodeHex(encodedValue string) string {
size := len(encodedValue)
// hex should have two characters per byte
if size%2 != 0 {
return ""
}
if !hasByte(encodedValue, likelyHexChars) {
return ""
}
decodedValue := make([]byte, size/2)
for i := 0; i < size; i += 2 {
n1 := hexMap[encodedValue[i]]
n2 := hexMap[encodedValue[i+1]]
if n1|n2 == '\xff' {
return ""
}
b := byte(n1<<4 | n2)
if !printableASCII[b] {
return ""
}
decodedValue[i/2] = b
}
return string(decodedValue)
}
+34
View File
@@ -0,0 +1,34 @@
package codec
// decodePercent decodes percent encoded strings
func decodePercent(encodedValue string) string {
encLen := len(encodedValue)
decodedValue := make([]byte, encLen)
decIndex := 0
encIndex := 0
for encIndex < encLen {
if encodedValue[encIndex] == '%' && encIndex+2 < encLen {
n1 := hexMap[encodedValue[encIndex+1]]
n2 := hexMap[encodedValue[encIndex+2]]
// Make sure they're hex characters
if n1|n2 != '\xff' {
b := byte(n1<<4 | n2)
if !printableASCII[b] {
return ""
}
decodedValue[decIndex] = b
encIndex += 3
decIndex += 1
continue
}
}
decodedValue[decIndex] = encodedValue[encIndex]
encIndex += 1
decIndex += 1
}
return string(decodedValue[:decIndex])
}
+173
View File
@@ -0,0 +1,173 @@
package codec
import (
"fmt"
)
// EncodedSegment represents a portion of text that is encoded in some way.
type EncodedSegment struct {
// predecessors are all of the segments from the previous decoding pass
predecessors []*EncodedSegment
// original start/end indices before decoding
original startEnd
// encoded start/end indices relative to the previous decoding pass.
// If it's a top level segment, original and encoded will be the
// same.
encoded startEnd
// decoded start/end indices in this pass after decoding
decoded startEnd
// decodedValue contains the decoded string for this segment
decodedValue string
// encodings is the encodings that make up this segment. encodingKind
// can be or'd together to hold multiple encodings
encodings encodingKind
// depth is how many decoding passes it took to decode this segment
depth int
}
// Tags returns additional meta data tags related to the types of segments
func Tags(segments []*EncodedSegment) []string {
// Return an empty list if we don't have any segments
if len(segments) == 0 {
return []string{}
}
// Since decoding is done in passes, the depth of all the segments
// should be the same
depth := segments[0].depth
// Collect the encodings from the segments
encodings := segments[0].encodings
for i := 1; i < len(segments); i++ {
encodings |= segments[i].encodings
}
kinds := encodings.kinds()
tags := make([]string, len(kinds)+1)
tags[len(tags)-1] = fmt.Sprintf("decode-depth:%d", depth)
for i, kind := range kinds {
tags[i] = fmt.Sprintf("decoded:%s", kind)
}
return tags
}
// CurrentLine returns from the start of the line containing the segments
// to the end of the line where the segment ends.
func CurrentLine(segments []*EncodedSegment, currentRaw string) string {
// Return the whole thing if no segments are provided
if len(segments) == 0 {
return currentRaw
}
start := 0
end := len(currentRaw)
// Merge the ranges together into a single decoded value
decoded := segments[0].decoded
for i := 1; i < len(segments); i++ {
decoded = decoded.merge(segments[i].decoded)
}
// Find the start of the range
for i := decoded.start; i > -1; i-- {
c := currentRaw[i]
if c == '\n' {
start = i
break
}
}
// Find the end of the range
for i := decoded.end; i < end; i++ {
c := currentRaw[i]
if c == '\n' {
end = i
break
}
}
return currentRaw[start:end]
}
// AdjustMatchIndex maps a match index from the current decode pass back to
// its location in the original text
func AdjustMatchIndex(segments []*EncodedSegment, matchIndex []int) []int {
// Don't adjust if we're not provided any segments
if len(segments) == 0 {
return matchIndex
}
// Map the match to the location in the original text
match := startEnd{matchIndex[0], matchIndex[1]}
// Map the match to its orignal location
adjusted := toOriginal(segments, match)
// Return the adjusted match index
return []int{
adjusted.start,
adjusted.end,
}
}
// SegmentsWithDecodedOverlap the segments where the start and end overlap its
// decoded range
func SegmentsWithDecodedOverlap(segments []*EncodedSegment, start, end int) []*EncodedSegment {
se := startEnd{start, end}
overlaps := []*EncodedSegment{}
for _, segment := range segments {
if segment.decoded.overlaps(se) {
overlaps = append(overlaps, segment)
}
}
return overlaps
}
// toOriginal maps a start/end to its start/end in the original text
// the provided start/end should be relative to the segment's decoded value
func toOriginal(predecessors []*EncodedSegment, decoded startEnd) startEnd {
if len(predecessors) == 0 {
return decoded
}
// Map the decoded value one level up where it was encoded
encoded := startEnd{}
for _, p := range predecessors {
if !p.decoded.overlaps(decoded) {
continue // Not in scope
}
// If fully contained, return the segments original start/end
if p.decoded.contains(decoded) {
return p.original
}
// Map the value to be relative to the predecessors's decoded values
if encoded.end == 0 {
encoded = p.encoded.add(p.decoded.overflow(decoded))
} else {
encoded = encoded.merge(p.encoded.add(p.decoded.overflow(decoded)))
}
}
// Should only get here if the thing passed in wasn't in a decoded
// value. This shouldn't be the case
if encoded.end == 0 {
return decoded
}
// Climb up another level
// (NOTE: each segment references all the predecessors)
return toOriginal(predecessors[0].predecessors, encoded)
}
+57
View File
@@ -0,0 +1,57 @@
package codec
import (
"fmt"
)
// startEnd represents the start and end of some data. It mainly exists as a
// helper when referencing the values
type startEnd struct {
start int
end int
}
// sub subtracts the values of two startEnds
func (s startEnd) sub(o startEnd) startEnd {
return startEnd{
s.start - o.start,
s.end - o.end,
}
}
// add adds the values of two startEnds
func (s startEnd) add(o startEnd) startEnd {
return startEnd{
s.start + o.start,
s.end + o.end,
}
}
// overlaps returns true if two startEnds overlap
func (s startEnd) overlaps(o startEnd) bool {
return o.start <= s.end && o.end >= s.start
}
// contains returns true if the other is fully contained within this one
func (s startEnd) contains(o startEnd) bool {
return s.start <= o.start && o.end <= s.end
}
// overflow returns a startEnd that tells how much the other goes outside the
// bounds of this one
func (s startEnd) overflow(o startEnd) startEnd {
return s.merge(o).sub(s)
}
// merge takes two start/ends and returns a single one that encompases both
func (s startEnd) merge(o startEnd) startEnd {
return startEnd{
min(s.start, o.start),
max(s.end, o.end),
}
}
// String returns a string representation for clearer debugging
func (s startEnd) String() string {
return fmt.Sprintf("[%d,%d]", s.start, s.end)
}
-306
View File
@@ -1,306 +0,0 @@
package detect
import (
"bytes"
"encoding/base64"
"fmt"
"regexp"
"unicode"
"github.com/zricethezav/gitleaks/v8/logging"
)
var b64LikelyChars [128]byte
var b64Regexp = regexp.MustCompile(`[\w/+-]{16,}={0,3}`)
var decoders = []func(string) ([]byte, error){
base64.StdEncoding.DecodeString,
base64.RawURLEncoding.DecodeString,
}
func init() {
// Basically look for anything that isn't just letters
for _, c := range `0123456789+/-_` {
b64LikelyChars[c] = 1
}
}
// EncodedSegment represents a portion of text that is encoded in some way.
// `decode` supports recusive decoding and can result in "segment trees".
// There can be multiple segments in the original text, so each can be thought
// of as its own tree with the root being the original segment.
type EncodedSegment struct {
// The parent segment in a segment tree. If nil, it is a root segment
parent *EncodedSegment
// Relative start/end are the bounds of the encoded value in the current pass.
relativeStart int
relativeEnd int
// Absolute start/end refer to the bounds of the root segment in this segment
// tree
absoluteStart int
absoluteEnd int
// Decoded start/end refer to the bounds of the decoded value in the current
// pass. These can differ from relative values because decoding can shrink
// or grow the size of the segment.
decodedStart int
decodedEnd int
// This is the actual decoded content in the segment
decodedValue string
// This is the type of encoding
encoding string
}
// isChildOf inspects the bounds of two segments to determine
// if one should be the child of another
func (s EncodedSegment) isChildOf(parent EncodedSegment) bool {
return parent.decodedStart <= s.relativeStart && parent.decodedEnd >= s.relativeEnd
}
// decodedOverlaps checks if the decoded bounds of the segment overlaps a range
func (s EncodedSegment) decodedOverlaps(start, end int) bool {
return start <= s.decodedEnd && end >= s.decodedStart
}
// adjustMatchIndex takes the matchIndex from the current decoding pass and
// updates it to match the absolute matchIndex in the original text.
func (s EncodedSegment) adjustMatchIndex(matchIndex []int) []int {
// The match is within the bounds of the segment so we just return
// the absolute start and end of the root segment.
if s.decodedStart <= matchIndex[0] && matchIndex[1] <= s.decodedEnd {
return []int{
s.absoluteStart,
s.absoluteEnd,
}
}
// Since it overlaps one side and/or the other, we're going to have to adjust
// and climb parents until we're either at the root or we've determined
// we're fully inside one of the parent segments.
adjustedMatchIndex := make([]int, 2)
if matchIndex[0] < s.decodedStart {
// It starts before the encoded segment so adjust the start to match
// the location before it was decoded
matchStartDelta := s.decodedStart - matchIndex[0]
adjustedMatchIndex[0] = s.relativeStart - matchStartDelta
} else {
// It starts within the encoded segment so set the bound to the
// relative start
adjustedMatchIndex[0] = s.relativeStart
}
if matchIndex[1] > s.decodedEnd {
// It ends after the encoded segment so adjust the end to match
// the location before it was decoded
matchEndDelta := matchIndex[1] - s.decodedEnd
adjustedMatchIndex[1] = s.relativeEnd + matchEndDelta
} else {
// It ends within the encoded segment so set the bound to the relative end
adjustedMatchIndex[1] = s.relativeEnd
}
// We're still not at a root segment so we'll need to keep on adjusting
if s.parent != nil {
return s.parent.adjustMatchIndex(adjustedMatchIndex)
}
return adjustedMatchIndex
}
// depth reports how many levels of decoding needed to be done (default is 1)
func (s EncodedSegment) depth() int {
depth := 1
// Climb the tree and increment the depth
for current := &s; current.parent != nil; current = current.parent {
depth++
}
return depth
}
// tags returns additional meta data tags related to the types of segments
func (s EncodedSegment) tags() []string {
return []string{
fmt.Sprintf("decoded:%s", s.encoding),
fmt.Sprintf("decode-depth:%d", s.depth()),
}
}
// Decoder decodes various types of data in place
type Decoder struct {
decodedMap map[string]string
}
// NewDecoder creates a default decoder struct
func NewDecoder() *Decoder {
return &Decoder{
decodedMap: make(map[string]string),
}
}
// decode returns the data with the values decoded in-place
func (d *Decoder) decode(data string, parentSegments []EncodedSegment) (string, []EncodedSegment) {
segments := d.findEncodedSegments(data, parentSegments)
if len(segments) > 0 {
result := bytes.NewBuffer(make([]byte, 0, len(data)))
relativeStart := 0
for _, segment := range segments {
result.WriteString(data[relativeStart:segment.relativeStart])
result.WriteString(segment.decodedValue)
relativeStart = segment.relativeEnd
}
result.WriteString(data[relativeStart:])
return result.String(), segments
}
return data, segments
}
// findEncodedSegments finds the encoded segments in the data and updates the
// segment tree for this pass
func (d *Decoder) findEncodedSegments(data string, parentSegments []EncodedSegment) []EncodedSegment {
if len(data) == 0 {
return []EncodedSegment{}
}
matchIndices := b64Regexp.FindAllStringIndex(data, -1)
if matchIndices == nil {
return []EncodedSegment{}
}
segments := make([]EncodedSegment, 0, len(matchIndices))
// Keeps up with offsets from the text changing size as things are decoded
decodedShift := 0
for _, matchIndex := range matchIndices {
encodedValue := data[matchIndex[0]:matchIndex[1]]
if !isLikelyB64(encodedValue) {
d.decodedMap[encodedValue] = ""
continue
}
decodedValue, alreadyDecoded := d.decodedMap[encodedValue]
// We haven't decoded this yet, so go ahead and decode it
if !alreadyDecoded {
decodedValue = decodeValue(encodedValue)
d.decodedMap[encodedValue] = decodedValue
}
// Skip this segment because there was nothing to check
if len(decodedValue) == 0 {
continue
}
// Create a segment for the encoded data
segment := EncodedSegment{
relativeStart: matchIndex[0],
relativeEnd: matchIndex[1],
absoluteStart: matchIndex[0],
absoluteEnd: matchIndex[1],
decodedStart: matchIndex[0] + decodedShift,
decodedEnd: matchIndex[0] + decodedShift + len(decodedValue),
decodedValue: decodedValue,
encoding: "base64",
}
// Shift decoded start and ends based on size changes
decodedShift += len(decodedValue) - len(encodedValue)
// Adjust the absolute position of segments contained in parent segments
for _, parentSegment := range parentSegments {
if segment.isChildOf(parentSegment) {
segment.absoluteStart = parentSegment.absoluteStart
segment.absoluteEnd = parentSegment.absoluteEnd
segment.parent = &parentSegment
break
}
}
logging.Debug().Msgf("segment found: %#v", segment)
segments = append(segments, segment)
}
return segments
}
// decoders tries a list of decoders and returns the first successful one
func decodeValue(encodedValue string) string {
for _, decoder := range decoders {
decodedValue, err := decoder(encodedValue)
if err == nil && len(decodedValue) > 0 && isASCII(decodedValue) {
return string(decodedValue)
}
}
return ""
}
func isASCII(b []byte) bool {
for i := 0; i < len(b); i++ {
if b[i] > unicode.MaxASCII || b[i] < '\t' {
return false
}
}
return true
}
// Skip a lot of method signatures and things at the risk of missing about
// 1% of base64
func isLikelyB64(s string) bool {
for _, c := range s {
if b64LikelyChars[c] != 0 {
return true
}
}
return false
}
// Find a segment where the decoded bounds overlaps a range
func segmentWithDecodedOverlap(encodedSegments []EncodedSegment, start, end int) *EncodedSegment {
for _, segment := range encodedSegments {
if segment.decodedOverlaps(start, end) {
return &segment
}
}
return nil
}
func (s EncodedSegment) currentLine(currentRaw string) string {
start := 0
end := len(currentRaw)
// Find the start of the range
for i := s.decodedStart; i > -1; i-- {
c := currentRaw[i]
if c == '\n' {
start = i
break
}
}
// Find the end of the range
for i := s.decodedEnd; i < end; i++ {
c := currentRaw[i]
if c == '\n' {
end = i
break
}
}
return currentRaw[start:end]
}
+184 -146
View File
@@ -9,8 +9,10 @@ import (
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/codec"
"github.com/zricethezav/gitleaks/v8/logging" "github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp" "github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
@@ -25,6 +27,10 @@ import (
const ( const (
gitleaksAllowSignature = "gitleaks:allow" gitleaksAllowSignature = "gitleaks:allow"
chunkSize = 100 * 1_000 // 100kb chunkSize = 100 * 1_000 // 100kb
// SlowWarningThreshold is the amount of time to wait before logging that a file is slow.
// This is useful for identifying problematic files and tuning the allowlist.
SlowWarningThreshold = 5 * time.Second
) )
var ( var (
@@ -212,26 +218,39 @@ 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)
// setup variables to handle different decoding passes // setup variables to handle different decoding passes
currentRaw := fragment.Raw currentRaw := fragment.Raw
encodedSegments := []EncodedSegment{} encodedSegments := []*codec.EncodedSegment{}
currentDecodeDepth := 0 currentDecodeDepth := 0
decoder := NewDecoder() decoder := codec.NewDecoder()
for { for {
// build keyword map for prefiltering rules // build keyword map for prefiltering rules
@@ -268,7 +287,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
} }
// decode the currentRaw for the next pass // decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.decode(currentRaw, encodedSegments) currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
// stop the loop when there's nothing else to decode // stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 { if len(encodedSegments) == 0 {
@@ -280,7 +299,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
} }
// detectRule scans the given fragment for the given rule and returns a list of findings // detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []EncodedSegment) []report.Finding { func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
var ( var (
findings []report.Finding findings []report.Finding
logger = func() zerolog.Logger { logger = func() zerolog.Logger {
@@ -292,46 +311,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 +360,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")
@@ -389,14 +371,15 @@ MatchLoop:
// Check if the decoded portions of the segment overlap with the match // Check if the decoded portions of the segment overlap with the match
// to see if its potentially a new match // to see if its potentially a new match
if len(encodedSegments) > 0 { if len(encodedSegments) > 0 {
if segment := segmentWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1]); segment != nil { segments := codec.SegmentsWithDecodedOverlap(encodedSegments, matchIndex[0], matchIndex[1])
matchIndex = segment.adjustMatchIndex(matchIndex) if len(segments) == 0 {
metaTags = append(metaTags, segment.tags()...)
currentLine = segment.currentLine(currentRaw)
} else {
// This item has already been added to a finding // This item has already been added to a finding
continue continue
} }
matchIndex = codec.AdjustMatchIndex(segments, matchIndex)
metaTags = append(metaTags, codec.Tags(segments)...)
currentLine = codec.CurrentLine(segments, currentRaw)
} else { } else {
// Fixes: https://github.com/gitleaks/gitleaks/issues/1352 // Fixes: https://github.com/gitleaks/gitleaks/issues/1352
// removes the incorrectly following line that was detected by regex expression '\n' // removes the incorrectly following line that was detected by regex expression '\n'
@@ -473,107 +456,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 +499,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 +523,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 {
continue
}
if len(a.StopWords) > 0 {
continue
}
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
}
+422 -199
View File
@@ -17,6 +17,7 @@ import (
"github.com/zricethezav/gitleaks/v8/cmd/scm" "github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/codec"
"github.com/zricethezav/gitleaks/v8/logging" "github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp" "github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/report" "github.com/zricethezav/gitleaks/v8/report"
@@ -26,7 +27,7 @@ import (
const maxDecodeDepth = 8 const maxDecodeDepth = 8
const configPath = "../testdata/config/" const configPath = "../testdata/config/"
const repoBasePath = "../testdata/repos/" const repoBasePath = "../testdata/repos/"
const b64TestValues = ` const encodedTestValues = `
# Decoded # Decoded
-----BEGIN PRIVATE KEY----- -----BEGIN PRIVATE KEY-----
135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb 135f/bRUBHrbHqLY/xS3I7Oth+8rgG+0tBwfMcbk05Sgxq6QUzSYIQAop+WvsTwk2sR+C38g0Mnb
@@ -44,16 +45,48 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiY29uZmlnIjoiVzJ
c21hbGwtc2VjcmV0 c21hbGwtc2VjcmV0
# This tests how it handles when the match bounds go outside the decoded value # This tests how it handles when the match bounds go outside the decoded value
secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU= secret=ZGVjb2RlZC1zZWNyZXQtdmFsdWUwMA==
# The above encoded again # The above encoded again
c2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0= c2VjcmV0PVpHVmpiMlJsWkMxelpXTnlaWFF0ZG1Gc2RXVT0=
# Confirm you can ignore on the decoded value # Confirm you can ignore on the decoded value
password="bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==" password="bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw=="
# This tests that it can do hex encoded data
secret=6465636F6465642D7365637265742D76616C756576484558
# This tests that it can do percent encoded data
## partial encoded data
secret=decoded-%73%65%63%72%65%74-valuev2
## scattered encoded
secret=%64%65coded-%73%65%63%72%65%74-valuev3
# Test multi levels of encoding where the source is a partal encoding
# it is important that the bounds of the predecessors are properly
# considered
## single percent encoding in the middle of multi layer b64
c2VjcmV0PVpHVmpiMl%4AsWkMxelpXTnlaWFF0ZG1Gc2RXVjJOQT09
## single percent encoding at the beginning of hex
secret%3d6465636F6465642D7365637265742D76616C75657635
## multiple percent encodings in a single layer base64
secret=ZGVjb2%52lZC1zZWNyZXQtdm%46sdWV4ODY= # ends in x86
## base64 encoded partially percent encoded value
secret=ZGVjb2RlZC0lNzMlNjUlNjMlNzIlNjUlNzQtdmFsdWU=
## one of the lines above that went through... a lot
## and there's surrounding text around it
Look at this value: %4EjMzMjU2NkE2MzZENTYzMDUwNTY3MDQ4%4eTY2RDcwNjk0RDY5NTUzMTRENkQ3ODYx%25%34%65TE3QTQ2MzY1NzZDNjQ0RjY1NTY3MDU5NTU1ODUyNkI2MjUzNTUzMDRFNkU0RTZCNTYzMTU1MzkwQQ== # isn't it crazy?
## Multi percent encode two random characters close to the bounds of the base64
## encoded data to make sure that the bounds are still correctly calculated
secret=ZG%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%36%25%33%31%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%33%25%33%322RlZC1zZWNyZXQtd%25%36%64%25%34%36%25%37%33dWU=
## The similar to the above but also touching the edge of the base64
secret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
## The similar to the above but also touching and overlapping the base64
secret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
` `
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 +98,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 +117,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 +144,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 +152,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 +175,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 +198,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 +221,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 +258,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,47 +306,127 @@ 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: "base64_encoded", cfgName: "valid/allowlist_global_multiple",
fragment: Fragment{ fragment: Fragment{
Raw: b64TestValues, 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 path when extending": {
cfgName: "valid/allowlist_rule_extend_default",
fragment: Fragment{
Raw: `token = "aebfab88-7596-481d-82e8-c60c8f7de0c0"`,
FilePath: "path/to/your/problematic/file.js",
},
},
"allowlist - ignore regex": {
cfgName: "valid/allowlist_rule_regex",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
},
// Decoding
"detect encoded": {
cfgName: "encoded",
fragment: Fragment{
Raw: encodedTestValues,
FilePath: "tmp.go", FilePath: "tmp.go",
}, },
expectedFindings: []report.Finding{ expectedFindings: []report.Finding{
@@ -402,6 +472,90 @@ func TestDetect(t *testing.T) {
EndColumn: 207, EndColumn: 207,
Entropy: 5.350665, Entropy: 5.350665,
}, },
{ // Encoded Small secret at the end to make sure it's picked up by the decoding
Description: "Small Secret",
Secret: "small-secret",
Match: "small-secret",
File: "tmp.go",
Line: "\nc21hbGwtc2VjcmV0",
RuleID: "small-secret",
Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
StartLine: 15,
EndLine: 15,
StartColumn: 2,
EndColumn: 17,
Entropy: 3.0849626,
},
{ // Secret where the decoded match goes outside the encoded value
Description: "Overlapping",
Secret: "decoded-secret-value00",
Match: "secret=decoded-secret-value00",
File: "tmp.go",
Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWUwMA==",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
StartLine: 18,
EndLine: 18,
StartColumn: 2,
EndColumn: 40,
Entropy: 3.4428623,
},
{ // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good)
Description: "Make sure this would be detected with no allowlist",
Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw",
Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"",
File: "tmp.go",
Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"",
RuleID: "decoded-password-dont-ignore",
Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"},
StartLine: 23,
EndLine: 23,
StartColumn: 2,
EndColumn: 68,
Entropy: 4.5841837,
},
{ // Hex encoded data check
Description: "Overlapping",
Secret: "decoded-secret-valuevHEX",
Match: "secret=decoded-secret-valuevHEX",
File: "tmp.go",
Line: "\nsecret=6465636F6465642D7365637265742D76616C756576484558",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:hex", "decode-depth:1"},
StartLine: 26,
EndLine: 26,
StartColumn: 2,
EndColumn: 56,
Entropy: 3.6531072,
},
{ // handle partial encoded percent data
Description: "Overlapping",
Secret: "decoded-secret-valuev2",
Match: "secret=decoded-secret-valuev2",
File: "tmp.go",
Line: "\nsecret=decoded-%73%65%63%72%65%74-valuev2",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decode-depth:1"},
StartLine: 30,
EndLine: 30,
StartColumn: 2,
EndColumn: 42,
Entropy: 3.4428623,
},
{ // handle partial encoded percent data
Description: "Overlapping",
Secret: "decoded-secret-valuev3",
Match: "secret=decoded-secret-valuev3",
File: "tmp.go",
Line: "\nsecret=%64%65coded-%73%65%63%72%65%74-valuev3",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decode-depth:1"},
StartLine: 32,
EndLine: 32,
StartColumn: 2,
EndColumn: 46,
Entropy: 3.4428623,
},
{ // Encoded AWS config with a access key id inside a JWT { // Encoded AWS config with a access key id inside a JWT
Description: "AWS IAM Unique Identifier", Description: "AWS IAM Unique Identifier",
Secret: "ASIAIOSFODNN7LXM10JI", Secret: "ASIAIOSFODNN7LXM10JI",
@@ -430,34 +584,6 @@ func TestDetect(t *testing.T) {
EndColumn: 344, EndColumn: 344,
Entropy: 4.721928, Entropy: 4.721928,
}, },
{ // Encoded Small secret at the end to make sure it's picked up by the decoding
Description: "Small Secret",
Secret: "small-secret",
Match: "small-secret",
File: "tmp.go",
Line: "\nc21hbGwtc2VjcmV0",
RuleID: "small-secret",
Tags: []string{"small", "secret", "decoded:base64", "decode-depth:1"},
StartLine: 15,
EndLine: 15,
StartColumn: 2,
EndColumn: 17,
Entropy: 3.0849626,
},
{ // Secret where the decoded match goes outside the encoded value
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret=ZGVjb2RlZC1zZWNyZXQtdmFsdWU=",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:base64", "decode-depth:1"},
StartLine: 18,
EndLine: 18,
StartColumn: 2,
EndColumn: 36,
Entropy: 3.3037016,
},
{ // Secret where the decoded match goes outside the encoded value and then encoded again { // Secret where the decoded match goes outside the encoded value and then encoded again
Description: "Overlapping", Description: "Overlapping",
Secret: "decoded-secret-value", Secret: "decoded-secret-value",
@@ -472,26 +598,124 @@ func TestDetect(t *testing.T) {
EndColumn: 49, EndColumn: 49,
Entropy: 3.3037016, Entropy: 3.3037016,
}, },
{ // This just confirms that with no allowlist the pattern is detected (i.e. the regex is good) { // handle encodings that touch eachother
Description: "Make sure this would be detected with no allowlist", Description: "Overlapping",
Secret: "lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw", Secret: "decoded-secret-valuev5",
Match: "password=\"lRqBK-z5kf4-please-ignore-me-X-XIJM2Pddw\"", Match: "secret=decoded-secret-valuev5",
File: "tmp.go", File: "tmp.go",
Line: "\npassword=\"bFJxQkstejVrZjQtcGxlYXNlLWlnbm9yZS1tZS1YLVhJSk0yUGRkdw==\"", Line: "\nsecret%3d6465636F6465642D7365637265742D76616C75657635",
RuleID: "decoded-password-dont-ignore", RuleID: "overlapping",
Tags: []string{"decode-ignore", "decoded:base64", "decode-depth:1"}, Tags: []string{"overlapping", "decoded:percent", "decoded:hex", "decode-depth:2"},
StartLine: 23, StartLine: 40,
EndLine: 23, EndLine: 40,
StartColumn: 2, StartColumn: 2,
EndColumn: 68, EndColumn: 54,
Entropy: 4.5841837, Entropy: 3.4428623,
},
{ // handle partial encoded percent data465642D7365637265742D76616C75657635
Description: "Overlapping",
Secret: "decoded-secret-valuev4",
Match: "secret=decoded-secret-valuev4",
File: "tmp.go",
Line: "\nc2VjcmV0PVpHVmpiMl%4AsWkMxelpXTnlaWFF0ZG1Gc2RXVjJOQT09",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:3"},
StartLine: 38,
EndLine: 38,
StartColumn: 2,
EndColumn: 55,
Entropy: 3.4428623,
},
{ // multiple percent encodings in a single layer base64
Description: "Overlapping",
Secret: "decoded-secret-valuex86",
Match: "secret=decoded-secret-valuex86",
File: "tmp.go",
Line: "\nsecret=ZGVjb2%52lZC1zZWNyZXQtdm%46sdWV4ODY= # ends in x86",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:2"},
StartLine: 42,
EndLine: 42,
StartColumn: 2,
EndColumn: 44,
Entropy: 3.6381476,
},
{ // base64 encoded partially percent encoded value
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret=ZGVjb2RlZC0lNzMlNjUlNjMlNzIlNjUlNzQtdmFsdWU=",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:2"},
StartLine: 44,
EndLine: 44,
StartColumn: 2,
EndColumn: 52,
Entropy: 3.3037016,
},
{ // one of the lines above that went through... a lot
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nLook at this value: %4EjMzMjU2NkE2MzZENTYzMDUwNTY3MDQ4%4eTY2RDcwNjk0RDY5NTUzMTRENkQ3ODYx%25%34%65TE3QTQ2MzY1NzZDNjQ0RjY1NTY3MDU5NTU1ODUyNkI2MjUzNTUzMDRFNkU0RTZCNTYzMTU1MzkwQQ== # isn't it crazy?",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:hex", "decoded:base64", "decode-depth:7"},
StartLine: 47,
EndLine: 47,
StartColumn: 22,
EndColumn: 177,
Entropy: 3.3037016,
},
{ // Multi percent encode two random characters close to the bounds of the base64
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret=ZG%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%36%25%33%31%25%32%35%25%33%32%25%33%35%25%32%35%25%33%33%25%33%36%25%32%35%25%33%33%25%33%322RlZC1zZWNyZXQtd%25%36%64%25%34%36%25%37%33dWU=",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:5"},
StartLine: 50,
EndLine: 50,
StartColumn: 2,
EndColumn: 300,
Entropy: 3.3037016,
},
{ // The similar to the above but also touching the edge of the base64
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:4"},
StartLine: 52,
EndLine: 52,
StartColumn: 2,
EndColumn: 86,
Entropy: 3.3037016,
},
{ // The similar to the above but also touching and overlapping the base64
Description: "Overlapping",
Secret: "decoded-secret-value",
Match: "secret=decoded-secret-value",
File: "tmp.go",
Line: "\nsecret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34",
RuleID: "overlapping",
Tags: []string{"overlapping", "decoded:percent", "decoded:base64", "decode-depth:4"},
StartLine: 54,
EndLine: 54,
StartColumn: 2,
EndColumn: 88,
Entropy: 3.3037016,
}, },
}, },
}, },
} }
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 +1053,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 +1127,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 +1139,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 +1147,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 +1155,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 +1164,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 +1175,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 +1198,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 +1222,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 +1232,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 +1255,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 +1267,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 +1289,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 +1313,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 +1335,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 +1350,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,
}, },
} }
@@ -1135,7 +1359,7 @@ let password = 'Summer2024!';`
f := tc.fragment f := tc.fragment
f.Raw = raw f.Raw = raw
actual := d.detectRule(f, raw, rule, []EncodedSegment{}) actual := d.detectRule(f, raw, rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(tc.expected, actual); diff != "" { if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff) t.Errorf("diff: (-want +got)\n%s", diff)
} }
@@ -1189,7 +1413,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`),
@@ -1297,7 +1520,7 @@ func TestWindowsFileSeparator_RulePath(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
for name, test := range tests { for name, test := range tests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{}) actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" { if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff) t.Errorf("diff: (-want +got)\n%s", diff)
} }
@@ -1320,7 +1543,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 +1559,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 +1587,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 +1605,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 +1637,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 +1654,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 +1671,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 +1690,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(\\.*)?$`)},
@@ -1483,7 +1706,7 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
for name, test := range tests { for name, test := range tests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []EncodedSegment{}) actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" { if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff) t.Errorf("diff: (-want +got)\n%s", diff)
} }
+9
View File
@@ -7,6 +7,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time"
"github.com/h2non/filetype" "github.com/h2non/filetype"
@@ -90,6 +91,7 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
if pa.Symlink != "" { if pa.Symlink != "" {
fragment.SymlinkFile = pa.Symlink fragment.SymlinkFile = pa.Symlink
} }
if isWindows { if isWindows {
fragment.FilePath = filepath.ToSlash(pa.Path) fragment.FilePath = filepath.ToSlash(pa.Path)
fragment.SymlinkFile = filepath.ToSlash(fragment.SymlinkFile) fragment.SymlinkFile = filepath.ToSlash(fragment.SymlinkFile)
@@ -98,12 +100,19 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
fragment.FilePath = pa.Path fragment.FilePath = pa.Path
} }
timer := time.AfterFunc(SlowWarningThreshold, func() {
logger.Debug().Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
})
for _, finding := range d.Detect(fragment) { for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1 // need to add 1 since line counting starts at 1
finding.StartLine += (totalLines - linesInChunk) + 1 finding.StartLine += (totalLines - linesInChunk) + 1
finding.EndLine += (totalLines - linesInChunk) + 1 finding.EndLine += (totalLines - linesInChunk) + 1
d.AddFinding(finding) d.AddFinding(finding)
} }
if timer != nil {
timer.Stop()
timer = nil
}
} }
if err != nil { if err != nil {
+16 -3
View File
@@ -8,6 +8,7 @@ import (
"os/exec" "os/exec"
"regexp" "regexp"
"strings" "strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff" "github.com/gitleaks/go-gitdiff/gitdiff"
@@ -42,9 +43,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)
@@ -61,9 +64,19 @@ func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.
FilePath: gitdiffFile.NewName, FilePath: gitdiffFile.NewName,
} }
timer := time.AfterFunc(SlowWarningThreshold, func() {
logging.Debug().
Str("commit", commitSHA[:7]).
Str("path", fragment.FilePath).
Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
})
for _, finding := range d.Detect(fragment) { for _, finding := range d.Detect(fragment) {
d.AddFinding(augmentGitFinding(remote, finding, textFragment, gitdiffFile)) d.AddFinding(augmentGitFinding(remote, finding, textFragment, gitdiffFile))
} }
if timer != nil {
timer.Stop()
timer = nil
}
} }
return nil return nil
}) })
+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 {
@@ -70,7 +70,7 @@
# goes outside the bounds of the encoded value # goes outside the bounds of the encoded value
id = 'overlapping' id = 'overlapping'
description = 'Overlapping' description = 'Overlapping'
regex = '''secret=(decoded-secret-value)''' regex = '''secret=(decoded-secret-value\w*)'''
tags = ['overlapping'] tags = ['overlapping']
secretGroup = 1 secretGroup = 1
+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.
+6
View File
@@ -1,6 +1,12 @@
title = "gitleaks config" title = "gitleaks config"
# https://learnxinyminutes.com/docs/toml/ for toml reference # https://learnxinyminutes.com/docs/toml/ for toml reference
[[rules]]
description = "1Password Secret Key"
id = "1password-secret-key"
regex = '''A3-[A-Z0-9]{6}-(?:(?:[A-Z0-9]{11})|(?:[A-Z0-9]{6}-[A-Z0-9]{5}))-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}'''
tags = ["1Password"]
[[rules]] [[rules]]
description = "AWS Access Key" description = "AWS Access Key"
id = "aws-access-key" id = "aws-access-key"
+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.
@@ -0,0 +1,11 @@
# https://github.com/gitleaks/gitleaks/issues/1844
[extend]
useDefault = true
[[rules]]
id = "generic-api-key"
[[rules.allowlists]]
description = "Exclude a specific file from generic-api-key rule"
paths = [
'''^path/to/your/problematic/file\.js$'''
]
@@ -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"]