Compare commits

..
Author SHA1 Message Date
Zach 2f0c6f34bf removed some important stuff on accident 2025-05-13 22:25:42 -05:00
Zach 66c5bc15d4 prob should sleep 2025-05-13 22:12:53 -05:00
Zach fa9fadbb84 possibly could just be an idiot 2025-05-13 22:06:12 -05:00
Zach d5e7364bcf skip windowS 2025-05-13 21:57:33 -05:00
Zach e0ea9cefde one tmp dir to rule them all, I think 2025-05-13 21:39:09 -05:00
Zach 56e409d9f1 Merge branch 'master' of github.com:gitleaks/gitleaks into archive-handling 2025-05-13 20:34:56 -05:00
Zach 5f210c9d35 rm comments 2025-04-28 09:43:17 -05:00
Zach 770baf7458 first pass at archive handling 2025-04-28 09:39:22 -05:00
100 changed files with 1167 additions and 4154 deletions

No files matched your search

+1 -3
View File
@@ -1,7 +1,5 @@
name: gitleaks
on:
push:
workflow_dispatch:
on: [push, workflow_dispatch]
jobs:
scan:
name: gitleaks
-1
View File
@@ -9,7 +9,6 @@
*.got
gitleaks
build
profile
# configs
.gitleaks.toml
+1 -3
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,6 +9,4 @@ useDefault = true
[allowlist]
paths = [
'''(^|/)cmd/generate/config/rules''',
'''.*test\.go''',
'''testdata'''
]
-2
View File
@@ -940,5 +940,3 @@ 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
-86
View File
@@ -1,86 +0,0 @@
version: '2'
linters:
default: none
# It might be worth going through some of the disabled linters and enabling
# them and fixing the items they call out e.g.: cyclop, prealloc,
# paralleltest, prealloc, errcheck, dupl, unused, testifylint, gosec,
# gocritic, perfsprint, exptostd, intrange, perfsprint (maybe others?)
disable:
- cyclop
- depguard
- dupl
- err113
- errcheck
- exhaustive
- exhaustruct
- exptostd
- forbidigo
- funcorder
- funlen
- gochecknoglobals
- gochecknoinits
- gocognit
- goconst
- gocritic
- gocyclo
- godot
- godox
- gosec
- gosmopolitan
- intrange
- lll
- maintidx
- mnd
- musttag
- nestif
- nilerr
- nlreturn
- nonamedreturns
- paralleltest
- perfsprint
- prealloc
- predeclared
- tagliatelle
- testifylint
- testpackage
- tparallel
- unparam
- unused
- varnamelen
- wastedassign
- whitespace
- wrapcheck
- wsl
- zerologlint # doesn't seem to catch gitleaks/v8/logging mistakes
enable:
- inamedparam
- misspell
- revive
- misspell
- inamedparam
- exhaustruct
- inamedparam
- misspell
- nonamedreturns
- staticcheck
- unconvert
exclusions:
rules:
- linters:
- staticcheck
source: 'detector\.Detect\w+\(|sources\.DirectoryTargets\(|detect\.(?:Fragment|RemoteInfo)'
- linters:
- misspell
source: '"(?:addres|busines|clas)",'
settings:
staticcheck:
checks:
- all
- '-QF1001'
- '-ST1000'
- '-ST1003'
- '-ST1018'
- '-ST1020'
- '-ST1021'
revive:
severity: error
+1 -2
View File
@@ -9,9 +9,8 @@
description: Detect hardcoded secrets using Gitleaks
entry: zricethezav/gitleaks git --pre-commit --redact --staged --verbose
language: docker_image
pass_filenames: false
- id: gitleaks-system
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: gitleaks git --pre-commit --redact --staged --verbose
entry: gitleaks git --pre-commit --redact --staged --verbose
language: system
+2 -2
View File
@@ -35,7 +35,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
RuleID: "beamer-api-token",
// Regex capture group for the actual secret
// Regex used for detecting secrets. See regex section below for more details
@@ -95,7 +95,7 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
the `rules.Beamer(),` in `main()`. Try and keep
this alphabetically pretty please.
1. Run `make config/gitleaks.toml`
1. Run `go generate ./...`
1. Check out your new rules in `config/gitleaks.toml` and see if everything looks good.
+3 -16
View File
@@ -1,4 +1,4 @@
.PHONY: test test-cover failfast profile clean format build
.PHONY: test test-cover
PKG=github.com/zricethezav/gitleaks
VERSION := `git fetch --tags && git tag | sort -V | tail -1`
@@ -12,26 +12,13 @@ test-cover:
format:
go fmt ./...
test: config/gitleaks.toml format
test: format
go test -v ./... --race $(PKG)
failfast: format
go test -failfast ./...
build: config/gitleaks.toml format
build: format
go mod tidy
go build $(LDFLAGS)
lint:
golangci-lint run
clean:
rm -rf profile
find . -type f -name '*.got.*' -delete
find . -type f -name '*.out' -delete
profile: build
./scripts/profile.sh './gitleaks' '.'
config/gitleaks.toml: $(wildcard cmd/generate/config/**/*)
go generate ./...
+6 -138
View File
@@ -24,7 +24,7 @@
[gitleaks-playground]: https://gitleaks.io/playground
[![GitHub Action Test][badge-build]][build]
[![Github Action Test][badge-build]][build]
[![Docker Hub][dockerhub-badge]][dockerhub]
[![Gitleaks Playground][gitleaks-playground-badge]][gitleaks-playground]
[![Gitleaks Action][gitleaks-badge]][gitleaks-action]
@@ -35,8 +35,7 @@
### 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).
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`.
```
➜ ~/code(master) gitleaks git -v
@@ -119,7 +118,7 @@ jobs:
- id: gitleaks
```
for a [native execution of gitleaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing gitleaks using the [official Docker images](#docker)
for a [native execution of GitLeaks](https://github.com/gitleaks/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/gitleaks/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
3. Auto-update the config to the latest repos' versions by executing `pre-commit autoupdate`
4. Install with `pre-commit install`
@@ -169,7 +168,6 @@ Flags:
--ignore-gitleaks-allow ignore gitleaks:allow comments
-l, --log-level string log level (trace, debug, info, warn, error, fatal) (default "info")
--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
@@ -192,7 +190,6 @@ If you find v8.19.0 broke an existing command (`detect`/`protect`), please open
There are three scanning modes: `git`, `dir`, and `stdin`.
#### Git
The `git` command lets you scan local git repos. Under the hood, gitleaks uses the `git log -p` command to scan patches.
You can configure the behavior of `git log -p` with the `log-opts` option.
For example, if you wanted to run gitleaks on a range of commits you could use the following
@@ -200,12 +197,10 @@ command: `gitleaks git -v --log-opts="--all commitA..commitB" path_to_repo`. See
If there is no target specified as a positional argument, then gitleaks will attempt to scan the current working directory as a git repo.
#### Dir
The `dir` (aliases include `files`, `directory`) command lets you scan directories and files. Example: `gitleaks dir -v path_to_directory_or_file`.
If there is no target specified as a positional argument, then gitleaks will scan the current working directory.
#### Stdin
You can also stream data to gitleaks with the `stdin` command. Example: `cat some_file | gitleaks -v stdin`
### Creating a baseline
@@ -375,7 +370,7 @@ id = "gitlab-pat"
# ⚠️ In v8.25.0 `[allowlist]` was replaced with `[[allowlists]]`.
#
#
# Global allowlists have a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
# secrets will be detected for said commit. The same logic applies for regexes and paths.
@@ -415,94 +410,6 @@ 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
@@ -544,47 +451,8 @@ ways:
Currently supported encodings:
- **percent** - Any printable ASCII percent encoded values
- **hex** - Any printable ASCII hex encoded values >= 32 characters
- **base64** - Any printable ASCII base64 encoded values >= 16 characters
#### Archive Scanning
Sometimes secrets are packaged within archive files like zip files or tarballs,
making them difficult to discover. Now you can tell gitleaks to automatically
extract and scan the contents of archives. The flag `--max-archive-depth`
enables this feature for both `dir` and `git` scan types. The default value of
"0" means this feature is disabled by default.
Recursive scanning is supported since archives can also contain other archives.
The `--max-archive-depth` flag sets the recursion limit. Recursion stops when
there are no new archives to extract, so setting a very high max depth just
sets the potential to go that deep. It will only go as deep as it needs to.
The findings for secrets located within an archive will include the path to the
file inside the archive. Inner paths are separated with `!`.
Example finding (shortened for brevity):
```
Finding: DB_PASSWORD=8ae31cacf141669ddfb5da
...
File: testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod
Line: 4
Commit: 6e6ee6596d337bb656496425fb98644eb62b4a82
...
Fingerprint: 6e6ee6596d337bb656496425fb98644eb62b4a82:testdata/archives/nested.tar.gz!archives/files.tar!files/.env.prod:generic-api-key:4
Link: https://github.com/leaktk/gitleaks/blob/6e6ee6596d337bb656496425fb98644eb62b4a82/testdata/archives/nested.tar.gz
```
This means a secret was detected on line 4 of `files/.env.prod.` which is in
`archives/files.tar` which is in `testdata/archives/nested.tar.gz`.
Currently supported formats:
The [compression](https://github.com/mholt/archives?tab=readme-ov-file#supported-compression-formats)
and [archive](https://github.com/mholt/archives?tab=readme-ov-file#supported-archive-formats)
formats supported by mholt's [archives package](https://github.com/mholt/archives)
are supported.
- **hex** - Any printable ASCII hex encoded values >= 32 characters
- **base64** - Any printable ASCII base64 encoded values >= 16 characters
#### Reporting
+21 -40
View File
@@ -19,13 +19,13 @@
package cmd
import (
"context"
"os"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -51,15 +51,15 @@ var detectCmd = &cobra.Command{
func runDetect(cmd *cobra.Command, args []string) {
// start timer
start := time.Now()
sourcePath := mustGetStringFlag(cmd, "source")
source := mustGetStringFlag(cmd, "source")
// setup config (aka, the thing that defines rules)
initConfig(sourcePath)
initConfig(source)
initDiagnostics()
cfg := Config(cmd)
// create detector
detector := Detector(cmd, cfg, sourcePath)
detector := Detector(cmd, cfg, source)
// parse flags
detector.FollowSymlinks = mustGetBoolFlag(cmd, "follow-symlinks")
@@ -71,65 +71,46 @@ func runDetect(cmd *cobra.Command, args []string) {
// - 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()
err error
)
if noGit {
findings, err = detector.DetectSource(
ctx, &sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: sourcePath,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
paths, err := sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlists,
)
if err != nil {
logging.Fatal().Err(err).Send()
}
if findings, err = detector.DetectFiles(paths); err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan directory")
logging.Error().Err(err).Msg("failed scan directory")
}
} else if fromPipe {
findings, err = detector.DetectSource(
ctx, &sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
if findings, err = detector.DetectReader(os.Stdin, 10); err != nil {
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}
} else {
var (
logOpts = mustGetStringFlag(cmd, "log-opts")
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
logOpts := mustGetStringFlag(cmd, "log-opts")
if gitCmd, err = sources.NewGitLogCmd(sourcePath, logOpts); err != nil {
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git cmd")
}
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
findings, err = detector.DetectSource(
ctx, &sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, sourcePath),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
if err != nil {
if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
}
+2 -32
View File
@@ -1,10 +1,7 @@
package cmd
import (
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"path/filepath"
"runtime"
@@ -37,14 +34,6 @@ func NewDiagnosticsManager(diagnosticsFlag string, diagnosticsDir string) (*Diag
OutputDir: diagnosticsDir,
}
if diagnosticsFlag == "http" {
if len(diagnosticsDir) != 0 {
return nil, errors.New("the diagnostics directory should not be set in http mode")
}
return dm, nil
}
// If no output directory is specified, use the current directory
if dm.OutputDir == "" {
var err error
@@ -98,10 +87,6 @@ func (dm *DiagnosticsManager) StartDiagnostics() error {
if err = dm.StartTraceProfile(); err != nil {
return err
}
case "http":
if err = dm.StartHttpHandler(); err != nil {
return err
}
default:
logging.Warn().Msgf("Unknown diagnostics type: %s", diagType)
}
@@ -127,25 +112,10 @@ func (dm *DiagnosticsManager) StopDiagnostics() {
dm.WriteMemoryProfile()
case "trace":
dm.StopTraceProfile()
case "http":
// No need to stop the http one
}
}
}
func (dm *DiagnosticsManager) StartHttpHandler() error {
if len(dm.DiagTypes) > 1 {
return errors.New("other diagnostics modes should not be enabled when http mode is enabled")
}
go func() {
logging.Error().Err(http.ListenAndServe("localhost:6060", nil)).Send()
}()
logging.Info().Str("url", "http://localhost:6060/debug/pprof/").Msg("Diagnostics server started")
return nil
}
// StartCPUProfile starts CPU profiling
func (dm *DiagnosticsManager) StartCPUProfile() error {
cpuProfilePath := filepath.Join(dm.OutputDir, "cpu.pprof")
@@ -155,7 +125,7 @@ func (dm *DiagnosticsManager) StartCPUProfile() error {
}
if err := pprof.StartCPUProfile(f); err != nil {
_ = f.Close()
f.Close()
return fmt.Errorf("could not start CPU profile: %w", err)
}
@@ -218,7 +188,7 @@ func (dm *DiagnosticsManager) StartTraceProfile() error {
}
if err := trace.Start(f); err != nil {
_ = f.Close()
f.Close()
return fmt.Errorf("could not start trace profile: %w", err)
}
+19 -15
View File
@@ -1,12 +1,12 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
@@ -34,7 +34,11 @@ func runDirectory(cmd *cobra.Command, args []string) {
initConfig(source)
initDiagnostics()
var err error
var (
findings []report.Finding
err error
)
// setup config (aka, the thing that defines rules)
cfg := Config(cmd)
@@ -46,28 +50,28 @@ func runDirectory(cmd *cobra.Command, args []string) {
// set follow symlinks flag
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
logging.Fatal().Err(err).Msg("could not get exit code")
}
findings, err := detector.DetectSource(
context.Background(),
&sources.Files{
Config: &cfg,
FollowSymlinks: detector.FollowSymlinks,
MaxFileSize: detector.MaxTargetMegaBytes * 1_000_000,
Path: source,
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
var paths <-chan sources.ScanTarget
paths, err = sources.DirectoryTargets(
source,
detector.Sema,
detector.FollowSymlinks,
detector.Config.Allowlists,
)
if err != nil {
logging.Fatal().Err(err)
}
findings, err = detector.DetectFiles(paths)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed scan directory")
}
+1 -3
View File
@@ -105,9 +105,7 @@ func CreateGlobalConfig() config.Config {
// Misc
regexp.MustCompile(`verification-metadata\.xml`),
regexp.MustCompile(`Database.refactorlog`),
// ----------- Git files ------------
regexp.MustCompile(`(?:^|/)\.git$`),
// regexp.MustCompile(`vendor`),
},
StopWords: []string{
"abcdefghijklmnopqrstuvwxyz", // character range
+10 -18
View File
@@ -2,9 +2,10 @@ package main
import (
"os"
"slices"
"text/template"
"golang.org/x/exp/slices"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
@@ -35,10 +36,6 @@ func main() {
rules.AlgoliaApiKey(),
rules.AlibabaAccessKey(),
rules.AlibabaSecretKey(),
rules.AnthropicAdminApiKey(),
rules.AnthropicApiKey(),
rules.ArtifactoryApiKey(),
rules.ArtifactoryReferenceToken(),
rules.AsanaClientID(),
rules.AsanaClientSecret(),
rules.Atlassian(),
@@ -129,7 +126,6 @@ func main() {
rules.HashiCorpTerraform(),
rules.HashicorpField(),
rules.Heroku(),
rules.HerokuV2(),
rules.HubSpot(),
rules.HuggingFaceAccessToken(),
rules.HuggingFaceOrganizationApiToken(),
@@ -165,7 +161,6 @@ func main() {
rules.NewRelicUserKey(),
rules.NewRelicBrowserAPIKey(),
rules.NewRelicInsertKey(),
rules.Notion(),
rules.NPM(),
rules.NugetConfigPassword(),
rules.NytimesAccessToken(),
@@ -254,6 +249,7 @@ 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 {
@@ -264,13 +260,6 @@ 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)
@@ -286,11 +275,14 @@ 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
@@ -1,69 +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 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
@@ -1,58 +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"
"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)
}
+7 -10
View File
@@ -13,9 +13,9 @@ func Atlassian() *config.Rule {
RuleID: "atlassian-api-token",
Regex: utils.MergeRegexps(
utils.GenerateSemiGenericRegex(
[]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,
[]string{"atlassian", "confluence", "jira"},
`[a-zA-Z0-9]{24}`,
false,
),
utils.GenerateUniqueTokenRegex(`ATATT3[A-Za-z0-9_\-=]{186}`, false),
),
@@ -24,13 +24,10 @@ func Atlassian() *config.Rule {
}
// validate
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 := 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 = append(tps, utils.GenerateSampleSecrets("jira", "ATATT3xFfGF0K3irG5tKKi-6u-wwaXQFeGwZ-IHR-hQ3CulkKtMSuteRQFfLZ6jihHThzZCg_UjnDt-4Wl_gIRf4zrZJs5JqaeuBhsfJ4W5GD6yGg3W7903gbvaxZPBjxIQQ7BgFDSkPS8oPispw4KLz56mdK-G6CIvLO6hHRrZHY0Q3tvJ6JxE=C63992E6")...)
fps := []string{"getPagesInConfluenceSpace,searchConfluenceUsingCql"}
return utils.Validate(r, tps, fps)
return utils.Validate(r, tps, nil)
}
+1 -1
View File
@@ -12,7 +12,7 @@ func AWS() *config.Rule {
r := config.Rule{
RuleID: "aws-access-token",
Description: "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.",
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b`),
Regex: regexp.MustCompile(`\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b`),
Entropy: 3,
Keywords: []string{
// https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids
+1 -1
View File
@@ -79,7 +79,7 @@ func GenericCredential() *config.Rule {
// Token
`|(?:csrf)[_.-]?token` +
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinates. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinats. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
// General
`|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])` +
-19
View File
@@ -24,22 +24,3 @@ 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
@@ -1,39 +0,0 @@
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)
}
+4 -2
View File
@@ -1,6 +1,8 @@
package rules
import (
"fmt"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
@@ -48,7 +50,7 @@ func PlaidAccessToken() *config.Rule {
RuleID: "plaid-api-token",
Description: "Discovered a Plaid API Token, potentially compromising financial data aggregation and banking services.",
Regex: utils.GenerateSemiGenericRegex([]string{"plaid"},
"access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12(), true),
fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12()), true),
Keywords: []string{
"plaid",
@@ -56,6 +58,6 @@ func PlaidAccessToken() *config.Rule {
}
// validate
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret("access-(?:sandbox|development|production)-"+utils.Hex8_4_4_4_12()))
tps := utils.GenerateSampleSecrets("plaid", secrets.NewSecret(fmt.Sprintf("access-(?:sandbox|development|production)-%s", utils.Hex8_4_4_4_12())))
return utils.Validate(r, tps, nil)
}
-5
View File
@@ -88,10 +88,5 @@ 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)
}
+8 -16
View File
@@ -1,12 +1,12 @@
package cmd
import (
"context"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
@@ -56,18 +56,19 @@ func runGit(cmd *cobra.Command, args []string) {
preCommit := mustGetBoolFlag(cmd, "pre-commit")
var (
findings []report.Finding
err error
findings []report.Finding
err error
gitCmd *sources.GitCmd
scmPlatform scm.Platform
remote *detect.RemoteInfo
)
if preCommit || staged {
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
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
} else {
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
logging.Fatal().Err(err).Msg("could not create Git log cmd")
@@ -75,19 +76,10 @@ func runGit(cmd *cobra.Command, args []string) {
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
logging.Fatal().Err(err).Send()
}
remote = detect.NewRemoteInfo(scmPlatform, source)
}
findings, err = detector.DetectSource(
context.Background(),
&sources.Git{
Cmd: gitCmd,
Config: &detector.Config,
Remote: sources.NewRemoteInfo(scmPlatform, source),
Sema: detector.Sema,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
findings, err = detector.DetectGit(gitCmd, remote)
if err != nil {
// don't exit on error, just log it
logging.Error().Err(err).Msg("failed to scan Git repository")
+11 -15
View File
@@ -76,11 +76,10 @@ func init() {
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", 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)")
// 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")
rootCmd.PersistentFlags().String("diagnostics-dir", "", "directory to store diagnostics output files when not using http mode (defaults to current directory)")
rootCmd.PersistentFlags().String("diagnostics", "", "enable diagnostics (comma-separated list: cpu,mem,trace). cpu=CPU profiling, mem=memory profiling, trace=execution tracing")
rootCmd.PersistentFlags().String("diagnostics-dir", "", "directory to store diagnostics output files (defaults to current directory)")
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
@@ -222,7 +221,6 @@ 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")
@@ -239,16 +237,12 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
detector := detect.NewDetector(cfg)
if detector.MaxDecodeDepth, err = cmd.Flags().GetInt("max-decode-depth"); err != nil {
logging.Fatal().Err(err).Send()
}
if detector.MaxArchiveDepth, err = cmd.Flags().GetInt("max-archive-depth"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// set color flag at first
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// also init logger again without color
if detector.NoColor {
@@ -259,7 +253,7 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
@@ -269,18 +263,18 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
// set ignore gitleaks:allow flag
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
logging.Fatal().Err(err).Send()
logging.Fatal().Err(err).Msg("")
}
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
@@ -427,6 +421,8 @@ func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding,
diagnosticsManager.StopDiagnostics()
}
detector.Cleanup()
totalBytes := detector.TotalBytes.Load()
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
if err == nil {
-8
View File
@@ -13,8 +13,6 @@ const (
GitHubPlatform
GitLabPlatform
AzureDevOpsPlatform
GiteaPlatform
BitbucketPlatform
// TODO: Add others.
)
@@ -25,8 +23,6 @@ func (p Platform) String() string {
"github",
"gitlab",
"azuredevops",
"gitea",
"bitbucket",
}[p]
}
@@ -42,10 +38,6 @@ 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)
}
+3 -12
View File
@@ -1,14 +1,12 @@
package cmd
import (
"context"
"os"
"time"
"github.com/spf13/cobra"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/sources"
)
func init() {
@@ -37,17 +35,10 @@ func runStdIn(cmd *cobra.Command, _ []string) {
// parse flag(s)
exitCode := mustGetIntFlag(cmd, "exit-code")
findings, err := detector.DetectSource(
context.Background(),
&sources.File{
Content: os.Stdin,
MaxArchiveDepth: detector.MaxArchiveDepth,
},
)
findings, err := detector.DetectReader(os.Stdin, 10)
if err != nil {
// log fatal to exit, no need to continue since a report will not be
// generated when scanning from a pipe...for now
// log fatal to exit, no need to continue since a report
// will not be generated when scanning from a pipe...for now
logging.Fatal().Err(err).Msg("failed scan input from stdin")
}
+16 -58
View File
@@ -1,10 +1,9 @@
package config
import (
"errors"
"fmt"
"strings"
ahocorasick "github.com/BobuSumisu/aho-corasick"
"golang.org/x/exp/maps"
"github.com/zricethezav/gitleaks/v8/regexp"
@@ -30,10 +29,10 @@ type Allowlist struct {
// Short human readable description of the allowlist.
Description string
// MatchCondition determines whether all criteria must match. Defaults to "OR".
// MatchCondition determines whether all criteria must match.
MatchCondition AllowlistMatchCondition
// Commits is a slice of commit SHAs that are allowed to be ignored.
// Commits is a slice of commit SHAs that are allowed to be ignored. Defaults to "OR".
Commits []string
// Paths is a slice of path regular expressions that are allowed to be ignored.
@@ -58,13 +57,6 @@ 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 {
@@ -77,36 +69,23 @@ func (a *Allowlist) Validate() error {
len(a.Paths) == 0 &&
len(a.Regexes) == 0 &&
len(a.StopWords) == 0 {
return errors.New("must contain at least one check for: commits, paths, regexes, or stopwords")
return fmt.Errorf("must contain at least one check for: commits, paths, regexes, or stopwords")
}
// Deduplicate commits and stopwords.
if len(a.Commits) > 0 {
uniqueCommits := make(map[string]struct{})
for _, commit := range a.Commits {
// Commits are case-insensitive.
uniqueCommits[strings.TrimSpace(strings.ToLower(commit))] = struct{}{}
uniqueCommits[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[strings.ToLower(stopWord)] = struct{}{}
uniqueStopwords[stopWord] = struct{}{}
}
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.StopWords = maps.Keys(uniqueStopwords)
}
a.validated = true
@@ -118,15 +97,10 @@ func (a *Allowlist) CommitAllowed(c string) (bool, string) {
if a == nil || c == "" {
return false, ""
}
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
}
for _, commit := range a.Commits {
if commit == c {
return true, c
}
}
return false, ""
@@ -137,12 +111,7 @@ func (a *Allowlist) PathAllowed(path string) bool {
if a == nil || path == "" {
return false
}
if a.pathPat != nil {
return a.pathPat.MatchString(path)
} else if len(a.Paths) > 0 {
return anyRegexMatch(path, a.Paths)
}
return false
return anyRegexMatch(path, a.Paths)
}
// RegexAllowed returns true if the regex is allowed to be ignored.
@@ -150,12 +119,7 @@ func (a *Allowlist) RegexAllowed(secret string) bool {
if a == nil || secret == "" {
return false
}
if a.regexPat != nil {
return a.regexPat.MatchString(secret)
} else if len(a.Regexes) > 0 {
return anyRegexMatch(secret, a.Regexes)
}
return false
return anyRegexMatch(secret, a.Regexes)
}
func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
@@ -164,15 +128,9 @@ func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
}
s = strings.ToLower(s)
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
}
for _, stopWord := range a.StopWords {
if strings.Contains(s, strings.ToLower(stopWord)) {
return true, stopWord
}
}
return false, ""
+3 -225
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,230 +151,8 @@ func TestValidate(t *testing.T) {
cmpopts.IgnoreUnexported(Allowlist{}),
}
)
if diff := cmp.Diff(tt.expected, tt.input, opts); diff != "" {
if diff := cmp.Diff(tt.input, tt.expected, 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)
}
}
+15 -46
View File
@@ -43,25 +43,15 @@ type ViperConfig struct {
// Deprecated: this is a shim for backwards-compatibility.
// TODO: Remove this in 9.x.
AllowList *viperRuleAllowlist
AllowList *viperRuleAllowlist
Allowlists []*viperRuleAllowlist
Required []*viperRequired
SkipReport 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
@@ -140,7 +130,6 @@ func (vc *ViperConfig) Translate() (Config, error) {
Path: pathPat,
Keywords: vr.Keywords,
Tags: vr.Tags,
SkipReport: vr.SkipReport,
}
// Parse the rule allowlists, including the older format for backwards compatibility.
@@ -152,40 +141,16 @@ func (vc *ViperConfig) Translate() (Config, error) {
vr.Allowlists = append(vr.Allowlists, vr.AllowList)
}
for _, a := range vr.Allowlists {
allowlist, err := vc.parseAllowlist(a)
allowlist, err := 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,
@@ -204,7 +169,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
vc.Allowlists = append(vc.Allowlists, vc.AllowList)
}
for _, a := range vc.Allowlists {
allowlist, err := vc.parseAllowlist(&a.viperRuleAllowlist)
allowlist, err := parseAllowlist(&a.viperRuleAllowlist)
if err != nil {
return Config{}, fmt.Errorf("[[allowlists]] %w", err)
}
@@ -225,11 +190,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(vc); err != nil {
if err := c.extendDefault(); err != nil {
return Config{}, err
}
} else if c.Extend.Path != "" {
if err := c.extendPath(vc); err != nil {
if err := c.extendPath(); err != nil {
return Config{}, err
}
}
@@ -257,7 +222,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
return c, nil
}
func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
func parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error) {
var matchCondition AllowlistMatchCondition
switch strings.ToUpper(a.Condition) {
case "AND", "&&":
@@ -314,7 +279,7 @@ func (c *Config) GetOrderedRules() []Rule {
return orderedRules
}
func (c *Config) extendDefault(parent *ViperConfig) error {
func (c *Config) extendDefault() error {
extendDepth++
viper.SetConfigType("toml")
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
@@ -334,7 +299,7 @@ func (c *Config) extendDefault(parent *ViperConfig) error {
return nil
}
func (c *Config) extendPath(parent *ViperConfig) error {
func (c *Config) extendPath() error {
extendDepth++
viper.SetConfigFile(c.Extend.Path)
if err := viper.ReadInConfig(); err != nil {
@@ -414,7 +379,9 @@ func (c *Config) extend(extensionConfig Config) {
}
baseRule.Tags = append(baseRule.Tags, currentRule.Tags...)
baseRule.Keywords = append(baseRule.Keywords, currentRule.Keywords...)
baseRule.Allowlists = append(baseRule.Allowlists, currentRule.Allowlists...)
for _, a := range currentRule.Allowlists {
baseRule.Allowlists = append(baseRule.Allowlists, a)
}
// The keywords from the base rule and the extended rule must be merged into the global keywords list
for _, k := range baseRule.Keywords {
c.Keywords[k] = struct{}{}
@@ -424,7 +391,9 @@ func (c *Config) extend(extensionConfig Config) {
}
// append allowlists, not attempting to merge
c.Allowlists = append(c.Allowlists, extensionConfig.Allowlists...)
for _, a := range extensionConfig.Allowlists {
c.Allowlists = append(c.Allowlists, a)
}
// sort to keep extended rules in order
sort.Strings(c.OrderedRules)
+11 -11
View File
@@ -1,7 +1,7 @@
package config
import (
"errors"
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
@@ -93,17 +93,17 @@ func TestTranslate(t *testing.T) {
{
cfgName: "invalid/rule_missing_id",
cfg: Config{},
wantError: errors.New("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
wantError: fmt.Errorf("rule |id| is missing or empty, regex: (?i)(discord[a-z0-9_ .\\-,]{0,25})(=|>|:=|\\|\\|:|<=|=>|:).{0,5}['\\\"]([a-h0-9]{64})['\\\"]"),
},
{
cfgName: "invalid/rule_no_regex_or_path",
cfg: Config{},
wantError: errors.New("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
wantError: fmt.Errorf("discord-api-key: both |regex| and |path| are empty, this rule will have no effect"),
},
{
cfgName: "invalid/rule_bad_entropy_group",
cfg: Config{},
wantError: errors.New("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
wantError: fmt.Errorf("discord-api-key: invalid regex secret group 5, max regex secret group 3"),
},
}
for _, tt := range tests {
@@ -206,22 +206,22 @@ func TestTranslateAllowlists(t *testing.T) {
{
cfgName: "invalid/allowlist_global_empty",
cfg: Config{},
wantError: errors.New("[[allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
wantError: fmt.Errorf("[[allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_global_old_and_new",
cfg: Config{},
wantError: errors.New("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]"),
wantError: fmt.Errorf("[allowlist] is deprecated, it cannot be used alongside [[allowlists]]"),
},
{
cfgName: "invalid/allowlist_global_target_rule_id",
cfg: Config{},
wantError: errors.New("[[allowlists]] target rule ID 'github-pat' does not exist"),
wantError: fmt.Errorf("[[allowlists]] target rule ID 'github-pat' does not exist"),
},
{
cfgName: "invalid/allowlist_global_regextarget",
cfg: Config{},
wantError: errors.New("[[allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
wantError: fmt.Errorf("[[allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
// Rule
@@ -302,17 +302,17 @@ func TestTranslateAllowlists(t *testing.T) {
{
cfgName: "invalid/allowlist_rule_empty",
cfg: Config{},
wantError: errors.New("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
wantError: fmt.Errorf("example: [[rules.allowlists]] must contain at least one check for: commits, paths, regexes, or stopwords"),
},
{
cfgName: "invalid/allowlist_rule_old_and_new",
cfg: Config{},
wantError: errors.New("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
wantError: fmt.Errorf("example: [rules.allowlist] is deprecated, it cannot be used alongside [[rules.allowlist]]"),
},
{
cfgName: "invalid/allowlist_rule_regextarget",
cfg: Config{},
wantError: errors.New("example: [[rules.allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
wantError: fmt.Errorf("example: [[rules.allowlists]] unknown allowlist |regexTarget| 'mtach' (expected 'match', 'line')"),
},
}
+3 -44
View File
@@ -41,7 +41,6 @@ paths = [
'''\.gem$''',
'''verification-metadata\.xml''',
'''Database.refactorlog''',
'''(?:^|/)\.git$''',
]
regexes = [
'''(?i)^true|false|null$''',
@@ -59,8 +58,8 @@ regexes = [
'''^/(?:bin|etc|home|opt|tmp|usr|var)/[\w ./-]+$''',
]
stopwords = [
"014df517-39d1-4453-b7b3-9930c563627c",
"abcdefghijklmnopqrstuvwxyz",
"014df517-39d1-4453-b7b3-9930c563627c",
]
[[rules]]
@@ -129,32 +128,6 @@ 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."
@@ -170,7 +143,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 = '''(?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]|$)'''
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]|$)'''
entropy = 3.5
keywords = [
"atlassian",
@@ -194,7 +167,7 @@ keywords = [
[[rules]]
id = "aws-access-token"
description = "Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms."
regex = '''\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b'''
regex = '''\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b'''
entropy = 3
keywords = [
"a3t",
@@ -2322,13 +2295,6 @@ 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."
@@ -2611,13 +2577,6 @@ 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."
+2 -15
View File
@@ -1,7 +1,6 @@
package config
import (
"errors"
"fmt"
"strings"
@@ -46,18 +45,6 @@ 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
}
type Required struct {
RuleID string
WithinLines *int
WithinColumns *int
}
// Validate guards against common misconfigurations.
@@ -77,12 +64,12 @@ func (r *Rule) Validate() error {
} else if r.Description != "" {
context = ", description: " + r.Description
}
return errors.New("rule |id| is missing or empty" + context)
return fmt.Errorf("rule |id| is missing or empty" + context)
}
// Ensure the rule actually matches something.
if r.Regex == nil && r.Path == nil {
return errors.New(r.RuleID + ": both |regex| and |path| are empty, this rule will have no effect")
return fmt.Errorf("%s: both |regex| and |path| are empty, this rule will have no effect", r.RuleID)
}
// Ensure |secretGroup| works.
-16
View File
@@ -1,8 +1,6 @@
package config
import (
"strings"
"github.com/zricethezav/gitleaks/v8/regexp"
)
@@ -24,17 +22,3 @@ 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())
}
+96
View File
@@ -0,0 +1,96 @@
package detect
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/mholt/archives"
"github.com/zricethezav/gitleaks/v8/sources"
)
// isArchive asks archives.Identify (with a nil stream, so only the filename)
// whether this file would be handled by an Extractor. If Identify returns
// a Format implementing archives.Extractor, we treat it as an archive.
func isArchive(path string) bool {
format, _, err := archives.Identify(context.Background(), path, nil)
if err != nil {
// no matching format at all
return false
}
_, ok := format.(archives.Extractor)
return ok
}
// ExtractArchive extracts all files from archivePath into a temp dir.
// Returns the list of ScanTargets (with real file paths) and the temp dir for cleanup.
func extractArchive(archivePath string) ([]sources.ScanTarget, string, error) {
tmpArchiveDir, err := os.MkdirTemp(tmpDir, "archive-*")
if err != nil {
return nil, "", fmt.Errorf("creating temp dir for archive: %w", err)
}
f, err := os.Open(archivePath)
if err != nil {
os.RemoveAll(tmpArchiveDir)
return nil, "", err
}
defer f.Close()
ctx := context.Background()
format, stream, err := archives.Identify(ctx, archivePath, f)
if err != nil {
os.RemoveAll(tmpArchiveDir)
return nil, "", err
}
extractor, ok := format.(archives.Extractor)
if !ok {
os.RemoveAll(tmpArchiveDir)
return nil, "", fmt.Errorf("format %T is not extractable", format)
}
// Walk and extract
var targets []sources.ScanTarget
err = extractor.Extract(ctx, stream, func(ctx context.Context, file archives.FileInfo) error {
name := file.Name()
// skip macOS metadata and __MACOSX folders
// TODO add more exceptions here if needed
base := filepath.Base(name)
if strings.HasPrefix(base, "._") || strings.HasPrefix(name, "__MACOSX/") {
return nil
}
if file.IsDir() {
return nil
}
// open and copy out
r, err := file.Open()
if err != nil {
return err
}
defer r.Close()
outPath := filepath.Join(tmpArchiveDir, file.Name())
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return err
}
outFile, err := os.Create(outPath)
if err != nil {
return err
}
defer outFile.Close()
if _, err := io.Copy(outFile, r); err != nil {
return err
}
targets = append(targets, sources.ScanTarget{Path: outPath})
return nil
})
return targets, tmpArchiveDir, err
}
+1 -17
View File
@@ -2,10 +2,9 @@ package codec
import (
"encoding/hex"
"github.com/stretchr/testify/assert"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
)
func TestDecode(t *testing.T) {
@@ -91,21 +90,6 @@ func TestDecode(t *testing.T) {
chunk: `secret="466973684D617048756E6B79212121363334"`,
expected: `secret="FishMapHunky!!!634"`,
},
{
name: "unicode encoded value",
chunk: `secret=U+0061 U+0062 U+0063 U+0064 U+0065 U+0066`,
expected: "secret=abcdef",
},
{
name: "unicode encoded value backslashed",
chunk: `secret=\\u0068\\u0065\\u006c\\u006c\\u006f\\u0020\\u0077\\u006f\\u0072\\u006c\\u0064\\u0020\\u0064\\u0075\\u0064\\u0065`,
expected: "secret=hello world dude",
},
{
name: "unicode encoded value backslashed mixed w/ hex",
chunk: `secret=\u0068\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064 6C6F76656C792070656F706C65206F66206561727468`,
expected: "secret=hello world lovely people of earth",
},
}
decoder := NewDecoder()
+5 -12
View File
@@ -19,22 +19,17 @@ var (
// (e.g. base64). If two encoding matches overlap the decoder will use
// this order to determine which encoding should wait till the next pass.
encodings = []*encoding{
{
&encoding{
kind: percentKind,
pattern: `%[0-9A-Fa-f]{2}(?:.*%[0-9A-Fa-f]{2})?`,
decode: decodePercent,
},
{
kind: unicodeKind,
pattern: `(?:(?:U\+[a-fA-F0-9]{4}(?:\s|$))+|(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+)`,
decode: decodeUnicode,
},
{
&encoding{
kind: hexKind,
pattern: `[0-9A-Fa-f]{32,}`,
decode: decodeHex,
},
{
&encoding{
kind: base64Kind,
pattern: `[\w\/+-]{16,}={0,2}`,
decode: decodeBase64,
@@ -45,7 +40,6 @@ var (
// encodingNames is used to map the encodingKinds to their name
var encodingNames = []string{
"percent",
"unicode",
"hex",
"base64",
}
@@ -57,9 +51,8 @@ type encodingKind int
var (
// make sure these go up by powers of 2
percentKind = encodingKind(1)
unicodeKind = encodingKind(2)
hexKind = encodingKind(4)
base64Kind = encodingKind(8)
hexKind = encodingKind(2)
base64Kind = encodingKind(4)
)
func (e encodingKind) String() string {
+1 -1
View File
@@ -49,7 +49,7 @@ func decodeHex(encodedValue string) string {
if n1|n2 == '\xff' {
return ""
}
b := n1<<4 | n2
b := byte(n1<<4 | n2)
if !printableASCII[b] {
return ""
}
+1 -1
View File
@@ -13,7 +13,7 @@ func decodePercent(encodedValue string) string {
n2 := hexMap[encodedValue[encIndex+2]]
// Make sure they're hex characters
if n1|n2 != '\xff' {
b := n1<<4 | n2
b := byte(n1<<4 | n2)
if !printableASCII[b] {
return ""
}
+1 -1
View File
@@ -43,7 +43,7 @@ func (s startEnd) overflow(o startEnd) startEnd {
return s.merge(o).sub(s)
}
// merge takes two start/ends and returns a single one that encompasses both
// merge takes two start/ends and returns a single one that encompases both
func (s startEnd) merge(o startEnd) startEnd {
return startEnd{
min(s.start, o.start),
-260
View File
@@ -1,260 +0,0 @@
package codec
import (
"bytes"
"regexp"
"strconv"
"strings"
"unicode/utf8"
)
var (
// Standard Unicode notation (e.g., U+1234)
unicodeCodePointPat = regexp.MustCompile(`U\+([a-fA-F0-9]{4}).?`)
// Multiple code points pattern - used for continuous sequences like "U+0074 U+006F U+006B..."
unicodeMultiCodePointPat = regexp.MustCompile(`(?:U\+[a-fA-F0-9]{4}(?:\s|$))+`)
// Common escape sequence used in programming languages (e.g., \u1234)
unicodeEscapePat = regexp.MustCompile(`(?i)\\{1,2}u([a-fA-F0-9]{4})`)
// Multiple escape sequences pattern - used for continuous sequences like "\u0074\u006F\u006B..."
unicodeMultiEscapePat = regexp.MustCompile(`(?i)(?:\\{1,2}u[a-fA-F0-9]{4})+`)
)
// Unicode characters are encoded as 1 to 4 bytes per rune.
const maxBytesPerRune = 4
// decodeUnicode decodes Unicode escape sequences in the given string
func decodeUnicode(encodedValue string) string {
// First, check if we have a continuous sequence of Unicode code points
if matches := unicodeMultiCodePointPat.FindAllString(encodedValue, -1); len(matches) > 0 {
// For each detected sequence of code points
for _, match := range matches {
// Decode the entire sequence at once
decodedSequence := decodeMultiCodePoint(match)
// If we successfully decoded something, replace it in the original string
if decodedSequence != "" && decodedSequence != match {
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
}
}
return encodedValue
}
// Next, check if we have a continuous sequence of escape sequences
if matches := unicodeMultiEscapePat.FindAllString(encodedValue, -1); len(matches) > 0 {
// For each detected sequence of escape sequences
for _, match := range matches {
// Decode the entire sequence at once
decodedSequence := decodeMultiEscape(match)
// If we successfully decoded something, replace it in the original string
if decodedSequence != "" && decodedSequence != match {
encodedValue = strings.Replace(encodedValue, match, decodedSequence, 1)
}
}
return encodedValue
}
// If no multi-patterns were matched, fall back to the original implementation
// for individual code points and escape sequences
// Create a copy of the input to work with
data := []byte(encodedValue)
// Store the result
var result []byte
// Check and decode Unicode code points (U+1234 format)
if unicodeCodePointPat.Match(data) {
result = decodeIndividualCodePoints(data)
}
// If no code points were found or we have a mix of formats,
// also check for Unicode escape sequences (\u1234 format)
if len(result) == 0 || unicodeEscapePat.Match(data) {
// If we already have some result from code point decoding,
// continue decoding escape sequences on that result
if len(result) > 0 {
result = decodeIndividualEscapes(result)
} else {
result = decodeIndividualEscapes(data)
}
}
// If nothing was decoded, return original string
if len(result) == 0 || bytes.Equal(result, data) {
return encodedValue
}
return string(result)
}
// decodeMultiCodePoint decodes a continuous sequence of Unicode code points (U+XXXX format)
func decodeMultiCodePoint(sequence string) string {
// If the sequence is empty, return empty string
if sequence == "" {
return ""
}
// Split the sequence by whitespace to get individual code points
codePoints := strings.Fields(sequence)
if len(codePoints) == 0 {
return sequence
}
// Decode each code point and build the result
var decodedRunes []rune
for _, cp := range codePoints {
// Check if it follows the U+XXXX pattern
if !strings.HasPrefix(cp, "U+") || len(cp) < 6 {
continue
}
// Extract the hexadecimal value
hexValue := cp[2:]
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
continue
}
// Convert to rune and add to result
decodedRunes = append(decodedRunes, rune(unicodeInt))
}
// If we didn't decode anything, return the original sequence
if len(decodedRunes) == 0 {
return sequence
}
// Return the decoded string
return string(decodedRunes)
}
// decodeMultiEscape decodes a continuous sequence of Unicode escape sequences (\uXXXX format)
func decodeMultiEscape(sequence string) string {
// If the sequence is empty, return empty string
if sequence == "" {
return ""
}
// Find all escape sequences
escapes := unicodeEscapePat.FindAllStringSubmatch(sequence, -1)
if len(escapes) == 0 {
return sequence
}
// Decode each escape sequence and build the result
var decodedRunes []rune
for _, esc := range escapes {
// Extract the hexadecimal value
hexValue := esc[1]
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
continue
}
// Convert to rune and add to result
decodedRunes = append(decodedRunes, rune(unicodeInt))
}
// If we didn't decode anything, return the original sequence
if len(decodedRunes) == 0 {
return sequence
}
// Return the decoded string
return string(decodedRunes)
}
// decodeIndividualCodePoints decodes individual Unicode code points (U+1234 format)
// This is a fallback for when we don't have a continuous sequence of code points
func decodeIndividualCodePoints(input []byte) []byte {
// Find all Unicode code point sequences in the input byte slice
indices := unicodeCodePointPat.FindAllSubmatchIndex(input, -1)
// If none found, return original input
if len(indices) == 0 {
return input
}
// Iterate over found indices in reverse order to avoid modifying the slice length
utf8Bytes := make([]byte, maxBytesPerRune)
for i := len(indices) - 1; i >= 0; i-- {
matches := indices[i]
startIndex := matches[0]
endIndex := matches[1]
hexStartIndex := matches[2]
hexEndIndex := matches[3]
// If the input is like `U+1234 U+5678` we should replace `U+1234 `.
// Otherwise, we should only replace `U+1234`.
if endIndex != hexEndIndex && endIndex < len(input) && input[endIndex-1] == ' ' {
endIndex = endIndex - 1
}
// Extract the hexadecimal value from the escape sequence
hexValue := string(input[hexStartIndex:hexEndIndex])
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
// If there's an error, continue to the next escape sequence
continue
}
// Convert the Unicode code point to a UTF-8 representation
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
// Replace the escape sequence with the UTF-8 representation
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
}
return input
}
// decodeIndividualEscapes decodes individual Unicode escape sequences (\u1234 format)
// This is a fallback for when we don't have a continuous sequence of escape sequences
func decodeIndividualEscapes(input []byte) []byte {
// Find all Unicode escape sequences in the input byte slice
indices := unicodeEscapePat.FindAllSubmatchIndex(input, -1)
// If none found, return original input
if len(indices) == 0 {
return input
}
// Iterate over found indices in reverse order to avoid modifying the slice length
utf8Bytes := make([]byte, maxBytesPerRune)
for i := len(indices) - 1; i >= 0; i-- {
matches := indices[i]
startIndex := matches[0]
hexStartIndex := matches[2]
endIndex := matches[3]
// Extract the hexadecimal value from the escape sequence
hexValue := string(input[hexStartIndex:endIndex])
// Parse the hexadecimal value to an integer
unicodeInt, err := strconv.ParseInt(hexValue, 16, 32)
if err != nil {
// If there's an error, continue to the next escape sequence
continue
}
// Convert the Unicode code point to a UTF-8 representation
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeInt))
// Replace the escape sequence with the UTF-8 representation
input = append(input[:startIndex], append(utf8Bytes[:utf8Len], input[endIndex:]...)...)
}
return input
}
+32 -251
View File
@@ -5,6 +5,7 @@ import (
"context"
"fmt"
"os"
"runtime"
"strings"
"sync"
"sync/atomic"
@@ -15,7 +16,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/sources"
ahocorasick "github.com/BobuSumisu/aho-corasick"
"github.com/fatih/semgroup"
@@ -26,6 +26,8 @@ import (
const (
gitleaksAllowSignature = "gitleaks:allow"
chunkSize = 100 * 1_000 // 100kb
// SlowWarningThreshold is the amount of time to wait before logging that a file is slow.
// This is useful for identifying problematic files and tuning the allowlist.
SlowWarningThreshold = 5 * time.Second
@@ -33,8 +35,18 @@ const (
var (
newLineRegexp = regexp.MustCompile("\n")
isWindows = runtime.GOOS == "windows"
tmpDir string
)
func init() {
var err error
tmpDir, err = os.MkdirTemp("", "gitleaks-*")
if err != nil {
logging.Fatal().Err(err).Msg("failed to create temp dir for archive extraction")
}
}
// Detector is the main detector struct
type Detector struct {
// Config is the configuration for the detector
@@ -51,9 +63,6 @@ type Detector struct {
// MaxDecodeDepths limits how many recursive decoding passes are allowed
MaxDecodeDepth int
// MaxArchiveDepth limits how deep the sources will explore nested archives
MaxArchiveDepth int
// files larger than this will be skipped
MaxTargetMegaBytes int
@@ -66,10 +75,6 @@ type Detector struct {
// IgnoreGitleaksAllow is a flag to ignore gitleaks:allow comments.
IgnoreGitleaksAllow bool
// commitMutex is to prevent concurrent access to the
// commit map when adding commits
commitMutex *sync.Mutex
// commitMap is used to keep track of commits that have been scanned.
// This is only used for logging purposes and git scans.
commitMap map[string]bool
@@ -106,10 +111,13 @@ type Detector struct {
TotalBytes atomic.Uint64
}
// Fragment is an alias for sources.Fragment for backwards compatibility
//
// Deprecated: This will be replaced with sources.Fragment in v9
type Fragment sources.Fragment
func (d *Detector) Cleanup() {
if tmpDir != "" {
if err := os.RemoveAll(tmpDir); err != nil {
logging.Warn().Err(err).Msg("failed to remove temp dir for archive extraction")
}
}
}
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
@@ -117,7 +125,6 @@ func NewDetector(cfg config.Config) *Detector {
commitMap: make(map[string]bool),
gitleaksIgnore: make(map[string]struct{}),
findingMutex: &sync.Mutex{},
commitMutex: &sync.Mutex{},
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: *ahocorasick.NewTrieBuilder().AddStrings(maps.Keys(cfg.Keywords)).Build(),
@@ -145,7 +152,7 @@ func NewDetectorDefaultConfig() (*Detector, error) {
}
func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
logging.Debug().Str("path", gitleaksIgnorePath).Msgf("found .gitleaksignore file")
logging.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
file, err := os.Open(gitleaksIgnorePath)
if err != nil {
return err
@@ -153,7 +160,7 @@ func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
defer func() {
// https://github.com/securego/gosec/issues/512
if err := file.Close(); err != nil {
logging.Warn().Err(err).Msgf("Error closing .gitleaksignore file")
logging.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
}
}()
@@ -198,68 +205,6 @@ func (d *Detector) DetectString(content string) []report.Finding {
})
}
// DetectSource scans the given source and returns a list of findings
func (d *Detector) DetectSource(ctx context.Context, source sources.Source) ([]report.Finding, error) {
err := source.Fragments(ctx, func(fragment sources.Fragment, err error) error {
logContext := logging.With()
if len(fragment.FilePath) > 0 {
logContext = logContext.Str("path", fragment.FilePath)
}
if len(fragment.CommitSHA) > 6 {
logContext = logContext.Str("commit", fragment.CommitSHA[:7])
d.addCommit(fragment.CommitSHA)
} else if len(fragment.CommitSHA) > 0 {
logContext = logContext.Str("commit", fragment.CommitSHA)
d.addCommit(fragment.CommitSHA)
logger := logContext.Logger()
logger.Warn().Msg("commit SHAs should be >= 7 characters long")
}
logger := logContext.Logger()
if err != nil {
// Log the error and move on to the next fragment
logger.Error().Err(err).Send()
return nil
}
// both the fragment's content and path should be empty for it to be
// considered empty at this point because of path based matches
if len(fragment.Raw) == 0 && len(fragment.FilePath) == 0 {
logger.Trace().Msg("skipping empty fragment")
return nil
}
var timer *time.Timer
// Only start the timer in debug mode
if logger.GetLevel() <= zerolog.DebugLevel {
timer = time.AfterFunc(SlowWarningThreshold, func() {
logger.Debug().Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
})
}
for _, finding := range d.Detect(Fragment(fragment)) {
d.AddFinding(finding)
}
// Stop the timer if it was created
if timer != nil {
timer.Stop()
}
return nil
})
if _, isGit := source.(*sources.Git); isGit {
logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
}
return d.Findings(), err
}
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
if fragment.Bytes == nil {
@@ -292,6 +237,9 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
return findings
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
// setup variables to handle different decoding passes
currentRaw := fragment.Raw
encodedSegments := []*codec.EncodedSegment{}
@@ -357,10 +305,6 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}()
)
if r.SkipReport == true && !fragment.InheritedFromFinding {
return findings
}
// check if commit or file is allowed for this rule.
if isAllowed, event := checkCommitOrPathAllowed(logger, fragment, r.Allowlists); isAllowed {
event.Msg("skipping file: rule allowlist")
@@ -372,21 +316,13 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// Path _only_ rule
if r.Path.MatchString(fragment.FilePath) || (fragment.WindowsFilePath != "" && r.Path.MatchString(fragment.WindowsFilePath)) {
finding := report.Finding{
Commit: fragment.CommitSHA,
RuleID: r.RuleID,
Description: r.Description,
File: fragment.FilePath,
SymlinkFile: fragment.SymlinkFile,
Match: "file detected: " + fragment.FilePath,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Tags: r.Tags,
}
if fragment.CommitInfo != nil {
finding.Author = fragment.CommitInfo.AuthorName
finding.Date = fragment.CommitInfo.Date
finding.Email = fragment.CommitInfo.AuthorEmail
finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
finding.Message = fragment.CommitInfo.Message
}
return append(findings, finding)
}
} else {
@@ -406,7 +342,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// if flag configure and raw data size bigger then the flag
if d.MaxTargetMegaBytes > 0 {
rawLength := len(currentRaw) / 1_000_000
rawLength := len(currentRaw) / 1000000
if rawLength > d.MaxTargetMegaBytes {
logger.Debug().
Int("size", rawLength).
@@ -416,14 +352,6 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}
}
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) {
@@ -456,18 +384,17 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
// in the finding will be the line/column numbers of the _match_
// not the _secret_, which will be different if the secretGroup
// value is set for this rule
loc := location(newlineIndices, fragment.Raw, matchIndex)
loc := location(fragment, matchIndex)
if matchIndex[1] > loc.endLineIndex {
loc.endLineIndex = matchIndex[1]
}
finding := report.Finding{
Commit: fragment.CommitSHA,
RuleID: r.RuleID,
Description: r.Description,
StartLine: fragment.StartLine + loc.startLine,
EndLine: fragment.StartLine + loc.endLine,
StartLine: loc.startLine,
EndLine: loc.endLine,
StartColumn: loc.startColumn,
EndColumn: loc.endColumn,
Line: fragment.Raw[loc.startLineIndex:loc.endLineIndex],
@@ -477,13 +404,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
SymlinkFile: fragment.SymlinkFile,
Tags: append(r.Tags, metaTags...),
}
if fragment.CommitInfo != nil {
finding.Author = fragment.CommitInfo.AuthorName
finding.Date = fragment.CommitInfo.Date
finding.Email = fragment.CommitInfo.AuthorEmail
finding.Link = createScmLink(fragment.CommitInfo.Remote, finding)
finding.Message = fragment.CommitInfo.Message
}
if !d.IgnoreGitleaksAllow && strings.Contains(finding.Line, gitleaksAllowSignature) {
logger.Trace().
Str("finding", finding.Secret).
@@ -543,145 +464,7 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
}
findings = append(findings, finding)
}
// Handle required rules (multi-part rules)
if fragment.InheritedFromFinding || len(r.RequiredRules) == 0 {
return findings
}
// Process required rules and create findings with auxiliary findings
return d.processRequiredRules(fragment, currentRaw, r, encodedSegments, findings, logger)
}
// processRequiredRules handles the logic for multi-part rules with auxiliary findings
func (d *Detector) processRequiredRules(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment, primaryFindings []report.Finding, logger zerolog.Logger) []report.Finding {
if len(primaryFindings) == 0 {
logger.Debug().Msg("no primary findings to process for required rules")
return primaryFindings
}
// Pre-collect all required rule findings once
allRequiredFindings := make(map[string][]report.Finding)
for _, requiredRule := range r.RequiredRules {
rule, ok := d.Config.Rules[requiredRule.RuleID]
if !ok {
logger.Error().Str("rule-id", requiredRule.RuleID).Msg("required rule not found in config")
continue
}
// Mark fragment as inherited to prevent infinite recursion
inheritedFragment := fragment
inheritedFragment.InheritedFromFinding = true
// Call detectRule once for each required rule
requiredFindings := d.detectRule(inheritedFragment, currentRaw, rule, encodedSegments)
allRequiredFindings[requiredRule.RuleID] = requiredFindings
logger.Debug().
Str("rule-id", requiredRule.RuleID).
Int("findings", len(requiredFindings)).
Msg("collected required rule findings")
}
var finalFindings []report.Finding
// Now process each primary finding against the pre-collected required findings
for _, primaryFinding := range primaryFindings {
var requiredFindings []*report.RequiredFinding
for _, requiredRule := range r.RequiredRules {
foundRequiredFindings, exists := allRequiredFindings[requiredRule.RuleID]
if !exists {
continue // Rule wasn't found earlier, skip
}
// Filter findings that are within proximity of the primary finding
for _, requiredFinding := range foundRequiredFindings {
if d.withinProximity(primaryFinding, requiredFinding, requiredRule) {
req := &report.RequiredFinding{
RuleID: requiredFinding.RuleID,
StartLine: requiredFinding.StartLine,
EndLine: requiredFinding.EndLine,
StartColumn: requiredFinding.StartColumn,
EndColumn: requiredFinding.EndColumn,
Line: requiredFinding.Line,
Match: requiredFinding.Match,
Secret: requiredFinding.Secret,
}
requiredFindings = append(requiredFindings, req)
}
}
}
// Check if we have at least one auxiliary finding for each required rule
if len(requiredFindings) > 0 && d.hasAllRequiredRules(requiredFindings, r.RequiredRules) {
// Create a finding with auxiliary findings
newFinding := primaryFinding // Copy the primary finding
newFinding.AddRequiredFindings(requiredFindings)
finalFindings = append(finalFindings, newFinding)
logger.Debug().
Str("primary-rule", r.RuleID).
Int("primary-line", primaryFinding.StartLine).
Int("auxiliary-count", len(requiredFindings)).
Msg("multi-part rule satisfied")
}
}
return finalFindings
}
// hasAllRequiredRules checks if we have at least one auxiliary finding for each required rule
func (d *Detector) hasAllRequiredRules(auxiliaryFindings []*report.RequiredFinding, requiredRules []*config.Required) bool {
foundRules := make(map[string]bool)
// AuxiliaryFinding
for _, aux := range auxiliaryFindings {
foundRules[aux.RuleID] = true
}
for _, required := range requiredRules {
if !foundRules[required.RuleID] {
return false
}
}
return true
}
func (d *Detector) withinProximity(primary, required report.Finding, requiredRule *config.Required) bool {
// fmt.Println(requiredRule.WithinLines)
// If neither within_lines nor within_columns is set, findings just need to be in the same fragment
if requiredRule.WithinLines == nil && requiredRule.WithinColumns == nil {
return true
}
// Check line proximity (vertical distance)
if requiredRule.WithinLines != nil {
lineDiff := abs(primary.StartLine - required.StartLine)
if lineDiff > *requiredRule.WithinLines {
return false
}
}
// Check column proximity (horizontal distance)
if requiredRule.WithinColumns != nil {
// Use the start column of each finding for proximity calculation
colDiff := abs(primary.StartColumn - required.StartColumn)
if colDiff > *requiredRule.WithinColumns {
return false
}
}
return true
}
// abs returns the absolute value of an integer
func abs(x int) int {
if x < 0 {
return -x
}
return x
return findings
}
// AddFinding synchronously adds a finding to the findings slice
@@ -732,9 +515,7 @@ func (d *Detector) Findings() []report.Finding {
// AddCommit synchronously adds a commit to the commit slice
func (d *Detector) addCommit(commit string) {
d.commitMutex.Lock()
d.commitMap[commit] = true
d.commitMutex.Unlock()
}
// checkCommitOrPathAllowed evaluates |fragment| against all provided |allowlists|.
+53 -1066
View File
File diff suppressed because it is too large. Load diff
+257
View File
@@ -0,0 +1,257 @@
package detect
import (
"bufio"
"bytes"
"io"
"os"
"path/filepath"
"strings"
"github.com/h2non/filetype"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
const maxPeekSize = 25 * 1_000 // 10kb
// DetectFiles schedules each ScanTarget—file or archive—for concurrent scanning.
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
for pa := range paths {
d.Sema.Go(func() error {
return d.detectScanTarget(pa)
})
}
if err := d.Sema.Wait(); err != nil {
return d.findings, err
}
return d.findings, nil
}
// detectScanTarget handles one ScanTarget: it unpacks archives recursively
// or scans a regular file, always using VirtualPath for reporting.
func (d *Detector) detectScanTarget(scanTarget sources.ScanTarget) error {
// Choose display path: either VirtualPath (archive chain) or on-disk path.
display := scanTarget.Path
if scanTarget.VirtualPath != "" {
display = scanTarget.VirtualPath
}
logger := logging.With().Str("path", display).Logger()
logger.Trace().Msg("Scanning path")
if isArchive(scanTarget.Path) {
logger.Debug().Msg("Found archive")
targets, tmpArchiveDir, err := extractArchive(scanTarget.Path)
if err != nil {
logger.Warn().Err(err).Msg("Failed to extract archive")
return nil
}
// Schedule each extracted file for its own scan, carrying forward VirtualPath.
for _, t := range targets {
t := t
// compute path INSIDE this archive
rel, rerr := filepath.Rel(tmpArchiveDir, t.Path)
if rerr != nil {
rel = filepath.Base(t.Path)
}
rel = filepath.ToSlash(rel)
// prepend existing chain or archive base name
if scanTarget.VirtualPath != "" {
t.VirtualPath = scanTarget.VirtualPath + "/" + rel
} else {
t.VirtualPath = filepath.Base(scanTarget.Path) + "/" + rel
}
d.Sema.Go(func() error {
return d.detectScanTarget(t)
})
}
return nil
}
// --- Regular file branch ---
f, err := os.Open(scanTarget.Path)
if err != nil {
if os.IsPermission(err) {
logger.Warn().Msg("Skipping file: permission denied")
return nil
}
return err
}
defer f.Close()
// Get file size
fileInfo, err := f.Stat()
if err != nil {
return err
}
fileSize := fileInfo.Size()
if d.MaxTargetMegaBytes > 0 {
rawLength := fileSize / 1000000
if rawLength > int64(d.MaxTargetMegaBytes) {
logger.Debug().
Int64("size", rawLength).
Msg("Skipping file: exceeds --max-target-megabytes")
return nil
}
}
// Skip binary files by sniffing header
head := make([]byte, 261)
if n, _ := io.ReadFull(f, head); n > 0 {
if kind, _ := filetype.Match(head[:n]); kind != filetype.Unknown {
logger.Debug().Str("kind", kind.Extension).Msg("Skipping binary")
return nil
}
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return err
}
reader := bufio.NewReader(f)
buf := make([]byte, chunkSize)
totalLines := 0
for {
n, err := reader.Read(buf)
if n > 0 {
// Only check the filetype at the start of file.
if totalLines == 0 {
// TODO: could other optimizations be introduced here?
if mimetype, err := filetype.Match(buf[:n]); err != nil {
return nil
} else if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
}
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
return readErr
}
chunk := peekBuf.String()
linesInChunk := strings.Count(chunk, "\n")
// build fragment and set FilePath to our display chain
fragment := Fragment{
Raw: chunk,
Bytes: peekBuf.Bytes(),
}
fragment.FilePath = display
// if this file was itself a symlink
if scanTarget.Symlink != "" {
fragment.SymlinkFile = scanTarget.Symlink
}
if isWindows {
fragment.FilePath = filepath.ToSlash(scanTarget.Path)
fragment.SymlinkFile = filepath.ToSlash(fragment.SymlinkFile)
fragment.WindowsFilePath = scanTarget.Path
}
// run detection and adjust line numbers
for _, finding := range d.Detect(fragment) {
finding.StartLine += totalLines + 1
finding.EndLine += totalLines + 1
// We have to augment the finding if the source is coming
// from a archive committed in Git
if scanTarget.Source == "github-archive" {
finding.Author = scanTarget.GitInfo.Author
finding.Commit = scanTarget.GitInfo.Commit
finding.Email = scanTarget.GitInfo.Email
finding.Date = scanTarget.GitInfo.Date
finding.Message = scanTarget.GitInfo.Message
}
d.AddFinding(finding)
}
totalLines += linesInChunk
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
// readUntilSafeBoundary consumes |f| until it finds two consecutive `\n` characters, up to |maxPeekSize|.
// This hopefully avoids splitting. (https://github.com/gitleaks/gitleaks/issues/1651)
func readUntilSafeBoundary(r *bufio.Reader, n int, maxPeekSize int, peekBuf *bytes.Buffer) error {
if peekBuf.Len() == 0 {
return nil
}
// Does the buffer end in consecutive newlines?
var (
data = peekBuf.Bytes()
lastChar = data[len(data)-1]
newlineCount = 0 // Tracks consecutive newlines
)
if isWhitespace(lastChar) {
for i := len(data) - 1; i >= 0; i-- {
lastChar = data[i]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
return nil
}
} else if lastChar == '\r' || lastChar == ' ' || lastChar == '\t' {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
break
}
}
}
// If not, read ahead until we (hopefully) find some.
newlineCount = 0
for {
data = peekBuf.Bytes()
// Check if the last character is a newline.
lastChar = data[len(data)-1]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
break
}
} else if lastChar == '\r' || lastChar == ' ' || lastChar == '\t' {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
newlineCount = 0 // Reset if a non-newline character is found
}
// Stop growing the buffer if it reaches maxSize
if (peekBuf.Len() - n) >= maxPeekSize {
break
}
// Read additional data into a temporary buffer
b, err := r.ReadByte()
if err != nil {
if err == io.EOF {
break
}
return err
}
peekBuf.WriteByte(b)
}
return nil
}
@@ -1,4 +1,4 @@
package sources
package detect
import (
"bufio"
@@ -65,8 +65,8 @@ func Test_readUntilSafeBoundary(t *testing.T) {
require.NoError(t, err)
// Assert
t.Log(peekBuf.String())
require.Equal(t, c.expected, peekBuf.String())
t.Logf(peekBuf.String())
require.Equal(t, c.expected, string(peekBuf.Bytes()))
})
}
}
-92
View File
@@ -1,92 +0,0 @@
package detect
import (
"context"
"errors"
"os"
"sync"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// DetectFiles runs detections against a chanel of scan targets
//
// Deprecated: Use sources.Files and Detector.DetectSource instead
func (d *Detector) DetectFiles(scanTargets <-chan sources.ScanTarget) ([]report.Finding, error) {
var wg sync.WaitGroup
for scanTarget := range scanTargets {
wg.Add(1)
d.Sema.Go(func() error {
defer wg.Done()
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) {
err = errors.New("permission denied")
}
logger.Warn().Err(err).Msg("skipping file")
return nil
}
defer func() {
_ = f.Close()
}()
info, err := f.Stat()
if err != nil {
logger.Error().Err(err).Msg("skipping file: could not get info")
return nil
}
// Empty; nothing to do here.
if info.Size() == 0 {
logger.Debug().Msg("skipping empty file")
return nil
}
// Too large; nothing to do here.
if d.MaxTargetMegaBytes > 0 {
rawLength := info.Size() / 1_000_000
if rawLength > int64(d.MaxTargetMegaBytes) {
logger.Warn().Msgf(
"skipping file: too large max_size=%dMB, size=%dMB",
d.MaxTargetMegaBytes, rawLength,
)
return nil
}
}
// Convert this to a file source
file := sources.File{
Content: f,
Path: scanTarget.Path,
Symlink: scanTarget.Symlink,
Config: &d.Config,
MaxArchiveDepth: d.MaxArchiveDepth,
}
ctx := context.Background()
return file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
logging.Error().Err(err)
return nil
}
for _, finding := range d.Detect(Fragment(fragment)) {
d.AddFinding(finding)
}
return nil
})
})
}
wg.Wait()
return d.findings, nil
}
+24
View File
@@ -0,0 +1,24 @@
package detect
// Fragment contains the data to be scanned
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
Bytes []byte
// FilePath is the path to the file, if applicable.
// The path separator MUST be normalized to `/`.
FilePath string
SymlinkFile string
// WindowsFilePath is the path with the original separator.
// This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565.
WindowsFilePath string `json:"-"` // TODO: remove this in v9.
// CommitSHA is the SHA of the commit if applicable
CommitSHA string
// newlineIndices is a list of indices of newlines in the raw content.
// This is used to calculate the line location of a finding
newlineIndices [][]int
}
+226 -20
View File
@@ -1,35 +1,241 @@
package detect
import (
"context"
"bytes"
"errors"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// RemoteInfo is an alias for sources.RemoteInfo for backwards compatibility
//
// Deprecated: This will be replaced with sources.RemoteInfo in v9
type RemoteInfo sources.RemoteInfo
// DetectGit runs detections against a GitCmd with its remote info
//
// Deprecated: Use sources.Git and detector.DetectSource instead
func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.Finding, error) {
return d.DetectSource(
context.Background(),
&sources.Git{
Cmd: cmd,
Config: &d.Config,
Remote: (*sources.RemoteInfo)(remote),
Sema: d.Sema,
MaxArchiveDepth: d.MaxArchiveDepth,
},
defer cmd.Wait()
var (
diffFilesCh = cmd.DiffFilesCh()
errCh = cmd.ErrCh()
)
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
break
}
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
for _, a := range d.Config.Allowlists {
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
continue
}
}
}
if isArchive(gitdiffFile.NewName) {
// Check if commit is allowed
d.Sema.Go(func() error {
// Check out the archive blob to disk
archivePath, err := cmd.CheckoutBlob(commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Warn().Err(err).Str("file", gitdiffFile.NewName).Msg("failed to checkout blob")
return nil
}
defer os.Remove(archivePath)
targets, tmpDir, err := extractArchive(archivePath)
if err != nil {
os.RemoveAll(tmpDir)
logging.Warn().Err(err).Msg("failed to extract archive")
return nil
}
// Scan each extracted file just as you would in directory mode
for _, t := range targets {
// build the “inside-archive” path
rel, _ := filepath.Rel(tmpDir, t.Path)
rel = filepath.ToSlash(rel)
// chain onto any existing VirtualPath (nested archives)
if t.VirtualPath != "" {
t.VirtualPath = t.VirtualPath + "/" + rel
} else {
t.VirtualPath = filepath.Base(gitdiffFile.NewName) + "/" + rel
}
// TODO this isn't a great solution, and it would be nice to
// have a better way to handle this.
// update taget to include git information:
t.Source = "github-archive"
t.GitInfo.Author = gitdiffFile.PatchHeader.Author.Name
t.GitInfo.Commit = commitSHA
t.GitInfo.Date = gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
t.GitInfo.Message = gitdiffFile.PatchHeader.Message()
t.GitInfo.Email = gitdiffFile.PatchHeader.Author.Email
d.detectScanTarget(t)
}
os.RemoveAll(tmpDir)
return nil
})
}
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
continue
}
d.addCommit(commitSHA)
d.Sema.Go(func() error {
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
Raw: textFragment.Raw(gitdiff.OpAdd),
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
}
timer := time.AfterFunc(SlowWarningThreshold, func() {
logging.Debug().
Str("commit", commitSHA[:7]).
Str("path", fragment.FilePath).
Msgf("Taking longer than %s to inspect fragment", SlowWarningThreshold.String())
})
for _, finding := range d.Detect(fragment) {
d.AddFinding(augmentGitFinding(remote, finding, textFragment, gitdiffFile))
}
if timer != nil {
timer.Stop()
timer = nil
}
}
return nil
})
case err, open := <-errCh:
if !open {
errCh = nil
break
}
return d.findings, err
}
}
if err := d.Sema.Wait(); err != nil {
return d.findings, err
}
logging.Info().Msgf("%d commits scanned.", len(d.commitMap))
logging.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
return d.findings, nil
}
// Deprecated: use sources.NewRemoteInfo instead
type RemoteInfo struct {
Platform scm.Platform
Url string
}
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
return (*RemoteInfo)(sources.NewRemoteInfo(platform, source))
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
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.")
platform = scm.NoPlatform
} else {
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
}
goto End
}
if platform == scm.UnknownPlatform {
platform = platformFromHost(remoteUrl)
if platform == scm.UnknownPlatform {
logging.Info().
Str("host", remoteUrl.Hostname()).
Msg("Unknown SCM platform. Use --platform to include links in findings.")
} else {
logging.Debug().
Str("host", remoteUrl.Hostname()).
Str("platform", platform.String()).
Msg("SCM platform parsed from host")
}
}
End:
var rUrl string
if remoteUrl != nil {
rUrl = remoteUrl.String()
}
return &RemoteInfo{
Platform: platform,
Url: rUrl,
}
}
var sshUrlpat = regexp.MustCompile(`^git@([a-zA-Z0-9.-]+):([\w/.-]+?)(?:\.git)?$`)
func getRemoteUrl(source string) (*url.URL, error) {
// This will return the first remote — typically, "origin".
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
stdout, err := cmd.Output()
if err != nil {
var exitError *exec.ExitError
if errors.As(err, &exitError) {
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
}
return nil, err
}
remoteUrl := string(bytes.TrimSpace(stdout))
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
}
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
parsedUrl, err := url.Parse(remoteUrl)
if err != nil {
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
}
// Remove any user info.
parsedUrl.User = nil
return parsedUrl, nil
}
func platformFromHost(u *url.URL) scm.Platform {
switch strings.ToLower(u.Hostname()) {
case "github.com":
return scm.GitHubPlatform
case "gitlab.com":
return scm.GitLabPlatform
case "dev.azure.com", "visualstudio.com":
return scm.AzureDevOpsPlatform
default:
return scm.UnknownPlatform
}
}
+8 -8
View File
@@ -10,7 +10,7 @@ type Location struct {
endLineIndex int
}
func location(newlineIndices [][]int, raw string, matchIndex []int) Location {
func location(fragment Fragment, matchIndex []int) Location {
var (
prevNewLine int
location Location
@@ -28,13 +28,13 @@ func location(newlineIndices [][]int, raw string, matchIndex []int) Location {
// When a fragment does NOT have any newlines, a default "newline"
// will be counted to make the subsequent location calculation logic work
// for fragments will no newlines.
if len(newlineIndices) == 0 {
newlineIndices = [][]int{
{len(raw), len(raw) + 1},
if len(fragment.newlineIndices) == 0 {
fragment.newlineIndices = [][]int{
{len(fragment.Raw), len(fragment.Raw) + 1},
}
}
for lineNum, pair := range newlineIndices {
for lineNum, pair := range fragment.newlineIndices {
_lineNum = lineNum
newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex {
@@ -65,11 +65,11 @@ func location(newlineIndices [][]int, raw string, matchIndex []int) Location {
// search for new line byte index
i := 0
for end+i < len(raw) {
if raw[end+i] == '\n' {
for end+i < len(fragment.Raw) {
if fragment.Raw[end+i] == '\n' {
break
}
if raw[end+i] == '\r' {
if fragment.Raw[end+i] == '\r' {
break
}
i++
+1 -1
View File
@@ -51,7 +51,7 @@ func TestGetLocation(t *testing.T) {
}
for _, test := range tests {
loc := location(test.linePairs, "", []int{test.start, test.end})
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
assert.Equal(t, test.wantLocation, loc)
}
}
+60 -41
View File
@@ -1,41 +1,52 @@
package detect
import (
"context"
"bufio"
"bytes"
"errors"
"io"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
// DetectReader accepts an io.Reader and a buffer size for the reader in KB
//
// Deprecated: Use sources.File with no path defined and Detector.DetectSource instead
func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
var findings []report.Finding
file := sources.File{
Content: r,
Buffer: make([]byte, 1000*bufSize),
MaxArchiveDepth: d.MaxArchiveDepth,
}
reader := bufio.NewReader(r)
buf := make([]byte, 1000*bufSize)
findings := []report.Finding{}
ctx := context.Background()
err := file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
return err
}
for {
n, err := reader.Read(buf)
for _, finding := range d.Detect(Fragment(fragment)) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
// "Callers should always process the n > 0 bytes returned before considering the error err."
// https://pkg.go.dev/io#Reader
if n > 0 {
// Try to split chunks across large areas of whitespace, if possible.
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
return findings, readErr
}
fragment := Fragment{
Raw: peekBuf.String(),
}
for _, finding := range d.Detect(fragment) {
findings = append(findings, finding)
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
return nil
})
if err != nil {
if err == io.EOF {
break
}
return findings, err
}
}
return findings, err
return findings, nil
}
// StreamDetectReader streams the detection results from the provided io.Reader.
@@ -71,37 +82,45 @@ func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, err
// } else {
// fmt.Println("Scanning completed successfully.")
// }
//
// Deprecated: Use sources.File.Fragments(context.Context, FragmentsFunc) instead
func (d *Detector) StreamDetectReader(r io.Reader, bufSize int) (<-chan report.Finding, <-chan error) {
findingsCh := make(chan report.Finding, 1)
errCh := make(chan error, 1)
file := sources.File{
Content: r,
Buffer: make([]byte, 1000*bufSize),
MaxArchiveDepth: d.MaxArchiveDepth,
}
go func() {
defer close(findingsCh)
defer close(errCh)
ctx := context.Background()
errCh <- file.Fragments(ctx, func(fragment sources.Fragment, err error) error {
if err != nil {
return err
}
reader := bufio.NewReader(r)
buf := make([]byte, 1000*bufSize)
for _, finding := range d.Detect(Fragment(fragment)) {
findingsCh <- finding
if d.Verbose {
printFinding(finding, d.NoColor)
for {
n, err := reader.Read(buf)
if n > 0 {
peekBuf := bytes.NewBuffer(buf[:n])
if readErr := readUntilSafeBoundary(reader, n, maxPeekSize, peekBuf); readErr != nil {
errCh <- readErr
return
}
fragment := Fragment{Raw: peekBuf.String()}
for _, finding := range d.Detect(fragment) {
findingsCh <- finding
if d.Verbose {
printFinding(finding, d.NoColor)
}
}
}
return nil
})
if err != nil {
if errors.Is(err, io.EOF) {
errCh <- nil
return
}
errCh <- err
return
}
}
}()
return findingsCh, errCh
+42 -56
View File
@@ -6,38 +6,59 @@ import (
"math"
"path/filepath"
"strings"
"time"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/logging"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
"github.com/charmbracelet/lipgloss"
"github.com/gitleaks/go-gitdiff/gitdiff"
)
// augmentGitFinding updates the start and end line numbers of a finding to include the
// delta from the git diff
func augmentGitFinding(remote *RemoteInfo, finding report.Finding, textFragment *gitdiff.TextFragment, f *gitdiff.File) report.Finding {
if !strings.HasPrefix(finding.Match, "file detected") {
finding.StartLine += int(textFragment.NewPosition)
finding.EndLine += int(textFragment.NewPosition)
}
if f.PatchHeader != nil {
finding.Commit = f.PatchHeader.SHA
if f.PatchHeader.Author != nil {
finding.Author = f.PatchHeader.Author.Name
finding.Email = f.PatchHeader.Author.Email
}
finding.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
finding.Message = f.PatchHeader.Message()
// Results from `git diff` shouldn't have a link.
if finding.Commit != "" {
finding.Link = createScmLink(remote.Platform, remote.Url, finding)
}
}
return finding
}
var linkCleaner = strings.NewReplacer(
" ", "%20",
"%", "%25",
)
func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
if remote.Platform == scm.UnknownPlatform ||
remote.Platform == scm.NoPlatform ||
finding.Commit == "" {
func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Finding) string {
if scmPlatform == scm.UnknownPlatform || scmPlatform == scm.NoPlatform {
return ""
}
// Clean the path.
filePath, _, hasInnerPath := strings.Cut(finding.File, sources.InnerPathSeparator)
filePath = linkCleaner.Replace(filePath)
var (
filePath = linkCleaner.Replace(finding.File)
ext = strings.ToLower(filepath.Ext(filePath))
)
switch remote.Platform {
switch scmPlatform {
case scm.GitHubPlatform:
link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
ext := strings.ToLower(filepath.Ext(filePath))
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
if ext == ".ipynb" || ext == ".md" {
link += "?plain=1"
}
@@ -49,10 +70,7 @@ func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
}
return link
case scm.GitLabPlatform:
link := fmt.Sprintf("%s/blob/%s/%s", remote.Url, finding.Commit, filePath)
if hasInnerPath {
return link
}
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
if finding.StartLine != 0 {
link += fmt.Sprintf("#L%d", finding.StartLine)
}
@@ -61,11 +79,8 @@ func createScmLink(remote *sources.RemoteInfo, finding report.Finding) string {
}
return link
case scm.AzureDevOpsPlatform:
link := fmt.Sprintf("%s/commit/%s?path=/%s", remote.Url, finding.Commit, filePath)
link := fmt.Sprintf("%s/commit/%s?path=/%s", remoteUrl, finding.Commit, filePath)
// Add line information if applicable
if hasInnerPath {
return link
}
if finding.StartLine != 0 {
link += fmt.Sprintf("&line=%d", finding.StartLine)
}
@@ -75,34 +90,6 @@ 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 ""
@@ -146,8 +133,8 @@ func filter(findings []report.Finding, redact uint) []report.Finding {
strings.Contains(fPrime.Secret, f.Secret) &&
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
genericMatch := strings.ReplaceAll(f.Match, f.Secret, "REDACTED")
betterMatch := strings.ReplaceAll(fPrime.Match, fPrime.Secret, "REDACTED")
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
logging.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false
break
@@ -232,9 +219,7 @@ 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
}
@@ -245,7 +230,6 @@ 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
}
@@ -257,7 +241,9 @@ func printFinding(f report.Finding, noColor bool) {
if f.Link != "" {
fmt.Printf("%-12s %s\n", "Link:", f.Link)
}
f.PrintRequiredFindings()
fmt.Println("")
}
func isWhitespace(ch byte) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
+23 -110
View File
@@ -7,30 +7,25 @@ import (
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/zricethezav/gitleaks/v8/sources"
)
func Test_createScmLink(t *testing.T) {
tests := map[string]struct {
remote *sources.RemoteInfo
finding report.Finding
want string
platform scm.Platform
url string
finding report.Finding
want string
}{
// None
"no platform": {
remote: &sources.RemoteInfo{
Platform: scm.NoPlatform,
Url: "",
},
want: "",
platform: scm.NoPlatform,
want: "",
},
// GitHub
"github - single line": {
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "metrics/% of sales/.env",
@@ -40,10 +35,8 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/20553ad96a4a080c94a54d677db97eed8ce2560d/metrics/%25%20of%20sales/.env#L25",
},
"github - multi line": {
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
finding: report.Finding{
Commit: "7bad9f7654cf9701b62400281748c0e8efd97666",
File: "config.json",
@@ -53,10 +46,8 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/7bad9f7654cf9701b62400281748c0e8efd97666/config.json#L235-L238",
},
"github - markdown": {
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
finding: report.Finding{
Commit: "1fc8961d172f39ffb671766e472aa76f8d713e87",
File: "docs/guides/ecosystem/discordjs.MD",
@@ -66,10 +57,8 @@ func Test_createScmLink(t *testing.T) {
want: "https://github.com/gitleaks/test/blob/1fc8961d172f39ffb671766e472aa76f8d713e87/docs/guides/ecosystem/discordjs.MD?plain=1#L34",
},
"github - jupyter notebook": {
remote: &sources.RemoteInfo{
Platform: scm.GitHubPlatform,
Url: "https://github.com/gitleaks/test",
},
platform: scm.GitHubPlatform,
url: "https://github.com/gitleaks/test",
finding: report.Finding{
Commit: "8f56bd2369595bcadbb007e88ba294630fb05c7b",
File: "Cloud/IPYNB/Overlapping Recommendation algorithm _OCuLaR_.ipynb",
@@ -81,10 +70,8 @@ func Test_createScmLink(t *testing.T) {
// GitLab
"gitlab - single line": {
remote: &sources.RemoteInfo{
Platform: scm.GitLabPlatform,
Url: "https://gitlab.com/example-org/example-group/gitleaks",
},
platform: scm.GitLabPlatform,
url: "https://gitlab.com/example-org/example-group/gitleaks",
finding: report.Finding{
Commit: "213ffd1c9bfa906eb4c7731771132c58a4ca0139",
File: ".gitlab-ci.yml",
@@ -94,10 +81,8 @@ func Test_createScmLink(t *testing.T) {
want: "https://gitlab.com/example-org/example-group/gitleaks/blob/213ffd1c9bfa906eb4c7731771132c58a4ca0139/.gitlab-ci.yml#L41",
},
"gitlab - multi line": {
remote: &sources.RemoteInfo{
Platform: scm.GitLabPlatform,
Url: "https://gitlab.com/example-org/example-group/gitleaks",
},
platform: scm.GitLabPlatform,
url: "https://gitlab.com/example-org/example-group/gitleaks",
finding: report.Finding{
Commit: "63410f74e23a4e51e1f60b9feb073b5d325af878",
File: ".vscode/launchSettings.json",
@@ -109,10 +94,8 @@ func Test_createScmLink(t *testing.T) {
// Azure DevOps
"azuredevops - single line": {
remote: &sources.RemoteInfo{
Platform: scm.AzureDevOpsPlatform,
Url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
},
platform: scm.AzureDevOpsPlatform,
url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
@@ -124,10 +107,8 @@ func Test_createScmLink(t *testing.T) {
// Azure DevOps
"azuredevops - multi line": {
remote: &sources.RemoteInfo{
Platform: scm.AzureDevOpsPlatform,
Url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
},
platform: scm.AzureDevOpsPlatform,
url: "https://dev.azure.com/exampleorganisation/exampleproject/_git/exampleRepository",
finding: report.Finding{
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
File: "examplefile.json",
@@ -136,78 +117,10 @@ 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) {
actual := createScmLink(tt.remote, tt.finding)
actual := createScmLink(tt.platform, tt.url, tt.finding)
assert.Equal(t, tt.want, actual)
})
}
+6 -4
View File
@@ -1,6 +1,8 @@
module github.com/zricethezav/gitleaks/v8
go 1.23.8
go 1.23.0
toolchain go1.23.4
require (
github.com/BobuSumisu/aho-corasick v1.0.3
@@ -10,7 +12,7 @@ require (
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/mholt/archives v0.1.1
github.com/rs/zerolog v1.33.0
github.com/spf13/cobra v1.9.1
github.com/spf13/viper v1.19.0
@@ -23,7 +25,7 @@ require (
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.3.0 // indirect
github.com/STARRY-S/zip v0.2.1 // indirect
github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.0 // indirect
@@ -60,7 +62,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.35.0 // indirect
golang.org/x/crypto v0.32.0 // indirect
)
require (
+6 -6
View File
@@ -29,8 +29,8 @@ 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/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/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
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=
@@ -150,8 +150,8 @@ github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRC
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mholt/archives v0.1.2 h1:UBSe5NfYKHI1sy+S5dJsEsG9jsKKk8NJA4HCC+xTI4A=
github.com/mholt/archives v0.1.2/go.mod h1:D7QzTHgw3ctfS6wgOO9dN+MFgdZpbksGCxprUOwZWDs=
github.com/mholt/archives v0.1.1 h1:c7J3qXN1FB54y0qiUXiq9Bxk4eCUc8pdXWwOhZdRzeY=
github.com/mholt/archives v0.1.1/go.mod h1:FQVz01Q2uXKB/35CXeW/QFO23xT+hSCGZHVtha78U4I=
github.com/minio/minlz v1.0.0 h1:Kj7aJZ1//LlTP1DM8Jm7lNKvvJS2m74gyyXXn3+uJWQ=
github.com/minio/minlz v1.0.0/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
@@ -245,8 +245,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.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
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=
+6 -62
View File
@@ -1,16 +1,12 @@
package report
import (
"fmt"
"math"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/zricethezav/gitleaks/v8/sources"
)
// Finding contains a whole bunch of information about a secret finding.
// Plenty of real estate in this bad boy so fillerup as needed.
// Finding contains information about strings that
// have been captured by a tree-sitter query.
type Finding struct {
// Rule is the name of the rule that was matched
RuleID string
@@ -25,7 +21,8 @@ type Finding struct {
Match string
// Captured secret
// Secret contains the full content of what is matched in
// the tree-sitter query.
Secret string
// File is the name of the file containing the finding
@@ -45,33 +42,6 @@ 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.
@@ -80,8 +50,8 @@ func (f *Finding) Redact(percent uint) {
if percent >= 100 {
secret = "REDACTED"
}
f.Line = strings.ReplaceAll(f.Line, f.Secret, secret)
f.Match = strings.ReplaceAll(f.Match, f.Secret, secret)
f.Line = strings.Replace(f.Line, f.Secret, secret, -1)
f.Match = strings.Replace(f.Match, f.Secret, secret, -1)
f.Secret = secret
}
@@ -98,29 +68,3 @@ 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))
}
}
}
+1 -2
View File
@@ -1,7 +1,6 @@
package report
import (
"errors"
"fmt"
"io"
"os"
@@ -18,7 +17,7 @@ var _ Reporter = (*TemplateReporter)(nil)
func NewTemplateReporter(templatePath string) (*TemplateReporter, error) {
if templatePath == "" {
return nil, errors.New("template path cannot be empty")
return nil, fmt.Errorf("template path cannot be empty")
}
file, err := os.ReadFile(templatePath)
-80
View File
@@ -1,80 +0,0 @@
#! /usr/bin/env bash
# NAME
# profile.sh - generate gitleaks profile data
#
# USAGE
# profile.sh <gitleaks-path> <benchmark-repo-path>
#
# DESCRIPTION
# Generates profile data for tuning gitleaks performance under ./profile/<timestamp>
#
# Options:
# <gitleaks-path> - gitleaks binary to profile
# <benchmark-repo-path> - git repo to run profile against
#
# SEE ALSO
# Dave Cheney GopherCon 2019 talk on go profiling:
#
# https://www.youtube.com/watch?v=nok0aYiGiYA
#
set -euo pipefail
gitleaks_path="$1"
test_repo_path="$2"
base_scan_cmd="${gitleaks_path} --exit-code=0 --max-decode-depth 8"
base_profile_dir="profile/$(date +%s)"
log() {
echo >&2 "$@"
}
log '========================================================================'
log 'generating profile data'
log '------------------------------------------------------------------------'
# Warm up the fs and also get benchmark data
for scan_mode in dir git
do
profile_dir="${base_profile_dir}/${scan_mode}"
scan_cmd="${base_scan_cmd} ${scan_mode} ${test_repo_path}"
mkdir -p "${profile_dir}"
echo "- mode: ${scan_mode}"
# include hyperfine benchmrak results if hyperfine is installed
if command -v hyperfine > /dev/null
then
export_path="${profile_dir}/benchmark.json"
echo " benchmark:"
echo " tool: hyperfine"
hyperfine -w 3 --export-json "${export_path}" "${scan_cmd}" &> /dev/null
echo " path: ${export_path}"
# Show the results if we can :D
if command -v yq > /dev/null
then
echo " results:"
yq -P -oy \
'.results[] | pick(["mean","stddev","median","user","system","min","max"])' \
${export_path} | sed 's/^/ /g'
else
echo " view: ${PAGER:-less} ${export_path}"
fi
fi
# generate profile data
echo " profile:"
for profile_mode in cpu mem trace
do
# Generate diagnostics data
${scan_cmd} --diagnostics=$profile_mode --diagnostics-dir="${profile_dir}" &> /dev/null
profile_file="$(find "${profile_dir}" -type f -name "${profile_mode}*")"
echo " - mode: ${profile_mode}"
echo " path: ${profile_file}"
if [[ "${profile_mode}" = "trace" ]]
then
echo " view: go tool trace ${profile_file}"
else
echo " view: go tool pprof -http=localhost: ${gitleaks_path} ${profile_file}"
fi
done
done
log '------------------------------------------------------------------------'
log "results in: ${base_profile_dir}"
log '========================================================================'
-125
View File
@@ -1,125 +0,0 @@
package sources
import (
"bufio"
"bytes"
"context"
"io"
"path/filepath"
"runtime"
"github.com/mholt/archives"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
const maxPeekSize = 25 * 1_000 // 10kb
var isWhitespace [256]bool
var isWindows = runtime.GOOS == "windows"
func init() {
// define whitespace characters
isWhitespace[' '] = true
isWhitespace['\t'] = true
isWhitespace['\n'] = true
isWhitespace['\r'] = true
}
// isArchive does a light check to see if the provided path is an archive or
// compressed file. The File source already does this, so this exists mainly
// to avoid expensive calls before sending things to the File source
func isArchive(ctx context.Context, path string) bool {
format, _, err := archives.Identify(ctx, path, nil)
return err == nil && format != nil
}
// shouldSkipPath checks a path against all the allowlists to see if it can
// be skipped
func shouldSkipPath(cfg *config.Config, path string) bool {
if cfg == nil {
logging.Trace().Str("path", path).Msg("not skipping path because config is nil")
return false
}
for _, a := range cfg.Allowlists {
if a.PathAllowed(path) ||
// TODO: Remove this in v9.
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
(isWindows && a.PathAllowed(filepath.ToSlash(path))) {
return true
}
}
return false
}
// readUntilSafeBoundary consumes |f| until it finds two consecutive `\n` characters, up to |maxPeekSize|.
// This hopefully avoids splitting. (https://github.com/gitleaks/gitleaks/issues/1651)
func readUntilSafeBoundary(r *bufio.Reader, n int, maxPeekSize int, peekBuf *bytes.Buffer) error {
if peekBuf.Len() == 0 {
return nil
}
// Does the buffer end in consecutive newlines?
var (
data = peekBuf.Bytes()
lastChar = data[len(data)-1]
newlineCount = 0 // Tracks consecutive newlines
)
if isWhitespace[lastChar] {
for i := len(data) - 1; i >= 0; i-- {
lastChar = data[i]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
return nil
}
} else if isWhitespace[lastChar] {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
break
}
}
}
// If not, read ahead until we (hopefully) find some.
newlineCount = 0
for {
data = peekBuf.Bytes()
// Check if the last character is a newline.
lastChar = data[len(data)-1]
if lastChar == '\n' {
newlineCount++
// Stop if two consecutive newlines are found
if newlineCount >= 2 {
break
}
} else if isWhitespace[lastChar] {
// The presence of other whitespace characters (`\r`, ` `, `\t`) shouldn't reset the count.
// (Intentionally do nothing.)
} else {
newlineCount = 0 // Reset if a non-newline character is found
}
// Stop growing the buffer if it reaches maxSize
if (peekBuf.Len() - n) >= maxPeekSize {
break
}
// Read additional data into a temporary buffer
b, err := r.ReadByte()
if err != nil {
if err == io.EOF {
break
}
return err
}
peekBuf.WriteByte(b)
}
return nil
}
+116
View File
@@ -0,0 +1,116 @@
package sources
import (
"io/fs"
"os"
"path/filepath"
"runtime"
"github.com/fatih/semgroup"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
type ScanTarget struct {
Path string
Symlink string
VirtualPath string
Source string
// The following items are only used for git archive scans
// (since we have to treat them like regular dir scans)
GitInfo GitInfo
// TODO one day use a single Metadata map
// instead of git fields
// Metadata map[string]string
}
var isWindows = runtime.GOOS == "windows"
func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget)
s.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
logger := logging.With().Str("path", path).Logger()
if err != nil {
if os.IsPermission(err) {
// This seems to only fail on directories at this stage.
logger.Warn().Msg("Skipping directory: permission denied")
return filepath.SkipDir
}
return err
}
// Empty; nothing to do here.
if fInfo.Size() == 0 {
return nil
}
// Unwrap symlinks, if |followSymlinks| is set.
scanTarget := ScanTarget{
Path: path,
}
if fInfo.Mode().Type() == fs.ModeSymlink {
if !followSymlinks {
logger.Debug().Msg("Skipping symlink")
return nil
}
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
realPathFileInfo, _ := os.Stat(realPath)
if realPathFileInfo.IsDir() {
logger.Warn().Str("target", realPath).Msg("Skipping symlinked directory")
return nil
}
scanTarget.Path = realPath
scanTarget.Symlink = path
}
// TODO: Also run this check against the resolved symlink?
var skip bool
for _, a := range allowlists {
skip = a.PathAllowed(path) ||
// TODO: Remove this in v9.
// This is an awkward hack to mitigate https://github.com/gitleaks/gitleaks/issues/1641.
(isWindows && a.PathAllowed(filepath.ToSlash(path)))
if skip {
break
}
}
if fInfo.IsDir() {
// Directory
if skip {
logger.Debug().Msg("Skipping directory due to global allowlist")
return filepath.SkipDir
}
if fInfo.Name() == ".git" {
// Don't scan .git directories.
// TODO: Add this to the config allowlist, instead of hard-coding it.
return filepath.SkipDir
}
} else {
// File
if skip {
logger.Debug().Msg("Skipping file due to global allowlist")
return nil
}
paths <- scanTarget
}
return nil
})
})
return paths, nil
}
-251
View File
@@ -1,251 +0,0 @@
package sources
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/h2non/filetype"
"github.com/mholt/archives"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
const defaultBufferSize = 100 * 1_000 // 100kb
const InnerPathSeparator = "!"
type seekReaderAt interface {
io.ReaderAt
io.Seeker
}
// File is a source for yielding fragments from a file or other reader
type File struct {
// Content provides a reader to the file's content
Content io.Reader
// Path is the resolved real path of the file
Path string
// Symlink represents a symlink to the file if that's how it was discovered
Symlink string
// Buffer is used for reading the content in chunks
Buffer []byte
// Config is the gitleaks config used for shouldSkipPath. If not set, then
// shouldSkipPath is ignored
Config *config.Config
// outerPaths is the list of container paths (e.g. archives) that lead to
// this file
outerPaths []string
// MaxArchiveDepth limits how deep the sources will explore nested archives
MaxArchiveDepth int
// archiveDepth is the current archive nesting depth
archiveDepth int
}
// Fragments yields fragments for the this source
func (s *File) Fragments(ctx context.Context, yield FragmentsFunc) error {
format, _, err := archives.Identify(ctx, s.Path, nil)
// Process the file as an archive if there's no error && Identify returns
// a format; but if there's an error or no format, just swallow the error
// and fall back on treating it like a normal file and let fileFragments
// decide what to do with it.
if err == nil && format != nil {
if s.archiveDepth+1 > s.MaxArchiveDepth {
// 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 {
return s.extractorFragments(ctx, extractor, s.Content, yield)
}
if decompressor, ok := format.(archives.Decompressor); ok {
return s.decompressorFragments(decompressor, s.Content, yield)
}
logging.Warn().Str("path", s.FullPath()).Msg("skipping unknown archive type")
}
return s.fileFragments(bufio.NewReader(s.Content), yield)
}
// extractorFragments recursively crawls archives and yields fragments
func (s *File) extractorFragments(ctx context.Context, extractor archives.Extractor, reader io.Reader, yield FragmentsFunc) error {
if _, isSeekReaderAt := reader.(seekReaderAt); !isSeekReaderAt {
switch extractor.(type) {
case archives.SevenZip, archives.Zip:
tmpfile, err := os.CreateTemp("", "gitleaks-archive-")
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could not create tmp file")
return nil
}
defer func() {
_ = tmpfile.Close()
_ = os.Remove(tmpfile.Name())
}()
_, err = io.Copy(tmpfile, reader)
if err != nil {
logging.Error().Str("path", s.FullPath()).Msg("could not copy archive file")
return nil
}
reader = tmpfile
}
}
return extractor.Extract(ctx, reader, func(_ context.Context, d archives.FileInfo) error {
if d.IsDir() {
return nil
}
innerReader, err := d.Open()
if err != nil {
logging.Error().Err(err).Str("path", s.FullPath()).Msg("could not open archive inner file")
return nil
}
defer innerReader.Close()
path := filepath.Clean(d.NameInArchive)
if s.Config != nil && shouldSkipPath(s.Config, path) {
logging.Debug().Str("path", s.FullPath()).Msg("skipping file: global allowlist")
return nil
}
file := &File{
Content: innerReader,
Path: path,
Symlink: s.Symlink,
outerPaths: append(s.outerPaths, filepath.ToSlash(s.Path)),
MaxArchiveDepth: s.MaxArchiveDepth,
archiveDepth: s.archiveDepth + 1,
}
if err := file.Fragments(ctx, yield); err != nil {
return err
}
return nil
})
}
// decompressorFragments recursively crawls archives and yields fragments
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(bufio.NewReader(innerReader), yield); err != nil {
_ = innerReader.Close()
return err
}
_ = innerReader.Close()
return nil
}
// fileFragments reads the file into fragments to yield
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)
}
totalLines := 0
for {
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))
}
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
}
}
// 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),
)
}
fragment.Raw = peekBuf.String()
fragment.Bytes = peekBuf.Bytes()
fragment.StartLine = totalLines + 1
// Count the number of newlines in this chunk
totalLines += strings.Count(fragment.Raw, "\n")
if len(s.Symlink) > 0 {
fragment.SymlinkFile = s.Symlink
}
if isWindows {
fragment.FilePath = filepath.ToSlash(fragment.FilePath)
fragment.SymlinkFile = filepath.ToSlash(s.Symlink)
fragment.WindowsFilePath = s.FullPath()
}
// 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
}
}
}
// FullPath returns the File.Path with any preceding outer paths
func (s *File) FullPath() string {
if len(s.outerPaths) > 0 {
return strings.Join(
// outerPaths have already been normalized to slash
append(s.outerPaths, s.Path),
InnerPathSeparator,
)
}
return s.Path
}
-180
View File
@@ -1,180 +0,0 @@
package sources
import (
"context"
"errors"
"io/fs"
"os"
"path/filepath"
"sync"
"github.com/fatih/semgroup"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
// TODO: remove this in v9 and have scanTargets yield file sources
type ScanTarget struct {
Path string
Symlink string
}
// Deprecated: Use Files and detector.DetectSource instead
func DirectoryTargets(sourcePath string, s *semgroup.Group, followSymlinks bool, allowlists []*config.Allowlist) (<-chan ScanTarget, error) {
paths := make(chan ScanTarget)
// create a Files source
files := Files{
FollowSymlinks: followSymlinks,
Path: sourcePath,
Sema: s,
Config: &config.Config{
Allowlists: allowlists,
},
}
s.Go(func() error {
err := files.scanTargets(func(scanTarget ScanTarget, err error) error {
paths <- scanTarget
return nil
})
close(paths)
return err
})
return paths, nil
}
// Files is a source for yielding fragments from a collection of files
type Files struct {
Config *config.Config
FollowSymlinks bool
MaxFileSize int
Path string
Sema *semgroup.Group
MaxArchiveDepth int
}
// scanTargets yields scan targets to a callback func
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()
if err != nil {
if os.IsPermission(err) {
// This seems to only fail on directories at this stage.
logger.Warn().Err(errors.New("permission denied")).Msg("skipping directory")
return filepath.SkipDir
}
logger.Warn().Err(err).Msg("skipping")
return nil
}
info, err := d.Info()
if err != nil {
if d.IsDir() {
logger.Error().Err(err).Msg("skipping directory: could not get info")
return filepath.SkipDir
}
logger.Error().Err(err).Msg("skipping file: could not get info")
return nil
}
if !d.IsDir() {
// Empty; nothing to do here.
if info.Size() == 0 {
logger.Debug().Msg("skipping empty file")
return nil
}
// Too large; nothing to do here.
if s.MaxFileSize > 0 && info.Size() > int64(s.MaxFileSize) {
logger.Warn().Msgf(
"skipping file: too large max_size=%dMB, size=%dMB",
s.MaxFileSize/1_000_000, info.Size()/1_000_000,
)
return nil
}
}
// set the initial scan target values
if d.Type() == fs.ModeSymlink {
if !s.FollowSymlinks {
logger.Debug().Msg("skipping symlink: follow symlinks disabled")
return nil
}
realPath, err := filepath.EvalSymlinks(path)
if err != nil {
logger.Error().Err(err).Msg("skipping symlink: could not evaluate")
return nil
}
if realPathFileInfo, _ := os.Stat(realPath); realPathFileInfo.IsDir() {
logger.Debug().Str("target", realPath).Msgf("skipping symlink: target is directory")
return nil
}
scanTarget = ScanTarget{
Path: realPath,
Symlink: path,
}
}
// handle dir cases (mainly just see if it should be skipped
if info.IsDir() {
if shouldSkipPath(s.Config, path) {
logger.Debug().Msg("skipping directory: global allowlist")
return filepath.SkipDir
}
return nil
}
if shouldSkipPath(s.Config, path) {
logger.Debug().Msg("skipping file: global allowlist")
return nil
}
return yield(scanTarget, nil)
})
}
// Fragments yields fragments from files discovered under the path
func (s *Files) Fragments(ctx context.Context, yield FragmentsFunc) error {
var wg sync.WaitGroup
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
}
// 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
})
wg.Wait()
return err
}
-28
View File
@@ -1,28 +0,0 @@
package sources
// Fragment represents a fragment of a source with its meta data
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
Bytes []byte
// FilePath is the path to the file if applicable.
// The path separator MUST be normalized to `/`.
FilePath string
SymlinkFile string
// WindowsFilePath is the path with the original separator.
// This provides a backwards-compatible solution to https://github.com/gitleaks/gitleaks/issues/1565.
WindowsFilePath string `json:"-"` // TODO: remove this in v9.
// CommitSHA is the SHA of the commit if applicable
CommitSHA string // TODO: remove this in v9 and use CommitInfo instead
// StartLine is the line number this fragment starts on
StartLine int
// CommitInfo captures additional information about the git commit if applicable
CommitInfo *CommitInfo
InheritedFromFinding bool // Indicates if this fragment is inherited from a finding
}
+44 -302
View File
@@ -2,24 +2,17 @@ package sources
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/zricethezav/gitleaks/v8/cmd/scm"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/logging"
)
@@ -27,36 +20,20 @@ var quotedOptPattern = regexp.MustCompile(`^(?:"[^"]+"|'[^']+')$`)
// GitCmd helps to work with Git's output.
type GitCmd struct {
repoPath string
cmd *exec.Cmd
diffFilesCh <-chan *gitdiff.File
errCh <-chan error
repoPath string
}
// blobReader provides a ReadCloser interface git cat-file blob to fetch
// a blob from a repo
type blobReader struct {
io.ReadCloser
cmd *exec.Cmd
}
// Close closes the underlying reader and then waits for the command to complete,
// releasing its resources.
func (br *blobReader) Close() error {
// Discard the remaining data from the pipe to avoid blocking
_, drainErr := io.Copy(io.Discard, br)
// Close the pipe (should signal the command to stop if it hasn't already)
closeErr := br.ReadCloser.Close()
// Wait to prevent zombie processes.
waitErr := br.cmd.Wait()
// Return the first error encountered
if drainErr != nil {
return drainErr
}
if closeErr != nil {
return closeErr
}
return waitErr
type GitInfo struct {
Source string
Commit string
Link string
Author string
Email string
Date string
Message string
}
// NewGitLogCmd returns `*DiffFilesCmd` with two channels: `<-chan *gitdiff.File` and `<-chan error`.
@@ -85,7 +62,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
cmd = exec.Command("git", args...)
} else {
cmd = exec.Command("git", "-C", sourceClean, "log", "-p", "-U0",
"--full-history", "--all", "--diff-filter=tuxdb")
"--full-history", "--all")
}
logging.Debug().Msgf("executing: %s", cmd.String())
@@ -111,10 +88,10 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
}
return &GitCmd{
repoPath: sourceClean,
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
repoPath: sourceClean,
}, nil
}
@@ -152,13 +129,43 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
}
return &GitCmd{
repoPath: sourceClean,
cmd: cmd,
diffFilesCh: gitdiffFiles,
errCh: errCh,
repoPath: sourceClean,
}, nil
}
// CheckoutBlob writes the contents of the blob at commit:filepath into a temp file
// and returns its path.
func (g *GitCmd) CheckoutBlob(commit, filepathInRepo string) (string, error) {
// Create a temp file with the same extension as the blob, if possible
ext := filepath.Ext(filepathInRepo)
// tmpDir, err := os.MkdirTemp("gitleaks", "archive-*")
tmpFile, err := os.CreateTemp("", "gitleaks-blob-*"+ext)
if err != nil {
return "", fmt.Errorf("creating temp file for blob: %w", err)
}
tmpFilePath := tmpFile.Name()
tmpFile.Close()
// git show <commit>:<path>
gitArgs := []string{"-C", g.repoPath, "show", fmt.Sprintf("%s:%s", commit, filepathInRepo)}
cmd := exec.Command("git", gitArgs...)
cmd.Stdout, err = os.OpenFile(tmpFilePath, os.O_WRONLY, 0o644)
if err != nil {
os.Remove(tmpFilePath)
return "", fmt.Errorf("opening temp file for write: %w", err)
}
if err := cmd.Run(); err != nil {
os.Remove(tmpFilePath)
return "", fmt.Errorf("git show failed: %w", err)
}
return tmpFilePath, nil
}
// DiffFilesCh returns a channel with *gitdiff.File.
func (c *GitCmd) DiffFilesCh() <-chan *gitdiff.File {
return c.diffFilesCh
@@ -173,31 +180,10 @@ func (c *GitCmd) ErrCh() <-chan error {
// stdin or copying from stdout or stderr to complete.
//
// Wait also closes underlying stdout and stderr.
func (c *GitCmd) Wait() error {
func (c *GitCmd) Wait() (err error) {
return c.cmd.Wait()
}
// 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) {
gitArgs := []string{"-C", c.repoPath, "cat-file", "blob", commit + ":" + path}
cmd := exec.Command("git", gitArgs...)
cmd.Stderr = io.Discard
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to get stdout pipe: %w", err)
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start git command: %w", err)
}
return &blobReader{
ReadCloser: stdout,
cmd: cmd,
}, nil
}
// listenForStdErr listens for stderr output from git, prints it to stdout,
// sends to errCh and closes it.
func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
@@ -246,247 +232,3 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
return
}
}
// RemoteInfo provides the info needed for reconstructing links from findings
type RemoteInfo struct {
Platform scm.Platform
Url string
}
// Git is a source for yielding fragments from a git repo
type Git struct {
Cmd *GitCmd
Config *config.Config
Remote *RemoteInfo
Sema *semgroup.Group
MaxArchiveDepth int
}
// CommitInfo captures metadata about the commit
type CommitInfo struct {
AuthorEmail string
AuthorName string
Date string
Message string
Remote *RemoteInfo
SHA string
}
// Fragments yields fragments from a git repo
func (s *Git) Fragments(ctx context.Context, yield FragmentsFunc) error {
defer func() {
_ = s.Cmd.Wait()
}()
var (
diffFilesCh = s.Cmd.DiffFilesCh()
errCh = s.Cmd.ErrCh()
wg sync.WaitGroup
)
// loop to range over both DiffFiles (stdout) and ErrCh (stderr)
for diffFilesCh != nil || errCh != nil {
select {
case gitdiffFile, open := <-diffFilesCh:
if !open {
diffFilesCh = nil
break
}
if gitdiffFile.IsDelete {
continue
}
// skip non-archive binary files
yieldAsArchive := false
if gitdiffFile.IsBinary {
if !isArchive(ctx, gitdiffFile.NewName) {
continue
}
yieldAsArchive = true
}
// Check if commit is allowed
commitSHA := ""
var commitInfo *CommitInfo
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
for _, a := range s.Config.Allowlists {
if ok, c := a.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
continue
}
}
commitInfo = &CommitInfo{
Date: gitdiffFile.PatchHeader.AuthorDate.UTC().Format(time.RFC3339),
Message: gitdiffFile.PatchHeader.Message(),
Remote: s.Remote,
SHA: commitSHA,
}
if gitdiffFile.PatchHeader.Author != nil {
commitInfo.AuthorName = gitdiffFile.PatchHeader.Author.Name
commitInfo.AuthorEmail = gitdiffFile.PatchHeader.Author.Email
}
}
wg.Add(1)
s.Sema.Go(func() error {
defer wg.Done()
if yieldAsArchive {
blob, err := s.Cmd.NewBlobReader(commitSHA, gitdiffFile.NewName)
if err != nil {
logging.Error().Err(err).Msg("could not read archive blob")
return nil
}
file := File{
Content: blob,
Path: gitdiffFile.NewName,
MaxArchiveDepth: s.MaxArchiveDepth,
Config: s.Config,
}
// enrich and yield fragments
err = file.Fragments(ctx, func(fragment Fragment, err error) error {
fragment.CommitSHA = commitSHA
fragment.CommitInfo = commitInfo
return yield(fragment, err)
})
// Close the blob reader and log any issues
if err := blob.Close(); err != nil {
logging.Debug().Err(err).Msg("blobReader.Close() returned an error")
}
return err
}
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
Raw: textFragment.Raw(gitdiff.OpAdd),
StartLine: int(textFragment.NewPosition),
CommitInfo: commitInfo,
}
if err := yield(fragment, nil); err != nil {
return err
}
}
return nil
})
case err, open := <-errCh:
if !open {
errCh = nil
break
}
return yield(Fragment{}, err)
}
}
wg.Wait()
return nil
}
// NewRemoteInfo builds a new RemoteInfo for generating finding links
func NewRemoteInfo(platform scm.Platform, source string) *RemoteInfo {
if platform == scm.NoPlatform {
return &RemoteInfo{Platform: platform}
}
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.")
platform = scm.NoPlatform
} else {
logging.Error().Err(err).Msg("skipping finding links: unable to parse remote URL")
}
goto End
}
if platform == scm.UnknownPlatform {
platform = platformFromHost(remoteUrl)
if platform == scm.UnknownPlatform {
logging.Info().
Str("host", remoteUrl.Hostname()).
Msg("Unknown SCM platform. Use --platform to include links in findings.")
} else {
logging.Debug().
Str("host", remoteUrl.Hostname()).
Str("platform", platform.String()).
Msg("SCM platform parsed from host")
}
}
End:
var rUrl string
if remoteUrl != nil {
rUrl = remoteUrl.String()
}
return &RemoteInfo{
Platform: platform,
Url: rUrl,
}
}
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".
cmd := exec.Command("git", "ls-remote", "--quiet", "--get-url")
if source != "." {
cmd.Dir = source
}
stdout, err := cmd.Output()
if err != nil {
var exitError *exec.ExitError
if errors.As(err, &exitError) {
return nil, fmt.Errorf("command failed (%d): %w, stderr: %s", exitError.ExitCode(), err, string(bytes.TrimSpace(exitError.Stderr)))
}
return nil, err
}
remoteUrl := string(bytes.TrimSpace(stdout))
if matches := sshUrlpat.FindStringSubmatch(remoteUrl); matches != nil {
remoteUrl = fmt.Sprintf("https://%s/%s", matches[1], matches[2])
}
remoteUrl = strings.TrimSuffix(remoteUrl, ".git")
parsedUrl, err := url.Parse(remoteUrl)
if err != nil {
return nil, fmt.Errorf("unable to parse remote URL: %w", err)
}
// Remove any user info.
parsedUrl.User = nil
return parsedUrl, nil
}
func platformFromHost(u *url.URL) scm.Platform {
switch strings.ToLower(u.Hostname()) {
case "github.com":
return scm.GitHubPlatform
case "gitlab.com":
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
}
}
-16
View File
@@ -1,16 +0,0 @@
package sources
import (
"context"
)
// FragmentsFunc is the type of function called by Fragments to yield the next
// fragment
type FragmentsFunc func(fragment Fragment, err error) error
// Source is a thing that can yield fragments
type Source interface {
// Fragments provides a filepath.WalkDir like interface for scanning the
// fragments in the source
Fragments(ctx context.Context, yield FragmentsFunc) error
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
-6
View File
@@ -1,6 +0,0 @@
DB_HOST=example.com
DB_PORT=443
DB_USERNAME=postgres
DB_PASSWORD=8ae31cacf141669ddfb5da
DB_NAME=best_db
DB_SSL=true
-1
View File
@@ -1 +0,0 @@
../testdata/repos/nogit/api.go:aws-access-key:20
-24
View File
@@ -1,24 +0,0 @@
package main
import "fmt"
func main() {
var a = "initial"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true
fmt.Println(d)
var e int
fmt.Println(e)
// opps I added a secret at line 20
awsToken := "AKIALALEMEL33243OLIA"
f := "apple"
fmt.Println(f)
}
-24
View File
@@ -1,24 +0,0 @@
package main
import "fmt"
func main() {
var a = "initial"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true
fmt.Println(d)
var e int
fmt.Println(e)
// opps I added a secret at line 20
awsToken := "AKIALALEMEL33243OLIA"
f := "apple"
fmt.Println(f)
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
-21
View File
@@ -1,21 +0,0 @@
title = "gitleaks config"
# https://learnxinyminutes.com/docs/toml/ for toml reference
[[rules]]
id = "aws-access-key"
description = "AWS Access Key"
regex = '''(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}'''
tags = ["key", "AWS"]
# Here to confirm that allowlists work in archives
[[rules]]
id = 'password'
description = "Find the DB password in .env.prod"
path = '''\.env\.prod$'''
regex = '''(?i)password=([^\s]+)'''
# Now ignore it to confirm allowlists work
[[allowlists]]
paths = [
'''\.env\.prod$''',
]
-14
View File
@@ -1,14 +0,0 @@
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
+1
View File
@@ -225,3 +225,4 @@ title = "gitleaks config"
description = "PyPI upload token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{50,1000}'''
tags = ["key", "pypi"]
+1
View File
@@ -0,0 +1 @@
archive.zip/api.go:aws-access-key:20
Binary file not shown.
View File
Whitespace-only changes.
-10
View File
@@ -1,10 +0,0 @@
# Archives
This repo has some archive files in its history!
Commits:
```
07d2bd71800f1abf0421abe9bc4a83a6fdca1f68 nested.tar.gz
db8789716fc664dbce0ed2d492570e92abf717a5 main.go.zst
```
-1
View File
@@ -1 +0,0 @@
ref: refs/heads/main
-1
View File
@@ -1 +0,0 @@
15fa60c13dccec6add267b7baa065977a6cc748a
-13
View File
@@ -1,13 +0,0 @@
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = git@github.com:gitleaks/test.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
remote = origin
merge = refs/heads/main
-1
View File
@@ -1 +0,0 @@
Unnamed repository; edit this file 'description' to name the repository.
Binary file not shown.
-6
View File
@@ -1,6 +0,0 @@
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
-1
View File
@@ -1 +0,0 @@
15fa60c13dccec6add267b7baa065977a6cc748a refs/heads/main
Binary file not shown.
-2
View File
@@ -1,2 +0,0 @@
P pack-9d774732f0e985d717a26e126e6574d089375b0d.pack
-2
View File
@@ -1,2 +0,0 @@
# pack-refs with: peeled fully-peeled sorted
15fa60c13dccec6add267b7baa065977a6cc748a refs/heads/main
View File
Whitespace-only changes.
Binary file not shown.