mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-27 11:44:23 +01:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f0c6f34bf | ||
|
|
66c5bc15d4 | ||
|
|
fa9fadbb84 | ||
|
|
d5e7364bcf | ||
|
|
e0ea9cefde | ||
|
|
56e409d9f1 | ||
|
|
5f210c9d35 | ||
|
|
770baf7458 |
No files matched your search
@@ -9,7 +9,6 @@
|
||||
*.got
|
||||
gitleaks
|
||||
build
|
||||
profile
|
||||
|
||||
# configs
|
||||
.gitleaks.toml
|
||||
|
||||
@@ -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
|
||||
@@ -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
@@ -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.
|
||||
|
||||
|
||||
@@ -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 ./...
|
||||
@@ -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! [](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.
|
||||
@@ -456,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
@@ -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
@@ -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
@@ -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")
|
||||
}
|
||||
|
||||
|
||||
@@ -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
-14
@@ -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"
|
||||
@@ -125,7 +126,6 @@ func main() {
|
||||
rules.HashiCorpTerraform(),
|
||||
rules.HashicorpField(),
|
||||
rules.Heroku(),
|
||||
rules.HerokuV2(),
|
||||
rules.HubSpot(),
|
||||
rules.HuggingFaceAccessToken(),
|
||||
rules.HuggingFaceOrganizationApiToken(),
|
||||
@@ -161,7 +161,6 @@ func main() {
|
||||
rules.NewRelicUserKey(),
|
||||
rules.NewRelicBrowserAPIKey(),
|
||||
rules.NewRelicInsertKey(),
|
||||
rules.Notion(),
|
||||
rules.NPM(),
|
||||
rules.NugetConfigPassword(),
|
||||
rules.NytimesAccessToken(),
|
||||
@@ -250,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 {
|
||||
@@ -260,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)
|
||||
@@ -282,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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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])` +
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
@@ -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
-20
@@ -76,12 +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)")
|
||||
rootCmd.PersistentFlags().BoolP("experimental-optimizations", "", false, "enables experimental allowlist optimizations, increasing performance at the cost of startup time")
|
||||
|
||||
// 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 {
|
||||
@@ -223,11 +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")
|
||||
}
|
||||
// set experimental feature flag(s)
|
||||
if mustGetBoolFlag(cmd, "experimental-optimizations") {
|
||||
logging.Warn().Msgf("using experimental allowlist optimizations, updates may contain breaking changes!")
|
||||
vc.EnableExperimentalAllowlistOptimizations = true
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
logging.Fatal().Err(err).Msg("Failed to load config")
|
||||
@@ -244,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 {
|
||||
@@ -264,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.
|
||||
@@ -274,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")
|
||||
@@ -432,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 {
|
||||
|
||||
@@ -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
@@ -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")
|
||||
}
|
||||
|
||||
|
||||
+17
-72
@@ -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,18 +57,6 @@ type Allowlist struct {
|
||||
|
||||
// validated is an internal flag to track whether `Validate()` has been called.
|
||||
validated bool
|
||||
|
||||
// EnableExperimentalOptimizations must be set prior to calling `Validate()`.
|
||||
// See: https://github.com/gitleaks/gitleaks/pull/1731
|
||||
//
|
||||
// NOTE: This flag may be removed in the future.
|
||||
EnableExperimentalOptimizations 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 {
|
||||
@@ -82,44 +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{}{}
|
||||
}
|
||||
if a.EnableExperimentalOptimizations {
|
||||
a.commitMap = uniqueCommits
|
||||
} else {
|
||||
a.Commits = maps.Keys(uniqueCommits)
|
||||
uniqueCommits[commit] = struct{}{}
|
||||
}
|
||||
a.Commits = maps.Keys(uniqueCommits)
|
||||
}
|
||||
if len(a.StopWords) > 0 {
|
||||
uniqueStopwords := make(map[string]struct{})
|
||||
for _, stopWord := range a.StopWords {
|
||||
uniqueStopwords[strings.ToLower(stopWord)] = struct{}{}
|
||||
}
|
||||
|
||||
values := maps.Keys(uniqueStopwords)
|
||||
if a.EnableExperimentalOptimizations {
|
||||
a.stopwordTrie = ahocorasick.NewTrieBuilder().AddStrings(values).Build()
|
||||
} else {
|
||||
a.StopWords = values
|
||||
}
|
||||
}
|
||||
|
||||
// Combine patterns into a single expression.
|
||||
if a.EnableExperimentalOptimizations {
|
||||
if len(a.Paths) > 0 {
|
||||
a.pathPat = joinRegexOr(a.Paths)
|
||||
}
|
||||
if len(a.Regexes) > 0 {
|
||||
a.regexPat = joinRegexOr(a.Regexes)
|
||||
uniqueStopwords[stopWord] = struct{}{}
|
||||
}
|
||||
a.StopWords = maps.Keys(uniqueStopwords)
|
||||
}
|
||||
|
||||
a.validated = true
|
||||
@@ -131,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, ""
|
||||
@@ -150,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.
|
||||
@@ -163,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) {
|
||||
@@ -177,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, ""
|
||||
|
||||
+2
-224
@@ -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"},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -156,225 +156,3 @@ func TestValidate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+22
-29
@@ -50,12 +50,6 @@ type ViperConfig struct {
|
||||
// TODO: Remove this in 9.x.
|
||||
AllowList *viperGlobalAllowlist
|
||||
Allowlists []*viperGlobalAllowlist
|
||||
|
||||
// EnableExperimentalAllowlistOptimizations enables a preview feature.
|
||||
// See: https://github.com/gitleaks/gitleaks/pull/1731
|
||||
//
|
||||
// NOTE: This flag may be removed in the future.
|
||||
EnableExperimentalAllowlistOptimizations bool
|
||||
}
|
||||
|
||||
type viperRuleAllowlist struct {
|
||||
@@ -147,7 +141,7 @@ 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)
|
||||
}
|
||||
@@ -175,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)
|
||||
}
|
||||
@@ -196,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
|
||||
}
|
||||
}
|
||||
@@ -228,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", "&&":
|
||||
@@ -261,14 +255,13 @@ func (vc *ViperConfig) parseAllowlist(a *viperRuleAllowlist) (*Allowlist, error)
|
||||
}
|
||||
|
||||
allowlist := &Allowlist{
|
||||
Description: a.Description,
|
||||
MatchCondition: matchCondition,
|
||||
Commits: a.Commits,
|
||||
Paths: allowlistPaths,
|
||||
RegexTarget: regexTarget,
|
||||
Regexes: allowlistRegexes,
|
||||
StopWords: a.StopWords,
|
||||
EnableExperimentalOptimizations: vc.EnableExperimentalAllowlistOptimizations,
|
||||
Description: a.Description,
|
||||
MatchCondition: matchCondition,
|
||||
Commits: a.Commits,
|
||||
Paths: allowlistPaths,
|
||||
RegexTarget: regexTarget,
|
||||
Regexes: allowlistRegexes,
|
||||
StopWords: a.StopWords,
|
||||
}
|
||||
if err := allowlist.Validate(); err != nil {
|
||||
return nil, err
|
||||
@@ -286,15 +279,13 @@ 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 {
|
||||
return fmt.Errorf("failed to load extended default config, err: %w", err)
|
||||
}
|
||||
defaultViperConfig := ViperConfig{
|
||||
EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
|
||||
}
|
||||
defaultViperConfig := ViperConfig{}
|
||||
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
|
||||
return fmt.Errorf("failed to load extended default config, err: %w", err)
|
||||
}
|
||||
@@ -308,15 +299,13 @@ 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 {
|
||||
return fmt.Errorf("failed to load extended config, err: %w", err)
|
||||
}
|
||||
extensionViperConfig := ViperConfig{
|
||||
EnableExperimentalAllowlistOptimizations: parent.EnableExperimentalAllowlistOptimizations,
|
||||
}
|
||||
extensionViperConfig := ViperConfig{}
|
||||
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
|
||||
return fmt.Errorf("failed to load extended config, err: %w", err)
|
||||
}
|
||||
@@ -390,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{}{}
|
||||
@@ -400,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
@@ -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
-18
@@ -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]]
|
||||
@@ -144,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",
|
||||
@@ -168,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",
|
||||
@@ -2296,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."
|
||||
@@ -2585,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
-3
@@ -1,7 +1,6 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
@@ -65,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.
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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
@@ -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 ""
|
||||
}
|
||||
|
||||
@@ -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 ""
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
-104
@@ -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 {
|
||||
@@ -293,7 +238,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
}
|
||||
|
||||
// add newline indices for location calculation in detectRule
|
||||
newlineIndices := newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
|
||||
fragment.newlineIndices = newLineRegexp.FindAllStringIndex(fragment.Raw, -1)
|
||||
|
||||
// setup variables to handle different decoding passes
|
||||
currentRaw := fragment.Raw
|
||||
@@ -314,14 +259,14 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
if len(rule.Keywords) == 0 {
|
||||
// if no keywords are associated with the rule always scan the
|
||||
// fragment using the rule
|
||||
findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
|
||||
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
|
||||
continue
|
||||
}
|
||||
|
||||
// check if keywords are in the fragment
|
||||
for _, k := range rule.Keywords {
|
||||
if _, ok := keywords[strings.ToLower(k)]; ok {
|
||||
findings = append(findings, d.detectRule(fragment, newlineIndices, currentRaw, rule, encodedSegments)...)
|
||||
findings = append(findings, d.detectRule(fragment, currentRaw, rule, encodedSegments)...)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -348,7 +293,7 @@ func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
}
|
||||
|
||||
// detectRule scans the given fragment for the given rule and returns a list of findings
|
||||
func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
|
||||
func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rule, encodedSegments []*codec.EncodedSegment) []report.Finding {
|
||||
var (
|
||||
findings []report.Finding
|
||||
logger = func() zerolog.Logger {
|
||||
@@ -371,21 +316,13 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
|
||||
// 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 {
|
||||
@@ -405,7 +342,7 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
|
||||
|
||||
// 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).
|
||||
@@ -447,18 +384,17 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
|
||||
// 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],
|
||||
@@ -468,13 +404,7 @@ func (d *Detector) detectRule(fragment Fragment, newlineIndices [][]int, current
|
||||
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).
|
||||
@@ -585,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|.
|
||||
|
||||
+32
-937
File diff suppressed because it is too large.
Load diff
@@ -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()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
package sources
|
||||
package detect
|
||||
|
||||
// Fragment represents a fragment of a source with its meta data
|
||||
// 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.
|
||||
// FilePath is the path to the file, if applicable.
|
||||
// The path separator MUST be normalized to `/`.
|
||||
FilePath string
|
||||
SymlinkFile string
|
||||
@@ -16,11 +16,9 @@ type Fragment struct {
|
||||
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
|
||||
CommitSHA string
|
||||
|
||||
// StartLine is the line number this fragment starts on
|
||||
StartLine int
|
||||
|
||||
// CommitInfo captures additional information about the git commit if applicable
|
||||
CommitInfo *CommitInfo
|
||||
// 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
@@ -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
@@ -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++
|
||||
|
||||
@@ -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
@@ -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
-51
@@ -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
|
||||
@@ -256,3 +243,7 @@ func printFinding(f report.Finding, noColor bool) {
|
||||
}
|
||||
fmt.Println("")
|
||||
}
|
||||
|
||||
func isWhitespace(ch byte) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
|
||||
}
|
||||
+23
-110
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,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
|
||||
@@ -25,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
|
||||
|
||||
@@ -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=
|
||||
|
||||
+2
-2
@@ -50,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
|
||||
}
|
||||
|
||||
|
||||
+1
-2
@@ -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)
|
||||
|
||||
@@ -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 '========================================================================'
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+44
-302
@@ -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.-]+):([\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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
-6
@@ -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
@@ -1 +0,0 @@
|
||||
../testdata/repos/nogit/api.go:aws-access-key:20
|
||||
Vendored
-24
@@ -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)
|
||||
}
|
||||
Vendored
-24
@@ -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)
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
-21
@@ -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$''',
|
||||
]
|
||||
Vendored
+1
@@ -225,3 +225,4 @@ title = "gitleaks config"
|
||||
description = "PyPI upload token"
|
||||
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9-_]{50,1000}'''
|
||||
tags = ["key", "pypi"]
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
archive.zip/api.go:aws-access-key:20
|
||||
Vendored
BIN
Binary file not shown.
Whitespace-only changes.
Vendored
-10
@@ -1,10 +0,0 @@
|
||||
# Archives
|
||||
|
||||
This repo has some archive files in its history!
|
||||
|
||||
Commits:
|
||||
|
||||
```
|
||||
07d2bd71800f1abf0421abe9bc4a83a6fdca1f68 nested.tar.gz
|
||||
db8789716fc664dbce0ed2d492570e92abf717a5 main.go.zst
|
||||
```
|
||||
Vendored
-1
@@ -1 +0,0 @@
|
||||
ref: refs/heads/main
|
||||
-1
@@ -1 +0,0 @@
|
||||
15fa60c13dccec6add267b7baa065977a6cc748a
|
||||
-13
@@ -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
@@ -1 +0,0 @@
|
||||
Unnamed repository; edit this file 'description' to name the repository.
|
||||
Vendored
BIN
Binary file not shown.
-6
@@ -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
@@ -1 +0,0 @@
|
||||
15fa60c13dccec6add267b7baa065977a6cc748a refs/heads/main
|
||||
Binary file not shown.
@@ -1,2 +0,0 @@
|
||||
P pack-9d774732f0e985d717a26e126e6574d089375b0d.pack
|
||||
|
||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
-2
@@ -1,2 +0,0 @@
|
||||
# pack-refs with: peeled fully-peeled sorted
|
||||
15fa60c13dccec6add267b7baa065977a6cc748a refs/heads/main
|
||||
Whitespace-only changes.
Vendored
BIN
Binary file not shown.
Reference in new issue
Block a user