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
38 changed files with 498 additions and 740 deletions

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.24
go-version: 1.23
- name: Build
run: go build ./...
+6 -17
View File
@@ -1,5 +1,3 @@
version: 2
project_name: gitleaks
builds:
@@ -17,26 +15,17 @@ builds:
goarm:
- "6"
- "7"
ignore:
- goos: windows
goarch: arm
tags:
- gore2regex
ldflags:
- -s -w -X=github.com/zricethezav/gitleaks/v8/version.Version={{.Version}}
- -s -w -X=github.com/zricethezav/gitleaks/v8/cmd.Version={{.Version}}
archives:
- ids: [gitleaks]
name_template: >-
{{ .ProjectName }}_
{{- .Version }}_
{{- .Os }}_
{{- if eq .Arch "amd64" }}x64
{{- else if eq .Arch "386" }}x32
{{- else }}{{ .Arch }}{{ end }}
{{- with .Arm }}v{{ . }}{{ end }}
- builds: [gitleaks]
format_overrides:
- goos: windows
formats: [zip]
format: zip
replacements:
amd64: x64
386: x32
release:
prerelease: true
+3 -3
View File
@@ -1,10 +1,10 @@
FROM golang:1.24 AS build
FROM golang:1.23 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN VERSION=$(git describe --tags --abbrev=0) && \
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X=github.com/zricethezav/gitleaks/v8/version.Version=${VERSION}"
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}"
FROM alpine:3.22
FROM alpine:3.19
RUN apk add --no-cache bash git openssh-client
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
+1 -1
View File
@@ -2,7 +2,7 @@
PKG=github.com/zricethezav/gitleaks
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/version.Version=$(VERSION)"
LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=$(VERSION)"
COVER=--cover --coverprofile=cover.out
test-cover:
+68 -75
View File
@@ -32,8 +32,12 @@
[![GoReportCard][go-report-card-badge]][go-report-card]
[![License][badge-license]][license]
### Join our Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/8Hzbrnkr7E)
Gitleaks is a tool for **detecting** secrets like passwords, API keys, and tokens in git repos, files, and whatever else you wanna throw at it via `stdin`. If you wanna learn more about how the detection engine works check out this blog: [Regex is (almost) all you need](https://lookingatcomputer.substack.com/p/regex-is-almost-all-you-need).
```
➜ ~/code(master) gitleaks git -v
@@ -57,11 +61,6 @@ Date: 2022-08-03T12:31:40Z
Fingerprint: cd5226711335c68be1e720b318b7bc3135a30eb2:cmd/generate/config/rules/sidekiq.go:sidekiq-secret:23
```
### GitHub Sponsors
Sponsor [@zricethezav on GitHub](https://github.com/sponsors/zricethezav/) to get
featured on this README.
## Getting Started
Gitleaks can be installed using Homebrew, Docker, or Go. Gitleaks is also available in binary form for many popular platforms and OS types on the [releases page](https://github.com/gitleaks/gitleaks/releases). In addition, Gitleaks can be implemented as a pre-commit hook directly in your repo or as a GitHub action using [Gitleaks-Action](https://github.com/gitleaks/gitleaks-action).
@@ -142,13 +141,10 @@ Detect hardcoded secrets................................................Skipped
## Usage
```
Gitleaks scans code, past or present, for secrets
Usage:
gitleaks [command]
Available Commands:
completion Generate the autocompletion script for the specified shell
dir scan directories or files for secrets
git scan git repositories for secrets
help Help about any command
@@ -164,16 +160,16 @@ Flags:
3. env var GITLEAKS_CONFIG_TOML with the file content
4. (target path)/.gitleaks.toml
If none of the four options are used, then gitleaks will use the default config
--diagnostics string enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof
--diagnostics-dir string directory to store diagnostics output files when not using http mode (defaults to current directory)
--diagnostics string enable diagnostics (comma-separated list: cpu,mem,trace). cpu=CPU profiling, mem=memory profiling, trace=execution tracing
--diagnostics-dir string directory to store diagnostics output files (defaults to current directory)
--enable-rule strings only enable specific rules by id
--exit-code int exit code when leaks have been encountered (default 1)
-i, --gitleaks-ignore-path string path to .gitleaksignore file or folder containing one (default ".")
-h, --help help for gitleaks
--ignore-gitleaks-allow ignore gitleaks:allow comments
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
--max-decode-depth int allow recursive decoding up to this depth (default "0", no decoding is done)
--max-archive-depth int allow scanning into nested archives up to this depth (default "0", no archive traversal is done)
--max-target-megabytes int files larger than this will be skipped
--no-banner suppress banner
--no-color turn off color for verbose output
@@ -181,7 +177,6 @@ Flags:
-f, --report-format string output format (json, csv, junit, sarif, template)
-r, --report-path string report file
--report-template string template file used to generate the report (implies --report-format=template)
--timeout int set a timeout for gitleaks commands in seconds (default "0", no timeout is set)
-v, --verbose show verbose output from scan
--version version for gitleaks
@@ -426,7 +421,7 @@ In v8.28.0 Gitleaks introduced composite rules, which are made up of a single "p
**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)
- **`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)
@@ -438,76 +433,76 @@ a = auxiliary (required) captured secret
fragment = section of data gitleaks is looking at
*Fragment-level proximity*
*Fragment-level proximity*
Any required finding in the fragment
┌────────┐
┌──────┤fragment├─────┐
│ └──────┬─┤ │ ┌───────┐
│ │a│◀────┼─│✓ MATCH│
│ ┌─┐└─┘ │ └───────┘
│┌─┐ │p│ │
││a│ ┌─┐└─┘ │ ┌───────┐
│└─┘ │a│◀──────────┼─│✓ MATCH│
└─▲─────┴─┴───────────┘ └───────┘
│ ┌───────┐
└────│✓ MATCH│
└───────┘
┌────────┐
┌──────┤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 │
└─────────┘
`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 │
└────────────────┴─┴─┘ └─────────┘
`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 ┌└────────┴ ┐ │
`withinLines = 4`
`withinColumns = 3`
┌────────┐
┌─────┤fragment├─────┐
+4L ┌└────────┴ ┐ │
│ ┌─┐ │ ┌───────────────┐
│ │ │a│◀┼───┼─│+2L/+1C ✓ MATCH│
│ ┌─┐└─┘ │ └───────────────┘
0L │ │p│ │ │
│ └─┘ │
│ │ │ │ ┌────────────┐
-4L ─ ─ ─ ─ ─ ─┌─┐ │ │-5L/+3C ✗ NO│
│ │a│◀┼─│ MATCH │
└───-3C────0L───+3C┴─┘ └────────────┘
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
@@ -651,5 +646,3 @@ You can always set the exit code when leaks are encountered with the --exit-code
1 - leaks or error encountered
126 - unknown flag
```
### Join the Discord! [![Discord](https://img.shields.io/discord/1102689410522284044.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/8Hzbrnkr7E)
+8 -5
View File
@@ -19,6 +19,7 @@
package cmd
import (
"context"
"os"
"time"
@@ -65,16 +66,18 @@ func runDetect(cmd *cobra.Command, args []string) {
exitCode := mustGetIntFlag(cmd, "exit-code")
noGit := mustGetBoolFlag(cmd, "no-git")
fromPipe := mustGetBoolFlag(cmd, "pipe")
// determine what type of scan:
// - git: scan the history of the repo
// - no-git: scan files by treating the repo as a plain directory
var (
err error
findings []report.Finding
ctx = context.Background()
)
if noGit {
findings, err = detector.DetectSource(
cmd.Context(), &sources.Files{
ctx, &sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
@@ -90,7 +93,7 @@ func runDetect(cmd *cobra.Command, args []string) {
}
} else if fromPipe {
findings, err = detector.DetectSource(
cmd.Context(), &sources.File{
ctx, &sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
@@ -108,7 +111,7 @@ func runDetect(cmd *cobra.Command, args []string) {
)
logOpts := mustGetStringFlag(cmd, "log-opts")
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), sourcePath, logOpts); err != nil {
if gitCmd, err = sources.NewGitLogCmd(sourcePath, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git cmd")
}
@@ -117,10 +120,10 @@ func runDetect(cmd *cobra.Command, args []string) {
}
findings, err = detector.DetectSource(
cmd.Context(), &sources.Git{
ctx, &sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, sourcePath),
Remote: sources.NewRemoteInfo(scmPlatform, sourcePath),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
+2 -1
View File
@@ -1,6 +1,7 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
@@ -55,7 +56,7 @@ func runDirectory(cmd *cobra.Command, args []string) {
}
findings, err := detector.DetectSource(
cmd.Context(),
context.Background(),
&sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
+1 -6
View File
@@ -31,13 +31,10 @@ func main() {
rules.AdobeClientID(),
rules.AdobeClientSecret(),
rules.AgeSecretKey(),
rules.AirtableApiKey(),
rules.AirtablePersonalAccessToken(),
rules.Airtable(),
rules.AlgoliaApiKey(),
rules.AlibabaAccessKey(),
rules.AlibabaSecretKey(),
rules.AmazonBedrockAPIKeyLongLived(),
rules.AmazonBedrockAPIKeyShortLived(),
rules.AnthropicAdminApiKey(),
rules.AnthropicApiKey(),
rules.ArtifactoryApiKey(),
@@ -153,8 +150,6 @@ func main() {
rules.LinkedinClientSecret(),
rules.LobAPIToken(),
rules.LobPubAPIToken(),
rules.LookerClientID(),
rules.LookerClientSecret(),
rules.MailChimp(),
rules.MailGunPubAPIToken(),
rules.MailGunPrivateAPIToken(),
+1 -17
View File
@@ -1,14 +1,12 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AirtableApiKey() *config.Rule {
func Airtable() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a possible Airtable API Key, potentially compromising database access and leading to data leakage or alteration.",
@@ -21,17 +19,3 @@ func AirtableApiKey() *config.Rule {
tps := utils.GenerateSampleSecrets("airtable", secrets.NewSecret(utils.AlphaNumeric("17")))
return utils.Validate(r, tps, nil)
}
func AirtablePersonalAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Uncovered a possible Airtable Personal AccessToken, potentially compromising database access and leading to data leakage or alteration.",
RuleID: "airtable-personnal-access-token",
Regex: regexp.MustCompile(`\b(pat[[:alnum:]]{14}\.[a-f0-9]{64})\b`),
Keywords: []string{"airtable"},
}
// validate
tps := utils.GenerateSampleSecrets("airtable", "pat"+secrets.NewSecret(utils.AlphaNumeric("14")+"\\."+utils.Hex("64")))
return utils.Validate(r, tps, nil)
}
-60
View File
@@ -47,63 +47,3 @@ func AWS() *config.Rule {
}
return utils.Validate(r, tps, fps)
}
func AmazonBedrockAPIKeyLongLived() *config.Rule {
// https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-how.html
// https://medium.com/@adan.alvarez/api-keys-for-bedrock-a-brief-security-overview-2133ed9a2b3f
r := config.Rule{
RuleID: "aws-amazon-bedrock-api-key-long-lived",
Description: "Identified a pattern that may indicate long-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage",
Regex: utils.GenerateUniqueTokenRegex(`ABSK[A-Za-z0-9+/]{109,269}={0,2}`, false),
Entropy: 3,
Keywords: []string{
"ABSK", // Amazon Bedrock API Key (long-lived)
},
}
// validate
tps := []string{
// Valid API key example
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXM=",
// Generate additional random test keys
utils.GenerateSampleSecret("bedrock", "ABSKQmVkcm9ja0FQSUtleS1"+secrets.NewSecret(utils.AlphaNumeric("108"))+"="),
utils.GenerateSampleSecret("bedrock", "ABSKQmVkcm9ja0FQSUtleS1"+secrets.NewSecret(utils.AlphaNumeric("246"))),
}
fps := []string{
// Too short key (missing characters)
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLE",
// Too long
"ABSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLE=",
// Wrong prefix
"AXSKQmVkcm9ja0FQSUtleS1EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXM=",
}
return utils.Validate(r, tps, fps)
}
func AmazonBedrockAPIKeyShortLived() *config.Rule {
// https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-how.html
// https://github.com/aws/aws-bedrock-token-generator-js/blob/86277e1489354192c64ffc8f995601daacc1f715/src/token.ts#L21
r := config.Rule{
RuleID: "aws-amazon-bedrock-api-key-short-lived",
Description: "Identified a pattern that may indicate short-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage",
Regex: regexp.MustCompile(`bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t`),
Entropy: 3,
Keywords: []string{
"bedrock-api-key-", // Amazon Bedrock API Key (short lived)
},
}
// validate
tps := utils.GenerateSampleSecrets("AmazonBedrockAPIKeyShortLived", `bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t`)
fps := []string{
// Too short key (missing characters)
"bedrock-api-key-",
// Wrong prefix
"bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29x",
}
return utils.Validate(r, tps, fps)
}
-5
View File
@@ -13,11 +13,6 @@
title = "{{.Title}}"
# minVersion indicates the minimum Gitleaks version required to use this config.
# If the running version is older, a warning will be logged and not all
# config-enabled features are guaranteed to work.
minVersion = "v8.25.0"
{{ with .Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}# TODO: change to [[allowlists]]{{println}}[allowlist]
{{- with .Description }}{{println}}description = "{{ . }}"{{ end }}
{{- with .MatchCondition }}{{println}}condition = "{{ .String }}"{{ end }}
-35
View File
@@ -1,35 +0,0 @@
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 LookerClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Looker Client ID, risking unauthorized access to a Looker account and exposing sensitive data.",
RuleID: "looker-client-id",
Regex: utils.GenerateSemiGenericRegex([]string{"looker"}, utils.AlphaNumeric("20"), true),
Keywords: []string{"looker"},
}
// validate
tps := utils.GenerateSampleSecrets("looker", secrets.NewSecret(utils.AlphaNumeric("20")))
return utils.Validate(r, tps, nil)
}
func LookerClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Found a Looker Client Secret, risking unauthorized access to a Looker account and exposing sensitive data.",
RuleID: "looker-client-secret",
Regex: utils.GenerateSemiGenericRegex([]string{"looker"}, utils.AlphaNumeric("24"), true),
Keywords: []string{"looker"},
}
// validate
tps := utils.GenerateSampleSecrets("looker", secrets.NewSecret(utils.AlphaNumeric("24")))
return utils.Validate(r, tps, nil)
}
+19 -19
View File
@@ -6,34 +6,34 @@ import (
)
func Notion() *config.Rule {
// Define the identifiers that match the Keywords
identifiers := []string{"ntn_"}
// 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,
}
// 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
// validate
tps := []string{
"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",
"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",
"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",
}
fps := []string{
fps:= []string{
"ntn_12345678901",
"ntn_123456789012345678901234567890123456789012345678901234567890",
"ntn_12345678901abc",
}
return utils.Validate(r, tps, fps)
}
return utils.Validate(r, tps, fps)
}
+6 -10
View File
@@ -10,22 +10,18 @@ func Sonar() *config.Rule {
r := config.Rule{
Description: "Uncovered a Sonar API token, potentially compromising software vulnerability scanning and code security.",
RuleID: "sonar-api-token",
Regex: utils.GenerateSemiGenericRegex([]string{"sonar[_.-]?(login|token)"}, "(?:squ_|sqp_|sqa_)?"+utils.AlphaNumericExtended("40"), true),
Regex: utils.GenerateSemiGenericRegex([]string{"sonar[_.-]?(login|token)"}, utils.AlphaNumericExtended("40"), true),
Keywords: []string{"sonar"},
SecretGroup: 2,
}
// validate
tps := utils.GenerateSampleSecrets("sonar", "12345678ABCDEFH1234567890ABCDEFH12345678")
tps = append(tps,
`const SONAR_LOGIN = "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN :::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ?= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`const SONAR_TOKEN = "squ_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "sqp_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.TOKEN = "sqa_12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`const SONAR_LOGIN = "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR_LOGIN := "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN :::= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
`SONAR.LOGIN ?= "12345678ABCDEFH1234567890ABCDEFH12345678"`, // gitleaks:allow
)
return utils.Validate(r, tps, nil)
}
+5 -4
View File
@@ -1,6 +1,7 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
@@ -62,13 +63,13 @@ func runGit(cmd *cobra.Command, args []string) {
)
if preCommit || staged {
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
}
// Remote info + links are irrelevant for staged changes.
scmPlatform = scm.NoPlatform
} else {
if gitCmd, err = sources.NewGitLogCmdContext(cmd.Context(), source, logOpts); err != nil {
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git log cmd")
}
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
@@ -77,11 +78,11 @@ func runGit(cmd *cobra.Command, args []string) {
}
findings, err = detector.DetectSource(
cmd.Context(),
context.Background(),
&sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfoContext(cmd.Context(), scmPlatform, source),
Remote: sources.NewRemoteInfo(scmPlatform, source),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
+1 -1
View File
@@ -53,7 +53,7 @@ func runProtect(cmd *cobra.Command, args []string) {
remote *detect.RemoteInfo
)
if gitCmd, err = sources.NewGitDiffCmdContext(cmd.Context(), source, staged); err != nil {
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
}
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
+4 -18
View File
@@ -2,7 +2,6 @@ package cmd
import (
"bytes"
"context"
"fmt"
"io"
"os"
@@ -20,7 +19,6 @@ import (
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/version"
)
const banner = `
@@ -44,18 +42,7 @@ var (
rootCmd = &cobra.Command{
Use: "gitleaks",
Short: "Gitleaks scans code, past or present, for secrets",
Version: version.Version,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Set the timeout for all the commands
if timeout, err := cmd.Flags().GetInt("timeout"); err != nil {
return err
} else if timeout > 0 {
ctx, cancel := context.WithTimeout(cmd.Context(), time.Duration(timeout)*time.Second)
cmd.SetContext(ctx)
cobra.OnFinalize(cancel)
}
return nil
},
Version: Version,
}
// diagnostics manager is global to ensure it can be started before a scan begins
@@ -74,7 +61,7 @@ func init() {
cobra.OnInitialize(initLog)
rootCmd.PersistentFlags().StringP("config", "c", "", configDescription)
rootCmd.PersistentFlags().Int("exit-code", 1, "exit code when leaks have been encountered")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file (use \"-\" for stdout)")
rootCmd.PersistentFlags().StringP("report-path", "r", "", "report file")
rootCmd.PersistentFlags().StringP("report-format", "f", "", "output format (json, csv, junit, sarif, template)")
rootCmd.PersistentFlags().StringP("report-template", "", "", "template file used to generate the report (implies --report-format=template)")
rootCmd.PersistentFlags().StringP("baseline-path", "b", "", "path to baseline with issues that can be ignored")
@@ -88,9 +75,8 @@ func init() {
rootCmd.PersistentFlags().Bool("no-banner", false, "suppress banner")
rootCmd.PersistentFlags().StringSlice("enable-rule", []string{}, "only enable specific rules by id")
rootCmd.PersistentFlags().StringP("gitleaks-ignore-path", "i", ".", "path to .gitleaksignore file or folder containing one")
rootCmd.PersistentFlags().Int("max-decode-depth", 5, "allow recursive decoding up to this depth")
rootCmd.PersistentFlags().Int("max-decode-depth", 0, "allow recursive decoding up to this depth (default \"0\", no decoding is done)")
rootCmd.PersistentFlags().Int("max-archive-depth", 0, "allow scanning into nested archives up to this depth (default \"0\", no archive traversal is done)")
rootCmd.PersistentFlags().Int("timeout", 0, "set a timeout for gitleaks commands in seconds (default \"0\", no timeout is set)")
// Add diagnostics flags
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (http OR comma-separated list: cpu,mem,trace). cpu=CPU prof, mem=memory prof, trace=exec tracing, http=serve via net/http/pprof")
@@ -250,7 +236,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
var err error
// Setup common detector
detector := detect.NewDetectorContext(cmd.Context(), cfg)
detector := detect.NewDetector(cfg)
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
logging.Fatal().Err(err).Send()
+2 -1
View File
@@ -1,6 +1,7 @@
package cmd
import (
"context"
"os"
"time"
@@ -37,7 +38,7 @@ func runStdIn(cmd *cobra.Command, _ []string) {
exitCode := mustGetIntFlag(cmd, "exit-code")
findings, err := detector.DetectSource(
cmd.Context(),
context.Background(),
&sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
+3 -2
View File
@@ -4,9 +4,10 @@ import (
"fmt"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/version"
)
var Version = "version is set by build process"
func init() {
rootCmd.AddCommand(versionCmd)
}
@@ -18,5 +19,5 @@ var versionCmd = &cobra.Command{
}
func runVersion(cmd *cobra.Command, args []string) {
fmt.Println(version.Version)
fmt.Println(Version)
}
+8 -67
View File
@@ -7,12 +7,10 @@ import (
"sort"
"strings"
gv "github.com/hashicorp/go-version"
"github.com/spf13/viper"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/regexp"
"github.com/zricethezav/gitleaks/v8/version"
)
var (
@@ -47,19 +45,16 @@ type ViperConfig struct {
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport bool
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport bool
SmartFilter bool
}
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperGlobalAllowlist
Allowlists []*viperGlobalAllowlist
MinVersion string
configPath string
}
type viperRequired struct {
@@ -94,7 +89,6 @@ type Config struct {
// used to keep sarif results consistent
OrderedRules []string
Allowlists []*Allowlist
MinVersion string
}
// Extend is a struct that allows users to define how they want their
@@ -148,6 +142,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
Keywords: vr.Keywords,
Tags: vr.Tags,
SkipReport: vr.SkipReport,
SmartFilter: vr.SmartFilter,
}
// Parse the rule allowlists, including the older format for backwards compatibility.
@@ -201,22 +196,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
Rules: rulesMap,
Keywords: keywords,
OrderedRules: orderedRules,
MinVersion: vc.MinVersion,
}
if extendDepth > 0 {
// annoying hack to set the current config with the extended path
// since if extendDepth > 0 we are operating an extended config.
c.Path = vc.configPath
} else {
// I don't love this
c.Path = viper.ConfigFileUsed()
}
if err := validateMinVersion(c.MinVersion, c.Path); err != nil {
return Config{}, err
}
// Parse the config allowlists, including the older format for backwards compatibility.
if vc.AllowList != nil {
// TODO: Remove this in v9.
@@ -241,8 +221,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
}
}
currentExtendDepth := extendDepth
if maxExtendDepth != currentExtendDepth {
if maxExtendDepth != extendDepth {
// disallow both usedefault and path from being set
if c.Extend.Path != "" && c.Extend.UseDefault {
return Config{}, errors.New("unable to load config due to extend.path and extend.useDefault being set")
@@ -259,7 +238,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
}
// Validate the rules after everything has been assembled (including extended configs).
if currentExtendDepth == 0 {
if extendDepth == 0 {
for _, rule := range c.Rules {
if err := rule.Validate(); err != nil {
return Config{}, err
@@ -280,41 +259,6 @@ func (vc *ViperConfig) Translate() (Config, error) {
return c, nil
}
func validateMinVersion(minVer string, configPath string) error {
if minVer == "" {
logging.Debug().Str("config path", configPath).
Msg("no minVersion specified in config... consider adding minVersion to ensure compatibility.")
return nil
}
if version.Version == version.DefaultMsg {
logging.Debug().
Str("required", minVer).
Msg("dev build, skipping config version check.")
return nil
}
minSemVer, err := gv.NewSemver(minVer)
if err != nil {
return fmt.Errorf("invalid minVersion '%s': %w", minVer, err)
}
currentSemVer, err := gv.NewSemver(version.Version)
if err != nil {
return fmt.Errorf("unable to parse current version: %w", err)
}
if currentSemVer.LessThan(minSemVer) {
logging.Warn().
Str("required", minVer).
Str("current", version.Version).
Str("config path", configPath).
Msg("config requires a newer Gitleaks version...")
}
return nil
}
func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
var matchCondition AllowlistMatchCondition
switch strings.ToUpper(a.Condition) {
@@ -402,13 +346,11 @@ func (c *Config) extendPath(parent *ViperConfig) error {
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
return fmt.Errorf("failed to load extended config, err: %w", err)
}
extensionViperConfig.configPath = c.Extend.Path
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
cfg, err := extensionViperConfig.Translate()
if err != nil {
return fmt.Errorf("failed to load extended config, err: %w", err)
}
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
c.extend(cfg)
return nil
}
@@ -488,5 +430,4 @@ func (c *Config) extend(extensionConfig Config) {
// sort to keep extended rules in order
sort.Strings(c.OrderedRules)
return
}
+4 -17
View File
@@ -93,7 +93,7 @@ func TestTranslate(t *testing.T) {
{
cfgName: "invalid/rule_missing_id",
cfg: Config{},
wantError: errors.New("rule |id| is missing or empty, description: Discord API key, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
wantError: errors.New("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
},
{
cfgName: "invalid/rule_no_regex_or_path",
@@ -449,7 +449,7 @@ func TestTranslateExtend(t *testing.T) {
Rules: map[string]Rule{"aws-access-key": {
RuleID: "aws-access-key",
Description: "AWS Access Key",
Regex: regexp.MustCompile("(a)(a)"),
Regex: regexp.MustCompile("(?:a)(?:a)"),
SecretGroup: 2,
Keywords: []string{},
Tags: []string{"key", "AWS"},
@@ -563,10 +563,6 @@ func TestTranslateExtend(t *testing.T) {
},
// Invalid
{
cfgName: "invalid/extend_invalid_ruleid",
wantError: errors.New("rule |id| is missing or empty"),
},
}
for _, tt := range tests {
@@ -593,17 +589,8 @@ func testTranslate(t *testing.T, test translateCase) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
cfg, err := vc.Translate()
if err != nil {
if test.wantError != nil {
assert.EqualError(t, err, test.wantError.Error())
} else {
require.NoError(t, err)
}
} else {
if test.wantError != nil {
t.Fatalf("expected error but got none: %v", test.wantError)
return
}
if err != nil && !assert.EqualError(t, err, test.wantError.Error()) {
return
}
if len(test.rules) > 0 {
+2 -39
View File
@@ -13,11 +13,6 @@
title = "gitleaks config"
# minVersion indicates the minimum Gitleaks version required to use this config.
# If the running version is older, a warning will be logged and not all
# config-enabled features are guaranteed to work.
minVersion = "v8.25.0"
# TODO: change to [[allowlists]]
[allowlist]
description = "global allow lists"
@@ -114,12 +109,6 @@ description = "Uncovered a possible Airtable API Key, potentially compromising d
regex = '''(?i)[\w.-]{0,50}?(?:airtable)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{17})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["airtable"]
[[rules]]
id = "airtable-personnal-access-token"
description = "Uncovered a possible Airtable Personal AccessToken, potentially compromising database access and leading to data leakage or alteration."
regex = '''\b(pat[[:alnum:]]{14}\.[a-f0-9]{64})\b'''
keywords = ["airtable"]
[[rules]]
id = "algolia-api-key"
description = "Identified an Algolia API Key, which could result in unauthorized search operations and data exposure on Algolia-managed platforms."
@@ -219,20 +208,6 @@ regexes = [
'''.+EXAMPLE$''',
]
[[rules]]
id = "aws-amazon-bedrock-api-key-long-lived"
description = "Identified a pattern that may indicate long-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage"
regex = '''\b(ABSK[A-Za-z0-9+/]{109,269}={0,2})(?:[\x60'"\s;]|\\[nr]|$)'''
entropy = 3
keywords = ["absk"]
[[rules]]
id = "aws-amazon-bedrock-api-key-short-lived"
description = "Identified a pattern that may indicate short-lived Amazon Bedrock API keys, risking unauthorized Amazon Bedrock usage"
regex = '''bedrock-api-key-YmVkcm9jay5hbWF6b25hd3MuY29t'''
entropy = 3
keywords = ["bedrock-api-key-"]
[[rules]]
id = "azure-ad-client-secret"
description = "Azure AD Client Secret"
@@ -651,6 +626,7 @@ keywords = [
"secret",
"token",
]
smartFilter=true
[[rules.allowlists]]
regexes = [
'''^[a-zA-Z_.-]+$''',
@@ -2529,18 +2505,6 @@ keywords = [
"_pub",
]
[[rules]]
id = "looker-client-id"
description = "Found a Looker Client ID, risking unauthorized access to a Looker account and exposing sensitive data."
regex = '''(?i)[\w.-]{0,50}?(?:looker)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{20})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["looker"]
[[rules]]
id = "looker-client-secret"
description = "Found a Looker Client Secret, risking unauthorized access to a Looker account and exposing sensitive data."
regex = '''(?i)[\w.-]{0,50}?(?:looker)(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9]{24})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["looker"]
[[rules]]
id = "mailchimp-api-key"
description = "Identified a Mailchimp API key, potentially compromising email marketing campaigns and subscriber data."
@@ -3043,8 +3007,7 @@ keywords = ["snyk"]
[[rules]]
id = "sonar-api-token"
description = "Uncovered a Sonar API token, potentially compromising software vulnerability scanning and code security."
regex = '''(?i)[\w.-]{0,50}?(?:sonar[_.-]?(login|token))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}((?:squ_|sqp_|sqa_)?[a-z0-9=_\-]{40})(?:[\x60'"\s;]|\\[nr]|$)'''
secretGroup = 2
regex = '''(?i)[\w.-]{0,50}?(?:sonar[_.-]?(login|token))(?:[ \t\w.-]{0,20})[\s'"]{0,3}(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)[\x60'"\s=]{0,5}([a-z0-9=_\-]{40})(?:[\x60'"\s;]|\\[nr]|$)'''
keywords = ["sonar"]
[[rules]]
+9 -9
View File
@@ -52,6 +52,8 @@ type Rule struct {
RequiredRules []*Required
SkipReport bool
SmartFilter bool
}
type Required struct {
@@ -69,17 +71,15 @@ func (r *Rule) Validate() error {
// Ensure |id| is present.
if strings.TrimSpace(r.RuleID) == "" {
// Try to provide helpful context, since |id| is empty.
var sb strings.Builder
if r.Description != "" {
sb.WriteString(", description: " + r.Description)
}
var context string
if r.Regex != nil {
sb.WriteString(", regex: " + r.Regex.String())
context = ", regex: " + r.Regex.String()
} else if r.Path != nil {
context = ", path: " + r.Path.String()
} else if r.Description != "" {
context = ", description: " + r.Description
}
if r.Path != nil {
sb.WriteString(", path: " + r.Path.String())
}
return errors.New("rule |id| is missing or empty" + sb.String())
return errors.New("rule |id| is missing or empty" + context)
}
// Ensure the rule actually matches something.
+1 -2
View File
@@ -3,9 +3,8 @@ package codec
import (
"fmt"
"math"
"regexp"
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
+1 -2
View File
@@ -2,11 +2,10 @@ package codec
import (
"bytes"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/zricethezav/gitleaks/v8/regexp"
)
var (
+147 -55
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,12 +122,13 @@ type Fragment sources.Fragment
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
return NewDetectorContext(context.Background(), cfg)
}
// 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")
}
// NewDetectorContext is the same as NewDetector but supports passing in a
// context to use for timeouts
func NewDetectorContext(ctx context.Context, cfg config.Config) *Detector {
return &Detector{
commitMap: make(map[string]bool),
gitleaksIgnore: make(map[string]struct{}),
@@ -127,7 +137,11 @@ func NewDetectorContext(ctx context.Context, cfg config.Config) *Detector {
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
Sema: semgroup.NewGroup(ctx, 40),
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}),
}
}
@@ -246,7 +260,7 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
})
}
for _, finding := range d.DetectContext(ctx, Fragment(fragment)) {
for _, finding := range d.Detect(Fragment(fragment)) {
d.AddFinding(finding)
}
@@ -268,12 +282,6 @@ func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]r
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
return d.DetectContext(context.Background(), fragment)
}
// DetectContext is the same as Detect but supports passing in a
// context to use for timeouts
func (d *Detector) DetectContext(ctx context.Context, fragment Fragment) []report.Finding {
if fragment.Bytes == nil {
d.TotalBytes.Add(uint64(len(fragment.Raw)))
}
@@ -310,57 +318,46 @@ func (d *Detector) DetectContext(ctx context.Context, fragment Fragment) []repor
currentDecodeDepth := 0
decoder := codec.NewDecoder()
ScanLoop:
for {
select {
case <-ctx.Done():
break ScanLoop
default:
// build keyword map for prefiltering rules
keywords := make(map[string]bool)
normalizedRaw := strings.ToLower(currentRaw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
// build keyword map for prefiltering rules
keywords := make(map[string]bool)
normalizedRaw := strings.ToLower(currentRaw)
matches := d.prefilter.MatchString(normalizedRaw)
for _, m := range matches {
keywords[normalizedRaw[m.Pos():int(m.Pos())+len(m.Match())]] = true
}
for _, rule := range d.Config.Rules {
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, currentRaw, rule, encodedSegments)...)
continue
}
for _, rule := range d.Config.Rules {
select {
case <-ctx.Done():
break ScanLoop
default:
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, 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, currentRaw, rule, encodedSegments)...)
break
}
}
// 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, currentRaw, rule, encodedSegments)...)
break
}
}
}
// increment the depth by 1 as we start our decoding pass
currentDecodeDepth++
// increment the depth by 1 as we start our decoding pass
currentDecodeDepth++
// stop the loop if we've hit our max decoding depth
if currentDecodeDepth > d.MaxDecodeDepth {
break ScanLoop
}
// stop the loop if we've hit our max decoding depth
if currentDecodeDepth > d.MaxDecodeDepth {
break
}
// decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
// decode the currentRaw for the next pass
currentRaw, encodedSegments = decoder.Decode(currentRaw, encodedSegments)
// stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 {
break ScanLoop
}
// stop the loop when there's nothing else to decode
if len(encodedSegments) == 0 {
break
}
}
@@ -564,6 +561,12 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
event.Msg("skipping finding: rule allowlist")
continue
}
if r.SmartFilter {
if !d.passesSmartFilter(finding.Secret) {
continue
}
}
findings = append(findings, finding)
}
@@ -576,6 +579,95 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
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 {
+4 -21
View File
@@ -1530,7 +1530,6 @@ func TestDetectWithArchives(t *testing.T) {
tests := []struct {
cfgName string
source string
expireContext bool
expectedFindings []report.Finding
}{
{
@@ -2060,12 +2059,6 @@ func TestDetectWithArchives(t *testing.T) {
},
},
},
{
source: filepath.Join(archivesBasePath, "nested.tar.gz"),
cfgName: "archives",
expireContext: true,
expectedFindings: []report.Finding{},
},
}
for _, tt := range tests {
@@ -2080,17 +2073,13 @@ func TestDetectWithArchives(t *testing.T) {
err = viper.Unmarshal(&vc)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
if tt.expireContext {
cancel()
}
cfg, _ := vc.Translate()
detector := NewDetectorContext(ctx, cfg)
detector := NewDetector(cfg)
detector.MaxArchiveDepth = 8
findings, err := detector.DetectSource(
ctx, &sources.Files{
context.Background(),
&sources.Files{
Path: tt.source,
Sema: detector.Sema,
Config: &cfg,
@@ -2098,13 +2087,7 @@ func TestDetectWithArchives(t *testing.T) {
},
)
if tt.expireContext {
require.EqualError(t, err, "context canceled")
} else {
cancel()
require.NoError(t, err)
}
require.NoError(t, err)
// TODO: Temporary mitigation.
// https://github.com/gitleaks/gitleaks/issues/1641
normalizedFindings := make([]report.Finding, len(findings))
+56 -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"
@@ -136,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")
@@ -261,3 +280,39 @@ func printFinding(f report.Finding, noColor bool) {
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
}
+8 -2
View File
@@ -1,21 +1,26 @@
module github.com/zricethezav/gitleaks/v8
go 1.24.11
go 1.24
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/hashicorp/go-version v1.7.0
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
)
@@ -29,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
+14 -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=
@@ -105,8 +113,6 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=
github.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
@@ -174,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=
@@ -234,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=
+1 -7
View File
@@ -29,13 +29,7 @@ func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
// TODO: Add helper functions like escaping for JSON, XML, etc.
t := template.New("custom")
funcMap := sprig.TxtFuncMap()
delete(funcMap, "env")
delete(funcMap, "expandenv")
delete(funcMap, "getHostByName")
t = t.Funcs(funcMap)
t = t.Funcs(sprig.TxtFuncMap())
t, err = t.Parse(templateText)
if err != nil {
return nil, fmt.Errorf("error parsing file: %w", err)
-49
View File
@@ -96,52 +96,3 @@ func TestWriteTemplate(t *testing.T) {
})
}
}
func TestTemplateDangerousFunctions(t *testing.T) {
tests := []struct {
name string
template string
wantErr string
}{
{
name: "env is blocked",
template: `{{ env "SECRET" }}`,
wantErr: `function "env" not defined`,
},
{
name: "expandenv is blocked",
template: `{{ expandenv "$SECRET" }}`,
wantErr: `function "expandenv" not defined`,
},
{
name: "getHostByName is blocked",
template: `{{ getHostByName "localhost" }}`,
wantErr: `function "getHostByName" not defined`,
},
{
name: "now is allowed (benign)",
template: `{{ now | date "2006-01-02" }}`,
wantErr: "", // should not error on parse
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpfile, err := os.CreateTemp(t.TempDir(), "test*.tmpl")
require.NoError(t, err)
defer os.Remove(tmpfile.Name())
_, err = tmpfile.WriteString(tt.template)
require.NoError(t, err)
tmpfile.Close()
_, err = NewTemplateReporter(tmpfile.Name())
if tt.wantErr != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
} else {
assert.NoError(t, err)
}
})
}
}
+67 -80
View File
@@ -12,7 +12,6 @@ import (
"github.com/h2non/filetype"
"github.com/mholt/archives"
"github.com/rs/zerolog"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
@@ -57,33 +56,26 @@ 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 {
var event *zerolog.Event
// Warn if the feature is enabled; else emit a trace log.
// Only warn when the feature is enabled
if s.MaxArchiveDepth != 0 {
event = logging.Warn()
} else {
event = logging.Trace()
logging.Warn().Str(
"path", s.FullPath(),
).Int(
"max_archive_depth", s.MaxArchiveDepth,
).Msg("skipping archive: exceeds max archive depth")
}
event.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 {
return s.extractorFragments(ctx, extractor, s.Content, yield)
}
if decompressor, ok := format.(archives.Decompressor); ok {
return s.decompressorFragments(ctx, decompressor, s.Content, yield)
return s.decompressorFragments(decompressor, s.Content, yield)
}
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
}
return s.fileFragments(ctx, bufio.NewReader(s.Content), yield)
return s.fileFragments(bufio.NewReader(s.Content), yield)
}
// extractorFragments recursively crawls archives and yields fragments
@@ -147,14 +139,14 @@ func (s *File) extractorFragments(ctx context.Context, extractor archives.Extrac
}
// decompressorFragments recursively crawls archives and yields fragments
func (s *File) decompressorFragments(ctx context.Context, decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
func (s *File) decompressorFragments(decompressor archives.Decompressor, reader io.Reader, yield FragmentsFunc) error {
innerReader, err := decompressor.OpenReader(reader)
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could read compressed file")
return nil
}
if err := s.fileFragments(ctx, bufio.NewReader(innerReader), yield); err != nil {
if err := s.fileFragments(bufio.NewReader(innerReader), yield); err != nil {
_ = innerReader.Close()
return err
}
@@ -164,7 +156,7 @@ func (s *File) decompressorFragments(ctx context.Context, decompressor archives.
}
// fileFragments reads the file into fragments to yield
func (s *File) fileFragments(ctx context.Context, reader *bufio.Reader, yield FragmentsFunc) error {
func (s *File) fileFragments(reader *bufio.Reader, yield FragmentsFunc) error {
// Create a buffer if the caller hasn't provided one
if s.Buffer == nil {
s.Buffer = make([]byte, defaultBufferSize)
@@ -172,80 +164,75 @@ func (s *File) fileFragments(ctx context.Context, reader *bufio.Reader, yield Fr
totalLines := 0
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
fragment := Fragment{
FilePath: s.FullPath(),
fragment := Fragment{
FilePath: s.FullPath(),
}
n, err := reader.Read(s.Buffer)
if n == 0 {
if err != nil && err != io.EOF {
return yield(fragment, fmt.Errorf("could not read file: %w", err))
}
n, err := reader.Read(s.Buffer)
if n == 0 {
if err != nil && err != io.EOF {
return yield(fragment, fmt.Errorf("could not read file: %w", err))
}
return nil
}
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not determine type: %w", err),
)
} else if mimetype.MIME.Type == "application" {
logging.Debug().
Str("mime_type", mimetype.MIME.Value).
Str("path", s.FullPath()).
Msgf("skipping binary file")
return nil
}
}
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(s.Buffer[:n]); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not determine type: %w", err),
)
} else if mimetype.MIME.Type == "application" {
logging.Debug().
Str("mime_type", mimetype.MIME.Value).
Str("path", s.FullPath()).
Msgf("skipping binary file")
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(s.Buffer[:n])
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
)
}
return nil
}
}
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(s.Buffer[:n])
if err := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); err != nil {
return yield(
fragment,
fmt.Errorf("could not read file: could not read until safe boundary: %w", err),
)
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
// log errors but continue since there's content
if err != nil && err != io.EOF {
logging.Warn().Err(err).Msgf("issue reading file")
}
// Done with the file!
if err == io.EOF {
return yield(fragment, nil)
}
if err := yield(fragment, err); err != nil {
return err
}
if err := yield(fragment, err); err != nil {
return err
}
}
}
+32 -43
View File
@@ -34,8 +34,7 @@ func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool,
}
s.Go(func() error {
ctx := context.Background()
err := files.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
paths <- scanTarget
return nil
})
@@ -57,7 +56,7 @@ type Files struct {
}
// scanTargets yields scan targets to a callback func
func (s *Files) scanTargets(ctx context.Context, yield func(ScanTarget, error) error) error {
func (s *Files) scanTargets(yield func(ScanTarget, error) error) error {
return filepath.WalkDir(s.Path, func(path string, d fs.DirEntry, err error) error {
scanTarget := ScanTarget{Path: path}
logger := logging.With().Str("path", path).Logger()
@@ -142,50 +141,40 @@ func (s *Files) scanTargets(ctx context.Context, yield func(ScanTarget, error) e
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
var wg sync.WaitGroup
err := s.scanTargets(ctx, func(scanTarget ScanTarget, err error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
err := s.scanTargets(func(scanTarget ScanTarget, err error) error {
wg.Add(1)
s.Sema.Go(func() error {
logger := logging.With().Str("path", scanTarget.Path).Logger()
logger.Trace().Msg("scanning path")
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("skipping file: permission denied")
}
wg.Done()
return nil
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("skipping file: permission denied")
}
// Convert this to a file source
file := File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: s.Config,
MaxArchiveDepth: s.MaxArchiveDepth,
}
err = file.Fragments(ctx, yield)
// Avoiding a defer in a hot loop
_ = f.Close()
wg.Done()
return err
})
return nil
}
return nil
}
// Convert this to a file source
file := File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: s.Config,
MaxArchiveDepth: s.MaxArchiveDepth,
}
err = file.Fragments(ctx, yield)
// Avoiding a defer in a hot loop
_ = f.Close()
wg.Done()
return err
})
return nil
})
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return err
}
wg.Wait()
return err
}
+12 -50
View File
@@ -63,12 +63,6 @@ func (br *blobReader) Close() error {
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
return NewGitLogCmdContext(context.Background(), source, logOpts)
}
// NewGitLogCmdContext is the same as NewGitLogCmd but supports passing in a
// context to use for timeouts
func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
if logOpts != "" {
@@ -88,9 +82,9 @@ func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*G
}
args = append(args, userArgs...)
cmd = exec.CommandContext(ctx, "git", args...)
cmd = exec.Command("git", args...)
} else {
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "log", "-p", "-U0",
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all", "--diff-filter=tuxdb")
}
@@ -128,17 +122,11 @@ func NewGitLogCmdContext(ctx context.Context, source string, logOpts string) (*G
// Caller should read everything from channels until receiving a signal about their closure and call
// the `func (*DiffFilesCmd) Wait()` error in order to release resources.
func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
return NewGitDiffCmdContext(context.Background(), source, staged)
}
// NewGitDiffCmdContext is the same as NewGitDiffCmd but supports passing in a
// context to use for timeouts
func NewGitDiffCmdContext(ctx context.Context, source string, staged bool) (*GitCmd, error) {
sourceClean := filepath.Clean(source)
var cmd *exec.Cmd
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff", ".")
if staged {
cmd = exec.CommandContext(ctx, "git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
"--staged", ".")
}
logging.Debug().Msgf("executing: %s", cmd.String())
@@ -189,24 +177,13 @@ func (c *GitCmd) Wait() error {
return c.cmd.Wait()
}
// String displays the command used for GitCmd
func (c *GitCmd) String() string {
return c.cmd.String()
}
// NewBlobReader returns an io.ReadCloser that can be used to read a blob
// within the git repo used to create the GitCmd.
//
// The caller is responsible for closing the reader.
func (c *GitCmd) NewBlobReader(commit, path string) (io.ReadCloser, error) {
return c.NewBlobReaderContext(context.Background(), commit, path)
}
// NewBlobReaderContext is the same as NewBlobReader but supports passing in a
// context to use for timeouts
func (c *GitCmd) NewBlobReaderContext(ctx context.Context, commit, path string) (io.ReadCloser, error) {
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
cmd := exec.CommandContext(ctx, "git", gitArgs...)
cmd := exec.Command("git", gitArgs...)
cmd.Stderr = io.Discard
stdout, err := cmd.StdoutPipe()
if err != nil {
@@ -298,9 +275,7 @@ type CommitInfo struct {
// Fragments yields fragments from a git repo
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer func() {
if err := s.Cmd.Wait(); err != nil {
logging.Debug().Err(err).Str("cmd", s.Cmd.String()).Msg("command aborted")
}
_ = s.Cmd.Wait()
}()
var (
@@ -312,8 +287,6 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case <-ctx.Done():
return ctx.Err()
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
@@ -363,7 +336,7 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer wg.Done()
if yieldAsArchive {
blob, err := s.Cmd.NewBlobReaderContext(ctx, commitSHA, gitdiffFile.NewName)
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Error().Err(err).Msg("could not read archive blob")
return nil
@@ -421,28 +394,17 @@ func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
wg.Wait()
return nil
}
wg.Wait()
return nil
}
// NewRemoteInfo builds a new RemoteInfo for generating finding links
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
return NewRemoteInfoContext(context.Background(), platform, source)
}
// NewRemoteInfoContext is the same as NewRemoteInfo but supports passing in a
// context to use for timeouts
func NewRemoteInfoContext(ctx context.Context, platform scm.Platform, source string) *RemoteInfo {
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
remoteUrl, err := getRemoteUrl(ctx, source)
remoteUrl, err := getRemoteUrl(source)
if err != nil {
if strings.Contains(err.Error(), "No remote configured") {
logging.Debug().Msg("skipping finding links: repository has no configured remote.")
@@ -480,9 +442,9 @@ End:
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):(?:\d{1,5}/)?([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(ctx context.Context, source string) (*url.URL, error) {
func getRemoteUrl(source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.CommandContext(ctx, "git", "ls-remote", "--quiet", "--get-url")
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
-7
View File
@@ -1,7 +0,0 @@
[extend]
useDefault = true
[[rules]]
[[rules.allowlists]]
paths = ['^.*\.(xml|log|json)$']
@@ -5,5 +5,5 @@ path = "../testdata/config/simple.toml"
[[rules]]
id = "aws-access-key"
regex = '''(a)(a)'''
regex = '''(?:a)(?:a)'''
secretGroup = 2
-5
View File
@@ -1,5 +0,0 @@
package version
// these two gotta be the same
var DefaultMsg = "version is set by build process"
var Version = "version is set by build process"