Compare commits

..
Author SHA1 Message Date
Zachary Rice 6eaf12267b the smartest filter 2025-10-07 09:21:44 -05:00
Zachary Rice 5f737c311b smart filter 2025-09-29 14:11:44 -05:00
Zachary Rice 4fb43823ef cant count 2025-07-20 11:14:25 -05:00
Zachary Rice b1c9c7ecbe Composite rules (#1905)
* composite rules

* add test config

* tests

* taking care of some pr comments

* naming
2025-07-20 11:13:38 -05:00
Hasnain Lakhani 72977e41b6 feat: add Anthropic API key detection (#1910)
Add detection rules for Anthropic API keys:
- anthropic-api-key: detects sk-ant-api03-... keys
- anthropic-admin-api-key: detects sk-ant-admin01-... keys

Both key types follow the pattern sk-ant-{type}-{93 chars}AA
and are detected as separate rules to align with gitleaks
patterns for multi-token providers.

The base regex patterns are aligned with what TruffleHog uses here: https://github.com/trufflesecurity/trufflehog/blob/main/pkg/detectors/anthropic/anthropic.go
2025-07-15 09:21:58 -05:00
Richard Gomez 7b02c98eb4 fix(git): handle port (#1912)
This fixes #1911
2025-07-14 19:00:48 -05:00
Zachary Rice 2a7bcffd7c dont prematurely calculate fragment newlines (#1909) 2025-07-08 20:48:55 -05:00
Richard Gomez bd79c3eaca feat(allowlist): promote optimizations (#1908) 2025-07-08 19:34:24 -05:00
Christophe Goessen 7fb4eda723 Fix: CVEs on go and go crypto (#1868)
* fix(CVE-2025-22871): update go to 1.23.8

* fix(CVE-2025-22869): update go crypto to 0.35.0
2025-07-08 09:13:33 -05:00
Christophe Goessen a044b815b3 feat: add artifactory reference token and api key detection (#1906)
* feat: add artifactory reference token and api key detection

* fix: match word boundary, add false positive tests

* fix: increase minimum entropy and fix tests
2025-07-07 20:11:05 -05:00
Zachary Rice bf380d4767 silly 2025-07-07 20:10:18 -05:00
Zachary Rice f487f85378 Update gitleaks.yml 2025-06-16 09:37:32 -05:00
Zach 958f55ac62 add just like that, no leaks 2025-06-08 19:51:04 -05:00
Zach c7acf33d96 Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-08 19:31:25 -05:00
Richard Gomez 9faaa4a09c Add experimental allowlist optimizations (#1731)
* feat(allowlist): optimization experiments

* refactor(allowlist): remove useOptimizations flag

* refactor(allowlist): simplify Validate() with helper func

* refactor(config): replace global feature flag
2025-06-08 10:33:05 -05:00
Lisa LinandRichard Gomez 79068b35e5 Detect Notion Public API Keys #1889 (#1890)
* add notion api rule

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

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

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

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

* change gitleaks toml

---------

Co-authored-by: Richard Gomez <32133502+rgmz@users.noreply.github.com>
2025-06-08 07:07:00 -05:00
Zach 80468eff1d Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-07 20:53:32 -05:00
Richard Gomez ef8223700a fix(atlassian): reduce false-positives for v1 pattern (#1892) 2025-06-07 20:33:34 -05:00
bplaxco 2463f11e71 Fix log suppresion issue (#1887)
The check for log suppresion enables archive scanning by default with no
max depth.
2025-06-05 08:26:06 -05:00
Kashif Khan 6f251eef65 Added Heroku API Key New Version (#1883)
* Added Heroku API Key New Version

* updated rule
2025-06-04 19:47:19 -05:00
Tilo Brueckner 20f9a1d4eb Add Platform Bitbucket (#1886) 2025-06-04 19:46:01 -05:00
Tilo Brueckner 722ce8213a Add Platform Gitea (#1884) 2025-06-04 09:15:06 -05:00
Zach 79780b884d Merge branch 'master' of github.com:gitleaks/gitleaks 2025-06-02 10:22:51 -05:00
Zachary Rice c5683ca6a3 prevent default warn message when max-archive-depth not set (#1881) 2025-06-01 12:10:45 -05:00
Zach 0357c3cbf6 prevent default warn message when max-archive-depth not set 2025-06-01 12:07:47 -05:00
30 changed files with 1400 additions and 96 deletions

No files matched your search

+3 -1
View File
@@ -1,5 +1,7 @@
name: gitleaks
on: [push, workflow_dispatch]
on:
push:
workflow_dispatch:
jobs:
scan:
name: gitleaks
+3 -1
View File
@@ -1,4 +1,4 @@
# This is NOT the default gitleaks config. The default gitleaks config is located
# This is NOT the default gitleaks config. The default gitleaks config is located
# here: https://github.com/gitleaks/gitleaks/blob/master/config/gitleaks.toml
# This gitleaks config extends the default config and ignores secrets located in the `cmd/generate/config/rules`
@@ -9,4 +9,6 @@ useDefault = true
[allowlist]
paths = [
'''(^|/)cmd/generate/config/rules''',
'''.*test\.go''',
'''testdata'''
]
+2
View File
@@ -940,3 +940,5 @@ e56870aecf8ac2733affc82e1ac25e3be9092db3:cmd/generate/config/rules/curl.go:gener
239e6323639b18ba8a1081f17788a658da075dd7:cmd/generate/config/rules/databricks.go:generic-api-key:22
c24a3a654b18d689732ec3199f0a19a254505b04:detect/detect_test.go:generic-api-key:52
c08cb1dc9aee87186dba4eebbc13b8aaa2351f0c:detect/detect_test.go:generic-api-key:52
ee0da5c7fa5f3c9a7f1617e162497199cac3537f:README.md:generic-api-key:480
782f3104786efdce0f809bce8a9ff31f2fa1c9ed:README.md:generic-api-key:481
+88
View File
@@ -415,6 +415,94 @@ Refer to the default [gitleaks config](https://github.com/gitleaks/gitleaks/blob
### Additional Configuration
#### Composite Rules (Multi-part or `required` Rules)
In v8.28.0 Gitleaks introduced composite rules, which are made up of a single "primary" rule and one or more auxiliary or `required` rules. To create a composite rule, add a `[[rules.required]]` table to the primary rule specifying an `id` and optionally `withinLines` and/or `withinColumns` proximity constraints. A fragment is a chunk of content that Gitleaks processes at once (typically a file, part of a file, or git diff), and proximity matching instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified area of the fragment.
**Proximity matching:** Using the `withinLines` and `withinColumns` fields instructs the primary rule to only report a finding if the auxiliary `required` rules also find matches within the specified proximity. You can set:
- **`withinLines: N`** - required findings must be within N lines (vertically)
- **`withinColumns: N`** - required findings must be within N characters (horizontally)
- **Both** - creates a rectangular search area (both constraints must be satisfied)
- **Neither** - fragment-level matching (required findings can be anywhere in the same fragment)
Here are diagrams illustrating each proximity behavior:
```
p = primary captured secret
a = auxiliary (required) captured secret
fragment = section of data gitleaks is looking at
*Fragment-level proximity*
Any required finding in the fragment
┌────────┐
┌──────┤fragment├─────┐
│ └──────┬─┤ │ ┌───────┐
│ │a│◀────┼─│✓ MATCH│
│ ┌─┐└─┘ │ └───────┘
│┌─┐ │p│ │
││a│ ┌─┐└─┘ │ ┌───────┐
│└─┘ │a│◀──────────┼─│✓ MATCH│
└─▲─────┴─┴───────────┘ └───────┘
│ ┌───────┐
└────│✓ MATCH│
└───────┘
*Column bounded proximity*
`withinColumns = 3`
┌────────┐
┌────┬─┤fragment├─┬───┐
│ └──────┬─┤ │ ┌───────────┐
│ │ │a│◀┼───┼─│+1C ✓ MATCH│
│ ┌─┐└─┘ │ └───────────┘
│┌─┐ │ │p│ │ │
┌──▶│a│ ┌─┐ └─┘ │ ┌───────────┐
│ │└─┘ ││a│◀────────┼───┼─│-2C ✓ MATCH│
│ │ ┘ │ └───────────┘
│ └── -3C ───0C─── +3C ─┘
│ ┌─────────┐
│ │ -4C ✗ NO│
└──│ MATCH │
└─────────┘
*Line bounded proximity*
`withinLines = 4`
┌────────┐
┌─────┤fragment├─────┐
+4L─ ─ ┴────────┘─ ─ ─│
│ │
│ ┌─┐ │ ┌────────────┐
│ ┌─┐ │a│◀──┼─│+1L ✓ MATCH │
0L ┌─┐ │p│ └─┘ │ ├────────────┤
│ │a│◀──┴─┴────────┼─│-1L ✓ MATCH │
│ └─┘ │ └────────────┘
│ │ ┌─────────┐
-4L─ ─ ─ ─ ─ ─ ─ ─┌─┐─│ │-5L ✗ NO │
│ │a│◀┼─│ MATCH │
└────────────────┴─┴─┘ └─────────┘
*Line and column bounded proximity*
`withinLines = 4`
`withinColumns = 3`
┌────────┐
┌─────┤fragment├─────┐
+4L ┌└────────┴ ┐ │
│ ┌─┐ │ ┌───────────────┐
│ │ │a│◀┼───┼─│+2L/+1C ✓ MATCH│
│ ┌─┐└─┘ │ └───────────────┘
0L │ │p│ │ │
│ └─┘ │
│ │ │ │ ┌────────────┐
-4L ─ ─ ─ ─ ─ ─┌─┐ │ │-5L/+3C ✗ NO│
│ │a│◀┼─│ MATCH │
└───-3C────0L───+3C┴─┘ └────────────┘
```
<details><summary>Some final quick thoughts on composite rules.</summary>This is an experimental feature! It's subject to change so don't go sellin' a new B2B SaaS feature built ontop of this feature. Scan type (git vs dir) based context is interesting. I'm monitoring the situation. Composite rules might not be super useful for git scans because gitleaks only looks at additions in the git history. It could be useful to scan non-additions in git history for `required` rules. Oh, right this is a readme, I'll shut up now.</details>
#### gitleaks:allow
If you are knowingly committing a test secret that gitleaks will catch you can add a `gitleaks:allow` comment to that line which will instruct gitleaks
+17 -8
View File
@@ -35,6 +35,10 @@ func main() {
rules.AlgoliaApiKey(),
rules.AlibabaAccessKey(),
rules.AlibabaSecretKey(),
rules.AnthropicAdminApiKey(),
rules.AnthropicApiKey(),
rules.ArtifactoryApiKey(),
rules.ArtifactoryReferenceToken(),
rules.AsanaClientID(),
rules.AsanaClientSecret(),
rules.Atlassian(),
@@ -125,6 +129,7 @@ func main() {
rules.HashiCorpTerraform(),
rules.HashicorpField(),
rules.Heroku(),
rules.HerokuV2(),
rules.HubSpot(),
rules.HuggingFaceAccessToken(),
rules.HuggingFaceOrganizationApiToken(),
@@ -160,6 +165,7 @@ func main() {
rules.NewRelicUserKey(),
rules.NewRelicBrowserAPIKey(),
rules.NewRelicInsertKey(),
rules.Notion(),
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
@@ -248,7 +254,6 @@ func main() {
Str("rule-id", rule.RuleID).
Msg("Failed to validate rule")
}
sortRule(rule)
// check if rule is in ruleLookUp
if _, ok := ruleLookUp[rule.RuleID]; ok {
@@ -259,6 +264,13 @@ func main() {
// TODO: eventually change all the signatures to get ride of this
// nasty dereferencing.
ruleLookUp[rule.RuleID] = *rule
// Slices are de-duplicated with a map, every iteration has a different order.
// This is an awkward workaround.
for _, allowlist := range rule.Allowlists {
slices.Sort(allowlist.Commits)
slices.Sort(allowlist.StopWords)
}
}
tmpl, err := template.ParseFiles(templatePath)
@@ -274,14 +286,11 @@ func main() {
cfg := base.CreateGlobalConfig()
cfg.Rules = ruleLookUp
for _, allowlist := range cfg.Allowlists {
slices.Sort(allowlist.Commits)
slices.Sort(allowlist.StopWords)
}
if err = tmpl.Execute(f, cfg); err != nil {
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)
}
}
+69
View File
@@ -0,0 +1,69 @@
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"
)
func AnthropicApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "anthropic-api-key",
Description: "Identified an Anthropic API Key, which may compromise AI assistant integrations and expose sensitive data to unauthorized access.",
Regex: utils.GenerateUniqueTokenRegex(`sk-ant-api03-[a-zA-Z0-9_\-]{93}AA`, false),
Keywords: []string{
"sk-ant-api03",
},
}
// validate
tps := []string{
// Valid API key example
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
// Generate additional random test keys
utils.GenerateSampleSecret("anthropic", "sk-ant-api03-"+secrets.NewSecret(utils.AlphaNumericExtendedShort("93"))+"AA"),
}
fps := []string{
// Too short key (missing characters)
"sk-ant-api03-abc123xyz-456de-klMnopqrstuvwx-3456yza789bcde-1234fghijklmnopAA",
// Wrong suffix
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzBB",
// Wrong prefix (admin key, not API key)
"sk-ant-admin01-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
}
return utils.Validate(r, tps, fps)
}
func AnthropicAdminApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "anthropic-admin-api-key",
Description: "Detected an Anthropic Admin API Key, risking unauthorized access to administrative functions and sensitive AI model configurations.",
Regex: utils.GenerateUniqueTokenRegex(`sk-ant-admin01-[a-zA-Z0-9_\-]{93}AA`, false),
Keywords: []string{
"sk-ant-admin01",
},
}
// validate
tps := []string{
// Valid admin key example
"sk-ant-admin01-abc12fake-456def789ghij-klmnopqrstuvwx-3456yza789bcde-12fakehijklmnopby56aaaogaopaaaabc123xyzAA",
// Generate additional random test keys
utils.GenerateSampleSecret("anthropic", "sk-ant-admin01-"+secrets.NewSecret(utils.AlphaNumericExtendedShort("93"))+"AA"),
}
fps := []string{
// Too short key (missing characters)
"sk-ant-admin01-abc123xyz-456de-klMnopqrstuvwx-3456yza789bcde-1234fghijklmnopAA",
// Wrong suffix
"sk-ant-admin01-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzBB",
// Wrong prefix (API key, not admin key)
"sk-ant-api03-abc123xyz-456def789ghij-klmnopqrstuvwx-3456yza789bcde-1234fghijklmnopby56aaaogaopaaaabc123xyzAA",
}
return utils.Validate(r, tps, fps)
}
+58
View File
@@ -0,0 +1,58 @@
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 ArtifactoryApiKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "artifactory-api-key",
Description: "Detected an Artifactory api key, posing a risk unauthorized access to the central repository.",
Regex: regexp.MustCompile(`\bAKCp[A-Za-z0-9]{69}\b`),
Entropy: 4.5,
Keywords: []string{"AKCp"},
}
// validate
tps := []string{
"artifactoryApiKey := \"AKCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "\"",
}
// false positives
fps := []string{
`lowEntropy := AKCpXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
"wrongStart := \"AkCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "\"",
"wrongLength := \"AkCp" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
"partOfAlongUnrelatedBlob gYnkgAkCp" + secrets.NewSecret(utils.AlphaNumeric("69")) + "VyZSB2",
}
return utils.Validate(r, tps, fps)
}
func ArtifactoryReferenceToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "artifactory-reference-token",
Description: "Detected an Artifactory reference token, posing a risk of impersonation and unauthorized access to the central repository.",
Regex: regexp.MustCompile(`\bcmVmd[A-Za-z0-9]{59}\b`),
Entropy: 4.5,
Keywords: []string{"cmVmd"},
}
// validate
tps := []string{
"artifactoryRefToken := \"cmVmd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
}
// false positives
fps := []string{
`lowEntropy := cmVmdXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`,
"wrongStart := \"cmVMd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "\"",
"wrongLength := \"cmVmd" + secrets.NewSecret(utils.AlphaNumeric("49")) + "\"",
"partOfAlongUnrelatedBlob gYnkgcmVmd" + secrets.NewSecret(utils.AlphaNumeric("59")) + "VyZSB2",
}
return utils.Validate(r, tps, fps)
}
+10 -7
View File
@@ -13,9 +13,9 @@ func Atlassian() *config.Rule {
RuleID: "atlassian-api-token",
Regex: utils.MergeRegexps(
utils.GenerateSemiGenericRegex(
[]string{"atlassian", "confluence", "jira"},
`[a-zA-Z0-9]{24}`,
false,
[]string{"(?-i:ATLASSIAN|[Aa]tlassian)", "(?-i:CONFLUENCE|[Cc]onfluence)", "(?-i:JIRA|[Jj]ira)"},
`[a-z0-9]{20}[a-f0-9]{4}`, // The last 4 characters are an MD5 hash.
true,
),
utils.GenerateUniqueTokenRegex(`ATATT3[A-Za-z0-9_\-=]{186}`, false),
),
@@ -24,10 +24,13 @@ func Atlassian() *config.Rule {
}
// validate
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("24")))
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("24")))...)
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("24")))...)
tps := utils.GenerateSampleSecrets("atlassian", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))
tps = append(tps, utils.GenerateSampleSecrets("confluence", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
tps = append(tps, utils.GenerateSampleSecrets("jira", secrets.NewSecret(utils.AlphaNumeric("20")+"[a-f0-9]{4}"))...)
tps = append(tps, `JIRA_API_TOKEN=HXe8DGg1iJd2AopzyxkFB7F2`)
tps = append(tps, utils.GenerateSampleSecrets("jira", "ATATT3xFfGF0K3irG5tKKi-6u-wwaXQFeGwZ-IHR-hQ3CulkKtMSuteRQFfLZ6jihHThzZCg_UjnDt-4Wl_gIRf4zrZJs5JqaeuBhsfJ4W5GD6yGg3W7903gbvaxZPBjxIQQ7BgFDSkPS8oPispw4KLz56mdK-G6CIvLO6hHRrZHY0Q3tvJ6JxE=C63992E6")...)
return utils.Validate(r, tps, nil)
fps := []string{"getPagesInConfluenceSpace,searchConfluenceUsingCql"}
return utils.Validate(r, tps, fps)
}
+19
View File
@@ -24,3 +24,22 @@ func Heroku() *config.Rule {
)
return utils.Validate(r, tps, nil)
}
func HerokuV2() *config.Rule {
// define rule
r := config.Rule{
Description: "Detected a Heroku API Key, potentially compromising cloud application deployments and operational security.",
RuleID: "heroku-api-key-v2",
Regex: utils.GenerateUniqueTokenRegex(`(HRKU-AA[0-9a-zA-Z_-]{58})`, false),
Entropy: 4,
Keywords: []string{"HRKU-AA"},
}
// validate
tps := utils.GenerateSampleSecrets("heroku", secrets.NewSecret(`\b(HRKU-AA[0-9a-zA-Z_-]{58})\b`))
tps = append(tps,
`const KEY = "HRKU-AAlQ1aVoHDujJ9QsDHdHlHO0hbzhoERRSO45ZQusSYHg_____w4_hLrAym_u""`,
`API_Key = "HRKU-AAy9Ppr_HD2pPuTyIiTYInO0hbzhoERRSO93ZQusSYHgaD7_WQ07FnF7L9FX"`,
)
return utils.Validate(r, tps, nil)
}
+39
View File
@@ -0,0 +1,39 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/config"
)
func Notion() *config.Rule {
// Define the identifiers that match the Keywords
identifiers := []string{"ntn_"}
// Define the regex pattern for Notion API token
secretRegex := `ntn_[0-9]{11}[A-Za-z0-9]{32}[A-Za-z0-9]{3}`
regex := utils.GenerateUniqueTokenRegex(secretRegex, false)
r := config.Rule{
Description: "Notion API token",
RuleID: "notion-api-token",
Regex: regex,
Entropy: 4,
Keywords: identifiers,
}
// validate
tps := []string{
"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",
"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",
"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",
}
fps:= []string{
"ntn_12345678901",
"ntn_123456789012345678901234567890123456789012345678901234567890",
"ntn_12345678901abc",
}
return utils.Validate(r, tps, fps)
}
+5
View File
@@ -88,5 +88,10 @@ func createSingleRuleDetector(r *config.Rule) *detect.Detector {
cfg := base.CreateGlobalConfig()
cfg.Rules = rules
cfg.Keywords = uniqueKeywords
for _, a := range cfg.Allowlists {
if err := a.Validate(); err != nil {
logging.Fatal().Err(err).Msg("invalid global allowlist")
}
}
return detect.NewDetector(cfg)
}
+1
View File
@@ -222,6 +222,7 @@ func Config(cmd *cobra.Command) config.Config {
if err := viper.Unmarshal(&vc); err != nil {
logging.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
logging.Fatal().Err(err).Msg("Failed to load config")
+8
View File
@@ -13,6 +13,8 @@ const (
GitHubPlatform
GitLabPlatform
AzureDevOpsPlatform
GiteaPlatform
BitbucketPlatform
// TODO: Add others.
)
@@ -23,6 +25,8 @@ func (p Platform) String() string {
"github",
"gitlab",
"azuredevops",
"gitea",
"bitbucket",
}[p]
}
@@ -38,6 +42,10 @@ func PlatformFromString(s string) (Platform, error) {
return GitLabPlatform, nil
case "azuredevops":
return AzureDevOpsPlatform, nil
case "gitea":
return GiteaPlatform, nil
case "bitbucket":
return BitbucketPlatform, nil
default:
return UnknownPlatform, fmt.Errorf("invalid scm platform value: %s", s)
}
+56 -14
View File
@@ -4,6 +4,7 @@ import (
"errors"
"strings"
ahocorasick "github.com/BobuSumisu/aho-corasick"
"golang.org/x/exp/maps"
"github.com/zricethezav/gitleaks/v8/regexp"
@@ -29,10 +30,10 @@ type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// MatchCondition determines whether all criteria must match.
// MatchCondition determines whether all criteria must match. Defaults to "OR".
MatchCondition AllowlistMatchCondition
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
// Paths is a slice of path regular expressions that are allowed to be ignored.
@@ -57,6 +58,13 @@ type Allowlist struct {
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
// commitMap is a normalized version of Commits, used for efficiency purposes.
// TODO: possible optimizations so that both short and long hashes work.
commitMap map[string]struct{}
regexPat *regexp.Regexp
pathPat *regexp.Regexp
stopwordTrie *ahocorasick.Trie
}
func (a *Allowlist) Validate() error {
@@ -76,16 +84,29 @@ func (a *Allowlist) Validate() error {
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
uniqueCommits[commit] = struct{}{}
// Commits are case-insensitive.
uniqueCommits[strings.TrimSpace(strings.ToLower(commit))] = struct{}{}
}
a.Commits = maps.Keys(uniqueCommits)
a.commitMap = uniqueCommits
}
if len(a.StopWords) > 0 {
uniqueStopwords := make(map[string]struct{})
for _, stopWord := range a.StopWords {
uniqueStopwords[stopWord] = struct{}{}
uniqueStopwords[strings.ToLower(stopWord)] = struct{}{}
}
a.StopWords = maps.Keys(uniqueStopwords)
values := maps.Keys(uniqueStopwords)
a.StopWords = values
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
}
// Combine patterns into a single expression.
if len(a.Paths) > 0 {
a.pathPat = joinRegexOr(a.Paths)
}
if len(a.Regexes) > 0 {
a.regexPat = joinRegexOr(a.Regexes)
}
a.validated = true
@@ -97,10 +118,15 @@ func (a *Allowlist) CommitAllowed(c string) (bool, string) {
if a == nil || c == "" {
return false, ""
}
for _, commit := range a.Commits {
if commit == c {
return true, c
if a.commitMap != nil {
if _, ok := a.commitMap[strings.ToLower(c)]; ok {
return true, ""
}
} else if len(a.Commits) > 0 {
for _, commit := range a.Commits {
if commit == c {
return true, c
}
}
}
return false, ""
@@ -111,7 +137,12 @@ func (a *Allowlist) PathAllowed(path string) bool {
if a == nil || path == "" {
return false
}
return anyRegexMatch(path, a.Paths)
if a.pathPat != nil {
return a.pathPat.MatchString(path)
} else if len(a.Paths) > 0 {
return anyRegexMatch(path, a.Paths)
}
return false
}
// RegexAllowed returns true if the regex is allowed to be ignored.
@@ -119,7 +150,12 @@ func (a *Allowlist) RegexAllowed(secret string) bool {
if a == nil || secret == "" {
return false
}
return anyRegexMatch(secret, a.Regexes)
if a.regexPat != nil {
return a.regexPat.MatchString(secret)
} else if len(a.Regexes) > 0 {
return anyRegexMatch(secret, a.Regexes)
}
return false
}
func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
@@ -128,9 +164,15 @@ func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
}
s = strings.ToLower(s)
for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) {
return true, stopWord
if a.stopwordTrie != nil {
if m := a.stopwordTrie.MatchFirstString(s); m != nil {
return true, m.MatchString()
}
} else if len(a.StopWords) > 0 {
for _, stopWord := range a.StopWords {
if strings.Contains(s, stopWord) {
return true, stopWord
}
}
}
return false, ""
+225 -3
View File
@@ -113,8 +113,8 @@ func TestValidate(t *testing.T) {
StopWords: []string{"stopwordA", "stopwordB", "stopwordA"},
},
expected: Allowlist{
Commits: []string{"commitA", "commitB"},
StopWords: []string{"stopwordA", "stopwordB"},
Commits: []string{"commita", "commitb"},
StopWords: []string{"stopworda", "stopwordb"},
},
},
}
@@ -151,8 +151,230 @@ func TestValidate(t *testing.T) {
cmpopts.IgnoreUnexported(Allowlist{}),
}
)
if diff := cmp.Diff(tt.input, tt.expected, opts); diff != "" {
if diff := cmp.Diff(tt.expected, tt.input, opts); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
}
}
var benchCommitAllowlist = func() *Allowlist {
allowlist := Allowlist{
Commits: []string{
"ba1beca8ac634d8b202e0daffebecceeb6dda2fc",
"74b19abcd33ff3a6cac8aebdcfccacde9ad40f5c",
"11ed23ff2df37b2c114ac13dbd902e3bdb8b9c63",
"d39bcd0ebd3c9fb8d2f1bfbc98fc92bceeb3eed3",
"faf321cf8f9f2cf654fab12f72ef64e6ffb7237e",
"5486ce1abcdfcc862efeb6f5071a1ddef0fb3926",
"fbcfdbdffdabf1c0f627ecdfcda91ca8c1b533ce",
"3db86dce50f1d99fe820a4bf42ffedaefedb1bcf",
"18ccec6cb316ce1abed9e8ec262ecd3dd4a3e222",
"20f1cc29eaa028e7e6bcdc82f2103c1af3899c5c",
"d90b5572e9bdb0cebf5edc3ad412c38ecd6b8ca6",
"a0c7a0addf82d2a84babdd8be1f3cee887cb69cf",
"0c3c967d21bca179e2d60b738fab848be9a65a45",
"85cb3ac8817afad5ffde45a29036f4a1fa8af2eb",
"cb9c19a9dcb05bebca7dacbed9b8afefeb2dc5ad",
"4bac7b9fbdc851caf3c5f0cece85acaa3ebb7fd2",
"ad2bfd0c271bbb1ac991fdfefcabb6dcc43cb3f5",
"0c522c2750ec2fdf134721ea6000841fed5ffdd1",
"fedbf91dddc017f9994edc7f3a75dcd9eabfdd2c",
"9e5205bdeb080d84bfb25dfcc86dccc3fe5be499",
"b5476d7901b105c2fdb5fc87a9f4fabdb40daf81",
"f8fdbc509fb3c3ef1c1cbe8e70ac933ac4109cc3",
"92727ea97463cd55eed3069ab54483ba20b94f3c",
"e4a01ce6fdb6f6a39d2c781f7dcba3ae37973d0b",
"dcdd273bdf8159faf60bfca6b2a20a98a9985cf3",
"3f1efb9b7705cc1cae9ebeafa8eaf95ab79d6bea",
"20831ce7da9e2cb78ad8cd2a73ca693d8ffaee9c",
"edffec40aa85fbf947b20b3ffcfe6e7f6a94d017",
"cfbbc60acefdc1f04ad26e022fba21f72ce5c25b",
"3beac0da108cbb4fac1ebcd060ba2b67aafbefdd",
"21a87495e1f1f4ee9d9dfab1c3e5ffbe4b6e7dba",
"a2a3e8ba9dcae74d7bc1267f07fec3a44a0c9b08",
"abe2c2ff0a9befc1cbae77ea6aebf8d3a46ee68f",
"9f9e4cea3bee21deb769f830bcf76185eba76ab6",
"48e2f92ccdd1cb33e10eba117386cb054e06f2e0",
"4e10cc0ae797adce6cec0beda8782b28ba2dcf8c",
"7d6eb5bc7bbee783ab012ee290f8b9acabe38367",
"bc5d1b99fd2cbacb225e574fd05c57a3f44ca35c",
"9a3ea6fd3dcfd135ea3b9bc63ab6494f5c54faaf",
"fc62eec1f10e646ec9a8dacaddf1becae7e31823",
"fd01d7f4dab422fba5b9abfeacee14aad6db0dee",
"d7a2bcbcab6a4f4af02dde8ceeef5b6ab0fd6ca5",
"0b1bf0ebfc1cca19eeb029cfb8e4abd8e72d82df",
"a1ea3f771dfbae1cadbc67c803b8b07081f3fdd0",
"78dfa84c70545f295b3b8fa3f8bd53d316ff682e",
"ca595eebf56ad6f118be2c5ddbeadac675a588ad",
"faadceaec7d0bb9cbef7e7f6cddc3a0fdb8e33b8",
"0b006e37964c7b1e3cdbafd21fe8e887886cb909",
"dffb3dfb72fa42ed49a69dae3838eaaf2a957ee0",
"2d927ebda284a25fb2cd8fc0dd42c9b7d333db5a",
"ffca0cdcbe9e33fd18a3bf692ea0f2a62d685aa4",
"ac0d9a8adbe32cbe7f99fdeccf22b5bf767d06fa",
"f4a2a0a2833f4cbcc2db2accd7cc4feacdeeeaed",
"5f4a1e0dcbd49ed99eadf4bf837f1efafea663c1",
"3e69fb30ea6761771f877d82ef8ee799eb1f56a0",
"2e13cb4dec42ca80918e2bdefb5df96bf9b1eebc",
"d480ed3e25cb82782bb6b3f0fffce8f7c3d9840b",
"7bd34bf663bd5900f0be9accb2091e3dc4a378bc",
"a9fdc3ccc7cfd3b2a73b55b957bbe73beedba2ea",
"b7ca933acc3ef5c8c5bfaede6bfc4f9acc7f4f39",
"248a04fea1bfc38f4a1b76ea4ce399ef0affe4cb",
"8ae496b4fb06c46ae5bfcdceda5e9773ca9ce25b",
"0ac468471f71e8d17c21eb9fe4d922549e13bc3a",
"db082f214cdbff93cdaefebabae455f2ed994730",
"df0c6eabe5ccffed0bf840f3c45a8fdf39c04f9b",
"aacaadfd5bd1e9efd6fc8a9b7ad8fe93ec3bbf23",
"4e9cbeaabc66d01da99cd85cbaf8db5bfaccf5c4",
"28b39fd14b2c8dbeab86aea69de0b5ccdf4ff7b2",
"a20ebfbef4c75e906a114eaad6a67deadb810ed9",
"f8fd3b4cd75b6fc28e21289e6d4ef7c4c7f22f68",
"ccf7e03c5f5c7d6fdbd9fbde2fd342ae15cbbe4e",
"cdcbcfe7c6d4cee31a27f338d1ff66d3cad4bbd5",
"d7c03aba693ba8de8aaea7fa9d8d46a733cd5989",
"48e3f4abb26eb44eefcaf3f188cea00cce46ddc1",
"c1a9c25e5e29804abbc8a0fccf1faf384fea28a5",
"f9e090c6b2af0ee3bde57f4a0352f5b02e675d35",
"1df2354e9eee4934c34dcbd2de0b1df9b5dcadac",
"7da5ad4d8fa965ea4aa4613a9dc4eabdc3406eeb",
"fe33bfb676572e7fafd8ae9ea88e0efa3c109bdd",
"fefeea80b187eefce0a9c184cb76976c2fcef98a",
"eea8efae44ab9eb43a5954df7fa63bb55fa1d8dc",
"f559c7bbe6b6bfba56e7f362604c721c2fee6d0d",
"bf1dbe006b93fb443aebbe77a2c9cfdfc3f6a6a0",
"cfd00d87f7bc44ed7bdcebbf493869a495ebfef8",
"7ca45a388fd9aaeb8ed7701c2af2beff9e52eebb",
"ca47c2fdb73b2d39a1eab115dffa1ef7a5ffacd0",
"cc0954dfddaabb996abc78c28dff83f7e3edb828",
"ad4adc1195dabcfaf0f7eaac4f3f3f6b152d7fd4",
"ab3e6b6ed2eb6dcd4ae4fd0db76efdecd72ecfaa",
"d16ccd31d433f7a41eceb7d544081c72b4d9bf3e",
"d0dbe09bb150bbd5bb4b85adc273df87350e7e6c",
"492bbbcaf6edd864dd3ca0aee5d4d60b1cd4214b",
"d73dbbe7a9effb828793a3adad04cecb1843ccbd",
"89b12dcbfc40e30ddecd7a19e0cf1e32a29ebccb",
"1cd815bd965ee0fd2e15bbe28c94688f15ebb3ad",
"a7f9b3babda7abfe0316bf7aeded7df7cfcf7bdf",
"9e832d5ebecc2e5aead9b5cdcdd6d2ba4dfeaee7",
"43fa54761faa5f8beffe9acfd402fcd24dfede71",
"dada4b08ae4aa37cff754b4ca29ebc134c54bac1",
"1b708f1fad29cc62bc39ae5dda8e9124acc00d2d",
},
}
_ = allowlist.Validate()
return &allowlist
}()
func BenchmarkCommitAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok, _ := benchCommitAllowlist.CommitAllowed("d0dbe09bb150bbd5bb4b85adc273df87350e7e6c")
assert.True(b, ok)
}
}
func BenchmarkCommitNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok, _ := benchCommitAllowlist.CommitAllowed("5fe58bf0b0be1735ad27aa6053b56323a905c223")
assert.False(b, ok)
}
}
var benchRegexAllowlist = func() *Allowlist {
a := Allowlist{
RegexTarget: "match",
Regexes: []*regexp.Regexp{
// Based on patterns from `generic.go`
regexp.MustCompile(`(?i)access(ibility|or)`),
regexp.MustCompile(`(?i)access[_.-]?id`),
regexp.MustCompile(`(?i)random[_.-]?access`),
regexp.MustCompile(`(?i)api[_.-]?(id|name|version)`),
regexp.MustCompile(`(?i)rapid|capital`),
regexp.MustCompile(`(?i)[a-z0-9-]*?api[a-z0-9-]*?:jar:`),
regexp.MustCompile(`(?i)author`),
regexp.MustCompile(`(?i)X-MS-Exchange-Organization-Auth`),
regexp.MustCompile(`(?i)Authentication-Results`),
regexp.MustCompile(`(?i)(credentials?[_.-]?id|withCredentials)`),
regexp.MustCompile(`(?i)(bucket|foreign|hot|idx|natural|primary|pub(lic)?|schema|sequence)[_.-]?key`),
regexp.MustCompile(`(?i)key[_.-]?(alias|board|code|frame|id|length|mesh|name|pair|ring|selector|signature|size|stone|storetype|word|up|down|left|right)`),
regexp.MustCompile(`(?i)key[_.-]?vault[_.-]?(id|name)|keyVaultToStoreSecrets`),
regexp.MustCompile(`(?i)key(store|tab)[_.-]?(file|path)`),
regexp.MustCompile(`(?i)issuerkeyhash`),
regexp.MustCompile(`(?i)(?-i:[DdMm]onkey|[DM]ONKEY)|keying`),
regexp.MustCompile(`(?i)(secret)[_.-]?(length|name|size)`),
regexp.MustCompile(`(?i)UserSecretsId`),
regexp.MustCompile(`(?i)(io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)`),
regexp.MustCompile(`(?i)(api|credentials|token)[_.-]?(endpoint|ur[il])`),
regexp.MustCompile(`(?i)public[_.-]?token`),
regexp.MustCompile(`(?i)(key|token)[_.-]?file`),
regexp.MustCompile(`([A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(\n|\z)`),
regexp.MustCompile(`([A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(\n|\z)`),
},
}
_ = a.Validate()
return &a
}()
func BenchmarkRegexAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchRegexAllowlist.RegexAllowed(`environment {
CREDENTIALS_ID = "K8S_CRED"
}`)
assert.True(b, ok)
}
}
func BenchmarkRegexNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchRegexAllowlist.RegexAllowed(`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`)
assert.False(b, ok)
}
}
var benchPathAllowlist = func() *Allowlist {
a := Allowlist{
Paths: []*regexp.Regexp{
// Copied from `base/config.go`
regexp.MustCompile(`gitleaks\.toml`),
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`),
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`),
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
regexp.MustCompile(`go\.(mod|sum|work(\.sum)?)$`),
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(`(^|/)gradlew(\.bat)?$`),
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
regexp.MustCompile(`(^|/)(angular|bootstrap|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
regexp.MustCompile(`(^|/)javascript\.json$`),
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
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)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
regexp.MustCompile(`\.gem$`),
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
},
}
_ = a.Validate()
return &a
}()
func BenchmarkPathAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchPathAllowlist.PathAllowed(`src/main/resources/static/js/jquery-ui-1.10.4.min.js`)
assert.True(b, ok)
}
}
func BenchmarkPathNotAllowed(b *testing.B) {
for n := 0; n < b.N; n++ {
ok := benchPathAllowlist.PathAllowed(`azure_scale_templates/sub_modules/vpc_template/inputs.auto.tfvars.json_backup`)
assert.False(b, ok)
}
}
+47 -10
View File
@@ -43,15 +43,26 @@ type ViperConfig struct {
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport bool
SmartFilter bool
}
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperGlobalAllowlist
AllowList *viperGlobalAllowlist
Allowlists []*viperGlobalAllowlist
}
type viperRequired struct {
ID string
WithinLines *int `mapstructure:"withinLines"`
WithinColumns *int `mapstructure:"withinColumns"`
}
type viperRuleAllowlist struct {
Description string
Condition string
@@ -130,6 +141,8 @@ func (vc *ViperConfig) Translate() (Config, error) {
Path: pathPat,
Keywords: vr.Keywords,
Tags: vr.Tags,
SkipReport: vr.SkipReport,
SmartFilter: vr.SmartFilter,
}
// Parse the rule allowlists, including the older format for backwards compatibility.
@@ -141,16 +154,40 @@ func (vc *ViperConfig) Translate() (Config, error) {
vr.Allowlists = append(vr.Allowlists, vr.AllowList)
}
for _, a := range vr.Allowlists {
allowlist, err := parseAllowlist(a)
allowlist, err := vc.parseAllowlist(a)
if err != nil {
return Config{}, fmt.Errorf("%s: [[rules.allowlists]] %w", cr.RuleID, err)
}
cr.Allowlists = append(cr.Allowlists, allowlist)
}
for _, r := range vr.Required {
if r.ID == "" {
return Config{}, fmt.Errorf("%s: [[rules.required]] rule ID is empty", cr.RuleID)
}
requiredRule := Required{
RuleID: r.ID,
WithinLines: r.WithinLines,
WithinColumns: r.WithinColumns,
// Distance: r.Distance,
}
cr.RequiredRules = append(cr.RequiredRules, &requiredRule)
}
orderedRules = append(orderedRules, cr.RuleID)
rulesMap[cr.RuleID] = cr
}
// after all the rules have been processed, let's ensure the required rules
// actually exist.
for _, r := range rulesMap {
for _, rr := range r.RequiredRules {
if _, ok := rulesMap[rr.RuleID]; !ok {
return Config{}, fmt.Errorf("%s: [[rules.required]] rule ID '%s' does not exist", r.RuleID, rr.RuleID)
}
}
}
// Assemble the config.
c := Config{
Title: vc.Title,
@@ -169,7 +206,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
vc.Allowlists = append(vc.Allowlists, vc.AllowList)
}
for _, a := range vc.Allowlists {
allowlist, err := parseAllowlist(&a.viperRuleAllowlist)
allowlist, err := vc.parseAllowlist(&a.viperRuleAllowlist)
if err != nil {
return Config{}, fmt.Errorf("[[allowlists]] %w", err)
}
@@ -190,11 +227,11 @@ func (vc *ViperConfig) Translate() (Config, error) {
return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
}
if c.Extend.UseDefault {
if err := c.extendDefault(); err != nil {
if err := c.extendDefault(vc); err != nil {
return Config{}, err
}
} else if c.Extend.Path != "" {
if err := c.extendPath(); err != nil {
if err := c.extendPath(vc); err != nil {
return Config{}, err
}
}
@@ -222,7 +259,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
return c, nil
}
func parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
var matchCondition AllowlistMatchCondition
switch strings.ToUpper(a.Condition) {
case "AND", "&&":
@@ -279,7 +316,7 @@ func (c *Config) GetOrderedRules() []Rule {
return orderedRules
}
func (c *Config) extendDefault() error {
func (c *Config) extendDefault(parent *ViperConfig) error {
extendDepth++
viper.SetConfigType("toml")
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
@@ -299,7 +336,7 @@ func (c *Config) extendDefault() error {
return nil
}
func (c *Config) extendPath() error {
func (c *Config) extendPath(parent *ViperConfig) error {
extendDepth++
viper.SetConfigFile(c.Extend.Path)
if err := viper.ReadInConfig(); err != nil {
+43 -2
View File
@@ -59,8 +59,8 @@ regexes = [
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
stopwords = [
"abcdefghijklmnopqrstuvwxyz",
"014df517-39d1-4453-b7b3-9930c563627c",
"abcdefghijklmnopqrstuvwxyz",
]
[[rules]]
@@ -129,6 +129,32 @@ regex = '''(?i)[\w.-]{0,50}?(?:alibaba)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,
entropy = 2
keywords = ["alibaba"]
[[rules]]
id = "anthropic-admin-api-key"
description = "Detected an Anthropic Admin API Key, risking unauthorized access to administrative functions and sensitive AI model configurations."
regex = '''\b(sk-ant-admin01-[a-zA-Z0-9_\-]{93}AA)(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["sk-ant-admin01"]
[[rules]]
id = "anthropic-api-key"
description = "Identified an Anthropic API Key, which may compromise AI assistant integrations and expose sensitive data to unauthorized access."
regex = '''\b(sk-ant-api03-[a-zA-Z0-9_\-]{93}AA)(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["sk-ant-api03"]
[[rules]]
id = "artifactory-api-key"
description = "Detected an Artifactory api key, posing a risk unauthorized access to the central repository."
regex = '''\bAKCp[A-Za-z0-9]{69}\b'''
entropy = 4.5
keywords = ["akcp"]
[[rules]]
id = "artifactory-reference-token"
description = "Detected an Artifactory reference token, posing a risk of impersonation and unauthorized access to the central repository."
regex = '''\bcmVmd[A-Za-z0-9]{59}\b'''
entropy = 4.5
keywords = ["cmvmd"]
[[rules]]
id = "asana-client-id"
description = "Discovered a potential Asana Client ID, risking unauthorized access to Asana projects and sensitive task information."
@@ -144,7 +170,7 @@ keywords = ["asana"]
[[rules]]
id = "atlassian-api-token"
description = "Detected an Atlassian API token, posing a threat to project management and collaboration tool security and data confidentiality."
regex = '''[\w.-]{0,50}?(?i:[\w.-]{0,50}?(?:atlassian|confluence|jira)(?:[ \t\w.-]{0,20})[\s'"]{0,3})(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-zA-Z0-9]{24})(?:[\x60'"\s;]|\\[nr]|$)|\b(ATATT3[A-Za-z0-9_\-=]{186})(?:[\x60'"\s;]|\\[nr]|$)'''
regex = '''(?i)[\w.-]{0,50}?(?:(?-i:ATLASSIAN|[Aa]tlassian)|(?-i:CONFLUENCE|[Cc]onfluence)|(?-i:JIRA|[Jj]ira))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{20}[a-f0-9]{4})(?:[\x60'"\s;]|\\[nr]|$)|\b(ATATT3[A-Za-z0-9_\-=]{186})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3.5
keywords = [
"atlassian",
@@ -600,6 +626,7 @@ keywords = [
"secret",
"token",
]
smartFilter=true
[[rules.allowlists]]
regexes = [
'''^[a-zA-Z_.-]+$''',
@@ -2296,6 +2323,13 @@ description = "Detected a Heroku API Key, potentially compromising cloud applica
regex = '''(?i)[\w.-]{0,50}?(?:heroku)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["heroku"]
[[rules]]
id = "heroku-api-key-v2"
description = "Detected a Heroku API Key, potentially compromising cloud application deployments and operational security."
regex = '''\b((HRKU-AA[0-9a-zA-Z_-]{58}))(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 4
keywords = ["hrku-aa"]
[[rules]]
id = "hubspot-api-key"
description = "Found a HubSpot API Token, posing a risk to CRM data integrity and unauthorized marketing operations."
@@ -2578,6 +2612,13 @@ description = "Discovered a New Relic user API Key, which could lead to compromi
regex = '''(?i)[\w.-]{0,50}?(?:new-relic|newrelic|new_relic)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}(NRAK-[a-z0-9]{27})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["nrak"]
[[rules]]
id = "notion-api-token"
description = "Notion API token"
regex = '''\b(ntn_[0-9]{11}[A-Za-z0-9]{32}[A-Za-z0-9]{3})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 4
keywords = ["ntn_"]
[[rules]]
id = "npm-access-token"
description = "Uncovered an npm access token, potentially compromising package management and code repository access."
+14
View File
@@ -46,6 +46,20 @@ type Rule struct {
// validated is an internal flag to track whether `Validate()` has been called.
validated bool
// If a rule has RequiredRules, it makes the rule dependent on the RequiredRules.
// In otherwords, this rule is now a composite rule.
RequiredRules []*Required
SkipReport bool
SmartFilter bool
}
type Required struct {
RuleID string
WithinLines *int
WithinColumns *int
}
// Validate guards against common misconfigurations.
+16
View File
@@ -1,6 +1,8 @@
package config
import (
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
@@ -22,3 +24,17 @@ func regexMatched(f string, re *regexp.Regexp) bool {
}
return false
}
// joinRegexOr combines multiple |patterns| into a single *regexp.Regexp.
func joinRegexOr(patterns []*regexp.Regexp) *regexp.Regexp {
var sb strings.Builder
sb.WriteString("(?:")
for i, pat := range patterns {
sb.WriteString(pat.String())
if i != len(patterns)-1 {
sb.WriteString("|")
}
}
sb.WriteString(")")
return regexp.MustCompile(sb.String())
}
+269 -7
View File
@@ -18,7 +18,12 @@ import (
"github.com/zricethezav/gitleaks/v8/sources"
ahocorasick "github.com/BobuSumisu/aho-corasick"
tiktoken_loader "github.com/pkoukk/tiktoken-go-loader"
"github.com/zricethezav/icanhazwordz"
"github.com/agnivade/levenshtein"
"github.com/fatih/semgroup"
"github.com/pkoukk/tiktoken-go"
"github.com/rs/zerolog"
"github.com/spf13/viper"
"golang.org/x/exp/maps"
@@ -104,6 +109,10 @@ type Detector struct {
Reporter report.Reporter
TotalBytes atomic.Uint64
tokenizer *tiktoken.Tiktoken
nltkSearcher *icanhazwordz.Searcher
}
// Fragment is an alias for sources.Fragment for backwards compatibility
@@ -113,6 +122,13 @@ type Fragment sources.Fragment
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
// grab offline tiktoken encoder
tiktoken.SetBpeLoader(tiktoken_loader.NewOfflineLoader())
tke, err := tiktoken.GetEncoding("cl100k_base")
if err != nil {
logging.Warn().Err(err).Msgf("Could not pull down cl100k_base tiktokenizer")
}
return &Detector{
commitMap: make(map[string]bool),
gitleaksIgnore: make(map[string]struct{}),
@@ -122,6 +138,10 @@ func NewDetector(cfg config.Config) *Detector {
Config: cfg,
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
Sema: semgroup.NewGroup(context.Background(), 40),
// tokenizer and nltkSearcher are used for a generic filter
tokenizer: tke,
nltkSearcher: icanhazwordz.NewSearcher(icanhazwordz.Filter{MinLength: 4, PreferLongestNonOverlapping: true}),
}
}
@@ -292,9 +312,6 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
return findings
}
// add newline indices for location calculation in detectRule
newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// setup variables to handle different decoding passes
currentRaw := fragment.Raw
encodedSegments := []*codec.EncodedSegment{}
@@ -314,14 +331,14 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
if len(rule.Keywords) == 0 {
// if no keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
continue
}
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := keywords[strings.ToLower(k)]; ok {
findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
break
}
}
@@ -348,7 +365,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
var (
findings []report.Finding
logger = func() zerolog.Logger {
@@ -360,6 +377,10 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
}()
)
if r.SkipReport && !fragment.InheritedFromFinding {
return findings
}
// check if commit or file is allowed for this rule.
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
event.Msg("skipping file: rule allowlist")
@@ -415,6 +436,14 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
}
}
matches := r.Regex.FindAllStringIndex(currentRaw, -1)
if len(matches) == 0 {
return findings
}
// TODO profile this, probably should replace with something more efficient
newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// use currentRaw instead of fragment.Raw since this represents the current
// decoding pass on the text
for _, matchIndex := range r.Regex.FindAllStringIndex(currentRaw, -1) {
@@ -532,9 +561,242 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
event.Msg("skipping finding: rule allowlist")
continue
}
if r.SmartFilter {
if !d.passesSmartFilter(finding.Secret) {
continue
}
}
findings = append(findings, finding)
}
return findings
// Handle required rules (multi-part rules)
if fragment.InheritedFromFinding || len(r.RequiredRules) == 0 {
return findings
}
// Process required rules and create findings with auxiliary findings
return d.processRequiredRules(fragment, currentRaw, r, encodedSegments, findings, logger)
}
// passesSmartFilter applies heuristics to determine if a string is likely a real looking secret
// rather than random text or common words. It uses token density, character distribution,
// and word analysis to filter out false positives. Returns true if the string passes
// the filter (likely a secret), false if it should be skipped.
func (d *Detector) passesSmartFilter(secret string) bool {
tokens := d.tokenizer.Encode(secret, nil, nil)
tokenLen := len(tokens)
// token vals < 100
numShortTokens := 0
for _, t := range tokens {
if t < 100 {
numShortTokens++
}
}
// token vals > 100
// longTokens := tokenLen - numShortTokens
density := len(secret) / tokenLen
shortTokenRatio := float32(numShortTokens / tokenLen)
result := d.nltkSearcher.Find(secret)
fourPlusCharWords := len(result.Matches)
// check if the secret has a close levenshtein distance to any of the results
// if it does, consider this c4. normalize cases
c4 := false
secretLower := strings.ToLower(secret)
for _, match := range result.Matches {
// Only check against words with 5+ characters
if len(match.Word) <= 5 {
continue
}
wordLower := strings.ToLower(match.Word)
distance := levenshtein.ComputeDistance(secretLower, wordLower)
// Consider it close if distance is <= 2 or <= 20% of the longer string length
maxLen := max(len(secretLower), len(wordLower))
threshold := max(2, maxLen/5)
if distance <= threshold {
c4 = true
break
}
// OR check if the match is 6 characters or more _and_ is a substring of the
// potential secret
if len(match.Word) <= 6 {
continue
}
if strings.Contains(strings.ToLower(secret), strings.ToLower(match.Word)) {
c4 = true
}
}
c1 := density <= 2.0
c2 := shortTokenRatio >= 0.25
c3 := len(secret) >= 9 && float32(density) <= 2.5
likelySecret := c1 || c2 || c3
// Check for irregularly cased English words
// majorityIrregularlyCased := false
hasIrregularCasing := false
for _, word := range result.UniqueWords {
if isIrregularlyCased(word, secret) {
hasIrregularCasing = true
break
}
}
// if len(result.UniqueWords) > 0 && irregularlyCased > len(result.UniqueWords)/2 {
// majorityIrregularlyCased = true
// }
// fmt.Println(hasIrregularCasing, fourPlusCharWords, secret)
// fmt.Println(c1, c2, c3, fourPlusCharWords)
// Make exception if words have irregular casing
if hasIrregularCasing && fourPlusCharWords > 1 {
pass := likelySecret
if !pass {
// fmt.Println("skipping: ", secret, "--", c1, c2, c3, fourPlusCharWords, result.UniqueWords, "(irregular casing exception)")
}
return pass
}
pass := likelySecret && !(fourPlusCharWords > 1) && !c4
if !pass {
// fmt.Println("skipping: ", secret, "--", c1, c2, c3, fourPlusCharWords, result.UniqueWords)
}
return pass
}
// processRequiredRules handles the logic for multi-part rules with auxiliary findings
func (d *Detector) processRequiredRules(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment, primaryFindings []report.Finding, logger zerolog.Logger) []report.Finding {
if len(primaryFindings) == 0 {
logger.Debug().Msg("no primary findings to process for required rules")
return primaryFindings
}
// Pre-collect all required rule findings once
allRequiredFindings := make(map[string][]report.Finding)
for _, requiredRule := range r.RequiredRules {
rule, ok := d.Config.Rules[requiredRule.RuleID]
if !ok {
logger.Error().Str("rule-id", requiredRule.RuleID).Msg("required rule not found in config")
continue
}
// Mark fragment as inherited to prevent infinite recursion
inheritedFragment := fragment
inheritedFragment.InheritedFromFinding = true
// Call detectRule once for each required rule
requiredFindings := d.detectRule(inheritedFragment, currentRaw, rule, encodedSegments)
allRequiredFindings[requiredRule.RuleID] = requiredFindings
logger.Debug().
Str("rule-id", requiredRule.RuleID).
Int("findings", len(requiredFindings)).
Msg("collected required rule findings")
}
var finalFindings []report.Finding
// Now process each primary finding against the pre-collected required findings
for _, primaryFinding := range primaryFindings {
var requiredFindings []*report.RequiredFinding
for _, requiredRule := range r.RequiredRules {
foundRequiredFindings, exists := allRequiredFindings[requiredRule.RuleID]
if !exists {
continue // Rule wasn't found earlier, skip
}
// Filter findings that are within proximity of the primary finding
for _, requiredFinding := range foundRequiredFindings {
if d.withinProximity(primaryFinding, requiredFinding, requiredRule) {
req := &report.RequiredFinding{
RuleID: requiredFinding.RuleID,
StartLine: requiredFinding.StartLine,
EndLine: requiredFinding.EndLine,
StartColumn: requiredFinding.StartColumn,
EndColumn: requiredFinding.EndColumn,
Line: requiredFinding.Line,
Match: requiredFinding.Match,
Secret: requiredFinding.Secret,
}
requiredFindings = append(requiredFindings, req)
}
}
}
// Check if we have at least one auxiliary finding for each required rule
if len(requiredFindings) > 0 && d.hasAllRequiredRules(requiredFindings, r.RequiredRules) {
// Create a finding with auxiliary findings
newFinding := primaryFinding // Copy the primary finding
newFinding.AddRequiredFindings(requiredFindings)
finalFindings = append(finalFindings, newFinding)
logger.Debug().
Str("primary-rule", r.RuleID).
Int("primary-line", primaryFinding.StartLine).
Int("auxiliary-count", len(requiredFindings)).
Msg("multi-part rule satisfied")
}
}
return finalFindings
}
// hasAllRequiredRules checks if we have at least one auxiliary finding for each required rule
func (d *Detector) hasAllRequiredRules(auxiliaryFindings []*report.RequiredFinding, requiredRules []*config.Required) bool {
foundRules := make(map[string]bool)
// AuxiliaryFinding
for _, aux := range auxiliaryFindings {
foundRules[aux.RuleID] = true
}
for _, required := range requiredRules {
if !foundRules[required.RuleID] {
return false
}
}
return true
}
func (d *Detector) withinProximity(primary, required report.Finding, requiredRule *config.Required) bool {
// fmt.Println(requiredRule.WithinLines)
// If neither within_lines nor within_columns is set, findings just need to be in the same fragment
if requiredRule.WithinLines == nil && requiredRule.WithinColumns == nil {
return true
}
// Check line proximity (vertical distance)
if requiredRule.WithinLines != nil {
lineDiff := abs(primary.StartLine - required.StartLine)
if lineDiff > *requiredRule.WithinLines {
return false
}
}
// Check column proximity (horizontal distance)
if requiredRule.WithinColumns != nil {
// Use the start column of each finding for proximity calculation
colDiff := abs(primary.StartColumn - required.StartColumn)
if colDiff > *requiredRule.WithinColumns {
return false
}
}
return true
}
// abs returns the absolute value of an integer
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// AddFinding synchronously adds a finding to the findings slice
+138 -27
View File
@@ -1,8 +1,10 @@
package detect
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
@@ -10,6 +12,7 @@ import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/rs/zerolog"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
@@ -86,6 +89,46 @@ secret=%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%
secret%3D%25%35%61%25%34%37%25%35%36jb2RlZC1zZWNyZXQtdmFsdWU%25%32%35%25%33%33%25%36%34
`
var multili = `
username = "admin"
password = "secret123"
`
func compare(t *testing.T, a, b []report.Finding) {
if diff := cmp.Diff(a, b,
cmpopts.SortSlices(func(a, b report.Finding) bool {
if a.File != b.File {
return a.File < b.File
}
if a.StartLine != b.StartLine {
return a.StartLine < b.StartLine
}
if a.StartColumn != b.StartColumn {
return a.StartColumn < b.StartColumn
}
if a.EndLine != b.EndLine {
return a.EndLine < b.EndLine
}
if a.EndColumn != b.EndColumn {
return a.EndColumn < b.EndColumn
}
if a.RuleID != b.RuleID {
return a.RuleID < b.RuleID
}
return a.Secret < b.Secret
}),
cmpopts.IgnoreFields(report.Finding{},
"Fingerprint", "Author", "Email", "Date", "Message", "Commit", "requiredFindings"),
cmpopts.EquateApprox(0.0001, 0), // For floating point Entropy comparison
); diff != "" {
t.Errorf("findings mismatch (-want +got):\n%s", diff)
}
}
func TestDetect(t *testing.T) {
logging.Logger = logging.Logger.Level(zerolog.TraceLevel)
tests := map[string]struct {
@@ -97,8 +140,9 @@ func TestDetect(t *testing.T) {
// I.e., if the finding is from a --no-git file, the line number will be
// increase by 1 in DetectFromFiles(). If the finding is from git,
// the line number will be increased by the patch delta.
expectedFindings []report.Finding
wantError error
expectedFindings []report.Finding
wantError error
expectedAuxOutput string
}{
// General
"valid allow comment (1)": {
@@ -424,6 +468,28 @@ const token = "mockSecret";
FilePath: "tmp.go",
},
},
"fragment level composite": {
cfgName: "composite",
fragment: Fragment{
Raw: multili,
},
expectedFindings: []report.Finding{
{
Description: "Primary rule",
RuleID: "primary-rule",
StartLine: 5,
EndLine: 5,
StartColumn: 5,
EndColumn: 26,
Line: "\n\t\t\tpassword = \"secret123\"",
Match: `password = "secret123"`,
Secret: "secret123",
Entropy: 2.9477028846740723,
Tags: []string{},
},
},
expectedAuxOutput: "Required: username-rule:1:admin\n",
},
// Decoding
"detect encoded": {
cfgName: "encoded",
@@ -736,11 +802,50 @@ const token = "mockSecret";
d.baselinePath = tt.baselinePath
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
compare(t, findings, tt.expectedFindings)
// extremely goofy way to test auxiliary findings
// capture stdout and print that sonabitch
// TODO
if tt.expectedAuxOutput != "" {
capturedOutput := captureStdout(func() {
for _, finding := range findings {
finding.PrintRequiredFindings()
}
})
// Clean up the output for comparison (remove ANSI color codes)
cleanOutput := stripANSI(capturedOutput)
expectedClean := stripANSI(tt.expectedAuxOutput)
assert.Equal(t, expectedClean, cleanOutput, "Auxiliary output should match")
}
})
}
}
func stripANSI(s string) string {
ansiRegex := regexp.MustCompile(`\x1b\[[0-9;]*m`)
return ansiRegex.ReplaceAllString(s, "")
}
func captureStdout(f func()) string {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
f()
w.Close()
os.Stdout = oldStdout
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}
// TestFromGit tests the FromGit function
func TestFromGit(t *testing.T) {
// TODO: Fix this test on windows.
@@ -2107,8 +2212,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2132,8 +2239,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2203,8 +2312,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2225,8 +2336,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2249,8 +2362,10 @@ func TestDetectRuleAllowlist(t *testing.T) {
},
expected: []report.Finding{
{
StartColumn: 50,
EndColumn: 60,
StartLine: 1,
EndLine: 1,
StartColumn: 18,
EndColumn: 28,
Line: "let username = 'james@mail.com';\nlet password = 'Summer2024!';",
Match: "Summer2024!",
Secret: "Summer2024!",
@@ -2275,6 +2390,9 @@ func TestDetectRuleAllowlist(t *testing.T) {
let password = 'Summer2024!';`
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
err := tc.allowlist.Validate()
require.NoError(t, err)
rule := config.Rule{
RuleID: "test-rule",
Regex: regexp.MustCompile(`Summer2024!`),
@@ -2287,10 +2405,9 @@ let password = 'Summer2024!';`
f := tc.fragment
f.Raw = raw
actual := d.detectRule(f, [][]int{}, raw, rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(f, raw, rule, []*codec.EncodedSegment{})
compare(t, tc.expected, actual)
})
}
}
@@ -2448,10 +2565,8 @@ func TestWindowsFileSeparator_RulePath(t *testing.T) {
require.NoError(t, err)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, [][]int{}, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
compare(t, test.expected, actual)
})
}
}
@@ -2634,12 +2749,8 @@ func TestWindowsFileSeparator_RuleAllowlistPaths(t *testing.T) {
require.NoError(t, err)
for name, test := range tests {
t.Run(name, func(t *testing.T) {
actual := d.detectRule(test.fragment, [][]int{}, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
if diff := cmp.Diff(test.expected, actual); diff != "" {
t.Errorf("diff: (-want +got)\n%s", diff)
}
actual := d.detectRule(test.fragment, test.fragment.Raw, test.rule, []*codec.EncodedSegment{})
compare(t, test.expected, actual)
})
}
}
//endregion
+89 -1
View File
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect/codec"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -75,6 +76,34 @@ func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
// This is a bit dirty, but Azure DevOps does not highlight the line when the lineStartColumn and lineEndColumn are not provided
link += "&lineStartColumn=1&lineEndColumn=10000000&type=2&lineStyle=plain&_a=files"
return link
case scm.GiteaPlatform:
link := fmt.Sprintf("%s/src/commit/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
ext := strings.ToLower(filepath.Ext(filePath))
if ext == ".ipynb" || ext == ".md" {
link += "?display=source"
}
if finding.StartLine != 0 {
link += fmt.Sprintf("#L%d", finding.StartLine)
}
if finding.EndLine != finding.StartLine {
link += fmt.Sprintf("-L%d", finding.EndLine)
}
return link
case scm.BitbucketPlatform:
link := fmt.Sprintf("%s/src/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
if finding.StartLine != 0 {
link += fmt.Sprintf("#lines-%d", finding.StartLine)
}
if finding.EndLine != finding.StartLine {
link += fmt.Sprintf(":%d", finding.EndLine)
}
return link
default:
// This should never happen.
return ""
@@ -108,14 +137,32 @@ func shannonEntropy(data string) (entropy float64) {
// filter will dedupe and redact findings
func filter(findings []report.Finding, redact uint) []report.Finding {
var retFindings []report.Finding
decoder := codec.NewDecoder()
encodedSegments := []*codec.EncodedSegment{}
for _, f := range findings {
include := true
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
for _, fPrime := range findings {
// TODO also check if a decoded secret == the generic secret. If it does, skip the generic secret
isDecoded := false
decodedSecret := ""
for _, t := range fPrime.Tags {
if strings.Contains(t, "decoded") {
isDecoded = true
}
}
if isDecoded {
decodedSecret, _ = decoder.Decode(f.Secret, encodedSegments)
decodedSecret = strings.TrimSuffix(decodedSecret, "\n")
}
if f.StartLine == fPrime.StartLine &&
f.Commit == fPrime.Commit &&
f.RuleID != fPrime.RuleID &&
strings.Contains(fPrime.Secret, f.Secret) &&
(strings.Contains(fPrime.Secret, f.Secret) || decodedSecret == fPrime.Secret) &&
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
genericMatch := strings.ReplaceAll(f.Match, f.Secret, "REDACTED")
@@ -204,7 +251,9 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Printf("%-12s %s\n", "RuleID:", f.RuleID)
fmt.Printf("%-12s %f\n", "Entropy:", f.Entropy)
if f.File == "" {
f.PrintRequiredFindings()
fmt.Println("")
return
}
@@ -215,6 +264,7 @@ func printFinding(f report.Finding, noColor bool) {
fmt.Printf("%-12s %d\n", "Line:", f.StartLine)
if f.Commit == "" {
fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
f.PrintRequiredFindings()
fmt.Println("")
return
}
@@ -226,5 +276,43 @@ func printFinding(f report.Finding, noColor bool) {
if f.Link != "" {
fmt.Printf("%-12s %s\n", "Link:", f.Link)
}
f.PrintRequiredFindings()
fmt.Println("")
}
func isIrregularlyCased(word, secret string) bool {
// Find the word in the secret (case-insensitive)
secretLower := strings.ToLower(secret)
wordLower := strings.ToLower(word)
index := strings.Index(secretLower, wordLower)
if index == -1 {
return false
}
// Extract the actual casing from the secret
actualWord := secret[index : index+len(word)]
// Check if it matches conventional casing patterns
return !isConventionallyCased(actualWord)
}
// Helper function to determine if a word follows conventional casing
func isConventionallyCased(word string) bool {
if len(word) == 0 {
return true
}
// Conventional patterns:
// - All lowercase (common)
// - All uppercase (acronyms, constants)
// - Title case (proper nouns)
// - First letter uppercase, rest lowercase
allLower := strings.ToLower(word) == word
allUpper := strings.ToUpper(word) == word
titleCase := strings.Title(strings.ToLower(word)) == word
return allLower || allUpper || titleCase
}
+68
View File
@@ -136,6 +136,74 @@ func Test_createScmLink(t *testing.T) {
},
want: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository/commit/20553ad96a4a080c94a54d677db97eed8ce2560d?path=/examplefile.json&line=25&lineEnd=30&lineStartColumn=1&lineEndColumn=10000000&type=2&lineStyle=plain&_a=files",
},
// Gitea
"gitea - single line": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 25,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#L25",
},
"gitea- multi line": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 30,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#L25-L30",
},
"gitea - markdown": {
remote: &sources.RemoteInfo{
Platform: scm.GiteaPlatform,
Url: "https://gitea.com/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "Readme.md",
StartLine: 34,
EndLine: 34,
},
want: "https://gitea.com/exampleorganisation/exampleproject/src/commit/20553ad96a4a080c94a54d677db97eed8ce2560d/Readme.md?display=source#L34",
},
// bitbucket
"bitbucket - single line": {
remote: &sources.RemoteInfo{
Platform: scm.BitbucketPlatform,
Url: "https://bitbucket.org/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 25,
},
want: "https://bitbucket.org/exampleorganisation/exampleproject/src/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#lines-25",
},
"bitbucket- multi line": {
remote: &sources.RemoteInfo{
Platform: scm.BitbucketPlatform,
Url: "https://bitbucket.org/exampleorganisation/exampleproject",
},
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
StartLine: 25,
EndLine: 30,
},
want: "https://bitbucket.org/exampleorganisation/exampleproject/src/20553ad96a4a080c94a54d677db97eed8ce2560d/examplefile.json#lines-25:30",
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
+8 -3
View File
@@ -1,22 +1,26 @@
module github.com/zricethezav/gitleaks/v8
go 1.23.0
go 1.24
toolchain go1.23.4
toolchain go1.24.3
require (
github.com/BobuSumisu/aho-corasick v1.0.3
github.com/Masterminds/sprig/v3 v3.3.0
github.com/agnivade/levenshtein v1.2.1
github.com/charmbracelet/lipgloss v0.5.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.9.1
github.com/google/go-cmp v0.6.0
github.com/h2non/filetype v1.1.3
github.com/mholt/archives v0.1.2
github.com/pkoukk/tiktoken-go v0.1.7
github.com/pkoukk/tiktoken-go-loader v0.0.1
github.com/rs/zerolog v1.33.0
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.10.0
github.com/zricethezav/icanhazwordz v0.0.3
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa
)
@@ -30,6 +34,7 @@ require (
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.0 // indirect
github.com/bodgit/windows v1.0.1 // indirect
github.com/dlclark/regexp2 v1.10.0 // indirect
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
@@ -62,7 +67,7 @@ require (
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
go.uber.org/multierr v1.11.0 // indirect
go4.org v0.0.0-20230225012048-214862532bf5 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/crypto v0.35.0 // indirect
)
require (
+16 -2
View File
@@ -29,8 +29,12 @@ github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
github.com/STARRY-S/zip v0.2.1 h1:pWBd4tuSGm3wtpoqRZZ2EAwOmcHK6XFf7bU9qcJXyFg=
github.com/STARRY-S/zip v0.2.1/go.mod h1:xNvshLODWtC4EJ702g7cTYn13G53o1+X9BWnPFpcWV4=
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 h1:8PmGpDEZl9yDpcdEr6Odf23feCxK3LNUNMxjXg41pZQ=
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
@@ -52,6 +56,10 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0=
github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 h1:2tV76y6Q9BB+NEBasnqvs7e49aEBFI8ejC89PSnWH+4=
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707/go.mod h1:qssHWj60/X5sZFNxpG4HBPDHVqxNm4DfnCKgrbZOT+s=
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
@@ -172,6 +180,10 @@ github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xl
github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkoukk/tiktoken-go v0.1.7 h1:qOBHXX4PHtvIvmOtyg1EeKlwFRiMKAcoMp4Q+bLQDmw=
github.com/pkoukk/tiktoken-go v0.1.7/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=
github.com/pkoukk/tiktoken-go-loader v0.0.1 h1:aOB2gRFzZTCCPi3YsOQXJO771P/5876JAsdebMyazig=
github.com/pkoukk/tiktoken-go-loader v0.0.1/go.mod h1:4mIkYyZooFlnenDlormIo6cd5wrlUKNr97wp9nGgEKo=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -232,6 +244,8 @@ github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52/go.mod h1:
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zricethezav/icanhazwordz v0.0.3 h1:fFNkjTgDPVfyeQtrwudcrnKGjowQ4VDYOq75ATT7WqU=
github.com/zricethezav/icanhazwordz v0.0.3/go.mod h1:5fMiqbebc6dKbzmgcHbU2TWrsjbgg5aF50JhLNfOtZ0=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
@@ -245,8 +259,8 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
+60 -4
View File
@@ -1,12 +1,16 @@
package report
import (
"fmt"
"math"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/zricethezav/gitleaks/v8/sources"
)
// Finding contains information about strings that
// have been captured by a tree-sitter query.
// Finding contains a whole bunch of information about a secret finding.
// Plenty of real estate in this bad boy so fillerup as needed.
type Finding struct {
// Rule is the name of the rule that was matched
RuleID string
@@ -21,8 +25,7 @@ type Finding struct {
Match string
// Secret contains the full content of what is matched in
// the tree-sitter query.
// Captured secret
Secret string
// File is the name of the file containing the finding
@@ -42,6 +45,33 @@ type Finding struct {
// unique identifier
Fingerprint string
// Fragment used for multi-part rule checking, CEL filtering,
// and eventually ML validation
Fragment *sources.Fragment `json:",omitempty"`
// TODO keeping private for now to during experimental phase
requiredFindings []*RequiredFinding
}
type RequiredFinding struct {
// contains a subset of the Finding fields
// only used for reporting
RuleID string
StartLine int
EndLine int
StartColumn int
EndColumn int
Line string `json:"-"`
Match string
Secret string
}
func (f *Finding) AddRequiredFindings(afs []*RequiredFinding) {
if f.requiredFindings == nil {
f.requiredFindings = make([]*RequiredFinding, 0)
}
f.requiredFindings = append(f.requiredFindings, afs...)
}
// Redact removes sensitive information from a finding.
@@ -68,3 +98,29 @@ func maskSecret(secret string, percent uint) string {
return secret[:lth] + "..."
}
func (f *Finding) PrintRequiredFindings() {
if len(f.requiredFindings) == 0 {
return
}
fmt.Printf("%-12s ", "Required:")
// Create orange style for secrets
orangeStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#bf9478"))
for i, aux := range f.requiredFindings {
auxSecret := strings.TrimSpace(aux.Secret)
// Truncate long secrets for readability
if len(auxSecret) > 40 {
auxSecret = auxSecret[:37] + "..."
}
// Format: rule-id:line:secret
if i == 0 {
fmt.Printf("%s:%d:%s\n", aux.RuleID, aux.StartLine, orangeStyle.Render(auxSecret))
} else {
fmt.Printf("%-12s %s:%d:%s\n", "", aux.RuleID, aux.StartLine, orangeStyle.Render(auxSecret))
}
}
}
+8 -5
View File
@@ -56,11 +56,14 @@ func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
// decide what to do with it.
if err == nil && format != nil {
if s.archiveDepth+1 > s.MaxArchiveDepth {
logging.Warn().Str(
"path", s.FullPath(),
).Int(
"max_archive_depth", s.MaxArchiveDepth,
).Msg("skipping archive: exceeds max archive depth")
// Only warn when the feature is enabled
if s.MaxArchiveDepth != 0 {
logging.Warn().Str(
"path", s.FullPath(),
).Int(
"max_archive_depth", s.MaxArchiveDepth,
).Msg("skipping archive: exceeds max archive depth")
}
return nil
}
if extractor, ok := format.(archives.Extractor); ok {
+2
View File
@@ -23,4 +23,6 @@ type Fragment struct {
// CommitInfo captures additional information about the git commit if applicable
CommitInfo *CommitInfo
InheritedFromFinding bool // Indicates if this fragment is inherited from a finding
}
+5 -1
View File
@@ -440,7 +440,7 @@ End:
}
}
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
@@ -482,6 +482,10 @@ func platformFromHost(u *url.URL) scm.Platform {
return scm.GitLabPlatform
case "dev.azure.com", "visualstudio.com":
return scm.AzureDevOpsPlatform
case "gitea.com", "code.forgejo.org", "codeberg.org":
return scm.GiteaPlatform
case "bitbucket.org":
return scm.BitbucketPlatform
default:
return scm.UnknownPlatform
}
+14
View File
@@ -0,0 +1,14 @@
title = "Fragment level composite rule"
[[rules]]
id = "primary-rule"
description = "Primary rule"
regex = 'password\s*=\s*"([^"]+)"'
[[rules.required]]
id = "username-rule"
[[rules]]
id = "username-rule"
description = "Username rule"
regex = 'username\s*=\s*"([^"]+)"'
skipReport = true