mirror of
https://github.com/gitleaks/gitleaks.git
synced 2026-11-27 19:54:24 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3188ad6005 | ||
|
|
7fc11bb264 | ||
|
|
36c52c6b73 | ||
|
|
1f323d8b69 | ||
|
|
d88bc094f7 | ||
|
|
3fdaefdaa3 | ||
|
|
f3ae52e138 | ||
|
|
d6a828a530 | ||
|
|
d2ffffecbd | ||
|
|
a43dc0d3d0 | ||
|
|
69ed20e25e | ||
|
|
52b895a603 | ||
|
|
3f4d91fc22 | ||
|
|
049f5b2435 | ||
|
|
7a6183dab0 | ||
|
|
3c7f3f0e08 | ||
|
|
0e3f4f7abb | ||
|
|
3ed85671a4 | ||
|
|
e977850ab4 | ||
|
|
ad7a4fb4ea | ||
|
|
b2cf03c7e3 | ||
|
|
a3f623cc69 | ||
|
|
cc71bb1e9a | ||
|
|
7bad9f7654 | ||
|
|
977236cb5f | ||
|
|
a211b1601f | ||
|
|
0e5f644b67 | ||
|
|
f320a60e6f | ||
|
|
c4526b2c55 | ||
|
|
748076d976 | ||
|
|
db8e5e672e | ||
|
|
973c794cf0 | ||
|
|
f0d4499064 | ||
|
|
ab38a46986 | ||
|
|
b022d1c856 | ||
|
|
b69b5157a0 | ||
|
|
7357adca5e | ||
|
|
4c3da6ebb7 | ||
|
|
dbe3746455 | ||
|
|
7edfc6b5d5 | ||
|
|
efe40cae39 | ||
|
|
7cb5f6f64c | ||
|
|
2930537190 |
No files matched your search
+4
-1
@@ -49,7 +49,10 @@ If you want to add a new rule to the [default Gitleaks configuration](https://gi
|
||||
tps := []string{
|
||||
generateSampleSecret("beamer", "b_"+secrets.NewSecret(alphaNumericExtended("44"))),
|
||||
}
|
||||
return validate(r, tps, nil)
|
||||
fps := []string{
|
||||
`R21A-A-V010SP13RC181024R16900-CN-B_250K-Release-OTA-97B6C6C59241976086FABDC41472150C.bfu`,
|
||||
}
|
||||
return validate(r, tps, fps)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ FROM golang:1.23 AS build
|
||||
WORKDIR /go/src/github.com/zricethezav/gitleaks
|
||||
COPY . .
|
||||
RUN VERSION=$(git describe --tags --abbrev=0) && \
|
||||
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X="github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}
|
||||
CGO_ENABLED=0 go build -o bin/gitleaks -ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=${VERSION}"
|
||||
|
||||
FROM alpine:3.19
|
||||
RUN apk add --no-cache bash git openssh-client
|
||||
|
||||
@@ -19,9 +19,6 @@
|
||||
<a href="https://github.com/gitleaks/gitleaks-action">
|
||||
<img alt="gitleaks badge" src="https://img.shields.io/badge/protected%20by-gitleaks-blue">
|
||||
</a>
|
||||
<a href="https://twitter.com/intent/follow?screen_name=zricethezav">
|
||||
<img src="https://img.shields.io/twitter/follow/zricethezav?label=Follow%20zricethezav&style=social&color=blue" alt="Follow @zricethezav" />
|
||||
</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
@@ -105,7 +102,7 @@ jobs:
|
||||
```
|
||||
repos:
|
||||
- repo: https://github.com/gitleaks/gitleaks
|
||||
rev: v8.19.0
|
||||
rev: v8.23.1
|
||||
hooks:
|
||||
- id: gitleaks
|
||||
```
|
||||
@@ -238,6 +235,8 @@ useDefault = true
|
||||
# or you can supply a path to a configuration. Path is relative to where gitleaks
|
||||
# was invoked, not the location of the base config.
|
||||
path = "common_config.toml"
|
||||
# If there are any rules you don't want to inherit, they can be specified here.
|
||||
disabledRules = [ "generic-api-key"]
|
||||
|
||||
# An array of tables that contain information that define instructions
|
||||
# on how to detect secrets
|
||||
@@ -443,11 +442,6 @@ $ gitleaks dir ~/leaky-repo/ --report-path "report.json" --report-format templat
|
||||
<img alt="CodeRabbit.ai Sponsorship" src="https://github.com/gitleaks/gitleaks/assets/15034943/76c30a85-887b-47ca-9956-17a8e55c6c41" width=200>
|
||||
</a>
|
||||
</p>
|
||||
<p align="left">
|
||||
<a href="https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks">
|
||||
<img alt="Tines Sponsorship" src="https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png" width=200>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
## Exit Codes
|
||||
|
||||
+39
-51
@@ -22,9 +22,11 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"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"
|
||||
)
|
||||
@@ -36,6 +38,7 @@ func init() {
|
||||
detectCmd.Flags().Bool("follow-symlinks", false, "scan files that are symlinks to other files")
|
||||
detectCmd.Flags().StringP("source", "s", ".", "path to source")
|
||||
detectCmd.Flags().String("log-opts", "", "git log options")
|
||||
detectCmd.Flags().String("platform", "", "the target platform used to generate links (github, gitlab)")
|
||||
}
|
||||
|
||||
var detectCmd = &cobra.Command{
|
||||
@@ -46,86 +49,71 @@ var detectCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func runDetect(cmd *cobra.Command, args []string) {
|
||||
source, err := cmd.Flags().GetString("source")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get source")
|
||||
}
|
||||
initConfig(source)
|
||||
|
||||
var findings []report.Finding
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
cfg := Config(cmd)
|
||||
|
||||
// start timer
|
||||
start := time.Now()
|
||||
source := mustGetStringFlag(cmd, "source")
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
initConfig(source)
|
||||
cfg := Config(cmd)
|
||||
|
||||
// create detector
|
||||
detector := Detector(cmd, cfg, source)
|
||||
|
||||
// set follow symlinks flag
|
||||
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
}
|
||||
// set exit code
|
||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get exit code")
|
||||
}
|
||||
// parse flags
|
||||
detector.FollowSymlinks = mustGetBoolFlag(cmd, "follow-symlinks")
|
||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||
noGit := mustGetBoolFlag(cmd, "no-git")
|
||||
fromPipe := mustGetBoolFlag(cmd, "pipe")
|
||||
|
||||
// determine what type of scan:
|
||||
// - git: scan the history of the repo
|
||||
// - no-git: scan files by treating the repo as a plain directory
|
||||
noGit, err := cmd.Flags().GetBool("no-git")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetBool() for no-git")
|
||||
}
|
||||
fromPipe, err := cmd.Flags().GetBool("pipe")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetBool() for pipe")
|
||||
}
|
||||
|
||||
// start the detector scan
|
||||
var (
|
||||
findings []report.Finding
|
||||
err error
|
||||
)
|
||||
if noGit {
|
||||
var paths <-chan sources.ScanTarget
|
||||
paths, err = sources.DirectoryTargets(
|
||||
paths, err := sources.DirectoryTargets(
|
||||
source,
|
||||
detector.Sema,
|
||||
detector.FollowSymlinks,
|
||||
detector.Config.Allowlist.PathAllowed,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
logging.Fatal().Err(err).Send()
|
||||
}
|
||||
|
||||
findings, err = detector.DetectFiles(paths)
|
||||
if err != nil {
|
||||
if findings, err = detector.DetectFiles(paths); err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err).Msg("failed scan directory")
|
||||
logging.Error().Err(err).Msg("failed scan directory")
|
||||
}
|
||||
} else if fromPipe {
|
||||
findings, err = detector.DetectReader(os.Stdin, 10)
|
||||
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
|
||||
log.Fatal().Err(err).Msg("failed scan input from stdin")
|
||||
logging.Fatal().Err(err).Msg("failed scan input from stdin")
|
||||
}
|
||||
} else {
|
||||
var (
|
||||
gitCmd *sources.GitCmd
|
||||
logOpts string
|
||||
logOpts = mustGetStringFlag(cmd, "log-opts")
|
||||
gitCmd *sources.GitCmd
|
||||
scmPlatform scm.Platform
|
||||
remote *detect.RemoteInfo
|
||||
)
|
||||
logOpts, err = cmd.Flags().GetString("log-opts")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetString() for log-opts")
|
||||
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
|
||||
logging.Fatal().Err(err).Msg("could not create Git cmd")
|
||||
}
|
||||
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not create Git cmd")
|
||||
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
||||
logging.Fatal().Err(err).Send()
|
||||
}
|
||||
findings, err = detector.DetectGit(gitCmd)
|
||||
if err != nil {
|
||||
if remote, err = detect.NewRemoteInfo(scmPlatform, source); err != nil {
|
||||
logging.Fatal().Err(err).Msg("failed to scan Git repository")
|
||||
}
|
||||
|
||||
if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err).Msg("failed to scan Git repository")
|
||||
logging.Error().Err(err).Msg("failed to scan Git repository")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -3,9 +3,9 @@ package cmd
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
"github.com/zricethezav/gitleaks/v8/sources"
|
||||
)
|
||||
@@ -47,12 +47,12 @@ func runDirectory(cmd *cobra.Command, args []string) {
|
||||
|
||||
// set follow symlinks flag
|
||||
if detector.FollowSymlinks, err = cmd.Flags().GetBool("follow-symlinks"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
// set exit code
|
||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get exit code")
|
||||
logging.Fatal().Err(err).Msg("could not get exit code")
|
||||
}
|
||||
|
||||
var paths <-chan sources.ScanTarget
|
||||
@@ -63,13 +63,13 @@ func runDirectory(cmd *cobra.Command, args []string) {
|
||||
detector.Config.Allowlist.PathAllowed,
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err)
|
||||
logging.Fatal().Err(err)
|
||||
}
|
||||
|
||||
findings, err = detector.DetectFiles(paths)
|
||||
if err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err).Msg("failed scan directory")
|
||||
logging.Error().Err(err).Msg("failed scan directory")
|
||||
}
|
||||
|
||||
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func CreateGlobalConfig() config.Config {
|
||||
@@ -33,9 +33,9 @@ func CreateGlobalConfig() config.Config {
|
||||
}(),
|
||||
|
||||
// ----------- Environment Variables -----------
|
||||
regexp.MustCompile(`^\$(\d+|{\d+})$`),
|
||||
regexp.MustCompile(`^\$([A-Z_]+|[a-z_]+)$`),
|
||||
regexp.MustCompile(`^\${([A-Z_]+|[a-z_]+)}$`),
|
||||
regexp.MustCompile(`^\$(?:\d+|{\d+})$`),
|
||||
regexp.MustCompile(`^\$(?:[A-Z_]+|[a-z_]+)$`),
|
||||
regexp.MustCompile(`^\${(?:[A-Z_]+|[a-z_]+)}$`),
|
||||
|
||||
// ----------- Interpolated Variables -----------
|
||||
// Ansible (https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_variables.html)
|
||||
@@ -43,14 +43,14 @@ func CreateGlobalConfig() config.Config {
|
||||
// GitHub Actions
|
||||
// https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables
|
||||
// https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions
|
||||
regexp.MustCompile(`^\$\{\{[ \t]*((env|github|secrets|vars)(\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
|
||||
regexp.MustCompile(`^\$\{\{[ \t]*(?:(?:env|github|secrets|vars)(?:\.[A-Za-z]\w+)+[\w "'&./=|]*)[ \t]*}}$`),
|
||||
// NuGet (https://learn.microsoft.com/en-us/nuget/reference/nuget-config-file#using-environment-variables)
|
||||
regexp.MustCompile(`^%([A-Z_]+|[a-z_]+)%$`),
|
||||
regexp.MustCompile(`^%(?:[A-Z_]+|[a-z_]+)%$`),
|
||||
// String formatting.
|
||||
regexp.MustCompile(`^%[+\-# 0]?[bcdeEfFgGoOpqstTUvxX]$`), // Golang (https://pkg.go.dev/fmt)
|
||||
regexp.MustCompile(`^\{\d{0,2}}$`), // Python (https://docs.python.org/3/tutorial/inputoutput.html)
|
||||
// Urban Code Deploy (https://www.ibm.com/support/pages/replace-token-step-replaces-replacement-values-windows-variables)
|
||||
regexp.MustCompile(`^@([A-Z_]+|[a-z_]+)@$`),
|
||||
regexp.MustCompile(`^@(?:[A-Z_]+|[a-z_]+)@$`),
|
||||
|
||||
// ----------- Miscellaneous -----------
|
||||
},
|
||||
@@ -58,49 +58,51 @@ func CreateGlobalConfig() config.Config {
|
||||
regexp.MustCompile(`gitleaks\.toml`),
|
||||
|
||||
// ----------- Documents and media -----------
|
||||
regexp.MustCompile(`(?i)\.(bmp|gif|jpe?g|svg|tiff?)$`), // Images
|
||||
regexp.MustCompile(`\.(eot|[ot]tf|woff2?)$`), // Fonts
|
||||
regexp.MustCompile(`(.*?)(doc|docx|zip|xls|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf)$`),
|
||||
regexp.MustCompile(`(?i)\.(?:bmp|gif|jpe?g|png|svg|tiff?)$`), // Images
|
||||
regexp.MustCompile(`(?i)\.(?:eot|[ot]tf|woff2?)$`), // Fonts
|
||||
regexp.MustCompile(`(?i)\.(?:docx?|xlsx?|pdf|bin|socket|vsidx|v2|suo|wsuo|.dll|pdb|exe|gltf|zip)$`),
|
||||
|
||||
// ----------- Golang files -----------
|
||||
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(`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)(?:/.*)?$`),
|
||||
|
||||
// ----------- Java files -----------
|
||||
// Gradle
|
||||
regexp.MustCompile(`(^|/)gradlew(\.bat)?$`),
|
||||
regexp.MustCompile(`(^|/)gradle\.lockfile$`),
|
||||
regexp.MustCompile(`(^|/)mvnw(\.cmd)?$`),
|
||||
regexp.MustCompile(`(^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
|
||||
regexp.MustCompile(`(?:^|/)gradlew(?:\.bat)?$`),
|
||||
regexp.MustCompile(`(?:^|/)gradle\.lockfile$`),
|
||||
regexp.MustCompile(`(?:^|/)mvnw(?:\.cmd)?$`),
|
||||
regexp.MustCompile(`(?:^|/)\.mvn/wrapper/MavenWrapperDownloader\.java$`),
|
||||
|
||||
// ----------- JavaScript files -----------
|
||||
// Dependencies and lock files.
|
||||
regexp.MustCompile(`(^|/)node_modules(/.*)?$`),
|
||||
regexp.MustCompile(`(^|/)(npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
|
||||
regexp.MustCompile(`(^|/)bower_components(/.*)?$`),
|
||||
regexp.MustCompile(`(?:^|/)node_modules(?:/.*)?$`),
|
||||
regexp.MustCompile(`(?:^|/)(?:npm-shrinkwrap\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock)$`),
|
||||
regexp.MustCompile(`(?:^|/)bower_components(?:/.*)?$`),
|
||||
// TODO: Add more common static assets, such as swagger-ui.
|
||||
regexp.MustCompile(`(^|/)(angular|jquery(-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(\.min)?\.js(\.map)?$`),
|
||||
regexp.MustCompile(`(?:^|/)(?:angular|bootstrap|jquery(?:-?ui)?|plotly|swagger-?ui)[a-zA-Z0-9.-]*(?:\.min)?\.js(?:\.map)?$`),
|
||||
regexp.MustCompile(`(?:^|/)javascript\.json$`),
|
||||
|
||||
// ----------- Python files -----------
|
||||
// Dependencies and lock files.
|
||||
regexp.MustCompile(`(^|/)(Pipfile|poetry)\.lock$`),
|
||||
regexp.MustCompile(`(?:^|/)(?:Pipfile|poetry)\.lock$`),
|
||||
// Virtual environments
|
||||
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)(?:^|/)(?:v?env|virtualenv)/lib(?:64)?(?:/.*)?$`),
|
||||
regexp.MustCompile(`(?i)(?:^|/)(?:lib(?:64)?/python[23](?:\.\d{1,2})+|python/[23](?:\.\d{1,2})+/lib(?:64)?)(?:/.*)?$`),
|
||||
// dist-info directory (https://py-pkgs.org/04-package-structure.html#building-sdists-and-wheels)
|
||||
regexp.MustCompile(`(?i)(^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(/.+)?$`),
|
||||
regexp.MustCompile(`(?i)(?:^|/)[a-z0-9_.]+-[0-9.]+\.dist-info(?:/.+)?$`),
|
||||
|
||||
// ----------- Ruby files -----------
|
||||
regexp.MustCompile(`(^|/)vendor/(bundle|ruby)(/.*?)?$`),
|
||||
regexp.MustCompile(`(?:^|/)vendor/(?:bundle|ruby)(?:/.*?)?$`),
|
||||
regexp.MustCompile(`\.gem$`), // tar archive
|
||||
|
||||
// Misc
|
||||
regexp.MustCompile(`verification-metadata\.xml`),
|
||||
regexp.MustCompile(`Database.refactorlog`),
|
||||
//regexp.MustCompile(`vendor`),
|
||||
// regexp.MustCompile(`vendor`),
|
||||
},
|
||||
StopWords: []string{
|
||||
"abcdefghijklmnopqrstuvwxyz", // character range
|
||||
// ----------- Secrets -----------
|
||||
// Checkmarx client secret. (https://github.com/checkmarx-ts/checkmarx-python-sdk/blob/86560f6e2a3e46d16322101294da10d5d190312d/README.md?plain=1#L56)
|
||||
"014df517-39d1-4453-b7b3-9930c563627c",
|
||||
|
||||
@@ -4,70 +4,70 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfigAllowlistRegexes(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
invalid []string
|
||||
valid []string
|
||||
}{
|
||||
"general placeholders": {
|
||||
invalid: []string{
|
||||
`true`, `True`, `false`, `False`, `null`, `NULL`,
|
||||
},
|
||||
var allowlistRegexTests = map[string]struct {
|
||||
invalid []string
|
||||
valid []string
|
||||
}{
|
||||
"general placeholders": {
|
||||
invalid: []string{
|
||||
`true`, `True`, `false`, `False`, `null`, `NULL`,
|
||||
},
|
||||
"general placeholders - repeated characters": {
|
||||
invalid: []string{
|
||||
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
|
||||
},
|
||||
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
|
||||
},
|
||||
"general placeholders - repeated characters": {
|
||||
invalid: []string{
|
||||
`aaaaaaaaaaaaaaaaa`, `BBBBBBBBBBbBBBBBBBbBB`, `********************`,
|
||||
},
|
||||
"environment variables": {
|
||||
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
|
||||
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
|
||||
valid: []string{`aaaaaaaaaaaaaaaaaaabaa`, `pas*************d`},
|
||||
},
|
||||
"environment variables": {
|
||||
invalid: []string{`$2`, `$GIT_PASSWORD`, `${GIT_PASSWORD}`, `$password`},
|
||||
valid: []string{`$yP@R.@=ibxI`, `$2a6WCust9aE`, `${not_complete1`},
|
||||
},
|
||||
"interpolated variables - ansible": {
|
||||
invalid: []string{
|
||||
`{{ x }}`, `{{ password }}`, `{{password}}`, `{{ data.proxy_password }}`,
|
||||
`{{ dict1 | ansible.builtin.combine(dict2) }}`,
|
||||
},
|
||||
"interpolated variables - ansible": {
|
||||
invalid: []string{
|
||||
`{{ x }}`, `{{ password }}`, `{{password}}`, `{{ data.proxy_password }}`,
|
||||
`{{ dict1 | ansible.builtin.combine(dict2) }}`,
|
||||
},
|
||||
},
|
||||
"interpolated variables - github actions": {
|
||||
invalid: []string{
|
||||
`${{ env.First_Name }}`,
|
||||
`${{ env.DAY_OF_WEEK == 'Monday' }}`,
|
||||
`${{env.JAVA_VERSION}}`,
|
||||
`${{ github.event.issue.title }}`,
|
||||
`${{ github.repository == "Gattocrucco/lsqfitgp" }}`,
|
||||
`${{ github.event.pull_request.number || github.ref }}`,
|
||||
`${{ github.event_name == 'pull_request' && github.event.action == 'unassigned' }}`,
|
||||
`${{ secrets.SuperSecret }}`,
|
||||
`${{ vars.JOB_NAME }}`,
|
||||
`${{ vars.USE_VARIABLES == 'true' }}`,
|
||||
},
|
||||
"interpolated variables - github actions": {
|
||||
invalid: []string{
|
||||
`${{ env.First_Name }}`,
|
||||
`${{ env.DAY_OF_WEEK == 'Monday' }}`,
|
||||
`${{env.JAVA_VERSION}}`,
|
||||
`${{ github.event.issue.title }}`,
|
||||
`${{ github.repository == "Gattocrucco/lsqfitgp" }}`,
|
||||
`${{ github.event.pull_request.number || github.ref }}`,
|
||||
`${{ github.event_name == 'pull_request' && github.event.action == 'unassigned' }}`,
|
||||
`${{ secrets.SuperSecret }}`,
|
||||
`${{ vars.JOB_NAME }}`,
|
||||
`${{ vars.USE_VARIABLES == 'true' }}`,
|
||||
},
|
||||
},
|
||||
"interpolated variables - nuget": {
|
||||
invalid: []string{
|
||||
`%MY_PASSWORD%`, `%password%`,
|
||||
},
|
||||
"interpolated variables - nuget": {
|
||||
invalid: []string{
|
||||
`%MY_PASSWORD%`, `%password%`,
|
||||
},
|
||||
},
|
||||
"interpolated variables - string fmt - golang": {
|
||||
invalid: []string{
|
||||
`%b`, `%c`, `%d`, `% d`, `%e`, `%E`, `%f`, `%F`, `%g`, `%G`, `%o`, `%O`, `%p`, `%q`, `%-s`, `%s`, `%t`, `%T`, `%U`, `%#U`, `%+v`, `%#v`, `%v`, `%x`, `%X`,
|
||||
},
|
||||
"interpolated variables - string fmt - golang": {
|
||||
invalid: []string{
|
||||
`%b`, `%c`, `%d`, `% d`, `%e`, `%E`, `%f`, `%F`, `%g`, `%G`, `%o`, `%O`, `%p`, `%q`, `%-s`, `%s`, `%t`, `%T`, `%U`, `%#U`, `%+v`, `%#v`, `%v`, `%x`, `%X`,
|
||||
},
|
||||
},
|
||||
"interpolated variables - string fmt - python": {
|
||||
invalid: []string{
|
||||
`{}`, `{0}`, `{10}`,
|
||||
},
|
||||
"interpolated variables - string fmt - python": {
|
||||
invalid: []string{
|
||||
`{}`, `{0}`, `{10}`,
|
||||
},
|
||||
},
|
||||
"interpolated variables - ucd": {
|
||||
invalid: []string{`@password@`, `@LDAP_PASS@`},
|
||||
valid: []string{`@username@mastodon.example`},
|
||||
},
|
||||
}
|
||||
},
|
||||
"interpolated variables - ucd": {
|
||||
invalid: []string{`@password@`, `@LDAP_PASS@`},
|
||||
valid: []string{`@username@mastodon.example`},
|
||||
},
|
||||
}
|
||||
|
||||
func TestConfigAllowlistRegexes(t *testing.T) {
|
||||
cfg := CreateGlobalConfig()
|
||||
allowlist := cfg.Allowlist
|
||||
for name, cases := range tests {
|
||||
for name, cases := range allowlistRegexTests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for _, c := range cases.invalid {
|
||||
if !allowlist.RegexAllowed(c) {
|
||||
@@ -84,50 +84,67 @@ func TestConfigAllowlistRegexes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigAllowlistPaths(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
invalid []string
|
||||
valid []string
|
||||
}{
|
||||
"javascript - common static assets": {
|
||||
invalid: []string{
|
||||
`src/main/static/lib/angular.1.2.16.min.js`,
|
||||
`src/main/resources/static/jquery-ui-1.12.1/jquery-ui-min.js`,
|
||||
`src/main/resources/static/js/jquery-ui-1.10.4.min.js`,
|
||||
`src-static/js/plotly.min.js`,
|
||||
`swagger/swaggerui/swagger-ui-bundle.js.map`,
|
||||
`swagger/swaggerui/swagger-ui-es-bundle.js.map`,
|
||||
`src/main/static/swagger-ui.min.js`,
|
||||
`swagger/swaggerui/swagger-ui.js`,
|
||||
},
|
||||
},
|
||||
"python": {
|
||||
invalid: []string{
|
||||
// lock files
|
||||
`Pipfile.lock`, `poetry.lock`,
|
||||
// virtual environments
|
||||
"env/lib/python3.7/site-packages/urllib3/util/url.py",
|
||||
"venv/Lib/site-packages/regex-2018.08.29.dist-info/DESCRIPTION.rst",
|
||||
"venv/lib64/python3.5/site-packages/pynvml.py",
|
||||
"python/python3/virtualenv/Lib/site-packages/pyphonetics/utils.py",
|
||||
"virtualenv/lib64/python3.7/base64.py",
|
||||
// packages
|
||||
"cde-root/usr/lib64/python2.4/site-packages/Numeric.pth",
|
||||
"lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py",
|
||||
"lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json",
|
||||
"code/python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py",
|
||||
"python/3.7.4/Lib/site-packages/fsspec/utils.py",
|
||||
"python/2.7.16.32/Lib/bsddb/test/test_dbenv.py",
|
||||
"python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json",
|
||||
// distinfo
|
||||
"libs/PyX-0.15.dist-info/AUTHORS",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func BenchmarkConfigAllowlistRegexes(b *testing.B) {
|
||||
cfg := CreateGlobalConfig()
|
||||
allowlist := cfg.Allowlist
|
||||
for name, cases := range tests {
|
||||
for n := 0; n < b.N; n++ {
|
||||
for _, cases := range allowlistRegexTests {
|
||||
for _, c := range cases.invalid {
|
||||
allowlist.RegexAllowed(c)
|
||||
}
|
||||
|
||||
for _, c := range cases.valid {
|
||||
allowlist.RegexAllowed(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var allowlistPathsTests = map[string]struct {
|
||||
invalid []string
|
||||
valid []string
|
||||
}{
|
||||
"javascript - common static assets": {
|
||||
invalid: []string{
|
||||
`tests/e2e/nuget/wwwroot/lib/bootstrap/dist/js/bootstrap.esm.min.js`,
|
||||
`src/main/static/lib/angular.1.2.16.min.js`,
|
||||
`src/main/resources/static/jquery-ui-1.12.1/jquery-ui-min.js`,
|
||||
`src/main/resources/static/js/jquery-ui-1.10.4.min.js`,
|
||||
`src-static/js/plotly.min.js`,
|
||||
`swagger/swaggerui/swagger-ui-bundle.js.map`,
|
||||
`swagger/swaggerui/swagger-ui-es-bundle.js.map`,
|
||||
`src/main/static/swagger-ui.min.js`,
|
||||
`swagger/swaggerui/swagger-ui.js`,
|
||||
},
|
||||
},
|
||||
"python": {
|
||||
invalid: []string{
|
||||
// lock files
|
||||
`Pipfile.lock`, `poetry.lock`,
|
||||
// virtual environments
|
||||
"env/lib/python3.7/site-packages/urllib3/util/url.py",
|
||||
"venv/Lib/site-packages/regex-2018.08.29.dist-info/DESCRIPTION.rst",
|
||||
"venv/lib64/python3.5/site-packages/pynvml.py",
|
||||
"python/python3/virtualenv/Lib/site-packages/pyphonetics/utils.py",
|
||||
"virtualenv/lib64/python3.7/base64.py",
|
||||
// packages
|
||||
"cde-root/usr/lib64/python2.4/site-packages/Numeric.pth",
|
||||
"lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py",
|
||||
"lib/python3.8/site-packages/botocore/data/alexaforbusiness/2017-11-09/service-2.json",
|
||||
"code/python/3.7.4/Lib/site-packages/dask/bytes/tests/test_bytes_utils.py",
|
||||
"python/3.7.4/Lib/site-packages/fsspec/utils.py",
|
||||
"python/2.7.16.32/Lib/bsddb/test/test_dbenv.py",
|
||||
"python/lib/python3.8/site-packages/boto3/data/ec2/2016-04-01/resources-1.json",
|
||||
// distinfo
|
||||
"libs/PyX-0.15.dist-info/AUTHORS",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func TestConfigAllowlistPaths(t *testing.T) {
|
||||
cfg := CreateGlobalConfig()
|
||||
allowlist := cfg.Allowlist
|
||||
for name, cases := range allowlistPathsTests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for _, c := range cases.invalid {
|
||||
if !allowlist.PathAllowed(c) {
|
||||
@@ -143,3 +160,19 @@ func TestConfigAllowlistPaths(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkConfigAllowlistPaths(b *testing.B) {
|
||||
cfg := CreateGlobalConfig()
|
||||
allowlist := cfg.Allowlist
|
||||
for n := 0; n < b.N; n++ {
|
||||
for _, cases := range allowlistPathsTests {
|
||||
for _, c := range cases.invalid {
|
||||
allowlist.PathAllowed(c)
|
||||
}
|
||||
|
||||
for _, c := range cases.valid {
|
||||
allowlist.PathAllowed(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,10 @@ import (
|
||||
"os"
|
||||
"text/template"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -148,6 +147,7 @@ func main() {
|
||||
rules.MailGunSigningKey(),
|
||||
rules.MapBox(),
|
||||
rules.MattermostAccessToken(),
|
||||
rules.Meraki(),
|
||||
rules.MessageBirdAPIToken(),
|
||||
rules.MessageBirdClientID(),
|
||||
rules.NetlifyAccessToken(),
|
||||
@@ -236,7 +236,7 @@ func main() {
|
||||
for _, rule := range configRules {
|
||||
// check if rule is in ruleLookUp
|
||||
if _, ok := ruleLookUp[rule.RuleID]; ok {
|
||||
log.Fatal().Msgf("rule id %s is not unique", rule.RuleID)
|
||||
logging.Fatal().Msgf("rule id %s is not unique", rule.RuleID)
|
||||
}
|
||||
// TODO: eventually change all the signatures to get ride of this
|
||||
// nasty dereferencing.
|
||||
@@ -245,18 +245,17 @@ func main() {
|
||||
|
||||
tmpl, err := template.ParseFiles(templatePath)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to parse template")
|
||||
logging.Fatal().Err(err).Msg("Failed to parse template")
|
||||
}
|
||||
|
||||
f, err := os.Create(gitleaksConfigPath)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to create rules.toml")
|
||||
logging.Fatal().Err(err).Msg("Failed to create rules.toml")
|
||||
}
|
||||
|
||||
cfg := base.CreateGlobalConfig()
|
||||
cfg.Rules = ruleLookUp
|
||||
if err = tmpl.Execute(f, cfg); err != nil {
|
||||
log.Fatal().Err(err).Msg("could not execute template")
|
||||
logging.Fatal().Err(err).Msg("could not execute template")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// https://developer.1password.com/docs/service-accounts/security/?token-example=encoded
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func AgeSecretKey() *config.Rule {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func AWS() *config.Rule {
|
||||
|
||||
@@ -3,12 +3,10 @@ package rules
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// References:
|
||||
|
||||
@@ -18,5 +18,8 @@ func Beamer() *config.Rule {
|
||||
|
||||
// validate
|
||||
tps := utils.GenerateSampleSecrets("beamer", "b_"+secrets.NewSecret(utils.AlphaNumericExtended("44")))
|
||||
return utils.Validate(r, tps, nil)
|
||||
fps := []string{
|
||||
`│ ├── R21A-A-V010SP13RC181024R16900-CN-B_250K-Release-OTA-97B6C6C59241976086FABDC41472150C.bfu`,
|
||||
}
|
||||
return utils.Validate(r, tps, fps)
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Clojars() *config.Rule {
|
||||
|
||||
@@ -24,9 +24,9 @@ paths = [{{ range $i, $path := . }}
|
||||
]{{ end }}
|
||||
{{- with .Allowlist.StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
|
||||
"{{ $stopword }}",{{ end }}
|
||||
]{{ end }}
|
||||
]{{ end }}{{println}}
|
||||
|
||||
{{ range $i, $rule := .Rules }}[[rules]]
|
||||
{{- range $i, $rule := .Rules }}{{println}}[[rules]]
|
||||
id = "{{$rule.RuleID}}"
|
||||
description = "{{$rule.Description}}"
|
||||
regex = '''{{$rule.Regex}}'''
|
||||
@@ -46,15 +46,7 @@ keywords = [{{ range $j, $keyword := . }}"{{ $keyword }}"{{ end }}]{{end}}{{ end
|
||||
tags = [
|
||||
{{ range $j, $tag := . }}"{{ $tag }}",{{ end }}
|
||||
]{{ end }}
|
||||
|
||||
{{- /*
|
||||
* Use [rules.allowlist] for a while, allow people to catch up with the new syntax.
|
||||
* TODO: Remove this a few major versions after 8.21.0
|
||||
* https://github.com/gitleaks/gitleaks/issues/1571
|
||||
*/}}
|
||||
{{- if eq (len $rule.Allowlists) 1 }}{{ with index $rule.Allowlists 0}}{{ if or .Regexes .Paths .Commits .StopWords }}
|
||||
# NOTE: Gitleaks >= v8.21.0 should use [[rules.allowlists] instead.
|
||||
[rules.allowlist]
|
||||
{{- with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}{{println}}[[rules.allowlists]]
|
||||
{{- with .MatchCondition }}{{println}}condition = "{{ .MatchCondition.String }}"{{ end }}
|
||||
{{- with .Commits -}}{{println}}commits = [
|
||||
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
|
||||
@@ -68,25 +60,5 @@ tags = [
|
||||
]{{ end }}
|
||||
{{- with .StopWords }}{{println}}stopwords = [{{ range $j, $stopword := . }}
|
||||
"{{ $stopword }}",{{ end }}
|
||||
]{{ end }}{{ end }}{{ end }}
|
||||
{{ else }}
|
||||
{{ with $rule.Allowlists }}{{ range $i, $allowlist := . }}{{ if or $allowlist.Regexes $allowlist.Paths $allowlist.Commits $allowlist.StopWords }}
|
||||
[[rules.allowlists]]
|
||||
{{ with $allowlist.MatchCondition }}condition = "{{ .String }}"
|
||||
{{ end -}}
|
||||
{{- with $allowlist.Commits }}commits = [
|
||||
{{ range $j, $commit := . }}"{{ $commit }}",{{ end }}
|
||||
]{{ end }}
|
||||
{{- with $allowlist.Paths }}paths = [
|
||||
{{ range $j, $path := . }}'''{{ $path }}''',{{ end }}
|
||||
]{{ end }}
|
||||
{{- with $allowlist.RegexTarget }}regexTarget = "{{ . }}"
|
||||
{{ end -}}
|
||||
{{- with $allowlist.Regexes }}regexes = [{{ range $i, $regex := . }}
|
||||
'''{{ $regex }}''',{{ end }}
|
||||
]{{ end }}
|
||||
{{ with $allowlist.StopWords }}stopwords = [{{ range $j, $stopword := . }}
|
||||
"{{ $stopword }}",{{ end }}
|
||||
]{{ end }}{{ end }}{{ end }}
|
||||
{{ end }}{{ end }}
|
||||
{{ end -}}
|
||||
]{{ end }}{{ end }}{{ end }}{{ end }}
|
||||
{{ end }}
|
||||
@@ -2,10 +2,10 @@ package rules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// https://curl.se/docs/manpage.html#-u
|
||||
@@ -13,18 +13,18 @@ func CurlBasicAuth() *config.Rule {
|
||||
r := config.Rule{
|
||||
RuleID: "curl-auth-user",
|
||||
Description: "Discovered a potential basic authorization token provided in a curl command, which could compromise the curl accessed resource.",
|
||||
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})(?:"([^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
|
||||
Regex: regexp.MustCompile(`\bcurl\b(?:.*|.*(?:[\r\n]{1,2}.*){1,5})[ \t\n\r](?:-u|--user)(?:=|[ \t]{0,5})("(:[^"]{3,}|[^:"]{3,}:|[^:"]{3,}:[^"]{3,})"|'([^:']{3,}:[^']{3,})'|((?:"[^"]{3,}"|'[^']{3,}'|[\w$@.-]+):(?:"[^"]{3,}"|'[^']{3,}'|[\w${}@.-]+)))(?:\s|\z)`),
|
||||
Keywords: []string{"curl"},
|
||||
Entropy: 2,
|
||||
Allowlists: []config.Allowlist{
|
||||
{
|
||||
Regexes: []*regexp.Regexp{
|
||||
regexp.MustCompile(`[^:]+:(change(it|me)|pass(word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
|
||||
regexp.MustCompile(`['"]?<[^>]+>['"]?:['"]?<[^>]+>|<[^:]+:[^>]+>['"]?`), // <placeholder>
|
||||
regexp.MustCompile(`[^:]+:\[[^]]+]`), // [placeholder]
|
||||
regexp.MustCompile(`['"]?[^:]+['"]?:['"]?\$(\d|\w+|\{(\d|\w+)})['"]?`), // $1 or $VARIABLE
|
||||
regexp.MustCompile(`\$\([^)]+\):\$\([^)]+\)`), // $(cat login.txt)
|
||||
regexp.MustCompile(`['"]?\$?{{[^}]+}}['"]?:['"]?\$?{{[^}]+}}['"]?`), // ${{ secrets.FOO }} or {{ .Values.foo }}
|
||||
regexp.MustCompile(`[^:]+:(?:change(?:it|me)|pass(?:word)?|pwd|test|token|\*+|x+)`), // common placeholder passwords
|
||||
regexp.MustCompile(`['"]?<[^>]+>['"]?:['"]?<[^>]+>|<[^:]+:[^>]+>['"]?`), // <placeholder>
|
||||
regexp.MustCompile(`[^:]+:\[[^]]+]`), // [placeholder]
|
||||
regexp.MustCompile(`['"]?[^:]+['"]?:['"]?\$(?:\d|\w+|\{(?:\d|\w+)})['"]?`), // $1 or $VARIABLE
|
||||
regexp.MustCompile(`\$\([^)]+\):\$\([^)]+\)`), // $(cat login.txt)
|
||||
regexp.MustCompile(`['"]?\$?{{[^}]+}}['"]?:['"]?\$?{{[^}]+}}['"]?`), // ${{ secrets.FOO }} or {{ .Values.foo }}
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -38,6 +38,8 @@ func CurlBasicAuth() *config.Rule {
|
||||
-H 'Content-type: text/plain' \
|
||||
-d 'world' \
|
||||
-u developer:yqDVtkqPECriaLRi`, // different line
|
||||
`curl -u ":d2LkV78zLx!t" https://localhost:9200`, // empty username
|
||||
`curl -u "d2LkV78zLx!t:" https://localhost:9200`, // empty password
|
||||
|
||||
// long
|
||||
`curl -sw '%{http_code}' -X POST --user 'johns:h0pk1ns~21s' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
||||
@@ -65,6 +67,7 @@ func CurlBasicAuth() *config.Rule {
|
||||
`curl -u "${_username}:${_password}"`,
|
||||
`curl -u "${username}":"${password}"`,
|
||||
`curl -k -X POST -I -u "SRVC_JENKINS:${APPID}"`,
|
||||
`curl -u ":" https://localhost:9200`, // empty username and password
|
||||
|
||||
// long
|
||||
`curl -sw '%{http_code}' -X POST --user '$USERNAME:$PASSWORD' $GItHUB_API_URL/$GIT_COMMIT --data`,
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Doppler() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Duffel() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Dynatrace() *config.Rule {
|
||||
@@ -16,7 +14,7 @@ func Dynatrace() *config.Rule {
|
||||
Description: "Detected a Dynatrace API token, potentially risking application performance monitoring and data exposure.",
|
||||
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
|
||||
Entropy: 4,
|
||||
Keywords: []string{"dt0c01"},
|
||||
Keywords: []string{"dt0c01."},
|
||||
}
|
||||
|
||||
// validate
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func EasyPost() *config.Rule {
|
||||
|
||||
@@ -34,14 +34,15 @@ func FacebookAccessToken() *config.Rule {
|
||||
RuleID: "facebook-access-token",
|
||||
Description: "Discovered a Facebook Access Token, posing a risk of unauthorized access to Facebook accounts and personal data exposure.",
|
||||
Regex: utils.GenerateUniqueTokenRegex(`\d{15,16}(\||%)[0-9a-z\-_]{27,40}`, true),
|
||||
Keywords: []string{"facebook"},
|
||||
Entropy: 3,
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := []string{
|
||||
`{"access_token":"911602140448729|AY-lRJZq9BoDLobvAiP25L7RcMg","token_type":"bearer"}`, // gitleaks:allow
|
||||
`1308742762612587|rhoK1cbv0DOU_RTX_87O4MkX7AI`, // gitleaks:allow
|
||||
`1477036645700765|wRPf2v3mt2JfMqCLK8n7oltrEmc`, // gitleaks:allow
|
||||
`{"facebook access_token":"911602140448729|AY-lRJZq9BoDLobvAiP25L7RcMg","token_type":"bearer"}`, // gitleaks:allow
|
||||
`facebook 1308742762612587|rhoK1cbv0DOU_RTX_87O4MkX7AI`, // gitleaks:allow
|
||||
`facebook 1477036645700765|wRPf2v3mt2JfMqCLK8n7oltrEmc`, // gitleaks:allow
|
||||
}
|
||||
return utils.Validate(r, tps, nil)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func FlutterwavePublicKey() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func FrameIO() *config.Rule {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Freemius() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// TODO this one could probably use some work
|
||||
@@ -36,6 +34,29 @@ func GCPAPIKey() *config.Rule {
|
||||
Keywords: []string{
|
||||
"AIza",
|
||||
},
|
||||
Allowlists: []config.Allowlist{
|
||||
{
|
||||
Regexes: []*regexp.Regexp{
|
||||
// example keys from https://github.com/firebase/firebase-android-sdk
|
||||
regexp.MustCompile(`AIzaSyabcdefghijklmnopqrstuvwxyz1234567`),
|
||||
regexp.MustCompile(`AIzaSyAnLA7NfeLquW1tJFpx_eQCxoX-oo6YyIs`),
|
||||
regexp.MustCompile(`AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM`),
|
||||
regexp.MustCompile(`AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU`),
|
||||
regexp.MustCompile(`AIzaSyD3asb-2pEZVqMkmL6M9N6nHZRR_znhrh0`),
|
||||
regexp.MustCompile(`AIzayDNSXIbFmlXbIE6mCzDLQAqITYefhixbX4A`),
|
||||
regexp.MustCompile(`AIzaSyAdOS2zB6NCsk1pCdZ4-P6GBdi_UUPwX7c`),
|
||||
regexp.MustCompile(`AIzaSyASWm6HmTMdYWpgMnjRBjxcQ9CKctWmLd4`),
|
||||
regexp.MustCompile(`AIzaSyANUvH9H9BsUccjsu2pCmEkOPjjaXeDQgY`),
|
||||
regexp.MustCompile(`AIzaSyA5_iVawFQ8ABuTZNUdcwERLJv_a_p4wtM`),
|
||||
regexp.MustCompile(`AIzaSyA4UrcGxgwQFTfaI3no3t7Lt1sjmdnP5sQ`),
|
||||
regexp.MustCompile(`AIzaSyDSb51JiIcB6OJpwwMicseKRhhrOq1cS7g`),
|
||||
regexp.MustCompile(`AIzaSyBF2RrAIm4a0mO64EShQfqfd2AFnzAvvuU`),
|
||||
regexp.MustCompile(`AIzaSyBcE-OOIbhjyR83gm4r2MFCu4MJmprNXsw`),
|
||||
regexp.MustCompile(`AIzaSyB8qGxt4ec15vitgn44duC5ucxaOi4FmqE`),
|
||||
regexp.MustCompile(`AIzaSyA8vmApnrHNFE0bApF4hoZ11srVL_n0nvY`),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// validate
|
||||
@@ -49,6 +70,23 @@ func GCPAPIKey() *config.Rule {
|
||||
`AIzaTesb6Tscfcni8vIpWZqNCXFDFslJtVSvFDqabcd123`, // text boundary end
|
||||
`apiKey: "AIzaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"`, // not enough entropy
|
||||
`AIZASYCO2CXRMC9ELSKLHLHRMBSWDEVEDZTLO2O`, // incorrect case
|
||||
// example keys from https://github.com/firebase/firebase-android-sdk
|
||||
`AIzaSyabcdefghijklmnopqrstuvwxyz1234567`,
|
||||
`AIzaSyAnLA7NfeLquW1tJFpx_eQCxoX-oo6YyIs`,
|
||||
`AIzaSyCkEhVjf3pduRDt6d1yKOMitrUEke8agEM`,
|
||||
`AIzaSyDMAScliyLx7F0NPDEJi1QmyCgHIAODrlU`,
|
||||
`AIzaSyD3asb-2pEZVqMkmL6M9N6nHZRR_znhrh0`,
|
||||
`AIzayDNSXIbFmlXbIE6mCzDLQAqITYefhixbX4A`,
|
||||
`AIzaSyAdOS2zB6NCsk1pCdZ4-P6GBdi_UUPwX7c`,
|
||||
`AIzaSyASWm6HmTMdYWpgMnjRBjxcQ9CKctWmLd4`,
|
||||
`AIzaSyANUvH9H9BsUccjsu2pCmEkOPjjaXeDQgY`,
|
||||
`AIzaSyA5_iVawFQ8ABuTZNUdcwERLJv_a_p4wtM`,
|
||||
`AIzaSyA4UrcGxgwQFTfaI3no3t7Lt1sjmdnP5sQ`,
|
||||
`AIzaSyDSb51JiIcB6OJpwwMicseKRhhrOq1cS7g`,
|
||||
`AIzaSyBF2RrAIm4a0mO64EShQfqfd2AFnzAvvuU`,
|
||||
`AIzaSyBcE-OOIbhjyR83gm4r2MFCu4MJmprNXsw`,
|
||||
`AIzaSyB8qGxt4ec15vitgn44duC5ucxaOi4FmqE`,
|
||||
`AIzaSyA8vmApnrHNFE0bApF4hoZ11srVL_n0nvY`,
|
||||
}
|
||||
return utils.Validate(r, tps, fps)
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func GenericCredential() *config.Rule {
|
||||
@@ -20,11 +19,10 @@ func GenericCredential() *config.Rule {
|
||||
"credential",
|
||||
"creds",
|
||||
"key",
|
||||
"passwd",
|
||||
"password",
|
||||
"passw(?:or)?d",
|
||||
"secret",
|
||||
"token",
|
||||
}, `[\w.=-]{10,150}`, true),
|
||||
}, `[\w.=-]{10,150}|[a-z0-9][a-z0-9+/]{11,}={0,3}`, true),
|
||||
Keywords: []string{
|
||||
"access",
|
||||
"api",
|
||||
@@ -39,17 +37,25 @@ func GenericCredential() *config.Rule {
|
||||
},
|
||||
Entropy: 3.5,
|
||||
Allowlists: []config.Allowlist{
|
||||
{
|
||||
// NOTE: this is a goofy hack to get around the fact there golang's regex engine does not support positive lookaheads.
|
||||
// Ideally we would want to ensure the secret contains both numbers and alphabetical characters, not just alphabetical characters.
|
||||
Regexes: []*regexp.Regexp{
|
||||
regexp.MustCompile(`^[a-zA-Z_.-]+$`),
|
||||
},
|
||||
},
|
||||
{
|
||||
Description: "Allowlist for Generic API Keys",
|
||||
MatchCondition: config.AllowlistMatchOr,
|
||||
RegexTarget: "match",
|
||||
Regexes: []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?i)(` +
|
||||
regexp.MustCompile(`(?i)(?:` +
|
||||
// Access
|
||||
`accessor` +
|
||||
`access(?:ibility|or)` +
|
||||
`|access[_.-]?id` +
|
||||
`|random[_.-]?access` +
|
||||
// API
|
||||
`|api[_.-]?(version|id)` + // version/id -> not a secret
|
||||
`|api[_.-]?(?:id|name|version)` + // id/name/version -> not a secret
|
||||
`|rapid|capital` + // common words containing "api"
|
||||
`|[a-z0-9-]*?api[a-z0-9-]*?:jar:` + // Maven META-INF dependencies that contain "api" in the name.
|
||||
// Auth
|
||||
@@ -57,26 +63,41 @@ func GenericCredential() *config.Rule {
|
||||
`|X-MS-Exchange-Organization-Auth` + // email header
|
||||
`|Authentication-Results` + // email header
|
||||
// Credentials
|
||||
`|(credentials?[_.-]?id|withCredentials)` + // Jenkins plugins
|
||||
`|(?:credentials?[_.-]?id|withCredentials)` + // Jenkins plugins
|
||||
// Key
|
||||
`|(bucket|foreign|hot|natural|primary|schema|sequence)[_.-]?key` +
|
||||
`|key[_.-]?(alias|board|code|ring|selector|size|stone|storetype|word|up|down|left|right)` +
|
||||
`|key(store|tab)[_.-]?(file|path)` +
|
||||
`|(?:bucket|foreign|hot|idx|natural|primary|pub(?:lic)?|schema|sequence)[_.-]?key` +
|
||||
`|key[_.-]?(?:alias|board|code|frame|id|length|mesh|name|pair|ring|selector|signature|size|stone|storetype|word|up|down|left|right)` +
|
||||
// Azure KeyVault
|
||||
`|key[_.-]?vault[_.-]?(?:id|name)|keyVaultToStoreSecrets` +
|
||||
`|key(?:store|tab)[_.-]?(?:file|path)` +
|
||||
`|issuerkeyhash` + // part of ssl cert
|
||||
`|(?-i:[DdMm]onkey|[DM]ONKEY)|keying` + // common words containing "key"
|
||||
// Secret
|
||||
`|(secret)[_.-]?name` + // name of e.g. env variable
|
||||
`|(?:secret)[_.-]?(?:length|name|size)` + // name of e.g. env variable
|
||||
`|UserSecretsId` + // https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=linux
|
||||
|
||||
// Token
|
||||
`|(?:io\.jsonwebtoken[ \t]?:[ \t]?[\w-]+)` + // Maven library coordinats. (e.g., https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt)
|
||||
|
||||
// General
|
||||
`|(api|credentials|token)[_.-]?(endpoint|ur[il])` +
|
||||
`|public[_.-]?(key|token)` + // public key -> not a secret
|
||||
`|(key|token)[_.-]?file` +
|
||||
`|(?:api|credentials|token)[_.-]?(?:endpoint|ur[il])` +
|
||||
`|public[_.-]?token` +
|
||||
`|(?:key|token)[_.-]?file` +
|
||||
// Empty variables capturing the next line (e.g., .env files)
|
||||
`|(?-i:(?:[A-Z_]+=\n[A-Z_]+=|[a-z_]+=\n[a-z_]+=)(?:\n|\z))` +
|
||||
`|(?-i:(?:[A-Z.]+=\n[A-Z.]+=|[a-z.]+=\n[a-z.]+=)(?:\n|\z))` +
|
||||
`)`),
|
||||
},
|
||||
StopWords: DefaultStopWords,
|
||||
StopWords: append(DefaultStopWords,
|
||||
"6fe4476ee5a1832882e326b506d14126", // https://github.com/yarnpkg/berry/issues/6201
|
||||
),
|
||||
},
|
||||
{
|
||||
RegexTarget: "line",
|
||||
Regexes: []*regexp.Regexp{
|
||||
// Docker build secrets (https://docs.docker.com/build/building/secrets/#using-build-secrets).
|
||||
regexp.MustCompile(`--mount=type=secret,`),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -92,6 +113,8 @@ func GenericCredential() *config.Rule {
|
||||
`some_api_token_123 = "`+newPlausibleSecret(`[a-zA-Z0-9]{60}`)+`"`,
|
||||
|
||||
// Auth
|
||||
`"user_auth": "am9obmRvZTpkMDY5NGIxYi1jMTcxLTQ4ODYt+TMyYS0wMmUwOWQ1/mIwNjc="`,
|
||||
|
||||
// Credentials
|
||||
`"credentials" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
|
||||
`creds = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
||||
@@ -109,13 +132,17 @@ func GenericCredential() *config.Rule {
|
||||
`todo_secret_do_not_commit = `+newPlausibleSecret(`[a-zA-Z0-9]{30}`),
|
||||
|
||||
// Token
|
||||
utils.GenerateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"), //gitleaks:allow
|
||||
utils.GenerateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
|
||||
` utils.GetEnvOrDefault("api_token", "dafa7817-e246-48f3-91a7-e87653d587b8")`,
|
||||
// `"env": {
|
||||
//"API_TOKEN": "Lj2^5O%xi214"`,
|
||||
)
|
||||
fps := []string{
|
||||
// Access
|
||||
`"accessor":"rA1wk0Y45YCufyfq",`,
|
||||
`report_access_id: e8e4df51-2054-49b0-ab1c-516ac95c691d`,
|
||||
`accessibilityYesOptionId = "0736f5ef-7e88-499a-80cc-90c85d2a5180"`,
|
||||
`_RandomAccessIterator>
|
||||
_LIBCPP_CONSTEXPR_AFTER_CXX11 `,
|
||||
|
||||
// API
|
||||
`this.ultraPictureBox1.Name = "ultraPictureBox1";`,
|
||||
@@ -126,6 +153,7 @@ func GenericCredential() *config.Rule {
|
||||
`[DEBUG] org.slf4j.slf4j-api:jar:1.7.8.:compile (version managed from default)`,
|
||||
`[DEBUG] org.neo4j.neo4j-graphdb-api:jar:3.5.12:test`,
|
||||
`apiUrl=apigee.corpint.com`,
|
||||
`X-API-Name": "NRG0-Hermes-INTERNAL-API",`,
|
||||
// TODO: Jetbrains IML files (requires line-level allowlist).
|
||||
// `<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.directory.api:api-asn1-api:1.0.0-M20" level="projcet" />`
|
||||
|
||||
@@ -147,6 +175,8 @@ func GenericCredential() *config.Rule {
|
||||
// Key
|
||||
`keyword: "Befaehigung_P2"`,
|
||||
`public_key = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
||||
`pub const X509_pubkey_st = struct_X509_pubkey_st;`,
|
||||
`|| pIdxKey->default_rc==0`,
|
||||
`monkeys-audio:mx64-uwp=fail`,
|
||||
`primaryKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||
`foreignKey=` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||
@@ -156,7 +186,6 @@ func GenericCredential() *config.Rule {
|
||||
`minisat-master-keying:x64-uwp=fail`,
|
||||
`IceSSL.KeyFile=s_rsa1024_priv.pem`,
|
||||
`"bucket_key": "SalesResults-1.2"`,
|
||||
// `<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
|
||||
`<key tag="SecurityIdentifier" name="SecurityIdentifier" type="STRING" />`,
|
||||
// `packageKey":` + newPlausibleSecret(`[a-zA-Z0-9\-_.=]{30}`),
|
||||
`schemaKey = 'DOC_Vector_5_32'`,
|
||||
@@ -166,7 +195,21 @@ func GenericCredential() *config.Rule {
|
||||
` doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;`,
|
||||
`o.keySelector=n,o.haKey=!1,`,
|
||||
// TODO: Requires line-level allowlists.
|
||||
` "key_name": "prod5zyxlmy-cmk",`,
|
||||
` "kms_key_id": "555ea4a3-d53a-4412-9c66-3a7cb667b0d6",`,
|
||||
` "key_vault_name": "web21prqodx24021",`,
|
||||
` keyVaultToStoreSecrets: cmp2-qat-1208358310`, // e.g., https://github.com/2uasimojo/community-operators-prod/blob/9e51e4c8e0b5caaa3087e8e18e6fb918b2c36643/operators/azure-service-operator/1.0.59040/manifests/azure.microsoft.com_cosmosdbs.yaml#L50
|
||||
`,apiKey:"6fe4476ee5a1832882e326b506d14126",`,
|
||||
`const validKeyChars = "0123456789abcdefghijklmnopqrstuvwxyz_-."`,
|
||||
`const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"`,
|
||||
`key_length = XSalsa20.key_length`,
|
||||
`pub const SN_id_Gost28147_89_None_KeyMeshing = "id-Gost28147-89-None-KeyMeshing"`,
|
||||
`KeyPair = X25519.KeyPair`,
|
||||
`BlindKeySignatures = Ed25519.BlindKeySignatures`,
|
||||
`AVEncVideoMaxKeyframeDistance, "2987123a-ba93-4704-b489-ec1e5f25292c"`,
|
||||
// `<add key="SchemaTable" value="G:\SchemaTable.xml" />`,
|
||||
//` { key: '9df21e95-3848-409d-8f94-c675cdfee839', value: 'Americas' },`,
|
||||
// `<TAR key="REF_ID_923.properties" value="/opts/config/alias/"/>`,
|
||||
// `secret:
|
||||
// secretName: app-decryption-secret
|
||||
// items:
|
||||
@@ -174,7 +217,7 @@ func GenericCredential() *config.Rule {
|
||||
// path: app-k8s.yml`,
|
||||
|
||||
// TODO: https://learn.microsoft.com/en-us/windows/apps/design/style/xaml-theme-resources
|
||||
// `<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
|
||||
//`<Color x:Key="NormalBrushGradient1">#FFBAE4FF</Color>`,
|
||||
|
||||
// Password
|
||||
`password combination.
|
||||
@@ -185,15 +228,25 @@ R5: Regulatory--21`,
|
||||
// Secret
|
||||
`LLM_SECRET_NAME = "NEXUS-GPT4-API-KEY"`,
|
||||
` <UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>`,
|
||||
`secret_length = X25519.secret_length`,
|
||||
`secretSize must be >= XXH3_SECRET_SIZE_MIN`,
|
||||
`# get build time secret for authentication
|
||||
#RUN --mount=type=secret,id=jfrog_secret \
|
||||
# JFROG_SECRET = $(cat /run/secrets/jfrog_secret) && \`,
|
||||
|
||||
// Token
|
||||
` access_token_url='https://github.com/login/oauth/access_token',`,
|
||||
`publicToken = "9Cnzj4p4WGeKLs1Pt8QuKUpRKfFLfRYC9AIKjbJTWit"`,
|
||||
`<SourceFile SourceLocation="F:\Extracts\" TokenFile="RTL_INST_CODE.cer">`,
|
||||
`notes = "Maven - io.jsonwebtoken:jjwt-jackson-0.11.2"`,
|
||||
// TODO: `TOKEN_AUDIENCE = "25872395-ed3a-4703-b647-22ec53f3683c"`,
|
||||
|
||||
// General
|
||||
`clientId = "73082700-1f09-405b-80d0-3131bfd6272d"`,
|
||||
`GITHUB_API_KEY=
|
||||
DYNATRACE_API_KEY=`,
|
||||
`snowflake.password=
|
||||
jdbc.snowflake.url=`,
|
||||
}
|
||||
return utils.Validate(r, tps, fps)
|
||||
}
|
||||
@@ -209,7 +262,7 @@ func newPlausibleSecret(regex string) string {
|
||||
if !regexp.MustCompile(`[1-9]`).MatchString(secret) {
|
||||
continue
|
||||
}
|
||||
if allowList.ContainsStopWord(secret) {
|
||||
if ok, _ := allowList.ContainsStopWord(secret); ok {
|
||||
continue
|
||||
}
|
||||
return secret
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
var githubAllowlist = []config.Allowlist{
|
||||
{
|
||||
Paths: []*regexp.Regexp{
|
||||
// https://github.com/octokit/auth-token.js/?tab=readme-ov-file#createtokenauthtoken-options
|
||||
regexp.MustCompile(`(^|/)@octokit/auth-token/README\.md$`),
|
||||
regexp.MustCompile(`(?:^|/)@octokit/auth-token/README\.md$`),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// overview with all GitLab tokens:
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func HarnessApiKey() *config.Rule {
|
||||
|
||||
@@ -3,12 +3,10 @@ package rules
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func HashiCorpTerraform() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func VaultServiceToken() *config.Rule {
|
||||
|
||||
@@ -59,5 +59,6 @@ func JFrogIdentityToken() *config.Rule {
|
||||
tps = append(tps, utils.GenerateSampleSecrets("artifactory", secrets.NewSecret(utils.AlphaNumeric("64")))...)
|
||||
tps = append(tps, utils.GenerateSampleSecrets("bintray", secrets.NewSecret(utils.AlphaNumeric("64")))...)
|
||||
tps = append(tps, utils.GenerateSampleSecrets("xray", secrets.NewSecret(utils.AlphaNumeric("64")))...)
|
||||
tps = append(tps, fmt.Sprintf("\"artifactory\", \"%s\"", secrets.NewSecret(utils.AlphaNumeric("64"))))
|
||||
return utils.Validate(r, tps, nil)
|
||||
}
|
||||
@@ -4,10 +4,10 @@ import (
|
||||
b64 "encoding/base64"
|
||||
"fmt"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func JWT() *config.Rule {
|
||||
|
||||
@@ -3,11 +3,9 @@ package rules
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// KubernetesSecret validates if we detected a kubernetes secret which contains data!
|
||||
@@ -41,9 +39,13 @@ func KubernetesSecret() *config.Rule {
|
||||
// variable: ""
|
||||
// variable: ''
|
||||
regexp.MustCompile(`[\w.-]+:(?:[ \t]*(?:\||>[-+]?)\s+)?[ \t]*(?:\{\{[ \t\w"|$:=,.-]+}}|""|'')`),
|
||||
// TODO: Requires multiple allowlists to target match.
|
||||
// Avoid overreach between directives.
|
||||
// regexp.MustCompile(`(kind:(.|\s)+\n---\n(.|\s)+\bdata:|data:(.|\s)+\n---\n(.|\s)+\bkind:)`),
|
||||
},
|
||||
},
|
||||
{
|
||||
// Avoid overreach between directives.
|
||||
RegexTarget: "match",
|
||||
Regexes: []*regexp.Regexp{
|
||||
regexp.MustCompile(`(kind:(?:.|\s)+\n---\n(?:.|\s)+\bdata:|data:(?:.|\s)+\n---\n(?:.|\s)+\bkind:)`),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -245,21 +247,20 @@ metadata:
|
||||
namespace: kubernetes-dashboard
|
||||
type: Opaque
|
||||
`,
|
||||
// TODO: Requires multiple allowlists.
|
||||
// "overly-permissive3.yaml": ` kind: Secret
|
||||
// target:
|
||||
// name: mysecret
|
||||
// creationPolicy: Owner
|
||||
//
|
||||
// ---
|
||||
//
|
||||
// kind: ConfigMap
|
||||
// data:
|
||||
// conversionStrategy: Default
|
||||
// decodingStrategy: None
|
||||
// key: secret/mysecret
|
||||
// property: foo
|
||||
// secretKey: foo`,
|
||||
"overly-permissive3.yaml": ` kind: Secret
|
||||
target:
|
||||
name: mysecret
|
||||
creationPolicy: Owner
|
||||
|
||||
---
|
||||
|
||||
kind: ConfigMap
|
||||
data:
|
||||
conversionStrategy: Default
|
||||
decodingStrategy: None
|
||||
key: secret/mysecret
|
||||
property: foo
|
||||
secretKey: foo`,
|
||||
// https://github.com/gitleaks/gitleaks/issues/1644
|
||||
"wrong-kind.yaml": `apiVersion: external-secrets.io/v1beta1
|
||||
kind: ExternalSecret
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func LinearAPIToken() *config.Rule {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
)
|
||||
|
||||
func Meraki() *config.Rule {
|
||||
// define rule
|
||||
r := config.Rule{
|
||||
RuleID: "cisco-meraki-api-key",
|
||||
Description: "Cisco Meraki is a cloud-managed IT solution that provides networking, security, and device management through an easy-to-use interface.",
|
||||
Regex: utils.GenerateSemiGenericRegex([]string{`(?-i:[Mm]eraki|MERAKI)`}, `[0-9a-f]{40}`, false),
|
||||
Entropy: 3,
|
||||
Keywords: []string{"meraki"},
|
||||
}
|
||||
|
||||
// validate
|
||||
tps := utils.GenerateSampleSecrets("meraki", secrets.NewSecret(utils.Hex("40")))
|
||||
fps := []string{
|
||||
`meraki: aaaaaaaaaa1111111111bbbbbbbbbb2222222222`, // low entropy
|
||||
`meraki-api-key: acdeFf05b1a6d4c890237bf08c5e6e8d2b4d0f2e`, // invalid case
|
||||
`meraki: abdefghjk0123456789mnopqrstuvwx12345678`, // invalid character
|
||||
`meraki_token = 5cb4a5f04cd412fe946667b17f0129ba17aeb2e0c7b5b7264efcebf7d022bfe2R21`, // invalid length
|
||||
`ReactNativeCameraKit: f15a5a04b0f6dc6073e6db0296e6ef2d8b8d2522`,
|
||||
}
|
||||
return utils.Validate(r, tps, fps)
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func NugetConfigPassword() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// OpenShift 4 user tokens are prefixed with `sha256~`.
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func PrivateKey() *config.Rule {
|
||||
@@ -21,7 +20,7 @@ func PrivateKey() *config.Rule {
|
||||
anything
|
||||
-----END PRIVATE KEY-----`,
|
||||
`-----BEGIN RSA PRIVATE KEY-----
|
||||
abcdefghijklmnopqrstuvwxyz
|
||||
abcdefghijksmnopqrstuvwxyz
|
||||
-----END RSA PRIVATE KEY-----
|
||||
`,
|
||||
`-----BEGIN PRIVATE KEY BLOCK-----
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func PyPiUploadToken() *config.Rule {
|
||||
|
||||
@@ -2,11 +2,11 @@ package rules
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func SentryAccessToken() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func ShopifySharedSecret() *config.Rule {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func SidekiqSecret() *config.Rule {
|
||||
|
||||
@@ -2,12 +2,11 @@ package rules
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// https://api.slack.com/authentication/token-types#bot
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func TeamsWebhook() *config.Rule {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package rules
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/utils"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func Twilio() *config.Rule {
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -19,17 +19,16 @@ const (
|
||||
identifierCaseInsensitivePrefix = `[\w.-]{0,50}?(?i:`
|
||||
identifierCaseInsensitiveSuffix = `)`
|
||||
identifierPrefix = `[\w.-]{0,50}?(?:`
|
||||
identifierSuffix = `)(?:[ \t\w.-]{0,20})(?:[\s|']|[\s|"]){0,3}`
|
||||
identifierSuffix = `)(?:[ \t\w.-]{0,20})[\s'"]{0,3}`
|
||||
|
||||
// commonly used assignment operators or function call
|
||||
//language=regexp
|
||||
operator = `(?:=|>|:{1,3}=|\|\|:|<=|=>|:|\?=)`
|
||||
operator = `(?:=|>|:{1,3}=|\|\||:|=>|\?=|,)`
|
||||
|
||||
// boundaries for the secret
|
||||
// \x60 = `
|
||||
secretPrefixUnique = `\b(`
|
||||
secretPrefix = `(?:'|\"|\s|=|\x60){0,5}(`
|
||||
secretSuffix = `)(?:['|\"|\n|\r|\s|\x60|;]|$)`
|
||||
secretPrefix = `[\x60'"\s=]{0,5}(`
|
||||
secretSuffix = `)(?:[\x60'"\s;]|\\[nr]|$)`
|
||||
)
|
||||
|
||||
func GenerateSemiGenericRegex(identifiers []string, secretRegex string, isCaseInsensitive bool) *regexp.Regexp {
|
||||
@@ -95,6 +94,7 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
|
||||
"json - string": "{\n \"{i}_token\": \"{s}\"\n}",
|
||||
// TODO: "json - escaped string": "\\{\n \\\"{i}_token\\\": \\\"{s}\\\"\n\\}",
|
||||
// TODO: "json - string key/value": "{\n \"name\": \"{i}_token\",\n \"value\": \"{s}\"\n}",
|
||||
"json - escaped newline in string": `{"config.ini": "{I}_TOKEN={s}\nBACKUP_ENABLED=true"}`,
|
||||
// XML
|
||||
// TODO: "xml - element": "<{i}Token>{s}</{i}Token>",
|
||||
"xml - element multiline": "<{i}Token>\n {s}\n</{i}Token>",
|
||||
@@ -131,6 +131,8 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
|
||||
// TODO: "comment - hashtag": "#{s} is the password",
|
||||
// TODO: "comment - semicolon": ";{s} is the password",
|
||||
// TODO: "csv - unquoted": `{i}Token,{s},`,
|
||||
"misc - comma operator": `System.setProperty("{I}_TOKEN", "{s}")`,
|
||||
// TODO: "misc - comma suffix": `environmentVariables = {PATH=/usr/local/bin, ENV=/etc/bashrc, {I}_PASSWORD={s}, LC_CTYPE=en_CA.UTF-8},`, // Spotted in `./Library/Logs/gradle-kotlin-dsl-resolver-xxxx.log`
|
||||
"logstash": " \"{i}Token\" => \"{s}\"",
|
||||
// TODO: "sql - tabular": "|{s}|",
|
||||
// TODO: "sql": "",
|
||||
@@ -147,7 +149,11 @@ func GenerateSampleSecrets(identifier string, secret string) []string {
|
||||
// "": "",
|
||||
}
|
||||
|
||||
replacer := strings.NewReplacer("{i}", identifier, "{s}", secret)
|
||||
replacer := strings.NewReplacer(
|
||||
"{i}", identifier,
|
||||
"{I}", strings.ToUpper(identifier),
|
||||
"{s}", secret,
|
||||
)
|
||||
cases := make([]string, 0, len(samples))
|
||||
for _, v := range samples {
|
||||
cases = append(cases, replacer.Replace(v))
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateSemiGenericRegex(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
identifiers []string
|
||||
secretRegex string
|
||||
isCaseInsensitive []bool
|
||||
validStrings []string
|
||||
invalidStrings []string
|
||||
}{
|
||||
{
|
||||
name: "secret is case sensitive, if isCaseInsensitive is false",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{false},
|
||||
validStrings: []string{"api_key=xxx"},
|
||||
invalidStrings: []string{"api_key=XXX", "api_key=xXx"},
|
||||
},
|
||||
{
|
||||
name: "secret is case insensitive, if isCaseInsensitive is true",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true},
|
||||
validStrings: []string{"api_key=xxx", "api_key=XXX", "api_key=xXx"},
|
||||
invalidStrings: []string{"api_key=x!x"},
|
||||
},
|
||||
{
|
||||
name: "identifier is case insensitive, regardless of isCaseInsensitive",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{"api_key=xxx", "ApI_KeY=xxx", "aPi_kEy=xxx", "API_KEY=xxx"},
|
||||
invalidStrings: []string{"api!key=xxx"},
|
||||
},
|
||||
{
|
||||
name: "identifier can be case sensitive",
|
||||
identifiers: []string{"(?-i:[Aa]pi_?[Kk]ey|API_?KEY)"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{"apikey=xxx", "ApiKey=xxx", "Apikey=xxx", "APIKEY=xxx", "api_key=xxx"},
|
||||
invalidStrings: []string{"ApIKeY=xxx", "aPikEy=xxx"},
|
||||
},
|
||||
{
|
||||
name: "identifier can be part of a longer word",
|
||||
identifiers: []string{"key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{"mykey=xxx", "keys=xxx", "key1=xxx", "keystore=xxx", "monkey=xxx"},
|
||||
invalidStrings: []string{},
|
||||
},
|
||||
{
|
||||
name: "identifier may be followed by specific characters",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{
|
||||
"api_key-----=xxx",
|
||||
"api_key.....=xxx",
|
||||
"api_key_____=xxx",
|
||||
"'''api_key'''=xxx",
|
||||
`"""api_key"""=xxx`,
|
||||
"api_key =xxx",
|
||||
"api_key\t\t\t\t\t=xxx",
|
||||
"api_key\n\n\n=xxx", // potentially invalid?,
|
||||
"api_key\r\n=xxx",
|
||||
// "api_key|||=xxx",
|
||||
},
|
||||
invalidStrings: []string{
|
||||
"api_key&=xxx",
|
||||
"$api_key$=xxx",
|
||||
"%api_key%=xxx",
|
||||
"api_key[0]=xxx",
|
||||
"api_key/*REMOVE*/=xxx",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "identifier and secret must be separated by specific operators",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{
|
||||
"api_key=xxx",
|
||||
"api_key: xxx",
|
||||
"<api_key>xxx",
|
||||
"api_key:=xxx",
|
||||
"api_key:::=xxx",
|
||||
// "api_key||:=xxx", // this isn't anything
|
||||
// "api_key <= xxx",
|
||||
"api_key => xxx",
|
||||
"api_key ?= xxx",
|
||||
"api_key, xxx",
|
||||
},
|
||||
invalidStrings: []string{
|
||||
"api_keyxxx",
|
||||
"api_key\txxx", // potentially valid in a tab-separated file
|
||||
"api_key; xxx",
|
||||
"api_key<xxx>",
|
||||
"api_key&xxx",
|
||||
"api_key = true ? 'xxx' : 'yyy'",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "secret is limited by specific boundaries",
|
||||
identifiers: []string{"api_key"},
|
||||
secretRegex: `[a-z]{3}`,
|
||||
isCaseInsensitive: []bool{true, false},
|
||||
validStrings: []string{
|
||||
"api_key= xxx ",
|
||||
"api_key=xxx\n",
|
||||
"api_key=xxx\r\n",
|
||||
"api_key=\n\n\n\n\nxxx", // potentially invalid (e.g. .env.example)
|
||||
"api_key=\r\n\r\nxxx",
|
||||
"api_key=\t\t\t\txxx\t",
|
||||
"api_key======xxx;",
|
||||
"api_key='''xxx'''",
|
||||
`api_key="""xxx"""`,
|
||||
"api_key=```xxx```",
|
||||
`api_key="xxx'`, // could try to match only same opening and closing quotes, might not be worth the complexity
|
||||
`api_key="don't do it!"`,
|
||||
`api_key="xxx;notpartofthematch"`,
|
||||
},
|
||||
invalidStrings: []string{
|
||||
"api_key=_xxx",
|
||||
"api_key=xxx_",
|
||||
"api_key=$xxx",
|
||||
"api_key=%xxx%",
|
||||
"api_key=[xxx]",
|
||||
"api_key=(xxx)",
|
||||
"api_key=<xxx>",
|
||||
"api_key={xxx}",
|
||||
"<api_key>xxx</api_key>", // potentially valid
|
||||
"example.com?api_key=xxx&other=yyy", // potentially valid
|
||||
},
|
||||
},
|
||||
// Note: these test cases do not necessarily prescribe the expected behavior of the function,
|
||||
// but rather document the current behavior, to ensure that future changes are intentional.
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
for _, isCaseInsensitive := range tt.isCaseInsensitive {
|
||||
regex := GenerateSemiGenericRegex(tt.identifiers, tt.secretRegex, isCaseInsensitive)
|
||||
for _, validString := range tt.validStrings {
|
||||
if !regex.MatchString(validString) {
|
||||
t.Errorf("Expected match, but got none, \nfor GenerateSemiGenericRegex(%v, /%v/, caseInsensitive=%v).MatchString(`%v`)\n%v",
|
||||
tt.identifiers, tt.secretRegex, isCaseInsensitive, validString, regex)
|
||||
}
|
||||
}
|
||||
for _, invalidString := range tt.invalidStrings {
|
||||
if regex.MatchString(invalidString) {
|
||||
t.Errorf("Expected no match, but got one, \nfor GenerateSemiGenericRegex(%v, /%v/, caseInsensitive=%v).MatchString(`%v`)\n%v",
|
||||
tt.identifiers, tt.secretRegex, isCaseInsensitive, invalidString, regex)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateUniqueTokenRegex(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
secretRegex string
|
||||
isCaseInsensitive bool
|
||||
validStrings []string
|
||||
invalidStrings []string
|
||||
}{
|
||||
{
|
||||
name: "case sensitive secret",
|
||||
secretRegex: `[a-c]{3}`,
|
||||
isCaseInsensitive: false,
|
||||
validStrings: []string{"abc"},
|
||||
invalidStrings: []string{"ABC", "Abc"},
|
||||
},
|
||||
{
|
||||
name: "case insensitive secret",
|
||||
secretRegex: `[a-c]{3}`,
|
||||
isCaseInsensitive: true,
|
||||
validStrings: []string{"abc", "ABC", "Abc"},
|
||||
invalidStrings: []string{"123"},
|
||||
},
|
||||
{
|
||||
name: "allowed boundaries",
|
||||
secretRegex: `[a-c]{3}`,
|
||||
isCaseInsensitive: false,
|
||||
validStrings: []string{
|
||||
"abc",
|
||||
" abc ",
|
||||
"\nabc\n",
|
||||
"\r\nabc\r\n",
|
||||
"\tabc\t",
|
||||
"'abc'",
|
||||
`"abc"`,
|
||||
"```abc```",
|
||||
"my abc's",
|
||||
".com?abc",
|
||||
},
|
||||
invalidStrings: []string{
|
||||
"abcabc",
|
||||
"_abc_",
|
||||
".com?abc&def", // potentially valid
|
||||
"/*abc*/",
|
||||
"<abc>",
|
||||
"<str>abc</str>", // potentially valid
|
||||
"{{{abc}}}",
|
||||
"abc, d",
|
||||
},
|
||||
},
|
||||
// Note: these test cases do not necessarily prescribe the expected behavior of the function,
|
||||
// but rather document the current behavior, to ensure that future changes are intentional.
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
regex := GenerateUniqueTokenRegex(tt.secretRegex, tt.isCaseInsensitive)
|
||||
for _, validString := range tt.validStrings {
|
||||
if !regex.MatchString(validString) {
|
||||
t.Errorf("Expected match, but got none, \nfor GenerateUniqueTokenRegex(/%v/, caseInsensitive=%v).MatchString(`%v`)\n%v",
|
||||
tt.secretRegex, tt.isCaseInsensitive, validString, regex)
|
||||
}
|
||||
}
|
||||
for _, invalidString := range tt.invalidStrings {
|
||||
if regex.MatchString(invalidString) {
|
||||
t.Errorf("Expected no match, but got one, \nfor GenerateUniqueTokenRegex(/%v/, caseInsensitive=%v).MatchString(`%v`)\n%v",
|
||||
tt.secretRegex, tt.isCaseInsensitive, invalidString, regex)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,10 @@ package utils
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/base"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
func Validate(rule config.Rule, truePositives []string, falsePositives []string) *config.Rule {
|
||||
@@ -19,7 +18,7 @@ func Validate(rule config.Rule, truePositives []string, falsePositives []string)
|
||||
d := createSingleRuleDetector(r)
|
||||
for _, tp := range truePositives {
|
||||
if len(d.DetectString(tp)) < 1 {
|
||||
log.Fatal().
|
||||
logging.Fatal().
|
||||
Str("rule", r.RuleID).
|
||||
Str("value", tp).
|
||||
Str("regex", r.Regex.String()).
|
||||
@@ -29,7 +28,7 @@ func Validate(rule config.Rule, truePositives []string, falsePositives []string)
|
||||
for _, fp := range falsePositives {
|
||||
findings := d.DetectString(fp)
|
||||
if len(findings) != 0 {
|
||||
log.Fatal().
|
||||
logging.Fatal().
|
||||
Str("rule", r.RuleID).
|
||||
Str("value", fp).
|
||||
Str("regex", r.Regex.String()).
|
||||
@@ -45,7 +44,7 @@ func ValidateWithPaths(rule config.Rule, truePositives map[string]string, falseP
|
||||
for path, tp := range truePositives {
|
||||
f := detect.Fragment{Raw: tp, FilePath: path}
|
||||
if len(d.Detect(f)) != 1 {
|
||||
log.Fatal().
|
||||
logging.Fatal().
|
||||
Str("rule", r.RuleID).
|
||||
Str("value", tp).
|
||||
Str("regex", r.Regex.String()).
|
||||
@@ -56,7 +55,7 @@ func ValidateWithPaths(rule config.Rule, truePositives map[string]string, falseP
|
||||
for path, fp := range falsePositives {
|
||||
f := detect.Fragment{Raw: fp, FilePath: path}
|
||||
if len(d.Detect(f)) != 0 {
|
||||
log.Fatal().
|
||||
logging.Fatal().
|
||||
Str("rule", r.RuleID).
|
||||
Str("value", fp).
|
||||
Str("regex", r.Regex.String()).
|
||||
|
||||
+33
-41
@@ -3,15 +3,18 @@ package cmd
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"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"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(gitCmd)
|
||||
gitCmd.Flags().String("platform", "", "the target platform used to generate links (github, gitlab)")
|
||||
gitCmd.Flags().Bool("staged", false, "scan staged commits (good for pre-commit)")
|
||||
gitCmd.Flags().Bool("pre-commit", false, "scan using git diff")
|
||||
gitCmd.Flags().String("log-opts", "", "git log options")
|
||||
@@ -25,10 +28,8 @@ var gitCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func runGit(cmd *cobra.Command, args []string) {
|
||||
var (
|
||||
findings []report.Finding
|
||||
err error
|
||||
)
|
||||
// start timer
|
||||
start := time.Now()
|
||||
|
||||
// grab source
|
||||
source := "."
|
||||
@@ -39,58 +40,49 @@ func runGit(cmd *cobra.Command, args []string) {
|
||||
}
|
||||
}
|
||||
|
||||
initConfig(source)
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
initConfig(source)
|
||||
cfg := Config(cmd)
|
||||
|
||||
// start timer
|
||||
start := time.Now()
|
||||
|
||||
// grab source
|
||||
// create detector
|
||||
detector := Detector(cmd, cfg, source)
|
||||
|
||||
// set exit code
|
||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get exit code")
|
||||
}
|
||||
// parse flags
|
||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||
logOpts := mustGetStringFlag(cmd, "log-opts")
|
||||
staged := mustGetBoolFlag(cmd, "staged")
|
||||
preCommit := mustGetBoolFlag(cmd, "pre-commit")
|
||||
|
||||
var (
|
||||
gitCmd *sources.GitCmd
|
||||
logOpts string
|
||||
preCommit bool
|
||||
staged bool
|
||||
findings []report.Finding
|
||||
err error
|
||||
|
||||
gitCmd *sources.GitCmd
|
||||
scmPlatform scm.Platform
|
||||
remote *detect.RemoteInfo
|
||||
)
|
||||
logOpts, err = cmd.Flags().GetString("log-opts")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetString() for log-opts")
|
||||
}
|
||||
staged, err = cmd.Flags().GetBool("staged")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetBool() for staged")
|
||||
}
|
||||
preCommit, err = cmd.Flags().GetBool("pre-commit")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call GetBool() for pre-commit")
|
||||
}
|
||||
|
||||
if preCommit || staged {
|
||||
gitCmd, err = sources.NewGitDiffCmd(source, staged)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not create Git diff cmd")
|
||||
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.
|
||||
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
|
||||
} else {
|
||||
gitCmd, err = sources.NewGitLogCmd(source, logOpts)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not create Git log cmd")
|
||||
if gitCmd, err = sources.NewGitLogCmd(source, logOpts); err != nil {
|
||||
logging.Fatal().Err(err).Msg("could not create Git log cmd")
|
||||
}
|
||||
if scmPlatform, err = scm.PlatformFromString(mustGetStringFlag(cmd, "platform")); err != nil {
|
||||
logging.Fatal().Err(err).Send()
|
||||
}
|
||||
if remote, err = detect.NewRemoteInfo(scmPlatform, source); err != nil {
|
||||
logging.Fatal().Err(err).Msg("failed to scan Git repository")
|
||||
}
|
||||
}
|
||||
|
||||
findings, err = detector.DetectGit(gitCmd)
|
||||
findings, err = detector.DetectGit(gitCmd, remote)
|
||||
if err != nil {
|
||||
// don't exit on error, just log it
|
||||
log.Error().Err(err).Msg("failed to scan Git repository")
|
||||
logging.Error().Err(err).Msg("failed to scan Git repository")
|
||||
}
|
||||
|
||||
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
||||
|
||||
+29
-16
@@ -3,9 +3,11 @@ package cmd
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"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"
|
||||
)
|
||||
@@ -25,27 +27,38 @@ var protectCmd = &cobra.Command{
|
||||
}
|
||||
|
||||
func runProtect(cmd *cobra.Command, args []string) {
|
||||
source, err := cmd.Flags().GetString("source")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get source")
|
||||
}
|
||||
initConfig(source)
|
||||
// start timer
|
||||
start := time.Now()
|
||||
source := mustGetStringFlag(cmd, "source")
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
initConfig(source)
|
||||
cfg := Config(cmd)
|
||||
|
||||
exitCode, _ := cmd.Flags().GetInt("exit-code")
|
||||
staged, _ := cmd.Flags().GetBool("staged")
|
||||
start := time.Now()
|
||||
// create detector
|
||||
detector := Detector(cmd, cfg, source)
|
||||
|
||||
// start git scan
|
||||
var findings []report.Finding
|
||||
gitCmd, err := sources.NewGitDiffCmd(source, staged)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
}
|
||||
findings, err = detector.DetectGit(gitCmd)
|
||||
// parse flags
|
||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||
staged := mustGetBoolFlag(cmd, "staged")
|
||||
|
||||
// start git scan
|
||||
var (
|
||||
findings []report.Finding
|
||||
err error
|
||||
|
||||
gitCmd *sources.GitCmd
|
||||
remote *detect.RemoteInfo
|
||||
)
|
||||
|
||||
if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
|
||||
logging.Fatal().Err(err).Msg("could not create Git diff cmd")
|
||||
}
|
||||
remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
|
||||
|
||||
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")
|
||||
}
|
||||
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
||||
}
|
||||
+88
-66
@@ -6,7 +6,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
@@ -16,6 +15,8 @@ import (
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/detect"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
@@ -70,79 +71,84 @@ func init() {
|
||||
|
||||
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
|
||||
if err != nil {
|
||||
log.Fatal().Msgf("err binding config %s", err.Error())
|
||||
logging.Fatal().Msgf("err binding config %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
var logLevel = zerolog.InfoLevel
|
||||
|
||||
func initLog() {
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
ll, err := rootCmd.Flags().GetString("log-level")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
logging.Fatal().Msg(err.Error())
|
||||
}
|
||||
|
||||
switch strings.ToLower(ll) {
|
||||
case "trace":
|
||||
zerolog.SetGlobalLevel(zerolog.TraceLevel)
|
||||
logLevel = zerolog.TraceLevel
|
||||
case "debug":
|
||||
zerolog.SetGlobalLevel(zerolog.DebugLevel)
|
||||
logLevel = zerolog.DebugLevel
|
||||
case "info":
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
logLevel = zerolog.InfoLevel
|
||||
case "warn":
|
||||
zerolog.SetGlobalLevel(zerolog.WarnLevel)
|
||||
logLevel = zerolog.WarnLevel
|
||||
case "err", "error":
|
||||
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
|
||||
logLevel = zerolog.ErrorLevel
|
||||
case "fatal":
|
||||
zerolog.SetGlobalLevel(zerolog.FatalLevel)
|
||||
logLevel = zerolog.FatalLevel
|
||||
default:
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
logging.Warn().Msgf("unknown log level: %s", ll)
|
||||
}
|
||||
logging.Logger = logging.Logger.Level(logLevel)
|
||||
}
|
||||
|
||||
func initConfig(source string) {
|
||||
hideBanner, err := rootCmd.Flags().GetBool("no-banner")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
logging.Fatal().Msg(err.Error())
|
||||
}
|
||||
if !hideBanner {
|
||||
_, _ = fmt.Fprint(os.Stderr, banner)
|
||||
}
|
||||
|
||||
logging.Debug().Msgf("using %s regex engine", regexp.Version)
|
||||
|
||||
cfgPath, err := rootCmd.Flags().GetString("config")
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
logging.Fatal().Msg(err.Error())
|
||||
}
|
||||
if cfgPath != "" {
|
||||
viper.SetConfigFile(cfgPath)
|
||||
log.Debug().Msgf("using gitleaks config %s from `--config`", cfgPath)
|
||||
logging.Debug().Msgf("using gitleaks config %s from `--config`", cfgPath)
|
||||
} else if os.Getenv("GITLEAKS_CONFIG") != "" {
|
||||
envPath := os.Getenv("GITLEAKS_CONFIG")
|
||||
viper.SetConfigFile(envPath)
|
||||
log.Debug().Msgf("using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
|
||||
logging.Debug().Msgf("using gitleaks config from GITLEAKS_CONFIG env var: %s", envPath)
|
||||
} else {
|
||||
fileInfo, err := os.Stat(source)
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
logging.Fatal().Msg(err.Error())
|
||||
}
|
||||
|
||||
if !fileInfo.IsDir() {
|
||||
log.Debug().Msgf("unable to load gitleaks config from %s since --source=%s is a file, using default config",
|
||||
logging.Debug().Msgf("unable to load gitleaks config from %s since --source=%s is a file, using default config",
|
||||
filepath.Join(source, ".gitleaks.toml"), source)
|
||||
viper.SetConfigType("toml")
|
||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||
log.Fatal().Msgf("err reading toml %s", err.Error())
|
||||
logging.Fatal().Msgf("err reading toml %s", err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(source, ".gitleaks.toml")); os.IsNotExist(err) {
|
||||
log.Debug().Msgf("no gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
||||
logging.Debug().Msgf("no gitleaks config found in path %s, using default gitleaks config", filepath.Join(source, ".gitleaks.toml"))
|
||||
viper.SetConfigType("toml")
|
||||
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
|
||||
log.Fatal().Msgf("err reading default config toml %s", err.Error())
|
||||
logging.Fatal().Msgf("err reading default config toml %s", err.Error())
|
||||
}
|
||||
return
|
||||
} else {
|
||||
log.Debug().Msgf("using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
|
||||
logging.Debug().Msgf("using existing gitleaks config %s from `(--source)/.gitleaks.toml`", filepath.Join(source, ".gitleaks.toml"))
|
||||
}
|
||||
|
||||
viper.AddConfigPath(source)
|
||||
@@ -150,7 +156,7 @@ func initConfig(source string) {
|
||||
viper.SetConfigType("toml")
|
||||
}
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Fatal().Msgf("unable to load gitleaks config, err: %s", err)
|
||||
logging.Fatal().Msgf("unable to load gitleaks config, err: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,18 +166,18 @@ func Execute() {
|
||||
// exit code 126: Command invoked cannot execute
|
||||
os.Exit(126)
|
||||
}
|
||||
log.Fatal().Msg(err.Error())
|
||||
logging.Fatal().Msg(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func Config(cmd *cobra.Command) config.Config {
|
||||
var vc config.ViperConfig
|
||||
if err := viper.Unmarshal(&vc); err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
logging.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
cfg, err := vc.Translate()
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to load config")
|
||||
logging.Fatal().Err(err).Msg("Failed to load config")
|
||||
}
|
||||
cfg.Path, _ = cmd.Flags().GetString("config")
|
||||
|
||||
@@ -185,23 +191,23 @@ 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 {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
|
||||
// set color flag at first
|
||||
if detector.NoColor, err = cmd.Flags().GetBool("no-color"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
// also init logger again without color
|
||||
if detector.NoColor {
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{
|
||||
logging.Logger = log.Output(zerolog.ConsoleWriter{
|
||||
Out: os.Stderr,
|
||||
NoColor: detector.NoColor,
|
||||
})
|
||||
}).Level(logLevel)
|
||||
}
|
||||
detector.Config.Path, err = cmd.Flags().GetString("config")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
|
||||
// if config path is not set, then use the {source}/.gitleaks.toml path.
|
||||
@@ -211,40 +217,40 @@ 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 {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
// set redact flag
|
||||
if detector.Redact, err = cmd.Flags().GetUint("redact"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
if detector.MaxTargetMegaBytes, err = cmd.Flags().GetInt("max-target-megabytes"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
// set ignore gitleaks:allow flag
|
||||
if detector.IgnoreGitleaksAllow, err = cmd.Flags().GetBool("ignore-gitleaks-allow"); err != nil {
|
||||
log.Fatal().Err(err).Msg("")
|
||||
logging.Fatal().Err(err).Msg("")
|
||||
}
|
||||
|
||||
gitleaksIgnorePath, err := cmd.Flags().GetString("gitleaks-ignore-path")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get .gitleaksignore path")
|
||||
logging.Fatal().Err(err).Msg("could not get .gitleaksignore path")
|
||||
}
|
||||
|
||||
if fileExists(gitleaksIgnorePath) {
|
||||
if err = detector.AddGitleaksIgnore(gitleaksIgnorePath); err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
}
|
||||
}
|
||||
|
||||
if fileExists(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")) {
|
||||
if err = detector.AddGitleaksIgnore(filepath.Join(gitleaksIgnorePath, ".gitleaksignore")); err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
}
|
||||
}
|
||||
|
||||
if fileExists(filepath.Join(source, ".gitleaksignore")) {
|
||||
if err = detector.AddGitleaksIgnore(filepath.Join(source, ".gitleaksignore")); err != nil {
|
||||
log.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
logging.Fatal().Err(err).Msg("could not call AddGitleaksIgnore")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,32 +259,32 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
||||
if baselinePath != "" {
|
||||
err = detector.AddBaseline(baselinePath, source)
|
||||
if err != nil {
|
||||
log.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
|
||||
logging.Error().Msgf("Could not load baseline. The path must point of a gitleaks report generated using the default format: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// If set, only apply rules that are defined in the flag
|
||||
rules, _ := cmd.Flags().GetStringSlice("enable-rule")
|
||||
if len(rules) > 0 {
|
||||
log.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
|
||||
logging.Info().Msg("Overriding enabled rules: " + strings.Join(rules, ", "))
|
||||
ruleOverride := make(map[string]config.Rule)
|
||||
for _, ruleName := range rules {
|
||||
if r, ok := cfg.Rules[ruleName]; ok {
|
||||
ruleOverride[ruleName] = r
|
||||
} else {
|
||||
log.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
|
||||
logging.Fatal().Msgf("Requested rule %s not found in rules", ruleName)
|
||||
}
|
||||
}
|
||||
detector.Config.Rules = ruleOverride
|
||||
}
|
||||
|
||||
// Validate report settings.
|
||||
reportPath := mustGetStringFlag("report-path")
|
||||
reportPath := mustGetStringFlag(cmd, "report-path")
|
||||
if reportPath != "" {
|
||||
if reportPath != report.StdoutReportPath {
|
||||
// Ensure the path is writable.
|
||||
if f, err := os.Create(reportPath); err != nil {
|
||||
log.Fatal().Err(err).Msgf("Report path is not writable: %s", reportPath)
|
||||
logging.Fatal().Err(err).Msgf("Report path is not writable: %s", reportPath)
|
||||
} else {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(reportPath)
|
||||
@@ -288,8 +294,8 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
||||
// Build report writer.
|
||||
var (
|
||||
reporter report.Reporter
|
||||
reportFormat = mustGetStringFlag("report-format")
|
||||
reportTemplate = mustGetStringFlag("report-template")
|
||||
reportFormat = mustGetStringFlag(cmd, "report-format")
|
||||
reportTemplate = mustGetStringFlag(cmd, "report-template")
|
||||
)
|
||||
switch strings.TrimSpace(strings.ToLower(reportFormat)) {
|
||||
case "csv":
|
||||
@@ -304,15 +310,15 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
||||
}
|
||||
case "template":
|
||||
if reporter, err = report.NewTemplateReporter(reportTemplate); err != nil {
|
||||
log.Fatal().Err(err).Msg("Invalid report template")
|
||||
logging.Fatal().Err(err).Msg("Invalid report template")
|
||||
}
|
||||
default:
|
||||
log.Fatal().Msgf("unknown report format %s", reportFormat)
|
||||
logging.Fatal().Msgf("unknown report format %s", reportFormat)
|
||||
}
|
||||
|
||||
// Sanity check.
|
||||
if reportTemplate != "" && reportFormat != "template" {
|
||||
log.Fatal().Msgf("Report format must be 'template' if --report-template is specified")
|
||||
logging.Fatal().Msgf("Report format must be 'template' if --report-template is specified")
|
||||
}
|
||||
|
||||
detector.ReportPath = reportPath
|
||||
@@ -322,14 +328,6 @@ func Detector(cmd *cobra.Command, cfg config.Config, source string) *detect.Dete
|
||||
return detector
|
||||
}
|
||||
|
||||
func mustGetStringFlag(name string) string {
|
||||
reportPath, err := rootCmd.Flags().GetString(name)
|
||||
if err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
return reportPath
|
||||
}
|
||||
|
||||
func bytesConvert(bytes uint64) string {
|
||||
unit := ""
|
||||
value := float32(bytes)
|
||||
@@ -358,27 +356,27 @@ func bytesConvert(bytes uint64) string {
|
||||
}
|
||||
|
||||
func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding, exitCode int, start time.Time, err error) {
|
||||
totalBytes := atomic.LoadUint64(&detector.TotalBytes)
|
||||
totalBytes := detector.TotalBytes.Load()
|
||||
bytesMsg := fmt.Sprintf("scanned ~%d bytes (%s)", totalBytes, bytesConvert(totalBytes))
|
||||
if err == nil {
|
||||
log.Info().Msgf("%s in %s", bytesMsg, FormatDuration(time.Since(start)))
|
||||
logging.Info().Msgf("%s in %s", bytesMsg, FormatDuration(time.Since(start)))
|
||||
if len(findings) != 0 {
|
||||
log.Warn().Msgf("leaks found: %d", len(findings))
|
||||
logging.Warn().Msgf("leaks found: %d", len(findings))
|
||||
} else {
|
||||
log.Info().Msg("no leaks found")
|
||||
logging.Info().Msg("no leaks found")
|
||||
}
|
||||
} else {
|
||||
log.Warn().Msg(bytesMsg)
|
||||
log.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
|
||||
logging.Warn().Msg(bytesMsg)
|
||||
logging.Warn().Msgf("partial scan completed in %s", FormatDuration(time.Since(start)))
|
||||
if len(findings) != 0 {
|
||||
log.Warn().Msgf("%d leaks found in partial scan", len(findings))
|
||||
logging.Warn().Msgf("%d leaks found in partial scan", len(findings))
|
||||
} else {
|
||||
log.Warn().Msg("no leaks found in partial scan")
|
||||
logging.Warn().Msg("no leaks found in partial scan")
|
||||
}
|
||||
}
|
||||
|
||||
// write report if desired
|
||||
if detector.Reporter != nil && len(findings) > 0 {
|
||||
if detector.Reporter != nil {
|
||||
var (
|
||||
file io.WriteCloser
|
||||
reportErr error
|
||||
@@ -403,7 +401,7 @@ func findingSummaryAndExit(detector *detect.Detector, findings []report.Finding,
|
||||
|
||||
ReportEnd:
|
||||
if reportErr != nil {
|
||||
log.Fatal().Err(reportErr).Msg("failed to write report")
|
||||
logging.Fatal().Err(reportErr).Msg("failed to write report")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,3 +437,27 @@ func FormatDuration(d time.Duration) string {
|
||||
}
|
||||
return d.Round(scale / 100).String()
|
||||
}
|
||||
|
||||
func mustGetBoolFlag(cmd *cobra.Command, name string) bool {
|
||||
value, err := cmd.Flags().GetBool(name)
|
||||
if err != nil {
|
||||
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func mustGetIntFlag(cmd *cobra.Command, name string) int {
|
||||
value, err := cmd.Flags().GetInt(name)
|
||||
if err != nil {
|
||||
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func mustGetStringFlag(cmd *cobra.Command, name string) string {
|
||||
value, err := cmd.Flags().GetString(name)
|
||||
if err != nil {
|
||||
logging.Fatal().Err(err).Msgf("could not get flag: %s", name)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package scm
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Platform int
|
||||
|
||||
const (
|
||||
NoPlatform Platform = iota
|
||||
GitHubPlatform
|
||||
GitLabPlatform
|
||||
// TODO: Add others.
|
||||
)
|
||||
|
||||
func (p Platform) String() string {
|
||||
return [...]string{
|
||||
"none",
|
||||
"github",
|
||||
"gitlab",
|
||||
}[p]
|
||||
}
|
||||
|
||||
func PlatformFromString(s string) (Platform, error) {
|
||||
switch strings.ToLower(s) {
|
||||
case "", "none":
|
||||
return NoPlatform, nil
|
||||
case "github":
|
||||
return GitHubPlatform, nil
|
||||
case "gitlab":
|
||||
return GitLabPlatform, nil
|
||||
default:
|
||||
return NoPlatform, fmt.Errorf("invalid scm platform value: %s", s)
|
||||
}
|
||||
}
|
||||
+12
-19
@@ -4,10 +4,9 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -20,31 +19,25 @@ var stdInCmd = &cobra.Command{
|
||||
Run: runStdIn,
|
||||
}
|
||||
|
||||
func runStdIn(cmd *cobra.Command, args []string) {
|
||||
initConfig(".")
|
||||
var (
|
||||
findings []report.Finding
|
||||
err error
|
||||
)
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
cfg := Config(cmd)
|
||||
|
||||
func runStdIn(cmd *cobra.Command, _ []string) {
|
||||
// start timer
|
||||
start := time.Now()
|
||||
|
||||
// setup config (aka, the thing that defines rules)
|
||||
initConfig(".")
|
||||
cfg := Config(cmd)
|
||||
|
||||
// create detector
|
||||
detector := Detector(cmd, cfg, "")
|
||||
|
||||
// set exit code
|
||||
exitCode, err := cmd.Flags().GetInt("exit-code")
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("could not get exit code")
|
||||
}
|
||||
// parse flag(s)
|
||||
exitCode := mustGetIntFlag(cmd, "exit-code")
|
||||
|
||||
findings, err = detector.DetectReader(os.Stdin, 10)
|
||||
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().Err(err).Msg("failed scan input from stdin")
|
||||
logging.Fatal().Err(err).Msg("failed scan input from stdin")
|
||||
}
|
||||
|
||||
findingSummaryAndExit(detector, findings, exitCode, start, err)
|
||||
|
||||
+10
-8
@@ -4,8 +4,9 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
type AllowlistMatchCondition int
|
||||
@@ -56,16 +57,17 @@ type Allowlist struct {
|
||||
}
|
||||
|
||||
// CommitAllowed returns true if the commit is allowed to be ignored.
|
||||
func (a *Allowlist) CommitAllowed(c string) bool {
|
||||
func (a *Allowlist) CommitAllowed(c string) (bool, string) {
|
||||
if c == "" {
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
for _, commit := range a.Commits {
|
||||
if commit == c {
|
||||
return true
|
||||
return true, c
|
||||
}
|
||||
}
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// PathAllowed returns true if the path is allowed to be ignored.
|
||||
@@ -78,14 +80,14 @@ func (a *Allowlist) RegexAllowed(secret string) bool {
|
||||
return anyRegexMatch(secret, a.Regexes)
|
||||
}
|
||||
|
||||
func (a *Allowlist) ContainsStopWord(s string) bool {
|
||||
func (a *Allowlist) ContainsStopWord(s string) (bool, string) {
|
||||
s = strings.ToLower(s)
|
||||
for _, stopWord := range a.StopWords {
|
||||
if strings.Contains(s, strings.ToLower(stopWord)) {
|
||||
return true
|
||||
return true, stopWord
|
||||
}
|
||||
}
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
func (a *Allowlist) Validate() error {
|
||||
|
||||
@@ -7,7 +7,8 @@ import (
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/stretchr/testify/assert"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func TestCommitAllowed(t *testing.T) {
|
||||
@@ -39,7 +40,8 @@ func TestCommitAllowed(t *testing.T) {
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.commitAllowed, tt.allowlist.CommitAllowed(tt.commit))
|
||||
isAllowed, _ := tt.allowlist.CommitAllowed(tt.commit)
|
||||
assert.Equal(t, tt.commitAllowed, isAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+45
-15
@@ -6,9 +6,10 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
//go:embed gitleaks.toml
|
||||
@@ -76,9 +77,10 @@ type Config struct {
|
||||
// Extend is a struct that allows users to define how they want their
|
||||
// configuration extended by other configuration files.
|
||||
type Extend struct {
|
||||
Path string
|
||||
URL string
|
||||
UseDefault bool
|
||||
Path string
|
||||
URL string
|
||||
UseDefault bool
|
||||
DisabledRules []string
|
||||
}
|
||||
|
||||
func (vc *ViperConfig) Translate() (Config, error) {
|
||||
@@ -204,7 +206,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
|
||||
if maxExtendDepth != extendDepth {
|
||||
// disallow both usedefault and path from being set
|
||||
if c.Extend.Path != "" && c.Extend.UseDefault {
|
||||
log.Fatal().Msg("unable to load config due to extend.path and extend.useDefault being set")
|
||||
logging.Fatal().Msg("unable to load config due to extend.path and extend.useDefault being set")
|
||||
}
|
||||
if c.Extend.UseDefault {
|
||||
c.extendDefault()
|
||||
@@ -215,7 +217,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
|
||||
|
||||
// Validate the rules after everything has been assembled (including extended configs).
|
||||
if extendDepth == 0 {
|
||||
for _, rule := range rulesMap {
|
||||
for _, rule := range c.Rules {
|
||||
if err := rule.Validate(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
@@ -239,20 +241,20 @@ func (c *Config) extendDefault() {
|
||||
extendDepth++
|
||||
viper.SetConfigType("toml")
|
||||
if err := viper.ReadConfig(strings.NewReader(DefaultConfig)); err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
defaultViperConfig := ViperConfig{}
|
||||
if err := viper.Unmarshal(&defaultViperConfig); err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
cfg, err := defaultViperConfig.Translate()
|
||||
if err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
log.Debug().Msg("extending config with default config")
|
||||
logging.Debug().Msg("extending config with default config")
|
||||
c.extend(cfg)
|
||||
|
||||
}
|
||||
@@ -261,20 +263,20 @@ func (c *Config) extendPath() {
|
||||
extendDepth++
|
||||
viper.SetConfigFile(c.Extend.Path)
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
extensionViperConfig := ViperConfig{}
|
||||
if err := viper.Unmarshal(&extensionViperConfig); err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
cfg, err := extensionViperConfig.Translate()
|
||||
if err != nil {
|
||||
log.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
logging.Fatal().Msgf("failed to load extended config, err: %s", err)
|
||||
return
|
||||
}
|
||||
log.Debug().Msgf("extending config with %s", c.Extend.Path)
|
||||
logging.Debug().Msgf("extending config with %s", c.Extend.Path)
|
||||
c.extend(cfg)
|
||||
}
|
||||
|
||||
@@ -283,7 +285,35 @@ func (c *Config) extendURL() {
|
||||
}
|
||||
|
||||
func (c *Config) extend(extensionConfig Config) {
|
||||
// Get config name for helpful log messages.
|
||||
var configName string
|
||||
if c.Extend.Path != "" {
|
||||
configName = c.Extend.Path
|
||||
} else {
|
||||
configName = "default"
|
||||
}
|
||||
// Convert |Config.DisabledRules| into a map for ease of access.
|
||||
disabledRuleIDs := map[string]struct{}{}
|
||||
for _, id := range c.Extend.DisabledRules {
|
||||
if _, ok := extensionConfig.Rules[id]; !ok {
|
||||
logging.Warn().
|
||||
Str("rule-id", id).
|
||||
Str("config", configName).
|
||||
Msg("Disabled rule doesn't exist in extended config.")
|
||||
}
|
||||
disabledRuleIDs[id] = struct{}{}
|
||||
}
|
||||
|
||||
for ruleID, baseRule := range extensionConfig.Rules {
|
||||
// Skip the rule.
|
||||
if _, ok := disabledRuleIDs[ruleID]; ok {
|
||||
logging.Debug().
|
||||
Str("rule-id", ruleID).
|
||||
Str("config", configName).
|
||||
Msg("Ignoring rule from extended config.")
|
||||
continue
|
||||
}
|
||||
|
||||
currentRule, ok := c.Rules[ruleID]
|
||||
if !ok {
|
||||
// Rule doesn't exist, add it to the config.
|
||||
|
||||
+27
-13
@@ -5,11 +5,11 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
const configPath = "../testdata/config/"
|
||||
@@ -39,8 +39,7 @@ func TestTranslate(t *testing.T) {
|
||||
Regexes: []*regexp.Regexp{regexp.MustCompile("123")},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -73,8 +72,7 @@ func TestTranslate(t *testing.T) {
|
||||
Regexes: []*regexp.Regexp{regexp.MustCompile("AKIALALEMEL33243OLIA")},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -92,8 +90,7 @@ func TestTranslate(t *testing.T) {
|
||||
Commits: []string{"allowthiscommit"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -111,8 +108,7 @@ func TestTranslate(t *testing.T) {
|
||||
Paths: []*regexp.Regexp{regexp.MustCompile(".go")},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -122,12 +118,11 @@ func TestTranslate(t *testing.T) {
|
||||
RuleID: "discord-api-key",
|
||||
Description: "Discord API key",
|
||||
Regex: regexp.MustCompile(`(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-h0-9]{64})['\"]`),
|
||||
Keywords: []string{},
|
||||
Entropy: 3.5,
|
||||
SecretGroup: 3,
|
||||
Keywords: []string{},
|
||||
Tags: []string{},
|
||||
},
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -350,6 +345,25 @@ func TestTranslate(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
cfgName: "extend_disabled",
|
||||
cfg: Config{
|
||||
Rules: map[string]Rule{
|
||||
"aws-secret-key": {
|
||||
RuleID: "aws-secret-key",
|
||||
Regex: regexp.MustCompile(`(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}`),
|
||||
Tags: []string{"key", "AWS"},
|
||||
Keywords: []string{},
|
||||
},
|
||||
"pypi-upload-token": {
|
||||
RuleID: "pypi-upload-token",
|
||||
Regex: regexp.MustCompile(`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
|
||||
Tags: []string{},
|
||||
Keywords: []string{},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
+224
-188
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -4,7 +4,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
// Rules contain information that define details on how to detect secrets
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
)
|
||||
|
||||
func anyRegexMatch(f string, res []*regexp.Regexp) bool {
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import (
|
||||
"regexp"
|
||||
"unicode"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
var b64LikelyChars [128]byte
|
||||
@@ -227,7 +227,7 @@ func (d *Decoder) findEncodedSegments(data string, parentSegments []EncodedSegme
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().Msgf("segment found: %#v", segment)
|
||||
logging.Debug().Msgf("segment found: %#v", segment)
|
||||
segments = append(segments, segment)
|
||||
}
|
||||
|
||||
|
||||
+80
-70
@@ -5,18 +5,18 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
|
||||
ahocorasick "github.com/BobuSumisu/aho-corasick"
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/exp/maps"
|
||||
)
|
||||
@@ -89,7 +89,7 @@ type Detector struct {
|
||||
ReportPath string
|
||||
Reporter report.Reporter
|
||||
|
||||
TotalBytes uint64
|
||||
TotalBytes atomic.Uint64
|
||||
}
|
||||
|
||||
// Fragment contains the data to be scanned
|
||||
@@ -144,7 +144,7 @@ func NewDetectorDefaultConfig() (*Detector, error) {
|
||||
}
|
||||
|
||||
func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
|
||||
log.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
|
||||
logging.Debug().Msgf("found .gitleaksignore file: %s", gitleaksIgnorePath)
|
||||
file, err := os.Open(gitleaksIgnorePath)
|
||||
|
||||
if err != nil {
|
||||
@@ -154,7 +154,7 @@ func (d *Detector) AddGitleaksIgnore(gitleaksIgnorePath string) error {
|
||||
// https://github.com/securego/gosec/issues/512
|
||||
defer func() {
|
||||
if err := file.Close(); err != nil {
|
||||
log.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
|
||||
logging.Warn().Msgf("Error closing .gitleaksignore file: %s\n", err)
|
||||
}
|
||||
}()
|
||||
scanner := bufio.NewScanner(file)
|
||||
@@ -184,9 +184,9 @@ func (d *Detector) DetectString(content string) []report.Finding {
|
||||
// Detect scans the given fragment and returns a list of findings
|
||||
func (d *Detector) Detect(fragment Fragment) []report.Finding {
|
||||
if fragment.Bytes == nil {
|
||||
atomic.AddUint64(&d.TotalBytes, uint64(len(fragment.Raw)))
|
||||
d.TotalBytes.Add(uint64(len(fragment.Raw)))
|
||||
}
|
||||
atomic.AddUint64(&d.TotalBytes, uint64(len(fragment.Bytes)))
|
||||
d.TotalBytes.Add(uint64(len(fragment.Bytes)))
|
||||
|
||||
var findings []report.Finding
|
||||
|
||||
@@ -256,11 +256,10 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
var (
|
||||
findings []report.Finding
|
||||
logger = func() zerolog.Logger {
|
||||
l := log.With().Str("rule-id", r.RuleID)
|
||||
l := logging.With().Str("rule-id", r.RuleID).Str("path", fragment.FilePath)
|
||||
if fragment.CommitSHA != "" {
|
||||
l = l.Str("commit", fragment.CommitSHA)
|
||||
}
|
||||
l = l.Str("path", fragment.FilePath)
|
||||
return l.Logger()
|
||||
}()
|
||||
)
|
||||
@@ -268,9 +267,9 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
// check if filepath or commit is allowed for this rule
|
||||
for _, a := range r.Allowlists {
|
||||
var (
|
||||
isAllowed bool
|
||||
commitAllowed = a.CommitAllowed(fragment.CommitSHA)
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath)
|
||||
isAllowed bool
|
||||
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath)
|
||||
)
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
// Determine applicable checks.
|
||||
@@ -295,11 +294,14 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
isAllowed = commitAllowed || pathAllowed
|
||||
}
|
||||
if isAllowed {
|
||||
logger.Trace().
|
||||
Str("condition", a.MatchCondition.String()).
|
||||
Bool("commit-allowed", commitAllowed).
|
||||
Bool("path-allowed", commitAllowed).
|
||||
Msg("Skipping fragment due to rule allowlist")
|
||||
event := logger.Trace().Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Str("allowed-commit", commit)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
event.Msg("skipping file: rule allowlist")
|
||||
return findings
|
||||
}
|
||||
}
|
||||
@@ -335,7 +337,10 @@ func (d *Detector) detectRule(fragment Fragment, currentRaw string, r config.Rul
|
||||
if d.MaxTargetMegaBytes > 0 {
|
||||
rawLength := len(currentRaw) / 1000000
|
||||
if rawLength > d.MaxTargetMegaBytes {
|
||||
log.Debug().Msgf("skipping file: %s scan due to size: %d", fragment.FilePath, rawLength)
|
||||
logger.Debug().
|
||||
Int("size", rawLength).
|
||||
Int("max-size", d.MaxTargetMegaBytes).
|
||||
Msg("skipping fragment: size")
|
||||
return findings
|
||||
}
|
||||
}
|
||||
@@ -395,7 +400,7 @@ MatchLoop:
|
||||
strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex], gitleaksAllowSignature) {
|
||||
logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Msg("Skipping finding due to 'gitleaks:allow' signature")
|
||||
Msg("skipping finding: 'gitleaks:allow' signature")
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -411,21 +416,28 @@ MatchLoop:
|
||||
finding.Secret = groups[r.SecretGroup]
|
||||
} else {
|
||||
// If |secretGroup| is not set, we will use the first suitable capture group.
|
||||
if len(groups) == 2 {
|
||||
// Use the only group.
|
||||
finding.Secret = groups[1]
|
||||
} else {
|
||||
// Use the first non-empty group.
|
||||
for _, s := range groups[1:] {
|
||||
if len(s) > 0 {
|
||||
finding.Secret = s
|
||||
break
|
||||
}
|
||||
for _, s := range groups[1:] {
|
||||
if len(s) > 0 {
|
||||
finding.Secret = s
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check entropy
|
||||
entropy := shannonEntropy(finding.Secret)
|
||||
finding.Entropy = float32(entropy)
|
||||
if r.Entropy != 0.0 {
|
||||
// entropy is too low, skip this finding
|
||||
if entropy <= r.Entropy {
|
||||
logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Float32("entropy", finding.Entropy).
|
||||
Msg("skipping finding: low entropy")
|
||||
continue
|
||||
}
|
||||
}
|
||||
// check if the regexTarget is defined in the allowlist "regexes" entry
|
||||
// or if the secret is in the list of stopwords
|
||||
globalAllowlistTarget := finding.Secret
|
||||
@@ -438,12 +450,13 @@ MatchLoop:
|
||||
if d.Config.Allowlist.RegexAllowed(globalAllowlistTarget) {
|
||||
logger.Trace().
|
||||
Str("finding", globalAllowlistTarget).
|
||||
Msg("Skipping finding due to global allowlist regex")
|
||||
Msg("skipping finding: global allowlist regex")
|
||||
continue
|
||||
} else if d.Config.Allowlist.ContainsStopWord(finding.Secret) {
|
||||
} else if ok, word := d.Config.Allowlist.ContainsStopWord(finding.Secret); ok {
|
||||
logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Msg("Skipping finding due to global allowlist stopword")
|
||||
Str("allowed-stopword", word).
|
||||
Msg("skipping finding: global allowlist stopword")
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -458,19 +471,24 @@ MatchLoop:
|
||||
}
|
||||
|
||||
var (
|
||||
isAllowed bool
|
||||
regexAllowed = a.RegexAllowed(allowlistTarget)
|
||||
containsStopword = a.ContainsStopWord(finding.Secret)
|
||||
isAllowed bool
|
||||
commitAllowed bool
|
||||
commit string
|
||||
pathAllowed bool
|
||||
regexAllowed = a.RegexAllowed(allowlistTarget)
|
||||
containsStopword, word = a.ContainsStopWord(finding.Secret)
|
||||
)
|
||||
// check if the secret is in the list of stopwords
|
||||
if a.MatchCondition == config.AllowlistMatchAnd {
|
||||
// Determine applicable checks.
|
||||
var allowlistChecks []bool
|
||||
if len(a.Commits) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, a.CommitAllowed(fragment.CommitSHA))
|
||||
commitAllowed, commit = a.CommitAllowed(fragment.CommitSHA)
|
||||
allowlistChecks = append(allowlistChecks, commitAllowed)
|
||||
}
|
||||
if len(a.Paths) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, a.PathAllowed(fragment.FilePath))
|
||||
pathAllowed = a.PathAllowed(fragment.FilePath)
|
||||
allowlistChecks = append(allowlistChecks, pathAllowed)
|
||||
}
|
||||
if len(a.Regexes) > 0 {
|
||||
allowlistChecks = append(allowlistChecks, regexAllowed)
|
||||
@@ -486,38 +504,25 @@ MatchLoop:
|
||||
}
|
||||
|
||||
if isAllowed {
|
||||
logger.Trace().
|
||||
event := logger.Trace().
|
||||
Str("finding", finding.Secret).
|
||||
Str("condition", a.MatchCondition.String()).
|
||||
Bool("regex-allowed", regexAllowed).
|
||||
Bool("contains-stopword", containsStopword).
|
||||
Msg("Skipping finding due to rule allowlist")
|
||||
Str("condition", a.MatchCondition.String())
|
||||
if commitAllowed {
|
||||
event.Str("allowed-commit", commit)
|
||||
}
|
||||
if pathAllowed {
|
||||
event.Bool("allowed-path", pathAllowed)
|
||||
}
|
||||
if regexAllowed {
|
||||
event.Bool("allowed-regex", regexAllowed)
|
||||
}
|
||||
if containsStopword {
|
||||
event.Str("allowed-stopword", word)
|
||||
}
|
||||
event.Msg("skipping finding: rule allowlist")
|
||||
continue MatchLoop
|
||||
}
|
||||
}
|
||||
|
||||
// check entropy
|
||||
entropy := shannonEntropy(finding.Secret)
|
||||
finding.Entropy = float32(entropy)
|
||||
if r.Entropy != 0.0 {
|
||||
if entropy <= r.Entropy {
|
||||
// entropy is too low, skip this finding
|
||||
continue
|
||||
}
|
||||
// NOTE: this is a goofy hack to get around the fact there golang's regex engine
|
||||
// does not support positive lookaheads. Ideally we would want to add a
|
||||
// restriction on generic rules regex that requires the secret match group
|
||||
// contains both numbers and alphabetical characters, not just alphabetical characters.
|
||||
// What this bit of code does is check if the ruleid is prepended with "generic" and enforces the
|
||||
// secret contains both digits and alphabetical characters.
|
||||
// TODO: this should be replaced with stop words
|
||||
if strings.HasPrefix(r.RuleID, "generic") {
|
||||
if !containsDigit(finding.Secret) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
findings = append(findings, finding)
|
||||
}
|
||||
return findings
|
||||
@@ -544,21 +549,26 @@ func (d *Detector) addFinding(finding report.Finding) {
|
||||
}
|
||||
|
||||
// check if we should ignore this finding
|
||||
logger := logging.With().Str("finding", finding.Secret).Logger()
|
||||
if _, ok := d.gitleaksIgnore[globalFingerprint]; ok {
|
||||
log.Debug().Msgf("ignoring finding with global Fingerprint %s",
|
||||
finding.Fingerprint)
|
||||
logger.Debug().
|
||||
Str("fingerprint", globalFingerprint).
|
||||
Msg("skipping finding: global fingerprint")
|
||||
return
|
||||
} else if finding.Commit != "" {
|
||||
// Awkward nested if because I'm not sure how to chain these two conditions.
|
||||
if _, ok := d.gitleaksIgnore[finding.Fingerprint]; ok {
|
||||
log.Debug().Msgf("ignoring finding with Fingerprint %s",
|
||||
finding.Fingerprint)
|
||||
logger.Debug().
|
||||
Str("fingerprint", finding.Fingerprint).
|
||||
Msgf("skipping finding: fingerprint")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if d.baseline != nil && !IsNew(finding, d.baseline) {
|
||||
log.Debug().Msgf("baseline duplicate -- ignoring finding with Fingerprint %s", finding.Fingerprint)
|
||||
logger.Debug().
|
||||
Str("fingerprint", finding.Fingerprint).
|
||||
Msgf("skipping finding: baseline")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+49
-36
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
@@ -11,9 +12,10 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
regexp "github.com/wasilibs/go-re2"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/config"
|
||||
"github.com/zricethezav/gitleaks/v8/regexp"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
"github.com/zricethezav/gitleaks/v8/sources"
|
||||
)
|
||||
@@ -503,9 +505,10 @@ func TestFromGit(t *testing.T) {
|
||||
}{
|
||||
{
|
||||
source: filepath.Join(repoBasePath, "small"),
|
||||
cfgName: "simple",
|
||||
cfgName: "simple", // the remote url is `git@github.com:gitleaks/test.git`
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "aws-access-key",
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 20,
|
||||
EndLine: 20,
|
||||
@@ -520,12 +523,13 @@ func TestFromGit(t *testing.T) {
|
||||
Author: "Zachary Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "Accidentally add a secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
Fingerprint: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587:main.go:aws-access-key:20",
|
||||
Link: "https://github.com/gitleaks/test/blob/1b6da43b82b22e4eaa10bcf8ee591e91abbfc587/main.go#L20",
|
||||
},
|
||||
{
|
||||
RuleID: "aws-access-key",
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
@@ -540,10 +544,10 @@ func TestFromGit(t *testing.T) {
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
|
||||
Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -553,6 +557,7 @@ func TestFromGit(t *testing.T) {
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "aws-access-key",
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 9,
|
||||
EndLine: 9,
|
||||
@@ -567,10 +572,10 @@ func TestFromGit(t *testing.T) {
|
||||
Author: "Zach Rice",
|
||||
Email: "zricer@protonmail.com",
|
||||
Message: "adding foo package with secret",
|
||||
RuleID: "aws-access-key",
|
||||
Tags: []string{"key", "AWS"},
|
||||
Entropy: 3.0841837,
|
||||
Fingerprint: "491504d5a31946ce75e22554cc34203d8e5ff3ca:foo/foo.go:aws-access-key:9",
|
||||
Link: "https://github.com/gitleaks/test/blob/491504d5a31946ce75e22554cc34203d8e5ff3ca/foo/foo.go#L9",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -580,41 +585,46 @@ func TestFromGit(t *testing.T) {
|
||||
defer moveDotGit(t, ".git", "dotGit")
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(strings.Join([]string{tt.cfgName, tt.logOpts}, "/"), func(t *testing.T) {
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
require.NoError(t, err)
|
||||
|
||||
viper.AddConfigPath(configPath)
|
||||
viper.SetConfigName("simple")
|
||||
viper.SetConfigType("toml")
|
||||
err := viper.ReadInConfig()
|
||||
require.NoError(t, err)
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
require.NoError(t, err)
|
||||
cfg, err := vc.Translate()
|
||||
require.NoError(t, err)
|
||||
detector := NewDetector(cfg)
|
||||
|
||||
var vc config.ViperConfig
|
||||
err = viper.Unmarshal(&vc)
|
||||
require.NoError(t, err)
|
||||
cfg, err := vc.Translate()
|
||||
require.NoError(t, err)
|
||||
detector := NewDetector(cfg)
|
||||
var ignorePath string
|
||||
info, err := os.Stat(tt.source)
|
||||
require.NoError(t, err)
|
||||
|
||||
var ignorePath string
|
||||
info, err := os.Stat(tt.source)
|
||||
require.NoError(t, err)
|
||||
if info.IsDir() {
|
||||
ignorePath = filepath.Join(tt.source, ".gitleaksignore")
|
||||
} else {
|
||||
ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
|
||||
}
|
||||
err = detector.AddGitleaksIgnore(ignorePath)
|
||||
require.NoError(t, err)
|
||||
|
||||
if info.IsDir() {
|
||||
ignorePath = filepath.Join(tt.source, ".gitleaksignore")
|
||||
} else {
|
||||
ignorePath = filepath.Join(filepath.Dir(tt.source), ".gitleaksignore")
|
||||
}
|
||||
err = detector.AddGitleaksIgnore(ignorePath)
|
||||
require.NoError(t, err)
|
||||
gitCmd, err := sources.NewGitLogCmd(tt.source, tt.logOpts)
|
||||
require.NoError(t, err)
|
||||
|
||||
gitCmd, err := sources.NewGitLogCmd(tt.source, tt.logOpts)
|
||||
require.NoError(t, err)
|
||||
findings, err := detector.DetectGit(gitCmd)
|
||||
require.NoError(t, err)
|
||||
remote, err := NewRemoteInfo(scm.NoPlatform, tt.source)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, f := range findings {
|
||||
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
findings, err := detector.DetectGit(gitCmd, remote)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, f := range findings {
|
||||
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
|
||||
}
|
||||
assert.ElementsMatch(t, tt.expectedFindings, findings)
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestFromGitStaged(t *testing.T) {
|
||||
@@ -629,6 +639,7 @@ func TestFromGitStaged(t *testing.T) {
|
||||
cfgName: "simple",
|
||||
expectedFindings: []report.Finding{
|
||||
{
|
||||
RuleID: "aws-access-key",
|
||||
Description: "AWS Access Key",
|
||||
StartLine: 7,
|
||||
EndLine: 7,
|
||||
@@ -649,8 +660,8 @@ func TestFromGitStaged(t *testing.T) {
|
||||
"key",
|
||||
"AWS",
|
||||
},
|
||||
RuleID: "aws-access-key",
|
||||
Fingerprint: "api/api.go:aws-access-key:7",
|
||||
Link: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -677,7 +688,9 @@ func TestFromGitStaged(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
gitCmd, err := sources.NewGitDiffCmd(tt.source, true)
|
||||
require.NoError(t, err)
|
||||
findings, err := detector.DetectGit(gitCmd)
|
||||
remote, err := NewRemoteInfo(scm.NoPlatform, tt.source)
|
||||
require.NoError(t, err)
|
||||
findings, err := detector.DetectGit(gitCmd, remote)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, f := range findings {
|
||||
|
||||
+95
-56
@@ -1,14 +1,15 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/h2non/filetype"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
"github.com/zricethezav/gitleaks/v8/sources"
|
||||
)
|
||||
@@ -18,7 +19,7 @@ const maxPeekSize = 25 * 1_000 // 10kb
|
||||
func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Finding, error) {
|
||||
for pa := range paths {
|
||||
d.Sema.Go(func() error {
|
||||
logger := log.With().Str("path", pa.Path).Logger()
|
||||
logger := logging.With().Str("path", pa.Path).Logger()
|
||||
logger.Trace().Msg("Scanning path")
|
||||
|
||||
f, err := os.Open(pa.Path)
|
||||
@@ -49,64 +50,32 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
|
||||
}
|
||||
}
|
||||
|
||||
// Buffer to hold file chunks
|
||||
buf := make([]byte, chunkSize)
|
||||
totalLines := 0
|
||||
var (
|
||||
// Buffer to hold file chunks
|
||||
reader = bufio.NewReaderSize(f, chunkSize)
|
||||
buf = make([]byte, chunkSize)
|
||||
totalLines = 0
|
||||
)
|
||||
for {
|
||||
n, err := f.Read(buf)
|
||||
n, err := reader.Read(buf)
|
||||
|
||||
// "Callers should always process the n > 0 bytes returned before considering the error err."
|
||||
// https://pkg.go.dev/io#Reader
|
||||
if n > 0 {
|
||||
// TODO: optimization could 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
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// If the chunk doesn't end in a newline, peek |maxPeekSize| until we find one.
|
||||
// This hopefully avoids splitting
|
||||
// See: https://github.com/gitleaks/gitleaks/issues/1651
|
||||
var (
|
||||
peekBuf = bytes.NewBuffer(buf[:n])
|
||||
tempBuf = make([]byte, 1)
|
||||
newlineCount = 0 // Tracks consecutive newlines
|
||||
)
|
||||
for {
|
||||
data := peekBuf.Bytes()
|
||||
if len(data) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Check if the last character is a newline.
|
||||
lastChar := data[len(data)-1]
|
||||
if lastChar == '\n' || lastChar == '\r' {
|
||||
newlineCount++
|
||||
|
||||
// Stop if two consecutive newlines are found
|
||||
if newlineCount >= 2 {
|
||||
break
|
||||
}
|
||||
} 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
|
||||
m, readErr := f.Read(tempBuf)
|
||||
if m > 0 {
|
||||
peekBuf.Write(tempBuf[:m])
|
||||
}
|
||||
|
||||
// Stop if EOF is reached
|
||||
if readErr != nil {
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
return readErr
|
||||
}
|
||||
// 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 readErr
|
||||
}
|
||||
|
||||
// Count the number of newlines in this chunk
|
||||
@@ -145,3 +114,73 @@ func (d *Detector) DetectFiles(paths <-chan sources.ScanTarget) ([]report.Findin
|
||||
|
||||
return d.findings, nil
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_readUntilSafeBoundary(t *testing.T) {
|
||||
// Arrange
|
||||
cases := []struct {
|
||||
name string
|
||||
r io.Reader
|
||||
expected string
|
||||
}{
|
||||
// Current split is fine, exit early.
|
||||
{
|
||||
name: "safe original split - LF",
|
||||
r: strings.NewReader("abc\n\ndefghijklmnop\n\nqrstuvwxyz"),
|
||||
expected: "abc\n\n",
|
||||
},
|
||||
{
|
||||
name: "safe original split - CRLF",
|
||||
r: strings.NewReader("a\r\n\r\nbcdefghijklmnop\n"),
|
||||
expected: "a\r\n\r\n",
|
||||
},
|
||||
// Current split is bad, look for a better one.
|
||||
{
|
||||
name: "safe split - LF",
|
||||
r: strings.NewReader("abcdefg\nhijklmnop\n\nqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnop\n\n",
|
||||
},
|
||||
{
|
||||
name: "safe split - CRLF",
|
||||
r: strings.NewReader("abcdefg\r\nhijklmnop\r\n\r\nqrstuvwxyz"),
|
||||
expected: "abcdefg\r\nhijklmnop\r\n\r\n",
|
||||
},
|
||||
{
|
||||
name: "safe split - blank line",
|
||||
r: strings.NewReader("abcdefg\nhijklmnop\n\t \t\nqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnop\n\t \t\n",
|
||||
},
|
||||
// Current split is bad, exhaust options.
|
||||
{
|
||||
name: "no safe split",
|
||||
r: strings.NewReader("abcdefg\nhijklmnopqrstuvwxyz"),
|
||||
expected: "abcdefg\nhijklmnopqrstuvwx",
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
buf := make([]byte, 5)
|
||||
n, err := c.r.Read(buf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Act
|
||||
reader := bufio.NewReader(c.r)
|
||||
peekBuf := bytes.NewBuffer(buf[:n])
|
||||
err = readUntilSafeBoundary(reader, n, 20, peekBuf)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Assert
|
||||
t.Logf(peekBuf.String())
|
||||
require.Equal(t, c.expected, string(peekBuf.Bytes()))
|
||||
})
|
||||
}
|
||||
}
|
||||
+108
-9
@@ -1,16 +1,28 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
func (d *Detector) DetectGit(gitCmd *sources.GitCmd) ([]report.Finding, error) {
|
||||
defer gitCmd.Wait()
|
||||
diffFilesCh := gitCmd.DiffFilesCh()
|
||||
errCh := gitCmd.ErrCh()
|
||||
func (d *Detector) DetectGit(cmd *sources.GitCmd, remote *RemoteInfo) ([]report.Finding, error) {
|
||||
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 {
|
||||
@@ -30,7 +42,8 @@ func (d *Detector) DetectGit(gitCmd *sources.GitCmd) ([]report.Finding, error) {
|
||||
commitSHA := ""
|
||||
if gitdiffFile.PatchHeader != nil {
|
||||
commitSHA = gitdiffFile.PatchHeader.SHA
|
||||
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
|
||||
if ok, c := d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA); ok {
|
||||
logging.Trace().Str("allowed-commit", c).Msg("skipping commit: global allowlist")
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -49,7 +62,7 @@ func (d *Detector) DetectGit(gitCmd *sources.GitCmd) ([]report.Finding, error) {
|
||||
}
|
||||
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
|
||||
d.addFinding(augmentGitFinding(remote.Platform, remote.Url, finding, textFragment, gitdiffFile))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -67,7 +80,93 @@ func (d *Detector) DetectGit(gitCmd *sources.GitCmd) ([]report.Finding, error) {
|
||||
if err := d.Sema.Wait(); err != nil {
|
||||
return d.findings, err
|
||||
}
|
||||
log.Info().Msgf("%d commits scanned.", len(d.commitMap))
|
||||
log.Debug().Msg("Note: this number might be smaller than expected due to commits with no additions")
|
||||
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
|
||||
}
|
||||
|
||||
type RemoteInfo struct {
|
||||
Platform scm.Platform
|
||||
Url string
|
||||
}
|
||||
|
||||
func NewRemoteInfo(platform scm.Platform, source string) (*RemoteInfo, error) {
|
||||
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
|
||||
goto End
|
||||
}
|
||||
return nil, fmt.Errorf("unable to get remote URL: %w", err)
|
||||
}
|
||||
|
||||
if platform == scm.NoPlatform {
|
||||
platform = platformFromHost(remoteUrl)
|
||||
if platform == scm.NoPlatform {
|
||||
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,
|
||||
}, nil
|
||||
}
|
||||
|
||||
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
|
||||
default:
|
||||
return scm.NoPlatform
|
||||
}
|
||||
}
|
||||
+13
-7
@@ -2,6 +2,7 @@ package detect
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
@@ -10,18 +11,23 @@ import (
|
||||
// DetectReader accepts an io.Reader and a buffer size for the reader in KB
|
||||
func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, error) {
|
||||
reader := bufio.NewReader(r)
|
||||
buf := make([]byte, 0, 1000*bufSize)
|
||||
buf := make([]byte, 1000*bufSize)
|
||||
findings := []report.Finding{}
|
||||
|
||||
for {
|
||||
n, err := reader.Read(buf[:cap(buf)])
|
||||
n, err := reader.Read(buf)
|
||||
|
||||
// "Callers should always process the n > 0 bytes returned before considering the error err."
|
||||
// https://pkg.go.dev/io#Reader
|
||||
if n > 0 {
|
||||
buf = buf[:n]
|
||||
// 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: string(buf),
|
||||
Raw: peekBuf.String(),
|
||||
}
|
||||
for _, finding := range d.Detect(fragment) {
|
||||
findings = append(findings, finding)
|
||||
@@ -32,10 +38,10 @@ func (d *Detector) DetectReader(r io.Reader, bufSize int) ([]report.Finding, err
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
return findings, err
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
break
|
||||
return findings, err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/require"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -13,11 +14,17 @@ const secret = "AKIAIRYLJVKMPEGZMPJS"
|
||||
|
||||
type mockReader struct {
|
||||
data []byte
|
||||
read bool
|
||||
}
|
||||
|
||||
func (r *mockReader) Read(p []byte) (n int, err error) {
|
||||
if r.read {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
// Copy data to the provided buffer.
|
||||
n = copy(p, r.data)
|
||||
r.read = true
|
||||
|
||||
// Return io.EOF along with the bytes.
|
||||
return n, io.EOF
|
||||
|
||||
+60
-15
@@ -4,20 +4,21 @@ import (
|
||||
// "encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// augmentGitFinding updates the start and end line numbers of a finding to include the
|
||||
// delta from the git diff
|
||||
func augmentGitFinding(finding report.Finding, textFragment *gitdiff.TextFragment, f *gitdiff.File) report.Finding {
|
||||
func augmentGitFinding(scmPlatform scm.Platform, remoteUrl string, 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)
|
||||
@@ -25,16 +26,64 @@ func augmentGitFinding(finding report.Finding, textFragment *gitdiff.TextFragmen
|
||||
|
||||
if f.PatchHeader != nil {
|
||||
finding.Commit = f.PatchHeader.SHA
|
||||
finding.Message = f.PatchHeader.Message()
|
||||
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(scmPlatform, remoteUrl, finding)
|
||||
}
|
||||
}
|
||||
return finding
|
||||
}
|
||||
|
||||
var linkCleaner = strings.NewReplacer(
|
||||
" ", "%20",
|
||||
"%", "%25",
|
||||
)
|
||||
|
||||
func createScmLink(scmPlatform scm.Platform, remoteUrl string, finding report.Finding) string {
|
||||
if scmPlatform == scm.NoPlatform {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Clean the path.
|
||||
var (
|
||||
filePath = linkCleaner.Replace(finding.File)
|
||||
ext = strings.ToLower(filepath.Ext(filePath))
|
||||
)
|
||||
|
||||
switch scmPlatform {
|
||||
case scm.GitHubPlatform:
|
||||
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
|
||||
if ext == ".ipynb" || ext == ".md" {
|
||||
link += "?plain=1"
|
||||
}
|
||||
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.GitLabPlatform:
|
||||
link := fmt.Sprintf("%s/blob/%s/%s", remoteUrl, finding.Commit, filePath)
|
||||
if finding.StartLine != 0 {
|
||||
link += fmt.Sprintf("#L%d", finding.StartLine)
|
||||
}
|
||||
if finding.EndLine != finding.StartLine {
|
||||
link += fmt.Sprintf("-%d", finding.EndLine)
|
||||
}
|
||||
return link
|
||||
default:
|
||||
// This should never happen.
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// shannonEntropy calculates the entropy of data using the formula defined here:
|
||||
// https://en.wiktionary.org/wiki/Shannon_entropy
|
||||
// Another way to think about what this is doing is calculating the number of bits
|
||||
@@ -74,7 +123,7 @@ func filter(findings []report.Finding, redact uint) []report.Finding {
|
||||
|
||||
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
|
||||
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
|
||||
log.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
|
||||
logging.Trace().Msgf("skipping %s finding (%s), %s rule takes precedence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
|
||||
include = false
|
||||
break
|
||||
}
|
||||
@@ -177,16 +226,12 @@ func printFinding(f report.Finding, noColor bool) {
|
||||
fmt.Printf("%-12s %s\n", "Email:", f.Email)
|
||||
fmt.Printf("%-12s %s\n", "Date:", f.Date)
|
||||
fmt.Printf("%-12s %s\n", "Fingerprint:", f.Fingerprint)
|
||||
if f.Link != "" {
|
||||
fmt.Printf("%-12s %s\n", "Link:", f.Link)
|
||||
}
|
||||
fmt.Println("")
|
||||
}
|
||||
|
||||
func containsDigit(s string) bool {
|
||||
for _, c := range s {
|
||||
switch c {
|
||||
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
return false
|
||||
func isWhitespace(ch byte) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package detect
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/cmd/scm"
|
||||
"github.com/zricethezav/gitleaks/v8/report"
|
||||
)
|
||||
|
||||
func Test_createScmLink(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
platform scm.Platform
|
||||
url string
|
||||
finding report.Finding
|
||||
want string
|
||||
}{
|
||||
// None
|
||||
"no platform": {
|
||||
platform: scm.NoPlatform,
|
||||
want: "",
|
||||
},
|
||||
|
||||
// GitHub
|
||||
"github - single line": {
|
||||
platform: scm.GitHubPlatform,
|
||||
url: "https://github.com/gitleaks/test",
|
||||
finding: report.Finding{
|
||||
Commit: "20553ad96a4a080c94a54d677db97eed8ce2560d",
|
||||
File: "metrics/% of sales/.env",
|
||||
StartLine: 25,
|
||||
EndLine: 25,
|
||||
},
|
||||
want: "https://github.com/gitleaks/test/blob/20553ad96a4a080c94a54d677db97eed8ce2560d/metrics/%25%20of%20sales/.env#L25",
|
||||
},
|
||||
"github - multi line": {
|
||||
platform: scm.GitHubPlatform,
|
||||
url: "https://github.com/gitleaks/test",
|
||||
finding: report.Finding{
|
||||
Commit: "7bad9f7654cf9701b62400281748c0e8efd97666",
|
||||
File: "config.json",
|
||||
StartLine: 235,
|
||||
EndLine: 238,
|
||||
},
|
||||
want: "https://github.com/gitleaks/test/blob/7bad9f7654cf9701b62400281748c0e8efd97666/config.json#L235-L238",
|
||||
},
|
||||
"github - markdown": {
|
||||
platform: scm.GitHubPlatform,
|
||||
url: "https://github.com/gitleaks/test",
|
||||
finding: report.Finding{
|
||||
Commit: "1fc8961d172f39ffb671766e472aa76f8d713e87",
|
||||
File: "docs/guides/ecosystem/discordjs.MD",
|
||||
StartLine: 34,
|
||||
EndLine: 34,
|
||||
},
|
||||
want: "https://github.com/gitleaks/test/blob/1fc8961d172f39ffb671766e472aa76f8d713e87/docs/guides/ecosystem/discordjs.MD?plain=1#L34",
|
||||
},
|
||||
"github - jupyter notebook": {
|
||||
platform: scm.GitHubPlatform,
|
||||
url: "https://github.com/gitleaks/test",
|
||||
finding: report.Finding{
|
||||
Commit: "8f56bd2369595bcadbb007e88ba294630fb05c7b",
|
||||
File: "Cloud/IPYNB/Overlapping Recommendation algorithm _OCuLaR_.ipynb",
|
||||
StartLine: 293,
|
||||
EndLine: 293,
|
||||
},
|
||||
want: "https://github.com/gitleaks/test/blob/8f56bd2369595bcadbb007e88ba294630fb05c7b/Cloud/IPYNB/Overlapping%20Recommendation%20algorithm%20_OCuLaR_.ipynb?plain=1#L293",
|
||||
},
|
||||
|
||||
// GitLab
|
||||
"gitlab - single line": {
|
||||
platform: scm.GitLabPlatform,
|
||||
url: "https://gitlab.com/example-org/example-group/gitleaks",
|
||||
finding: report.Finding{
|
||||
Commit: "213ffd1c9bfa906eb4c7731771132c58a4ca0139",
|
||||
File: ".gitlab-ci.yml",
|
||||
StartLine: 41,
|
||||
EndLine: 41,
|
||||
},
|
||||
want: "https://gitlab.com/example-org/example-group/gitleaks/blob/213ffd1c9bfa906eb4c7731771132c58a4ca0139/.gitlab-ci.yml#L41",
|
||||
},
|
||||
"gitlab - multi line": {
|
||||
platform: scm.GitLabPlatform,
|
||||
url: "https://gitlab.com/example-org/example-group/gitleaks",
|
||||
finding: report.Finding{
|
||||
Commit: "63410f74e23a4e51e1f60b9feb073b5d325af878",
|
||||
File: ".vscode/launchSettings.json",
|
||||
StartLine: 6,
|
||||
EndLine: 8,
|
||||
},
|
||||
want: "https://gitlab.com/example-org/example-group/gitleaks/blob/63410f74e23a4e51e1f60b9feb073b5d325af878/.vscode/launchSettings.json#L6-8",
|
||||
},
|
||||
}
|
||||
for name, tt := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
actual := createScmLink(tt.platform, tt.url, tt.finding)
|
||||
assert.Equal(t, tt.want, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@ module github.com/zricethezav/gitleaks/v8
|
||||
|
||||
go 1.23
|
||||
|
||||
toolchain go1.23.4
|
||||
|
||||
require (
|
||||
github.com/BobuSumisu/aho-corasick v1.0.3
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible
|
||||
github.com/Masterminds/sprig/v3 v3.3.0
|
||||
github.com/charmbracelet/lipgloss v0.5.0
|
||||
github.com/fatih/semgroup v1.2.0
|
||||
github.com/gitleaks/go-gitdiff v0.9.1
|
||||
@@ -18,12 +20,12 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.1 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver v1.5.0 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.3.0 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/huandu/xstrings v1.5.0 // indirect
|
||||
github.com/imdario/mergo v0.3.16 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
@@ -32,6 +34,7 @@ require (
|
||||
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 // indirect
|
||||
github.com/muesli/termenv v0.15.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/shopspring/decimal v1.4.0 // indirect
|
||||
github.com/tetratelabs/wazero v1.8.2 // indirect
|
||||
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
|
||||
golang.org/x/crypto v0.29.0 // indirect
|
||||
@@ -48,7 +51,7 @@ require (
|
||||
github.com/pelletier/go-toml v1.9.3 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/spf13/afero v1.6.0 // indirect
|
||||
github.com/spf13/cast v1.3.1 // indirect
|
||||
github.com/spf13/cast v1.7.0 // indirect
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.2.0 // indirect
|
||||
|
||||
@@ -36,6 +36,8 @@ cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0Zeo
|
||||
cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk=
|
||||
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
|
||||
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
|
||||
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
|
||||
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||
github.com/BobuSumisu/aho-corasick v1.0.3 h1:uuf+JHwU9CHP2Vx+wAy6jcksJThhJS9ehR8a+4nPE9g=
|
||||
github.com/BobuSumisu/aho-corasick v1.0.3/go.mod h1:hm4jLcvZKI2vRF2WDU1N4p/jpWtpOzp3nLmi9AzX/XE=
|
||||
@@ -43,10 +45,10 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
|
||||
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
|
||||
github.com/Masterminds/semver/v3 v3.3.0 h1:B8LGeaivUe71a5qox1ICM/JLl0NqZSW5CHyL+hmvYS0=
|
||||
github.com/Masterminds/semver/v3 v3.3.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs=
|
||||
github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0=
|
||||
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
|
||||
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
|
||||
@@ -81,6 +83,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fatih/semgroup v1.2.0 h1:h/OLXwEM+3NNyAdZEpMiH1OzfplU09i2qXPVThGZvyg=
|
||||
github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS879kgm8=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
@@ -186,8 +190,6 @@ github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI
|
||||
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
|
||||
github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
@@ -198,11 +200,13 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb h1:w1g9wNDIE/pHSTmAaUhv4TZQuPBS6GV3mMz5hkgziIU=
|
||||
@@ -255,12 +259,16 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.26.1 h1:/ihwxqH+4z8UxyI70wM1z9yCvkWcfz/a3mj48k/Zngc=
|
||||
github.com/rs/zerolog v1.26.1/go.mod h1:/wSSJWX7lVrsOwlbyTRSOJvqRlc+WjWlfes+CiJ+tmc=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
|
||||
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
||||
@@ -268,8 +276,9 @@ github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIK
|
||||
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
|
||||
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
|
||||
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
|
||||
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
|
||||
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw=
|
||||
github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk=
|
||||
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package logging
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var Logger zerolog.Logger
|
||||
|
||||
func init() {
|
||||
// send all logs to stdout
|
||||
Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).
|
||||
Level(zerolog.InfoLevel).
|
||||
With().Timestamp().Logger()
|
||||
}
|
||||
|
||||
func With() zerolog.Context {
|
||||
return Logger.With()
|
||||
}
|
||||
|
||||
func Trace() *zerolog.Event {
|
||||
return Logger.Trace()
|
||||
}
|
||||
|
||||
func Debug() *zerolog.Event {
|
||||
return Logger.Debug()
|
||||
}
|
||||
func Info() *zerolog.Event {
|
||||
return Logger.Info()
|
||||
}
|
||||
func Warn() *zerolog.Event {
|
||||
return Logger.Warn()
|
||||
}
|
||||
|
||||
func Error() *zerolog.Event {
|
||||
return Logger.Error()
|
||||
}
|
||||
|
||||
func Err(err error) *zerolog.Event {
|
||||
return Logger.Err(err)
|
||||
}
|
||||
|
||||
func Fatal() *zerolog.Event {
|
||||
return Logger.Fatal()
|
||||
}
|
||||
|
||||
func Panic() *zerolog.Event {
|
||||
return Logger.Panic()
|
||||
}
|
||||
@@ -4,15 +4,11 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/zricethezav/gitleaks/v8/cmd"
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// send all logs to stdout
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
|
||||
// this block sets up a go routine to listen for an interrupt signal
|
||||
// which will immediately exit gitleaks
|
||||
stopChan := make(chan os.Signal, 1)
|
||||
@@ -24,5 +20,5 @@ func main() {
|
||||
|
||||
func listenForInterrupt(stopScan chan os.Signal) {
|
||||
<-stopScan
|
||||
log.Fatal().Msg("Interrupt signal received. Exiting...")
|
||||
logging.Fatal().Msg("Interrupt signal received. Exiting...")
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build stdregex
|
||||
|
||||
package regexp
|
||||
|
||||
import (
|
||||
re "regexp"
|
||||
)
|
||||
|
||||
const Version = "stdlib"
|
||||
|
||||
type Regexp = re.Regexp
|
||||
|
||||
func MustCompile(str string) *re.Regexp {
|
||||
return re.MustCompile(str)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build !stdregex
|
||||
|
||||
package regexp
|
||||
|
||||
import (
|
||||
re "github.com/wasilibs/go-re2"
|
||||
)
|
||||
|
||||
const Version = "github.com/wasilibs/go-re2"
|
||||
|
||||
type Regexp = re.Regexp
|
||||
|
||||
func MustCompile(str string) *re.Regexp {
|
||||
return re.MustCompile(str)
|
||||
}
|
||||
+19
-7
@@ -17,8 +17,11 @@ func (r *CsvReporter) Write(w io.WriteCloser, findings []Finding) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
cw := csv.NewWriter(w)
|
||||
err := cw.Write([]string{"RuleID",
|
||||
var (
|
||||
cw = csv.NewWriter(w)
|
||||
err error
|
||||
)
|
||||
columns := []string{"RuleID",
|
||||
"Commit",
|
||||
"File",
|
||||
"SymlinkFile",
|
||||
@@ -34,12 +37,17 @@ func (r *CsvReporter) Write(w io.WriteCloser, findings []Finding) error {
|
||||
"Email",
|
||||
"Fingerprint",
|
||||
"Tags",
|
||||
})
|
||||
if err != nil {
|
||||
}
|
||||
// A miserable attempt at "omitempty" so tests don't yell at me.
|
||||
if findings[0].Link != "" {
|
||||
columns = append(columns, "Link")
|
||||
}
|
||||
|
||||
if err = cw.Write(columns); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range findings {
|
||||
err = cw.Write([]string{f.RuleID,
|
||||
row := []string{f.RuleID,
|
||||
f.Commit,
|
||||
f.File,
|
||||
f.SymlinkFile,
|
||||
@@ -55,8 +63,12 @@ func (r *CsvReporter) Write(w io.WriteCloser, findings []Finding) error {
|
||||
f.Email,
|
||||
f.Fingerprint,
|
||||
strings.Join(f.Tags, " "),
|
||||
})
|
||||
if err != nil {
|
||||
}
|
||||
if findings[0].Link != "" {
|
||||
row = append(row, f.Link)
|
||||
}
|
||||
|
||||
if err = cw.Write(row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
+4
-3
@@ -8,7 +8,10 @@ import (
|
||||
// Finding contains information about strings that
|
||||
// have been captured by a tree-sitter query.
|
||||
type Finding struct {
|
||||
// Rule is the name of the rule that was matched
|
||||
RuleID string
|
||||
Description string
|
||||
|
||||
StartLine int
|
||||
EndLine int
|
||||
StartColumn int
|
||||
@@ -26,6 +29,7 @@ type Finding struct {
|
||||
File string
|
||||
SymlinkFile string
|
||||
Commit string
|
||||
Link string `json:",omitempty"`
|
||||
|
||||
// Entropy is the shannon entropy of Value
|
||||
Entropy float32
|
||||
@@ -36,9 +40,6 @@ type Finding struct {
|
||||
Message string
|
||||
Tags []string
|
||||
|
||||
// Rule is the name of the rule that was matched
|
||||
RuleID string
|
||||
|
||||
// unique identifier
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import (
|
||||
"os"
|
||||
"text/template"
|
||||
|
||||
"github.com/Masterminds/sprig"
|
||||
"github.com/Masterminds/sprig/v3"
|
||||
)
|
||||
|
||||
type TemplateReporter struct {
|
||||
|
||||
@@ -6,7 +6,8 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fatih/semgroup"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
type ScanTarget struct {
|
||||
@@ -20,7 +21,7 @@ func DirectoryTargets(source string, s *semgroup.Group, followSymlinks bool, sho
|
||||
defer close(paths)
|
||||
return filepath.Walk(source,
|
||||
func(path string, fInfo os.FileInfo, err error) error {
|
||||
logger := log.With().Str("path", path).Logger()
|
||||
logger := logging.With().Str("path", path).Logger()
|
||||
|
||||
if err != nil {
|
||||
if os.IsPermission(err) {
|
||||
|
||||
+15
-7
@@ -10,7 +10,8 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gitleaks/go-gitdiff/gitdiff"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/zricethezav/gitleaks/v8/logging"
|
||||
)
|
||||
|
||||
var quotedOptPattern = regexp.MustCompile(`^(?:"[^"]+"|'[^']+')$`)
|
||||
@@ -41,7 +42,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
}
|
||||
}
|
||||
if len(quotedOpts) > 0 {
|
||||
log.Warn().Msgf("the following `--log-opts` values may not work as expected: %v\n\tsee https://github.com/gitleaks/gitleaks/issues/1153 for more information", quotedOpts)
|
||||
logging.Warn().Msgf("the following `--log-opts` values may not work as expected: %v\n\tsee https://github.com/gitleaks/gitleaks/issues/1153 for more information", quotedOpts)
|
||||
}
|
||||
|
||||
args = append(args, userArgs...)
|
||||
@@ -51,7 +52,7 @@ func NewGitLogCmd(source string, logOpts string) (*GitCmd, error) {
|
||||
"--full-history", "--all")
|
||||
}
|
||||
|
||||
log.Debug().Msgf("executing: %s", cmd.String())
|
||||
logging.Debug().Msgf("executing: %s", cmd.String())
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
@@ -91,7 +92,7 @@ func NewGitDiffCmd(source string, staged bool) (*GitCmd, error) {
|
||||
cmd = exec.Command("git", "-C", sourceClean, "diff", "-U0", "--no-ext-diff",
|
||||
"--staged", ".")
|
||||
}
|
||||
log.Debug().Msgf("executing: %s", cmd.String())
|
||||
logging.Debug().Msgf("executing: %s", cmd.String())
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
@@ -157,6 +158,9 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
// you may want to set your diff.renameLimit variable to at least
|
||||
// (some large number) and retry the command.
|
||||
//
|
||||
// Auto packing the repository in background for optimum performance.
|
||||
// See "git help gc" for manual housekeeping.
|
||||
//
|
||||
// we skip exiting the program as git log -p/git diff will continue
|
||||
// to send data to stdout and finish executing. This next bit of
|
||||
// code prevents gitleaks from stopping mid scan if this error is
|
||||
@@ -166,10 +170,14 @@ func listenForStdErr(stderr io.ReadCloser, errCh chan<- error) {
|
||||
strings.Contains(scanner.Text(),
|
||||
"inexact rename detection was skipped") ||
|
||||
strings.Contains(scanner.Text(),
|
||||
"you may want to set your diff.renameLimit") {
|
||||
log.Warn().Msg(scanner.Text())
|
||||
"you may want to set your diff.renameLimit") ||
|
||||
strings.Contains(scanner.Text(),
|
||||
"See \"git help gc\" for manual housekeeping") ||
|
||||
strings.Contains(scanner.Text(),
|
||||
"Auto packing the repository in background for optimum performance") {
|
||||
logging.Warn().Msg(scanner.Text())
|
||||
} else {
|
||||
log.Error().Msgf("[git] %s", scanner.Text())
|
||||
logging.Error().Msgf("[git] %s", scanner.Text())
|
||||
errEncountered = true
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
title = "gitleaks extend disable"
|
||||
|
||||
[extend]
|
||||
path = "../testdata/config/extend_disabled_base.toml"
|
||||
disabledRules = [
|
||||
'custom-rule1'
|
||||
]
|
||||
|
||||
[[rules]]
|
||||
id = "pypi-upload-token"
|
||||
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
title = "gitleaks extended 3"
|
||||
|
||||
|
||||
[[rules]]
|
||||
id = "aws-secret-key"
|
||||
regex = '''(?i)aws_(.{0,20})?=?.[\'\"0-9a-zA-Z\/+]{40}'''
|
||||
tags = ["key", "AWS"]
|
||||
|
||||
[[rules]]
|
||||
id = "custom-rule1"
|
||||
regex = '''[Cc]ustom!'''
|
||||
+1
-1
@@ -1,5 +1,6 @@
|
||||
[
|
||||
{
|
||||
"RuleID": "test-rule",
|
||||
"Description": "",
|
||||
"StartLine": 1,
|
||||
"EndLine": 2,
|
||||
@@ -16,7 +17,6 @@
|
||||
"Date": "10-19-2003",
|
||||
"Message": "opps",
|
||||
"Tags": [],
|
||||
"RuleID": "test-rule",
|
||||
"Fingerprint": ""
|
||||
}
|
||||
]
|
||||
+2
-2
@@ -2,10 +2,10 @@
|
||||
<testsuites>
|
||||
<testsuite failures="2" name="gitleaks" tests="2" time="">
|
||||
<testcase classname="Test Rule" file="auth.py" name="test-rule has detected a secret in file auth.py, line 1, at commit 0000000000000000." time="">
|
||||
<failure message="test-rule has detected a secret in file auth.py, line 1, at commit 0000000000000000." type="Test Rule">{
	"Description": "Test Rule",
	"StartLine": 1,
	"EndLine": 2,
	"StartColumn": 1,
	"EndColumn": 2,
	"Match": "line containing secret",
	"Secret": "a secret",
	"File": "auth.py",
	"SymlinkFile": "",
	"Commit": "0000000000000000",
	"Entropy": 0,
	"Author": "John Doe",
	"Email": "johndoe@gmail.com",
	"Date": "10-19-2003",
	"Message": "opps",
	"Tags": [],
	"RuleID": "test-rule",
	"Fingerprint": ""
}</failure>
|
||||
<failure message="test-rule has detected a secret in file auth.py, line 1, at commit 0000000000000000." type="Test Rule">{
	"RuleID": "test-rule",
	"Description": "Test Rule",
	"StartLine": 1,
	"EndLine": 2,
	"StartColumn": 1,
	"EndColumn": 2,
	"Match": "line containing secret",
	"Secret": "a secret",
	"File": "auth.py",
	"SymlinkFile": "",
	"Commit": "0000000000000000",
	"Entropy": 0,
	"Author": "John Doe",
	"Email": "johndoe@gmail.com",
	"Date": "10-19-2003",
	"Message": "opps",
	"Tags": [],
	"Fingerprint": ""
}</failure>
|
||||
</testcase>
|
||||
<testcase classname="Test Rule" file="auth.py" name="test-rule has detected a secret in file auth.py, line 2." time="">
|
||||
<failure message="test-rule has detected a secret in file auth.py, line 2." type="Test Rule">{
	"Description": "Test Rule",
	"StartLine": 2,
	"EndLine": 3,
	"StartColumn": 1,
	"EndColumn": 2,
	"Match": "line containing secret",
	"Secret": "a secret",
	"File": "auth.py",
	"SymlinkFile": "",
	"Commit": "",
	"Entropy": 0,
	"Author": "",
	"Email": "",
	"Date": "",
	"Message": "",
	"Tags": [],
	"RuleID": "test-rule",
	"Fingerprint": ""
}</failure>
|
||||
<failure message="test-rule has detected a secret in file auth.py, line 2." type="Test Rule">{
	"RuleID": "test-rule",
	"Description": "Test Rule",
	"StartLine": 2,
	"EndLine": 3,
	"StartColumn": 1,
	"EndColumn": 2,
	"Match": "line containing secret",
	"Secret": "a secret",
	"File": "auth.py",
	"SymlinkFile": "",
	"Commit": "",
	"Entropy": 0,
	"Author": "",
	"Email": "",
	"Date": "",
	"Message": "",
	"Tags": [],
	"Fingerprint": ""
}</failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
Reference in new issue
Block a user