Compare commits

...
39 Commits
Author SHA1 Message Date
Zachary Rice 82f7d61593 Update dockerfile (#848)
* bump alpine and add default safe dir for git

* comment out safe dir fix

* update deps
2022-04-20 18:19:33 -05:00
Zachary Rice a42b32bdf1 fix EOL in secret suffix (#847)
* fix EOL in secret suffix

* allow quoted key value syntax
2022-04-20 17:55:07 -05:00
foolioo 79638b080c unpin docker version in pre-commit hook (#832)
eliminating inconsistency. e.g. for version 8.6.1, pre-commit hooks points to outdated version https://github.com/zricethezav/gitleaks/blob/c33ee3f25215635c0afbb210672779e7efb6f1d2/.pre-commit-hooks.yaml#L10
2022-04-19 21:33:23 -05:00
Zachary Rice 3474c58c9e Generate tps (#845)
* WIP

* simplify tp generation
2022-04-18 21:59:38 -05:00
Zachary Rice d8cd93cabe maybe fix out of bounds (#843) 2022-04-18 14:57:40 -05:00
Zachary Rice 48b79facfa optimize keywords (#841)
* optimize keywords

* use defaults for concurrency again
2022-04-16 17:41:40 -05:00
0xn3va e23f7f58f3 Update detect.go (#839) 2022-04-12 21:44:00 -05:00
Zachary Rice 606bb1a13b Standardize/alphabetize rules, add cmd/generate/config package (#840) 2022-04-12 21:40:48 -05:00
aeongdesu e784980515 fix ghcr.io typo in README.md (#835) 2022-04-08 08:05:06 -05:00
Zachary Rice c33ee3f252 normalize keyword check (#830) 2022-04-06 09:55:36 -05:00
Zachary Rice b0a958f55e Keyword (#825)
* wip keywords optimization

* update readme

* limit concurrency to 4

* update readme
2022-04-05 11:50:50 -05:00
foolioo 237b03af18 doc gitleaks-docker pre-commit hook (#819)
relates to #818
2022-03-29 20:05:28 -05:00
Zach Rice f348991d21 Merge branch 'master' of github.com:zricethezav/gitleaks 2022-03-29 11:54:05 -05:00
Zach Rice e0745adbd2 skip content checks for path only rules 2022-03-29 11:53:48 -05:00
foolioo 1ddc924a67 use official docker image as pre-commit hook (#818)
* use official docker image as pre-commit hook

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml

* Update .pre-commit-hooks.yaml
2022-03-28 17:18:12 -05:00
Zach Rice 0b07625567 remove stopwords from global allowlist 2022-03-28 08:03:16 -05:00
Adam Shannon 0cabbf8ca8 detect: skip binary files with --no-git (#810) 2022-03-22 14:32:47 -05:00
Zachary Rice ba9e089e35 fixing a location off by one edge case for --no-git (#812) 2022-03-22 14:22:46 -05:00
Zachary Rice 31ff8677dd Update README.md 2022-03-21 13:36:29 -05:00
Zachary Rice 3e5e63956e Allow tag (#809)
* gitleaks:allow signature

* readd all tests

* fixing tests
2022-03-19 10:32:04 -05:00
Zachary Rice 57f9bc83d1 Stop words (#808)
* use regex for stopwords

* fix up regex

* rm stopwords
2022-03-19 09:31:38 -05:00
Zachary Rice 6e72472b60 Refactor detect, add entropy to all findings (#804)
Refactor `detect`, add `entropy` to all findings
2022-03-12 11:50:01 -06:00
Isaac Dawson 9326f35380 Escape - character in regex character groups (#802)
* fix char escape

* add test

* fix verbosity in make test
2022-03-07 08:33:06 -06:00
jetexe 19555579c8 adding go mod/sum to ignore (#797) 2022-03-01 10:16:17 -06:00
Greg JohnsonandGreg Johnson 60dd607312 GitLab pats may contain underscores as well as dashes (#794)
* gitlab pats may contain underscores as well as dashes

* include testdata index binary

Co-authored-by: Greg Johnson (codeEmitter) <gjohnson@gitlab.com>
2022-02-28 08:03:09 -06:00
Andrzej Amghar c3b799ec63 ignore k8s apiVersion in generic-api-key pattern (#760) 2022-02-22 17:00:20 -06:00
rui 4b6f4d0de5 build: updates for go1.17 (#769)
* build: remove `GO111MODULE` as it turned on by default

Signed-off-by: Rui Chen <rui@chenrui.dev>

* build: update for go1.17

* run test

Signed-off-by: Rui Chen <rui@chenrui.dev>

* lint: remove unused code
2022-02-22 16:49:45 -06:00
Zachary Rice fbfb3f591e allow non-last-element secret groups (#792) 2022-02-22 16:34:56 -06:00
Zachary Rice b91799aa18 fixing segfault when using a rule with only a path (#791)
* fixing segfault when using a rule with only a path

* DRYing
2022-02-22 15:58:03 -06:00
Luca Regne db1b54bf9f Fix: Typo in LinkedIn id (#789) 2022-02-22 09:49:55 -06:00
Ian Mckay e9529744f8 Fix vendor name casing, Flutterwave typo (#785) 2022-02-19 10:24:47 -06:00
Chris Wolf d1f642a9df Sarif results with empty rules now represents as [] instead of null/nil (#786) 2022-02-19 10:20:35 -06:00
Greg Myers 9261f1c47f Fix typos in README.md (#780)
comand ==> command
awsome ==> awesome
precendence ==> precedence
2022-01-29 12:08:55 -06:00
Zachary Rice 991223abab remove godoc text filtering (#763) 2022-01-07 10:59:51 -06:00
Zachary Rice 801d44a6e4 limit number of goroutines for historic scanning as well (#761) 2022-01-07 08:58:47 -06:00
Zach Rice 44d7d89e19 always write sarif results 2021-12-28 19:13:26 -06:00
Zachary Rice aae23acff3 limit goroutines on file scanning to avoid pegging them cores (#759) 2021-12-21 18:10:29 -06:00
Zachary Rice 705595aaf6 Adding Typeform to sponsorships 2021-12-21 08:26:47 -06:00
Zachary Rice 43ec22429f write a report regardless if leaks are present (#758) 2021-12-17 17:26:14 -06:00
100 changed files with 4358 additions and 1592 deletions

No files matched your search

-4
View File
@@ -11,8 +11,6 @@ on:
jobs:
build:
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- uses: actions/checkout@v2
@@ -26,8 +24,6 @@ jobs:
test:
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- uses: actions/checkout@v2
+3
View File
@@ -9,7 +9,10 @@
*.got
gitleaks
build
# configs
.gitleaks.toml
cmd/generate/config/gitleaks.toml
# Test binary
*.out
+5
View File
@@ -4,3 +4,8 @@
entry: gitleaks protect --verbose --redact --staged
language: golang
pass_filenames: false
- id: gitleaks-docker
name: Detect hardcoded secrets
description: Detect hardcoded secrets using Gitleaks
entry: zricethezav/gitleaks protect --verbose --redact --staged
language: docker_image
+15 -3
View File
@@ -1,12 +1,24 @@
FROM golang:1.17 AS build
FROM golang:1.18 AS build
WORKDIR /go/src/github.com/zricethezav/gitleaks
COPY . .
RUN VERSION=$(git describe --tags --abbrev=0) && \
GO111MODULE=on 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.14.2
FROM alpine:3.15.4
RUN adduser -D gitleaks && \
apk add --no-cache bash git openssh-client
COPY --from=build /go/src/github.com/zricethezav/gitleaks/bin/* /usr/bin/
USER gitleaks
# default to avoid the follow error:
# 11:09PM ERR fatal: unsafe repository ('/path' is owned by someone else)
# 11:09PM ERR To add an exception for this directory, call:
# 11:09PM ERR
# 11:09PM ERR git config --global --add safe.directory /path
# This means that when you run gitleaks from docker you must mount to /path
# in order to avoid this error.
# TODO waiting to push this until I've thought a bit more about it
# RUN git config --global --add safe.directory /path
ENTRYPOINT ["gitleaks"]
+2 -2
View File
@@ -6,7 +6,7 @@ LDFLAGS=-ldflags "-X=github.com/zricethezav/gitleaks/v8/cmd.Version=$(VERSION)"
COVER=--cover --coverprofile=cover.out
test-cover:
go test ./... --race $(COVER) $(PKG) -v
go test -v ./... --race $(COVER) $(PKG)
go tool cover -html=cover.out
format:
@@ -14,7 +14,7 @@ format:
test: format
go vet ./...
go test ./... --race $(PKG) -v
go test -v ./... --race $(PKG)
build: format
go vet ./...
+68 -75
View File
@@ -1,10 +1,10 @@
# gitleaks
```
○
│╲
│ ○
○ ░
░ gitleaks
┌─○───┐
│ │╲ │
│ │ ○ │
│ ○ ░ │
└─░───┘
```
@@ -41,7 +41,7 @@ brew install gitleaks
docker pull zricethezav/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
```
#### ghrc.io
#### ghcr.io
```bash
docker pull ghcr.io/zricethezav/gitleaks:latest
docker run -v ${path_to_host_folder_to_scan}:/path zricethezav/gitleaks:latest [COMMAND] --source="/path" [OPTIONS]
@@ -62,13 +62,15 @@ make build
### Pre-Commit
1. Install pre-commit from https://pre-commit.com/#install
2. Create a `.pre-commit-config.yaml` file at the root of your repository with the following content:
```
repos:
- repo: https://github.com/zricethezav/gitleaks
rev: v8.2.0
hooks:
- id: gitleaks
```
```
repos:
- repo: https://github.com/zricethezav/gitleaks
rev: v8.2.0
hooks:
- id: gitleaks
```
for a [native execution of GitLeaks](https://github.com/zricethezav/gitleaks/releases) or use the [`gitleaks-docker` pre-commit ID](https://github.com/zricethezav/gitleaks/blob/master/.pre-commit-hooks.yaml) for executing GitLeaks using the [official Docker images](#docker)
3. Install with `pre-commit install`
4. Now you're all set!
```
@@ -116,7 +118,7 @@ Use "gitleaks [command] --help" for more information about a command.
### Commands
There are two commands you will use to detect secrets; `detect` and `protect`.
#### Detect
The `detect` command is used to scan repos, directories, and files. This comand can be used on developer machines and in CI environments.
The `detect` command is used to scan repos, directories, and files. This command can be used on developer machines and in CI environments.
When running `detect` on a git repository, gitleaks will parse the output of a `git log -p` command (you can see how this executed
[here](https://github.com/zricethezav/gitleaks/blob/7240e16769b92d2a1b137c17d6bf9d55a8562899/git/git.go#L17-L25)).
@@ -200,97 +202,88 @@ title = "Gitleaks title"
# An array of tables that contain information that define instructions
# on how to detect secrets
[[rules]]
# Unique identifier for this rule
id = "awesome-rule-1"
# Short human readable description of the rule.
description = "awsome rule 1"
description = "awesome rule 1"
# Golang regular expression used to detect secrets. Note Golang's regex engine
# does not support lookaheads.
regex = '''one-go-style-regex-for-this-rule'''
# Golang regular expression used to match paths. This can be used as a standalone rule or it can be used
# in conjunction with a valid `regex` entry.
path = '''a-file-path-regex'''
# Array of strings used for metadata and reporting purposes.
tags = ["tag","another tag"]
# Int used to extract secret from regex match and used as the group that will have
# its entropy checked if `entropy` is set.
secretGroup = 3
# Float representing the minimum shannon entropy a regex group must have to be considered a secret.
entropy = 3.5
# Keywords are used for pre-regex check filtering. Rules that contain
# keywords will perform a quick string compare check to make sure the
# keyword(s) are in the content being scanned. Ideally these values should
# either be part of the idenitifer or unique strings specific to the rule's regex
# (introduced in v8.6.0)
keywords = [
"auth",
"password",
"token",
]
# You can include an allowlist table for a single rule to reduce false positives or ignore commits
# with known/rotated secrets
[rules.allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = ['''one-file-path-regex''']
regexes = ['''one-regex-within-the-already-matched-regex''']
paths = [
'''go\.mod''',
'''go\.sum'''
]
regexes = [
'''process''',
'''getenv''',
]
# This is a global allowlist which has a higher order of precendence than rule-specific allowlists.
# This is a global allowlist which has a higher order of precedence than rule-specific allowlists.
# If a commit listed in the `commits` field below is encountered then that commit will be skipped and no
# secrets will be detected for said commit. The same logic applies for regexes and paths.
[allowlist]
description = "ignore commit A"
commits = [ "commit-A", "commit-B"]
paths = ['''one-file-path-regex''']
regexes = ['''one-regex-within-the-already-matched-regex''']
description = "global allow list"
commits = [ "commit-A", "commit-B", "commit-C"]
paths = [
'''gitleaks\.toml''',
'''(.*?)(jpg|gif|doc)'''
]
regexes = [
'''219-09-9999''',
'''078-05-1120''',
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
]
```
Refer to the default [gitleaks config](https://github.com/zricethezav/gitleaks/blob/master/config/gitleaks.toml) for examples and advice on writing regular expressions for secret detection.
### Tips on Writing Regular Expressions
Gitleaks rules are defined by regular expressions and entropy ranges.
Some secrets have unique signatures which make detecting those secrets easy.
Examples of those secrets would be Gitlab Personal Access Tokens, AWS keys, and Github Access Tokens.
All these examples have defined prefixes like `glpat`, `AKIA`, `ghp_`, etc.
Other secrets might just be a hash which means we need to write more complex rules to verify
that what we are matching is a secret.
Here is an example of a semi-generic secret
```
discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ"
```
We can write a regular expression to capture the variable name (identifier),
the assignment symbol (like '=' or ':='), and finally the actual secret.
The structure of a rule to match this example secret is below:
Beginning string
quotation
│ End string quotation
│ │
▼ ▼
(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]
▲ ▲ ▲
│ │ │
│ │ │
identifier assignment symbol
Secret
#### A Note on Generic Secrets
Let's continue with the example `discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ"`.
This secret would match both the `discord-client-secret` rule and the `generic-api-key` rule in the default config.
```
[[rules]]
id = "discord-client-secret"
description = "Discord client secret"
regex = '''(?i)(discord[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([a-z0-9=_\-]{32})['\"]'''
secretGroup = 3
[[rules]]
id = "generic-api-key"
description = "Generic API Key"
regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]'''
entropy = 3.7
secretGroup = 4
```
If gitleaks encountered `discord_client_secret = "8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ"`, only the `discord` rule would report a finding because
the generic rule has the string `generic` somewhere in the rule's `id`. If a secret is encountered and both a `generic` and non-generic rule have discovered the same secret, the non-generic
will be given precedence.
## Sponsorships
[![Tines-Sponsorship-Badge-Purple](https://user-images.githubusercontent.com/15034943/146411864-4878f936-b4f7-49a0-b625-f9f40c704bfa.png)](https://www.tines.com/?utm_source=oss&utm_medium=sponsorship&utm_campaign=gitleaks)
<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>
<a href="https://www.typeform.com/">
<img src="https://user-images.githubusercontent.com/15034943/146945294-a6473d55-86b8-4f53-941e-7f185ad6b3d7.png" width=200/>
</a>
</p>
## Exit Codes
+68 -33
View File
@@ -11,7 +11,6 @@ import (
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/git"
"github.com/zricethezav/gitleaks/v8/report"
)
@@ -35,56 +34,92 @@ func runDetect(cmd *cobra.Command, args []string) {
err error
)
viper.Unmarshal(&vc)
// Load config
if err = viper.Unmarshal(&vc); err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg.Path, _ = cmd.Flags().GetString("config")
source, _ := cmd.Flags().GetString("source")
logOpts, _ := cmd.Flags().GetString("log-opts")
verbose, _ := cmd.Flags().GetBool("verbose")
redact, _ := cmd.Flags().GetBool("redact")
noGit, _ := cmd.Flags().GetBool("no-git")
exitCode, _ := cmd.Flags().GetInt("exit-code")
if cfg.Path == "" {
cfg.Path = filepath.Join(source, ".gitleaks.toml")
}
// start timer
start := time.Now()
if noGit {
if logOpts != "" {
log.Fatal().Err(err).Msg("--log-opts cannot be used with --no-git")
}
findings, err = detect.FromFiles(source, cfg, detect.Options{
Verbose: verbose,
Redact: redact,
})
if err != nil {
log.Fatal().Err(err).Msg("Failed to scan files")
}
} else {
files, err := git.GitLog(source, logOpts)
if err != nil {
log.Fatal().Err(err).Msg("Failed to get git log")
}
findings = detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
// Setup detector
detector := detect.NewDetector(cfg)
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
log.Fatal().Err(err)
}
source, err := cmd.Flags().GetString("source")
if err != nil {
log.Fatal().Err(err)
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
log.Fatal().Err(err)
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
log.Fatal().Err(err)
}
// set exit code
exitCode, err := cmd.Flags().GetInt("exit-code")
if err != nil {
log.Fatal().Err(err)
}
// 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)
}
// start the detector scan
if noGit {
findings, err = detector.DetectFiles(source)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
} else {
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err)
}
findings, err = detector.DetectGit(source, logOpts, detect.DetectType)
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
}
// log info about the scan
log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
log.Info().Msgf("scan completed in %s", time.Since(start))
// write report if desired
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
report.Write(findings, cfg, ext, reportPath)
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
log.Fatal().Err(err)
}
}
if len(findings) != 0 {
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"os"
"text/template"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/cmd/generate/config/rules"
"github.com/zricethezav/gitleaks/v8/config"
)
const (
templatePath = "rules/config.tmpl"
)
func main() {
configRules := []*config.Rule{}
configRules = append(configRules, rules.AdobeClientID())
configRules = append(configRules, rules.AdobeClientSecret())
configRules = append(configRules, rules.AgeSecretKey())
configRules = append(configRules, rules.AlibabaAccessKey())
configRules = append(configRules, rules.AlibabaSecretKey())
configRules = append(configRules, rules.AsanaClientID())
configRules = append(configRules, rules.AsanaClientSecret())
configRules = append(configRules, rules.Atlassian())
configRules = append(configRules, rules.AWS())
configRules = append(configRules, rules.BitBucketClientID())
configRules = append(configRules, rules.BitBucketClientSecret())
configRules = append(configRules, rules.Beamer())
configRules = append(configRules, rules.Clojars())
configRules = append(configRules, rules.Contentful())
configRules = append(configRules, rules.Databricks())
configRules = append(configRules, rules.DiscordAPIToken())
configRules = append(configRules, rules.DiscordClientID())
configRules = append(configRules, rules.DiscordClientSecret())
configRules = append(configRules, rules.DropBoxAPISecret())
configRules = append(configRules, rules.DropBoxLongLivedAPIToken())
configRules = append(configRules, rules.DropBoxShortLivedAPIToken())
configRules = append(configRules, rules.Doppler())
configRules = append(configRules, rules.Duffel())
configRules = append(configRules, rules.Dynatrace())
configRules = append(configRules, rules.EasyPost())
configRules = append(configRules, rules.EasyPostTestAPI())
configRules = append(configRules, rules.Facebook())
configRules = append(configRules, rules.FastlyAPIToken())
configRules = append(configRules, rules.FinicityClientSecret())
configRules = append(configRules, rules.FinicityAPIToken())
configRules = append(configRules, rules.FlutterwavePublicKey())
configRules = append(configRules, rules.FlutterwaveSecretKey())
configRules = append(configRules, rules.FlutterwaveSecretKey())
configRules = append(configRules, rules.FrameIO())
configRules = append(configRules, rules.GenericCredential())
configRules = append(configRules, rules.GoCardless())
// TODO figure out what makes sense for GCP
// configRules = append(configRules, rules.GCPServiceAccount())
configRules = append(configRules, rules.GitHubPat())
configRules = append(configRules, rules.GitHubOauth())
configRules = append(configRules, rules.GitHubApp())
configRules = append(configRules, rules.GitHubRefresh())
configRules = append(configRules, rules.Gitlab())
configRules = append(configRules, rules.Hashicorp())
configRules = append(configRules, rules.Heroku())
configRules = append(configRules, rules.HubSpot())
configRules = append(configRules, rules.Intercom())
configRules = append(configRules, rules.LinearAPIToken())
configRules = append(configRules, rules.LinearClientSecret())
configRules = append(configRules, rules.LinkedinClientID())
configRules = append(configRules, rules.LinkedinClientSecret())
configRules = append(configRules, rules.LobAPIToken())
configRules = append(configRules, rules.LobPubAPIToken())
configRules = append(configRules, rules.MailChimp())
configRules = append(configRules, rules.MailGunPubAPIToken())
configRules = append(configRules, rules.MailGunPrivateAPIToken())
configRules = append(configRules, rules.MailGunSigningKey())
configRules = append(configRules, rules.MapBox())
configRules = append(configRules, rules.MessageBirdAPIToken())
configRules = append(configRules, rules.MessageBirdClientID())
configRules = append(configRules, rules.NewRelicUserID())
configRules = append(configRules, rules.NewRelicUserKey())
configRules = append(configRules, rules.NewRelicBrowserAPIKey())
configRules = append(configRules, rules.NPM())
configRules = append(configRules, rules.PlanetScalePassword())
configRules = append(configRules, rules.PlanetScaleToken())
configRules = append(configRules, rules.PostManAPI())
configRules = append(configRules, rules.PrivateKey())
configRules = append(configRules, rules.PulumiAPIToken())
configRules = append(configRules, rules.PyPiUploadToken())
configRules = append(configRules, rules.RubyGemsAPIToken())
configRules = append(configRules, rules.SendGridAPIToken())
configRules = append(configRules, rules.SendInBlueAPIToken())
configRules = append(configRules, rules.ShippoAPIToken())
configRules = append(configRules, rules.ShopifyAccessToken())
configRules = append(configRules, rules.ShopifyCustomAccessToken())
configRules = append(configRules, rules.ShopifyPrivateAppAccessToken())
configRules = append(configRules, rules.ShopifySharedSecret())
configRules = append(configRules, rules.SlackAccessToken())
configRules = append(configRules, rules.SlackWebHook())
configRules = append(configRules, rules.StripeAccessToken())
configRules = append(configRules, rules.Twilio())
configRules = append(configRules, rules.TwitchAPIToken())
configRules = append(configRules, rules.Twitter())
configRules = append(configRules, rules.Typeform())
config := config.Config{
Rules: configRules,
}
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
log.Fatal().Err(err).Msg("Failed to parse template")
}
f, err := os.Create("gitleaks.toml")
if err != nil {
log.Fatal().Err(err).Msg("Failed to create rules.toml")
}
tmpl.Execute(f, config)
}
// TODO introduce skiplists:
// https://github.com/danielmiessler/SecLists/blob/master/Miscellaneous/wordlist-skipfish.fuzz.txt
+39
View File
@@ -0,0 +1,39 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AdobeClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Adobe Client ID (Oauth Web)",
RuleID: "adobe-client-id",
Regex: generateSemiGenericRegex([]string{"adobe"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"adobe"},
}
// validate
tps := []string{
generateSampleSecret("adobe", secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
func AdobeClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Adobe Client Secret",
RuleID: "adobe-client-secret",
Regex: generateUniqueTokenRegex(`(p8e-)(?i)[a-z0-9]{32}`),
Keywords: []string{"p8e-"},
}
// validate
tps := []string{
"adobeClient := \"p8e-" + secrets.NewSecret(hex("32")) + "\"",
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func AgeSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Age secret key",
RuleID: "age secret key",
Regex: regexp.MustCompile(`AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}`),
Keywords: []string{"AGE-SECRET-KEY-1"},
}
// validate
tps := []string{
`apiKey := "AGE-SECRET-KEY-1QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ`, // gitleaks:allow
}
return validate(r, tps)
}
+41
View File
@@ -0,0 +1,41 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AlibabaAccessKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Alibaba AccessKey ID",
RuleID: "alibaba-access-key-id",
Regex: generateUniqueTokenRegex(`(LTAI)(?i)[a-z0-9]{20}`),
Keywords: []string{"LTAI"},
}
// validate
tps := []string{
"alibabaKey := \"LTAI" + secrets.NewSecret(hex("20")) + "\"",
}
return validate(r, tps)
}
// TODO
func AlibabaSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Alibaba Secret Key",
RuleID: "alibaba-secret-key",
Regex: generateSemiGenericRegex([]string{"alibaba"},
alphaNumeric("30")),
SecretGroup: 1,
Keywords: []string{"alibaba"},
}
// validate
tps := []string{
generateSampleSecret("alibaba", secrets.NewSecret(alphaNumeric("30"))),
}
return validate(r, tps)
}
+39
View File
@@ -0,0 +1,39 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func AsanaClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Asana Client ID",
RuleID: "asana-client-id",
Regex: generateSemiGenericRegex([]string{"asana"}, numeric("16")),
SecretGroup: 1,
Keywords: []string{"asana"},
}
// validate
tps := []string{
generateSampleSecret("asana", secrets.NewSecret(numeric("16"))),
}
return validate(r, tps)
}
func AsanaClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Asana Client Secret",
RuleID: "asana-client-secret",
Regex: generateSemiGenericRegex([]string{"asana"}, alphaNumeric("32")),
Keywords: []string{"asana"},
}
// validate
tps := []string{
generateSampleSecret("asana", secrets.NewSecret(alphaNumeric("32"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Atlassian() *config.Rule {
// define rule
r := config.Rule{
Description: "Atlassian API token",
RuleID: "atlassian-api-token",
Regex: generateSemiGenericRegex([]string{"atlassian", "confluence"}, alphaNumeric("24")),
SecretGroup: 1,
Keywords: []string{"atlassian", "confluence"},
}
// validate
tps := []string{
generateSampleSecret("atlassian", secrets.NewSecret(alphaNumeric("24"))),
generateSampleSecret("confluence", secrets.NewSecret(alphaNumeric("24"))),
}
return validate(r, tps)
}
+31
View File
@@ -0,0 +1,31 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func AWS() *config.Rule {
// define rule
r := config.Rule{
Description: "AWS",
RuleID: "aws-access-token",
Regex: regexp.MustCompile(
"(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Keywords: []string{
"AKIA",
"AGPA",
"AIDA",
"AROA",
"AIPA",
"ANPA",
"ANVA",
"ASIA",
},
}
// validate
tps := []string{generateSampleSecret("AWS", "AKIALALEMEL33243OLIB")} // gitleaks:allow
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Beamer() *config.Rule {
// define rule
r := config.Rule{
Description: "Beamer API token",
RuleID: "beamer-api-token",
SecretGroup: 1,
Regex: generateSemiGenericRegex([]string{"beamer"},
`b_[a-z0-9=_\-]{44}`),
Keywords: []string{"beamer"},
}
// validate
tps := []string{
generateSampleSecret("beamer", "b_"+secrets.NewSecret(alphaNumericExtended("44"))),
}
return validate(r, tps)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func BitBucketClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "BitBucket Client ID",
RuleID: "bitbucket-client-id",
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumeric("32")),
SecretGroup: 1,
Keywords: []string{"bitbucket"},
}
// validate
tps := []string{
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("32"))),
}
return validate(r, tps)
}
func BitBucketClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "BitBucket Client Secret",
RuleID: "bitbucket-client-secret",
Regex: generateSemiGenericRegex([]string{"bitbucket"}, alphaNumericExtended("64")),
SecretGroup: 1,
Keywords: []string{"bitbucket"},
}
// validate
tps := []string{
generateSampleSecret("bitbucket", secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Clojars() *config.Rule {
// define rule
r := config.Rule{
Description: "Clojars API token",
RuleID: "clojars-api-token",
Regex: regexp.MustCompile(`(?i)(CLOJARS_)[a-z0-9]{60}`),
Keywords: []string{"clojars"},
}
// validate
tps := []string{
generateSampleSecret("clojars", "CLOJARS_"+secrets.NewSecret(alphaNumeric("60"))),
}
return validate(r, tps)
}
+45
View File
@@ -0,0 +1,45 @@
# This is the default gitleaks configuration file.
# Rules and allowlists are defined within this file.
# Rules instruct gitleaks on what should be considered a secret.
# Allowlists instruct gitleaks on what is allowed, i.e. not a secret.
title = "gitleaks config"
[allowlist]
description = "global allow lists"
regexes = [
'''219-09-9999''',
'''078-05-1120''',
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
]
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
'''(go.mod|go.sum)$'''
]
{{ range $i, $rule := .Rules }}[[rules]]
{{ if and $rule.SecretGroup $rule.Entropy }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
entropy = {{ $rule.Entropy}}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else if $rule.SecretGroup }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
secretGroup = {{ $rule.SecretGroup }}
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{ else }}description = "{{$rule.Description}}"
id = "{{$rule.RuleID}}"
regex = '''{{$rule.Regex}}'''
keywords = [
{{ range $j, $keyword := $rule.Keywords }}"{{$keyword}}",{{end}}
]
{{end}}{{end}}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Contentful() *config.Rule {
// define rule
r := config.Rule{
Description: "Contentful delivery API token",
RuleID: "contentful-delivery-api-token",
Regex: generateSemiGenericRegex([]string{"contentful"},
alphaNumericExtended("43")),
SecretGroup: 1,
Keywords: []string{"contentful"},
}
// validate
tps := []string{
generateSampleSecret("contentful", secrets.NewSecret(alphaNumeric("43"))),
}
return validate(r, tps)
}
+22
View File
@@ -0,0 +1,22 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Databricks() *config.Rule {
// define rule
r := config.Rule{
Description: "Databricks API token",
RuleID: "databricks-api-token",
Regex: generateUniqueTokenRegex(`dapi[a-h0-9]{32}`),
Keywords: []string{"dapi"},
}
// validate
tps := []string{
generateSampleSecret("databricks", "dapi"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
+57
View File
@@ -0,0 +1,57 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func DiscordAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord API key",
RuleID: "discord-api-token",
Regex: generateSemiGenericRegex([]string{"discord"}, hex("64")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(hex("64"))),
}
return validate(r, tps)
}
func DiscordClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord client ID",
RuleID: "discord-client-id",
Regex: generateSemiGenericRegex([]string{"discord"}, numeric("18")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(numeric("18"))),
}
return validate(r, tps)
}
func DiscordClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Discord client secret",
RuleID: "discord-client-secret",
Regex: generateSemiGenericRegex([]string{"discord"}, alphaNumericExtended("32")),
SecretGroup: 1,
Keywords: []string{"discord"},
}
// validate
tps := []string{
generateSampleSecret("discord", secrets.NewSecret(numeric("32"))),
}
return validate(r, tps)
}
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Doppler() *config.Rule {
// define rule
r := config.Rule{
Description: "Doppler API token",
RuleID: "doppler-api-token",
Regex: regexp.MustCompile(`(dp\.pt\.)(?i)[a-z0-9]{43}`),
Keywords: []string{"doppler"},
}
// validate
tps := []string{
generateSampleSecret("doppler", "dp.pt."+secrets.NewSecret(alphaNumeric("43"))),
}
return validate(r, tps)
}
// TODO add additional doppler formats:
// https://docs.doppler.com/reference/auth-token-formats
+49
View File
@@ -0,0 +1,49 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func DropBoxAPISecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Dropbox API secret",
RuleID: "doppler-api-token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, alphaNumeric("15")),
SecretGroup: 1,
Keywords: []string{"dropbox"},
}
// validate
tps := []string{
generateSampleSecret("dropbox", secrets.NewSecret(alphaNumeric("15"))),
}
return validate(r, tps)
}
func DropBoxShortLivedAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "dropbox-short-lived-api-token",
Description: "Dropbox short lived API token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, `sl\.[a-z0-9\-=_]{135}`),
Keywords: []string{"dropbox"},
}
// validate TODO
return &r
}
func DropBoxLongLivedAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "dropbox-long-lived-api-token",
Description: "Dropbox long lived API token",
Regex: generateSemiGenericRegex([]string{"dropbox"}, `[a-z0-9]{11}(AAAAAAAAAA)[a-z0-9\-_=]{43}`),
Keywords: []string{"dropbox"},
}
// validate TODO
return &r
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Duffel() *config.Rule {
// define rule
r := config.Rule{
RuleID: "duffel-api-token",
Description: "Duffel API token",
Regex: regexp.MustCompile(`duffel_(test|live)_(?i)[a-z0-9_\-=]{43}`),
Keywords: []string{"duffel"},
}
// validate
tps := []string{
generateSampleSecret("duffel", "duffel_test_"+secrets.NewSecret(alphaNumericExtended("43"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Dynatrace() *config.Rule {
// define rule
r := config.Rule{
Description: "Dynatrace API token",
RuleID: "dynatrace-api-token",
Regex: regexp.MustCompile(`dt0c01\.(?i)[a-z0-9]{24}\.[a-z0-9]{64}`),
Keywords: []string{"dynatrace"},
}
// validate
tps := []string{
generateSampleSecret("dynatrace", "dt0c01."+secrets.NewSecret(alphaNumeric("24"))+"."+secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func EasyPost() *config.Rule {
// define rule
r := config.Rule{
Description: "EasyPost API token",
RuleID: "easypost-api-token",
Regex: regexp.MustCompile(`EZAK(?i)[a-z0-9]{54}`),
Keywords: []string{"EZAK"},
}
// validate
tps := []string{
generateSampleSecret("EZAK", "EZAK"+secrets.NewSecret(alphaNumeric("54"))),
}
return validate(r, tps)
}
func EasyPostTestAPI() *config.Rule {
// define rule
r := config.Rule{
Description: "EasyPost test API token",
RuleID: "easypost-test-api-token",
Regex: regexp.MustCompile(`EZTK(?i)[a-z0-9]{54}`),
Keywords: []string{"EZTK"},
}
// validate
tps := []string{
generateSampleSecret("EZTK", "EZTK"+secrets.NewSecret(alphaNumeric("54"))),
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Facebook() *config.Rule {
// define rule
r := config.Rule{
Description: "facebook",
RuleID: "facebook",
Regex: generateSemiGenericRegex([]string{"facebook"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"facebook"},
}
// validate
tps := []string{
generateSampleSecret("facebook", secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FastlyAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Fastly API key",
RuleID: "fastly-api-token",
Regex: generateSemiGenericRegex([]string{"fastly"}, alphaNumericExtended("32")),
SecretGroup: 1,
Keywords: []string{"fastly"},
}
// validate
tps := []string{
generateSampleSecret("fastly", secrets.NewSecret(alphaNumericExtended("32"))),
}
return validate(r, tps)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FinicityClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Client Secret",
RuleID: "finicity-client-secret",
Regex: generateSemiGenericRegex([]string{"finicity"}, alphaNumeric("20")),
SecretGroup: 1,
Keywords: []string{"finicity"},
}
// validate
tps := []string{
generateSampleSecret("finicity", secrets.NewSecret(alphaNumeric("20"))),
}
return validate(r, tps)
}
func FinicityAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity API token",
RuleID: "finicity-api-token",
Regex: generateSemiGenericRegex([]string{"finicity"}, hex("32")),
SecretGroup: 1,
Keywords: []string{"finicity"},
}
// validate
tps := []string{
generateSampleSecret("finicity", secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
+56
View File
@@ -0,0 +1,56 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FlutterwavePublicKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Public Key",
RuleID: "flutterwave-public-key",
Regex: regexp.MustCompile(`FLWPUBK_TEST-(?i)[a-h0-9]{32}-X`),
Keywords: []string{"FLWPUBK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWPUBK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
}
return validate(r, tps)
}
func FlutterwaveSecretKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Secret Key",
RuleID: "flutterwave-public-key",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{32}-X`),
Keywords: []string{"FLWSECK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("32"))+"-X"),
}
return validate(r, tps)
}
func FlutterwaveEncKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Finicity Secret Key",
RuleID: "flutterwave-public-key",
Regex: regexp.MustCompile(`FLWSECK_TEST-(?i)[a-h0-9]{12}`),
Keywords: []string{"FLWSECK_TEST"},
}
// validate
tps := []string{
generateSampleSecret("flutterwavePubKey", "FLWSECK_TEST-"+secrets.NewSecret(hex("12"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func FrameIO() *config.Rule {
// define rule
r := config.Rule{
Description: "Frame.io API token",
RuleID: "frameio-api-token",
Regex: regexp.MustCompile(`fio-u-(?i)[a-z0-9\-_=]{64}`),
Keywords: []string{"fio-u-"},
}
// validate
tps := []string{
generateSampleSecret("frameio", "fio-u-"+secrets.NewSecret(alphaNumericExtended("64"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
// TODO this one could probably use some work
func GCPServiceAccount() *config.Rule {
// define rule
r := config.Rule{
Description: "Google (GCP) Service-account",
RuleID: "gcp-service-account",
Regex: regexp.MustCompile(`\"type\": \"service_account\"`),
Keywords: []string{`\"type\": \"service_account\"`},
}
// validate
tps := []string{
`"type": "service_account"`,
}
return validate(r, tps)
}
+45
View File
@@ -0,0 +1,45 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func GenericCredential() *config.Rule {
// define rule
r := config.Rule{
RuleID: "generic-api-key",
Description: "Generic API Key",
Regex: generateSemiGenericRegex([]string{
"key",
"api[^Version]",
"token",
"pat",
"secret",
"client",
"password",
"auth",
}, `[0-9a-z\-_.=]{10,150}`),
SecretGroup: 1,
Keywords: []string{
"key",
"api",
"token",
"secret",
"client",
"pat",
"password",
"auth",
},
Entropy: 3.7,
}
// validate
tps := []string{
generateSampleSecret("generic", "CLOJARS_34bf0e88955ff5a1c328d6a7491acc4f48e865a7b8dd4d70a70749037443"),
generateSampleSecret("generic", "Zf3D0LXCM3EIMbgJpUNnkRtOfOueHznB"),
`"client_id" : "0afae57f3ccfd9d7f5767067bc48b30f719e271ba470488056e37ab35d4b6506"`,
`"client_secret" : "6da89121079f83b2eb6acccf8219ea982c3d79bccc3e9c6a85856480661f8fde",`,
// TODO add more
}
return validate(r, tps)
}
+73
View File
@@ -0,0 +1,73 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func GitHubPat() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub Personal Access Token",
RuleID: "github-pat",
Regex: regexp.MustCompile(`ghp_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghp_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghp_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps)
}
func GitHubOauth() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub OAuth Access Token",
RuleID: "github-oauth",
Regex: regexp.MustCompile(`gho_[0-9a-zA-Z]{36}`),
Keywords: []string{"gho_"},
}
// validate
tps := []string{
generateSampleSecret("github", "gho_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps)
}
func GitHubApp() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub App Token",
RuleID: "github-app-token",
Regex: regexp.MustCompile(`(ghu|ghs)_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghu_", "ghs_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghu_"+secrets.NewSecret(alphaNumeric("36"))),
generateSampleSecret("github", "ghs_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps)
}
func GitHubRefresh() *config.Rule {
// define rule
r := config.Rule{
Description: "GitHub Refresh Token",
RuleID: "github-refresh-token",
Regex: regexp.MustCompile(`ghr_[0-9a-zA-Z]{36}`),
Keywords: []string{"ghr_"},
}
// validate
tps := []string{
generateSampleSecret("github", "ghr_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Gitlab() *config.Rule {
// define rule
r := config.Rule{
Description: "Gitlab Personal Access Token",
RuleID: "gitlab-pat",
Regex: regexp.MustCompile(`glpat-[0-9a-zA-Z\-\_]{20}`),
Keywords: []string{"glpat-"},
}
// validate
tps := []string{
generateSampleSecret("gitlab", "glpat-"+secrets.NewSecret(alphaNumeric("20"))),
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func GoCardless() *config.Rule {
// define rule
r := config.Rule{
RuleID: "gocardless-api-token",
Description: "GoCardless API token",
Regex: generateSemiGenericRegex([]string{"gocardless"}, `live_(?i)[a-z0-9\-_=]{40}`),
Keywords: []string{
"live_",
"gocardless",
},
}
// validate
tps := []string{
generateSampleSecret("gocardless", "live_"+secrets.NewSecret(alphaNumericExtended("40"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Hashicorp() *config.Rule {
// define rule
r := config.Rule{
Description: "HashiCorp Terraform user/org API token",
RuleID: "hashicorp-tf-api-token",
Regex: regexp.MustCompile(`(?i)[a-z0-9]{14}\.atlasv1\.[a-z0-9\-_=]{60,70}`),
Keywords: []string{"atlasv1"},
}
// validate
tps := []string{
generateSampleSecret("hashicorpToken", secrets.NewSecret(hex("14"))+".atlasv1."+secrets.NewSecret(alphaNumericExtended("60,70"))),
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func Heroku() *config.Rule {
// define rule
r := config.Rule{
Description: "Heroku API Key",
RuleID: "heroku-api-key",
Regex: generateSemiGenericRegex([]string{"heroku"},
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
SecretGroup: 1,
Keywords: []string{"heroku"},
}
// validate
tps := []string{
`const HEROKU_KEY = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/config"
)
func HubSpot() *config.Rule {
// define rule
r := config.Rule{
Description: "HubSpot API Token",
RuleID: "hubspot-api-key",
Regex: generateSemiGenericRegex([]string{"hubspot"},
`[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}`),
SecretGroup: 1,
Keywords: []string{"hubspot"},
}
// validate
tps := []string{
`const hubspotKey = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Intercom() *config.Rule {
// define rule
r := config.Rule{
Description: "Intercom API Token",
RuleID: "intercom-api-key",
Regex: generateSemiGenericRegex([]string{"intercom"}, alphaNumericExtended("60")),
SecretGroup: 1,
Keywords: []string{"intercom"},
}
// validate
tps := []string{
generateSampleSecret("intercom", secrets.NewSecret(alphaNumericExtended("60"))),
}
return validate(r, tps)
}
+40
View File
@@ -0,0 +1,40 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LinearAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Linear API Token",
RuleID: "linear-api-key",
Regex: regexp.MustCompile(`lin_api_(?i)[a-z0-9]{40}`),
Keywords: []string{"lin_api_"},
}
// validate
tps := []string{
generateSampleSecret("linear", "lin_api_"+secrets.NewSecret(alphaNumeric("40"))),
}
return validate(r, tps)
}
func LinearClientSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Linear Client Secret",
RuleID: "linear-client-secret",
Regex: generateSemiGenericRegex([]string{"linear"}, hex("32")),
Keywords: []string{"linear"},
}
// validate
tps := []string{
generateSampleSecret("linear", secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
+52
View File
@@ -0,0 +1,52 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LinkedinClientSecret() *config.Rule {
// define rule
r := config.Rule{
RuleID: "linkedin-client-secret",
Description: "LinkedIn Client secret",
Regex: generateSemiGenericRegex([]string{
"linkedin",
"linked-in",
}, alphaNumeric("16")),
SecretGroup: 1,
Keywords: []string{
"linkedin",
"linked-in",
},
}
// validate
tps := []string{
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("16"))),
}
return validate(r, tps)
}
func LinkedinClientID() *config.Rule {
// define rule
r := config.Rule{
RuleID: "linkedin-client-id",
Description: "LinkedIn Client ID",
Regex: generateSemiGenericRegex([]string{
"linkedin",
"linked-in",
}, alphaNumeric("14")),
SecretGroup: 1,
Keywords: []string{
"linkedin",
"linked-in",
},
}
// validate
tps := []string{
generateSampleSecret("linkedin", secrets.NewSecret(alphaNumeric("14"))),
}
return validate(r, tps)
}
+45
View File
@@ -0,0 +1,45 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func LobPubAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Lob Publishable API Key",
RuleID: "lob-pub-api-key",
Regex: generateSemiGenericRegex([]string{"lob"}, `(test|live)_pub_[a-f0-9]{31}`),
Keywords: []string{
"test_pub",
"live_pub",
"_pub",
},
}
// validate
tps := []string{
generateSampleSecret("lob", "test_pub_"+secrets.NewSecret(hex("31"))),
}
return validate(r, tps)
}
func LobAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Lob API Key",
RuleID: "lob-api-key",
Regex: generateSemiGenericRegex([]string{"lob"}, `(live|test)_[a-f0-9]{35}`),
Keywords: []string{
"test_",
"live_",
},
}
// validate
tps := []string{
generateSampleSecret("lob", "test_"+secrets.NewSecret(hex("35"))),
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MailChimp() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailchimp-api-key",
Description: "Mailchimp API key",
Regex: generateSemiGenericRegex([]string{"mailchimp"}, `[a-f0-9]{32}-us20`),
SecretGroup: 1,
Keywords: []string{
"mailchimp",
},
}
// validate
tps := []string{
generateSampleSecret("mailchimp", secrets.NewSecret(hex("32"))+"-us20"),
}
return validate(r, tps)
}
+63
View File
@@ -0,0 +1,63 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MailGunPrivateAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-private-api-token",
Description: "Mailgun private API token",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `key-[a-f0-9]{32}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", "key-"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
func MailGunPubAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-pub-key",
Description: "Mailgun public validation key",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `pubkey-[a-f0-9]{32}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", "pubkey-"+secrets.NewSecret(hex("32"))),
}
return validate(r, tps)
}
func MailGunSigningKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "mailgun-signing-key",
Description: "Mailgun webhook signing key",
Regex: generateSemiGenericRegex([]string{"mailgun"}, `[a-h0-9]{32}-[a-h0-9]{8}-[a-h0-9]{8}`),
SecretGroup: 1,
Keywords: []string{
"mailgun",
},
}
// validate
tps := []string{
generateSampleSecret("mailgun", secrets.NewSecret(hex("32"))+"-00001111-22223333"),
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MapBox() *config.Rule {
// define rule
r := config.Rule{
Description: "MapBox API token",
RuleID: "mapbox-api-token",
Regex: generateSemiGenericRegex([]string{"mapbox"}, `pk\.[a-z0-9]{60}\.[a-z0-9]{22}`),
SecretGroup: 1,
Keywords: []string{"mapbox"},
}
// validate
tps := []string{
generateSampleSecret("mapbox", "pk."+secrets.NewSecret(alphaNumeric("60"))+"."+secrets.NewSecret(alphaNumeric("22"))),
}
return validate(r, tps)
}
+58
View File
@@ -0,0 +1,58 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func MessageBirdAPIToken() *config.Rule {
// define rule
r := config.Rule{
Description: "MessageBird API token",
RuleID: "messagebird-api-token",
Regex: generateSemiGenericRegex([]string{
"messagebird",
"message-bird",
"message_bird",
}, alphaNumeric("25")),
SecretGroup: 1,
Keywords: []string{
"messagebird",
"message-bird",
"message_bird",
},
}
// validate
tps := []string{
generateSampleSecret("messagebird", secrets.NewSecret(alphaNumeric("25"))),
generateSampleSecret("message-bird", secrets.NewSecret(alphaNumeric("25"))),
generateSampleSecret("message_bird", secrets.NewSecret(alphaNumeric("25"))),
}
return validate(r, tps)
}
func MessageBirdClientID() *config.Rule {
// define rule
r := config.Rule{
Description: "MessageBird client ID",
RuleID: "messagebird-client-id",
Regex: generateSemiGenericRegex([]string{
"messagebird",
"message-bird",
"message_bird",
}, `[a-h0-9]{8}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{4}-[a-h0-9]{12}`),
SecretGroup: 1,
Keywords: []string{
"messagebird",
"message-bird",
"message_bird",
},
}
// validate
tps := []string{
`const MessageBirdClientID = "12345678-ABCD-ABCD-ABCD-1234567890AB"`, // gitleaks:allow
}
return validate(r, tps)
}
+77
View File
@@ -0,0 +1,77 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func NewRelicUserID() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-user-api-key",
Description: "New Relic user API Key",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, `NRAK-[a-z0-9]{27}`),
SecretGroup: 1,
Keywords: []string{
"NRAK",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", "NRAK-"+secrets.NewSecret(alphaNumeric("27"))),
}
return validate(r, tps)
}
func NewRelicUserKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-user-api-id",
Description: "New Relic user API ID",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, alphaNumeric("64")),
SecretGroup: 1,
Keywords: []string{
"new-relic",
"newrelic",
"new_relic",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", secrets.NewSecret(alphaNumeric("64"))),
}
return validate(r, tps)
}
func NewRelicBrowserAPIKey() *config.Rule {
// define rule
r := config.Rule{
RuleID: "new-relic-browser-api-token",
Description: "New Relic ingest browser API token",
Regex: generateSemiGenericRegex([]string{
"new-relic",
"newrelic",
"new_relic",
}, `NRJS-[a-f0-9]{19}`),
SecretGroup: 1,
Keywords: []string{
"NRJS-",
},
}
// validate
tps := []string{
generateSampleSecret("new-relic", "NRJS-"+secrets.NewSecret(hex("19"))),
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func NPM() *config.Rule {
// define rule
r := config.Rule{
RuleID: "npm-access-token",
Description: "npm access token",
Regex: generateUniqueTokenRegex(`npm_[a-z0-9]{36}`),
SecretGroup: 1,
Keywords: []string{
"npm_",
},
}
// validate
tps := []string{
generateSampleSecret("npmAccessToken", "npm_"+secrets.NewSecret(alphaNumeric("36"))),
}
return validate(r, tps)
}
+44
View File
@@ -0,0 +1,44 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PlanetScalePassword() *config.Rule {
// define rule
r := config.Rule{
RuleID: "planetscale-password",
Description: "PlanetScale password",
Regex: generateUniqueTokenRegex(`pscale_pw_(?i)[a-z0-9=\-_\.]{43}`),
SecretGroup: 1,
Keywords: []string{
"pscale_pw_",
},
}
// validate
tps := []string{
generateSampleSecret("planetScalePassword", "pscale_pw_"+secrets.NewSecret(alphaNumericExtended("43"))),
}
return validate(r, tps)
}
func PlanetScaleToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "planetscale-api-token",
Description: "PlanetScale API token",
Regex: generateUniqueTokenRegex(`pscale_tkn_(?i)[a-z0-9=\-_\.]{43}`),
SecretGroup: 1,
Keywords: []string{
"pscale_tkn_",
},
}
// validate
tps := []string{
generateSampleSecret("planetScalePassword", "pscale_tkn_"+secrets.NewSecret(alphaNumericExtended("43"))),
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PostManAPI() *config.Rule {
// define rule
r := config.Rule{
RuleID: "postman-api-token",
Description: "Postman API token",
Regex: generateUniqueTokenRegex(`PMAK-(?i)[a-f0-9]{24}\-[a-f0-9]{34}`),
SecretGroup: 1,
Keywords: []string{
"PMAK-",
},
}
// validate
tps := []string{
generateSampleSecret("postmanAPItoken", "PMAK-"+secrets.NewSecret(hex("24"))+"-"+secrets.NewSecret(hex("34"))),
}
return validate(r, tps)
}
+23
View File
@@ -0,0 +1,23 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/config"
)
func PrivateKey() *config.Rule {
// define rule
r := config.Rule{
Description: "Private Key",
RuleID: "private-key",
Regex: regexp.MustCompile(`(?i)-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY-----[\s\S-]*KEY----`),
Keywords: []string{"-----BEGIN PRIVATE"},
}
// validate
tps := []string{`-----BEGIN PRIVATE KEY-----
anything
-----END PRIVATE KEY-----`} // gitleaks:allow
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PulumiAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "pulumi-api-token",
Description: "Pulumi API token",
Regex: generateUniqueTokenRegex(`pul-[a-f0-9]{40}`),
SecretGroup: 1,
Keywords: []string{
"pul-",
},
}
// validate
tps := []string{
generateSampleSecret("pulumi-api-token", "pul-"+secrets.NewSecret(hex("40"))),
}
return validate(r, tps)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func PyPiUploadToken() *config.Rule {
// define rule
r := config.Rule{
Description: "PyPI upload token",
RuleID: "pypi-upload-token",
Regex: regexp.MustCompile(
`pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}`),
Keywords: []string{
"pypi-AgEIcHlwaS5vcmc",
},
}
// validate
tps := []string{"pypiToken := \"pypi-AgEIcHlwaS5vcmc" + secrets.NewSecret(hex("32")) +
secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func RubyGemsAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "rubygems-api-token",
Description: "Rubygem API token",
Regex: generateUniqueTokenRegex(`rubygems_[a-f0-9]{48}`),
SecretGroup: 1,
Keywords: []string{
"rubygems_",
},
}
// validate
tps := []string{
generateSampleSecret("rubygemsAPIToken", "rubygems_"+secrets.NewSecret(hex("48"))),
}
return validate(r, tps)
}
+91
View File
@@ -0,0 +1,91 @@
package rules
import (
"fmt"
"regexp"
"strings"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
)
const (
// case insensitive prefix
caseInsensitive = `(?i)`
// identifier prefix (just an ignore group)
identifierPrefix = `(?:`
identifierSuffix = `)(?:[0-9a-z\-_\s.]{0,20})(?:[\s|']|[\s|"]){0,3}`
// commonly used assignment operators or function call
operator = `(?:=|>|:=|\|\|:|<=|=>|:)`
// boundaries for the secret
// \x60 = `
secretPrefixUnique = `\b(`
secretPrefix = `(?:'|\"|\s|=|\x60){0,5}(`
secretSuffix = `)(?:['|\"|\n|\r|\s|\x60]|$)`
)
func generateSemiGenericRegex(identifiers []string, secretRegex string) *regexp.Regexp {
var sb strings.Builder
sb.WriteString(caseInsensitive)
sb.WriteString(identifierPrefix)
sb.WriteString(strings.Join(identifiers, "|"))
sb.WriteString(identifierSuffix)
sb.WriteString(operator)
sb.WriteString(secretPrefix)
sb.WriteString(secretRegex)
sb.WriteString(secretSuffix)
return regexp.MustCompile(sb.String())
}
func generateUniqueTokenRegex(secretRegex string) *regexp.Regexp {
var sb strings.Builder
sb.WriteString(caseInsensitive)
sb.WriteString(secretPrefixUnique)
sb.WriteString(secretRegex)
sb.WriteString(secretSuffix)
return regexp.MustCompile(sb.String())
}
func generateSampleSecret(identifier string, secret string) string {
return fmt.Sprintf("%s_api_token = \"%s\"", identifier, secret)
}
func validate(r config.Rule, truePositives []string) *config.Rule {
// normalize keywords like in the config package
var keywords []string
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
r.Keywords = keywords
d := detect.NewDetector(config.Config{
Rules: []*config.Rule{&r},
Keywords: keywords,
})
for _, tp := range truePositives {
if len(d.DetectString(tp)) != 1 {
log.Fatal().Msgf("Failed to validate %s", r.RuleID)
}
}
return &r
}
func numeric(size string) string {
return fmt.Sprintf(`[0-9]{%s}`, size)
}
func hex(size string) string {
return fmt.Sprintf(`[a-f0-9]{%s}`, size)
}
func alphaNumeric(size string) string {
return fmt.Sprintf(`[a-z0-9]{%s}`, size)
}
func alphaNumericExtended(size string) string {
return fmt.Sprintf(`[a-z0-9=_\-]{%s}`, size)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SendGridAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "sendgrid-api-token",
Description: "SendGrid API token",
Regex: generateUniqueTokenRegex(`SG\.(?i)[a-z0-9=_\-\.]{66}`),
SecretGroup: 1,
Keywords: []string{
"SG.",
},
}
// validate
tps := []string{
generateSampleSecret("sengridAPIToken", "SG."+secrets.NewSecret(alphaNumericExtended("66"))),
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SendInBlueAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "sendinblue-api-token",
Description: "Sendinblue API token",
Regex: generateUniqueTokenRegex(`xkeysib-[a-f0-9]{64}\-(?i)[a-z0-9]{16}`),
SecretGroup: 1,
Keywords: []string{
"xkeysib-",
},
}
// validate
tps := []string{
generateSampleSecret("sendinblue", "xkeysib-"+secrets.NewSecret(hex("64"))+"-"+secrets.NewSecret(alphaNumeric("16"))),
}
return validate(r, tps)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func ShippoAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "shippo-api-token",
Description: "Shippo API token",
Regex: generateUniqueTokenRegex(`shippo_(live|test)_[a-f0-9]{40}`),
SecretGroup: 1,
Keywords: []string{
"shippo_",
},
}
// validate
tps := []string{
generateSampleSecret("shippo", "shippo_live_"+secrets.NewSecret(hex("40"))),
generateSampleSecret("shippo", "shippo_test_"+secrets.NewSecret(hex("40"))),
}
return validate(r, tps)
}
+64
View File
@@ -0,0 +1,64 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func ShopifySharedSecret() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify shared secret",
RuleID: "shopify-shared-secret",
Regex: regexp.MustCompile(`shpss_[a-fA-F0-9]{32}`),
Keywords: []string{"shpss_"},
}
// validate
tps := []string{"shopifySecret := \"shpss_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps)
}
func ShopifyAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify access token",
RuleID: "shopify-access-token",
Regex: regexp.MustCompile(`shpat_[a-fA-F0-9]{32}`),
Keywords: []string{"shpat_"},
}
// validate
tps := []string{"shopifyToken := \"shpat_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps)
}
func ShopifyCustomAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify custom access token",
RuleID: "shopify-custom-access-token",
Regex: regexp.MustCompile(`shpca_[a-fA-F0-9]{32}`),
Keywords: []string{"shpca_"},
}
// validate
tps := []string{"shopifyToken := \"shpca_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps)
}
func ShopifyPrivateAppAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Shopify private app access token",
RuleID: "shopify-private-app-access-token",
Regex: regexp.MustCompile(`shppa_[a-fA-F0-9]{32}`),
Keywords: []string{"shppa_"},
}
// validate
tps := []string{"shopifyToken := \"shppa_" + secrets.NewSecret(hex("32")) + "\""}
return validate(r, tps)
}
+50
View File
@@ -0,0 +1,50 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func SlackAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Slack token",
RuleID: "slack-access-token",
Regex: regexp.MustCompile(
"xox[baprs]-([0-9a-zA-Z]{10,48})"),
Keywords: []string{
"xoxb",
"xoxa",
"xoxp",
"xoxr",
"xoxs",
},
}
// validate
tps := []string{
"\"slackToken\": \"xoxb-" + secrets.NewSecret(alphaNumeric("30")) + "\"",
}
return validate(r, tps)
}
func SlackWebHook() *config.Rule {
// define rule
r := config.Rule{
Description: "Slack Webhook",
RuleID: "slack-web-hook",
Regex: regexp.MustCompile(
`https:\/\/hooks.slack.com\/services\/[A-Za-z0-9+\/]{44,46}`),
Keywords: []string{
"hooks.slack.com",
},
}
// validate
tps := []string{
"https://hooks.slack.com/services/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", // gitleaks:allow
}
return validate(r, tps)
}
+27
View File
@@ -0,0 +1,27 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func StripeAccessToken() *config.Rule {
// define rule
r := config.Rule{
Description: "Stripe",
RuleID: "stripe-access-token",
Regex: regexp.MustCompile(`(?i)(sk|pk)_(test|live)_[0-9a-z]{10,32}`),
Keywords: []string{
"sk_test",
"pk_test",
"sk_live",
"pk_live",
},
}
// validate
tps := []string{"stripeToken := \"sk_test_" + secrets.NewSecret(alphaNumeric("30")) + "\""}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"regexp"
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Twilio() *config.Rule {
// define rule
r := config.Rule{
Description: "Twilio API Key",
RuleID: "twilio-api-key",
Regex: regexp.MustCompile(`SK[0-9a-fA-F]{32}`),
Keywords: []string{"twilio"},
}
// validate
tps := []string{
"twilioAPIKey := \"SK" + secrets.NewSecret(hex("32")) + "\"",
}
return validate(r, tps)
}
+25
View File
@@ -0,0 +1,25 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func TwitchAPIToken() *config.Rule {
// define rule
r := config.Rule{
RuleID: "twitch-api-token",
Description: "Twitch API token",
Regex: generateSemiGenericRegex([]string{"twitch"}, alphaNumeric("30")),
SecretGroup: 1,
Keywords: []string{
"twitch",
},
}
// validate
tps := []string{
generateSampleSecret("twitch", secrets.NewSecret(alphaNumeric("30"))),
}
return validate(r, tps)
}
+24
View File
@@ -0,0 +1,24 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Twitter() *config.Rule {
// define rule
r := config.Rule{
Description: "twitter",
RuleID: "twitter",
Regex: generateSemiGenericRegex([]string{"twitter"}, hex("35,44")),
SecretGroup: 1,
Keywords: []string{"twitter"},
}
// validate
tps := []string{
"twitterToken := \"" + secrets.NewSecret(hex("36")) + "aaaa\"",
"twitterToken := `" + secrets.NewSecret(hex("36")) + "aaaa`",
}
return validate(r, tps)
}
+26
View File
@@ -0,0 +1,26 @@
package rules
import (
"github.com/zricethezav/gitleaks/v8/cmd/generate/secrets"
"github.com/zricethezav/gitleaks/v8/config"
)
func Typeform() *config.Rule {
// define rule
r := config.Rule{
RuleID: "typeform-api-token",
Description: "Typeform API token",
Regex: generateSemiGenericRegex([]string{"typeform"},
`tfp_[a-z0-9\-_\.=]{59}`),
SecretGroup: 1,
Keywords: []string{
"tfp_",
},
}
// validate
tps := []string{
generateSampleSecret("typeformAPIToken", "tfp_"+secrets.NewSecret(alphaNumericExtended("59"))),
}
return validate(r, tps)
}
+15
View File
@@ -0,0 +1,15 @@
// Package reggen generates text based on regex definitions
// This is a slightly altered version of https://github.com/lucasjones/reggen
package secrets
import (
"github.com/lucasjones/reggen"
)
func NewSecret(regex string) string {
g, err := reggen.NewGenerator(regex)
if err != nil {
panic(err)
}
return g.Generate(1)
}
+47 -14
View File
@@ -11,7 +11,6 @@ import (
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect"
"github.com/zricethezav/gitleaks/v8/git"
"github.com/zricethezav/gitleaks/v8/report"
)
@@ -30,41 +29,75 @@ func runProtect(cmd *cobra.Command, args []string) {
initConfig()
var vc config.ViperConfig
viper.Unmarshal(&vc)
if err := viper.Unmarshal(&vc); err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg, err := vc.Translate()
if err != nil {
log.Fatal().Err(err).Msg("Failed to load config")
}
cfg.Path, _ = cmd.Flags().GetString("config")
source, _ := cmd.Flags().GetString("source")
verbose, _ := cmd.Flags().GetBool("verbose")
redact, _ := cmd.Flags().GetBool("redact")
exitCode, _ := cmd.Flags().GetInt("exit-code")
staged, _ := cmd.Flags().GetBool("staged")
if cfg.Path == "" {
cfg.Path = filepath.Join(source, ".gitleaks.toml")
}
start := time.Now()
files, err := git.GitDiff(source, staged)
// Setup detector
detector := detect.NewDetector(cfg)
detector.Config.Path, err = cmd.Flags().GetString("config")
if err != nil {
log.Fatal().Err(err).Msg("Failed to get git log")
log.Fatal().Err(err)
}
source, err := cmd.Flags().GetString("source")
if err != nil {
log.Fatal().Err(err)
}
// if config path is not set, then use the {source}/.gitleaks.toml path.
// note that there may not be a `{source}/.gitleaks.toml` file, this is ok.
if detector.Config.Path == "" {
detector.Config.Path = filepath.Join(source, ".gitleaks.toml")
}
// set verbose flag
if detector.Verbose, err = cmd.Flags().GetBool("verbose"); err != nil {
log.Fatal().Err(err)
}
// set redact flag
if detector.Redact, err = cmd.Flags().GetBool("redact"); err != nil {
log.Fatal().Err(err)
}
findings := detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
// get log options for git scan
logOpts, err := cmd.Flags().GetString("log-opts")
if err != nil {
log.Fatal().Err(err)
}
// start git scan
var findings []report.Finding
if staged {
findings, err = detector.DetectGit(source, logOpts, detect.ProtectStagedType)
} else {
findings, err = detector.DetectGit(source, logOpts, detect.ProtectType)
}
if err != nil {
// don't exit on error, just log it
log.Error().Err(err)
}
// log info about the scan
log.Info().Msgf("scan completed in %s", time.Since(start))
if len(findings) != 0 {
log.Warn().Msgf("leaks found: %d", len(findings))
} else {
log.Info().Msg("no leaks found")
}
log.Info().Msgf("scan duration: %s", time.Since(start))
reportPath, _ := cmd.Flags().GetString("report-path")
ext, _ := cmd.Flags().GetString("report-format")
if reportPath != "" {
report.Write(findings, cfg, ext, reportPath)
if err = report.Write(findings, cfg, ext, reportPath); err != nil {
log.Fatal().Err(err)
}
}
if len(findings) != 0 {
os.Exit(exitCode)
+11 -4
View File
@@ -45,7 +45,10 @@ func init() {
rootCmd.PersistentFlags().StringP("log-level", "l", "info", "log level (debug, info, warn, error, fatal)")
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "show verbose output from scan")
rootCmd.PersistentFlags().Bool("redact", false, "redact secrets from logs and stdout")
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
if err != nil {
log.Fatal().Msgf("err binding config %s", err.Error())
}
}
func initLog() {
@@ -71,7 +74,7 @@ func initLog() {
}
func initConfig() {
fmt.Fprintf(os.Stderr, banner)
fmt.Fprint(os.Stderr, banner)
cfgPath, err := rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal().Msg(err.Error())
@@ -97,14 +100,18 @@ func initConfig() {
log.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")
viper.ReadConfig(strings.NewReader(config.DefaultConfig))
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
log.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"))
viper.SetConfigType("toml")
viper.ReadConfig(strings.NewReader(config.DefaultConfig))
if err = viper.ReadConfig(strings.NewReader(config.DefaultConfig)); err != nil {
log.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"))
+17 -11
View File
@@ -2,13 +2,23 @@ package config
import "regexp"
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
type Allowlist struct {
// Short human readable description of the allowlist.
Description string
Regexes []*regexp.Regexp
Paths []*regexp.Regexp
Commits []string
// Regexes is slice of content regular expressions that are allowed to be ignored.
Regexes []*regexp.Regexp
// Paths is a slice of path regular expressions that are allowed to be ignored.
Paths []*regexp.Regexp
// Commits is a slice of commit SHAs that are allowed to be ignored.
Commits []string
}
// CommitAllowed returns true if the commit is allowed to be ignored.
func (a *Allowlist) CommitAllowed(c string) bool {
if c == "" {
return false
@@ -21,16 +31,12 @@ func (a *Allowlist) CommitAllowed(c string) bool {
return false
}
// PathAllowed returns true if the path is allowed to be ignored.
func (a *Allowlist) PathAllowed(path string) bool {
if anyRegexMatch(path, a.Paths) {
return true
}
return false
return anyRegexMatch(path, a.Paths)
}
// RegexAllowed returns true if the regex is allowed to be ignored.
func (a *Allowlist) RegexAllowed(s string) bool {
if anyRegexMatch(s, a.Regexes) {
return true
}
return false
return anyRegexMatch(s, a.Regexes)
}
+17 -2
View File
@@ -4,6 +4,7 @@ import (
_ "embed"
"fmt"
"regexp"
"strings"
)
//go:embed gitleaks.toml
@@ -20,6 +21,7 @@ type ViperConfig struct {
Entropy float64
SecretGroup int
Regex string
Keywords []string
Path string
Tags []string
@@ -42,10 +44,14 @@ type Config struct {
Description string
Rules []*Rule
Allowlist Allowlist
Keywords []string
}
func (vc *ViperConfig) Translate() (Config, error) {
var rules []*Rule
var (
rules []*Rule
keywords []string
)
for _, r := range vc.Rules {
var allowlistRegexes []*regexp.Regexp
for _, a := range r.Allowlist.Regexes {
@@ -56,6 +62,14 @@ func (vc *ViperConfig) Translate() (Config, error) {
allowlistPaths = append(allowlistPaths, regexp.MustCompile(a))
}
if r.Keywords == nil {
r.Keywords = []string{}
} else {
for _, k := range r.Keywords {
keywords = append(keywords, strings.ToLower(k))
}
}
if r.Tags == nil {
r.Tags = []string{}
}
@@ -80,6 +94,7 @@ func (vc *ViperConfig) Translate() (Config, error) {
SecretGroup: r.SecretGroup,
Entropy: r.Entropy,
Tags: r.Tags,
Keywords: r.Keywords,
Allowlist: Allowlist{
Regexes: allowlistRegexes,
Paths: allowlistPaths,
@@ -90,7 +105,6 @@ func (vc *ViperConfig) Translate() (Config, error) {
return Config{}, fmt.Errorf("%s invalid regex secret group %d, max regex secret group %d", r.Description, r.SecretGroup, r.Regex.NumSubexp())
}
rules = append(rules, r)
}
var allowlistRegexes []*regexp.Regexp
for _, a := range vc.Allowlist.Regexes {
@@ -108,5 +122,6 @@ func (vc *ViperConfig) Translate() (Config, error) {
Paths: allowlistPaths,
Commits: vc.Allowlist.Commits,
},
Keywords: keywords,
}, nil
}
+8 -51
View File
@@ -25,6 +25,7 @@ func TestTranslate(t *testing.T) {
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Regexes: []*regexp.Regexp{
@@ -43,6 +44,7 @@ func TestTranslate(t *testing.T) {
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Commits: []string{"allowthiscommit"},
@@ -59,6 +61,7 @@ func TestTranslate(t *testing.T) {
Description: "AWS Access Key",
Regex: regexp.MustCompile("(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"),
Tags: []string{"key", "AWS"},
Keywords: []string{},
RuleID: "aws-access-key",
Allowlist: Allowlist{
Paths: []*regexp.Regexp{
@@ -81,6 +84,7 @@ func TestTranslate(t *testing.T) {
Entropy: 3.5,
SecretGroup: 3,
Tags: []string{},
Keywords: []string{},
},
},
},
@@ -103,7 +107,10 @@ func TestTranslate(t *testing.T) {
}
var vc ViperConfig
viper.Unmarshal(&vc)
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if tt.wantError != nil {
if err == nil {
@@ -115,53 +122,3 @@ func TestTranslate(t *testing.T) {
assert.Equal(t, cfg.Rules, tt.cfg.Rules)
}
}
func TestIncludeEntropy(t *testing.T) {
tests := []struct {
rule Rule
secret string
entropy float32
include bool
}{
{
rule: Rule{
RuleID: "generic-api-key",
SecretGroup: 4,
Entropy: 3.5,
Regex: regexp.MustCompile(`(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]`),
},
secret: `e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5`,
entropy: 3.7906235872459746,
include: true,
},
{
rule: Rule{
RuleID: "generic-api-key",
SecretGroup: 4,
Entropy: 4,
Regex: regexp.MustCompile(`(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]`),
},
secret: `e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5`,
entropy: 3.7906235872459746,
include: false,
},
{
rule: Rule{
RuleID: "generic-api-key",
SecretGroup: 4,
Entropy: 3.0,
Regex: regexp.MustCompile(`(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]`),
},
secret: `ssh-keyboard-interactive`,
entropy: 0,
include: false,
},
}
for _, tt := range tests {
include, entropy := tt.rule.IncludeEntropy(tt.secret)
assert.Equal(t, true, tt.rule.EntropySet())
assert.Equal(t, tt.entropy, float32(entropy))
assert.Equal(t, tt.include, include)
}
}
+721 -542
View File
File diff suppressed because it is too large. Load diff
+30 -32
View File
@@ -2,44 +2,42 @@ package config
import (
"regexp"
"strings"
)
// Rules contain information that define details on how to detect secrets
type Rule struct {
// Description is the description of the rule.
Description string
RuleID string
Entropy float64
// RuleID is a unique identifier for this rule
RuleID string
// Entropy is a float representing the minimum shannon
// entropy a regex group must have to be considered a secret.
Entropy float64
// SecretGroup is an int used to extract secret from regex
// match and used as the group that will have its entropy
// checked if `entropy` is set.
SecretGroup int
Regex *regexp.Regexp
Path *regexp.Regexp
Tags []string
Allowlist Allowlist
}
func (r *Rule) IncludeEntropy(secret string) (bool, float64) {
// 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. 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.
if strings.HasPrefix(r.RuleID, "generic") {
if !containsDigit(secret) {
return false, 0.0
}
}
// group = 0 will check the entropy of the whole regex match
e := shannonEntropy(secret)
if e > r.Entropy {
return true, e
}
// Regex is a golang regular expression used to detect secrets.
Regex *regexp.Regexp
return false, e
}
// Path is a golang regular expression used to
// filter secrets by path
Path *regexp.Regexp
func (r *Rule) EntropySet() bool {
if r.Entropy == 0.0 {
return false
}
return true
// Tags is an array of strings used for metadata
// and reporting purposes.
Tags []string
// Keywords are used for pre-regex check filtering. Rules that contain
// keywords will perform a quick string compare check to make sure the
// keyword(s) are in the content being scanned.
Keywords []string
// Allowlist allows a rule to be ignored for specific
// regexes, paths, and/or commits
Allowlist Allowlist
}
-36
View File
@@ -1,7 +1,6 @@
package config
import (
"math"
"regexp"
)
@@ -23,38 +22,3 @@ func regexMatched(f string, re *regexp.Regexp) bool {
}
return false
}
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
}
// 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
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
// more bits needed to encode that data.
func shannonEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
charCounts := make(map[rune]int)
for _, char := range data {
charCounts[char]++
}
invLength := 1.0 / float64(len(data))
for _, count := range charCounts {
freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
}
+401 -114
View File
@@ -1,149 +1,436 @@
package detect
import (
"encoding/json"
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/rs/zerolog/log"
"sync"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/detect/git"
"github.com/zricethezav/gitleaks/v8/report"
"github.com/fatih/semgroup"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/h2non/filetype"
ahocorasick "github.com/petar-dambovaliev/aho-corasick"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type Options struct {
// Type used to differentiate between git scan types:
// $ gitleaks detect
// $ gitleaks protect
// $ gitleaks protect staged
type GitScanType int
const (
DetectType GitScanType = iota
ProtectType
ProtectStagedType
gitleaksAllowSignature = "gitleaks:allow"
)
// Detector is the main detector struct
type Detector struct {
// Config is the configuration for the detector
Config config.Config
// Redact is a flag to redact findings. This is exported
// so users using gitleaks as a library can set this flag
// without calling `detector.Start(cmd *cobra.Command)`
Redact bool
// verbose is a flag to print findings
Verbose bool
Redact bool
// commitMap is used to keep track of commits that have been scanned.
// This is only used for logging purposes and git scans.
commitMap map[string]bool
// findingMutex is to prevent concurrent access to the
// findings slice when adding findings.
findingMutex *sync.Mutex
// findings is a slice of report.Findings. This is the result
// of the detector's scan which can then be used to generate a
// report.
findings []report.Finding
// prefilter is a ahocorasick struct used for doing efficient string
// matching given a set of words (keywords from the rules in the config)
prefilter ahocorasick.AhoCorasick
}
func DetectFindings(cfg config.Config, b []byte, filePath string, commit string) []report.Finding {
var findings []report.Finding
linePairs := regexp.MustCompile("\n").FindAllIndex(b, -1)
// Fragment contains the data to be scanned
type Fragment struct {
// Raw is the raw content of the fragment
Raw string
// check if we should skip file based on the global allowlist or if the file is the same as the gitleaks config
if cfg.Allowlist.PathAllowed(filePath) || filePath == cfg.Path {
// FilePath is the path to the file if applicable
FilePath string
// CommitSHA is the SHA of the commit if applicable
CommitSHA string
// newlineIndices is a list of indices of newlines in the raw content.
// This is used to calculate the line location of a finding
newlineIndices [][]int
// keywords is a map of all the keywords contain within the contents
// of this fragment
keywords map[string]bool
}
// NewDetector creates a new detector with the given config
func NewDetector(cfg config.Config) *Detector {
builder := ahocorasick.NewAhoCorasickBuilder(ahocorasick.Opts{
AsciiCaseInsensitive: true,
MatchOnlyWholeWords: false,
MatchKind: ahocorasick.LeftMostLongestMatch,
DFA: true,
})
return &Detector{
commitMap: make(map[string]bool),
findingMutex: &sync.Mutex{},
findings: make([]report.Finding, 0),
Config: cfg,
prefilter: builder.Build(cfg.Keywords),
}
}
// NewDetectorDefaultConfig creates a new detector with the default config
func NewDetectorDefaultConfig() (*Detector, error) {
viper.SetConfigType("toml")
err := viper.ReadConfig(strings.NewReader(config.DefaultConfig))
if err != nil {
return nil, err
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
return nil, err
}
cfg, err := vc.Translate()
if err != nil {
return nil, err
}
return NewDetector(cfg), nil
}
// DetectBytes scans the given bytes and returns a list of findings
func (d *Detector) DetectBytes(content []byte) []report.Finding {
return d.DetectString(string(content))
}
// DetectString scans the given string and returns a list of findings
func (d *Detector) DetectString(content string) []report.Finding {
return d.Detect(Fragment{
Raw: content,
})
}
// detectRule scans the given fragment for the given rule and returns a list of findings
func (d *Detector) detectRule(fragment Fragment, rule *config.Rule) []report.Finding {
var findings []report.Finding
// check if filepath or commit is allowed for this rule
if rule.Allowlist.CommitAllowed(fragment.CommitSHA) ||
rule.Allowlist.PathAllowed(fragment.FilePath) {
return findings
}
for _, r := range cfg.Rules {
pathSkip := false
if r.Allowlist.CommitAllowed(commit) {
continue
}
if r.Allowlist.PathAllowed(filePath) {
continue
}
// Check if path should be considered
if r.Path != nil {
if r.Path.Match([]byte(filePath)) {
if r.Regex == nil {
// This is a path only rule
f := report.Finding{
Description: r.Description,
File: filePath,
RuleID: r.RuleID,
Match: fmt.Sprintf("file detected: %s", filePath),
Tags: r.Tags,
}
findings = append(findings, f)
pathSkip = true
}
} else {
pathSkip = true
if rule.Path != nil && rule.Regex == nil {
// Path _only_ rule
if rule.Path.Match([]byte(fragment.FilePath)) {
finding := report.Finding{
Description: rule.Description,
File: fragment.FilePath,
RuleID: rule.RuleID,
Match: fmt.Sprintf("file detected: %s", fragment.FilePath),
Tags: rule.Tags,
}
return append(findings, finding)
}
if pathSkip {
} else if rule.Path != nil {
// if path is set _and_ a regex is set, then we need to check both
// so if the path does not match, then we should return early and not
// consider the regex
if !rule.Path.Match([]byte(fragment.FilePath)) {
return findings
}
}
// if path only rule, skip content checks
if rule.Regex == nil {
return findings
}
matchIndices := rule.Regex.FindAllStringIndex(fragment.Raw, -1)
for _, matchIndex := range matchIndices {
// extract secret from match
secret := strings.Trim(fragment.Raw[matchIndex[0]:matchIndex[1]], "\n")
// determine location of match. Note that the location
// in the finding will be the line/column numbers of the _match_
// not the _secret_, which will be different if the secretGroup
// value is set for this rule
loc := location(fragment, matchIndex)
finding := report.Finding{
Description: rule.Description,
File: fragment.FilePath,
RuleID: rule.RuleID,
StartLine: loc.startLine,
EndLine: loc.endLine,
StartColumn: loc.startColumn,
EndColumn: loc.endColumn,
Secret: secret,
Match: secret,
Tags: rule.Tags,
}
if strings.Contains(fragment.Raw[loc.startLineIndex:loc.endLineIndex],
gitleaksAllowSignature) {
continue
}
matchIndices := r.Regex.FindAllIndex(b, -1)
for _, m := range matchIndices {
location := getLocation(linePairs, m[0], m[1])
secret := strings.Trim(string(b[m[0]:m[1]]), "\n")
f := report.Finding{
Description: r.Description,
File: filePath,
RuleID: r.RuleID,
StartLine: location.startLine,
EndLine: location.endLine,
StartColumn: location.startColumn,
EndColumn: location.endColumn,
Secret: secret,
Match: secret,
Tags: r.Tags,
}
// check if the secret is in the allowlist
if rule.Allowlist.RegexAllowed(finding.Secret) ||
d.Config.Allowlist.RegexAllowed(finding.Secret) {
continue
}
if r.Allowlist.RegexAllowed(f.Secret) || cfg.Allowlist.RegexAllowed(f.Secret) {
// extract secret from secret group if set
if rule.SecretGroup != 0 {
groups := rule.Regex.FindStringSubmatch(secret)
if len(groups) <= rule.SecretGroup || len(groups) == 0 {
// Config validation should prevent this
continue
}
// extract secret from secret group if set
if r.SecretGroup != 0 {
groups := r.Regex.FindStringSubmatch(secret)
if len(groups)-1 > r.SecretGroup || len(groups) == 0 {
// Config validation should prevent this
break
}
secret = groups[r.SecretGroup]
f.Secret = secret
}
// extract secret from secret group if set
if r.EntropySet() {
include, entropy := r.IncludeEntropy(secret)
if include {
f.Entropy = float32(entropy)
findings = append(findings, f)
}
} else {
findings = append(findings, f)
}
secret = groups[rule.SecretGroup]
finding.Secret = secret
}
}
return dedupe(findings)
}
func limit(s string) string {
if len(s) > 500 {
return s[:500] + "..."
}
return s
}
func printFinding(f report.Finding) {
var b []byte
b, _ = json.MarshalIndent(f, "", " ")
fmt.Println(string(b))
}
func dedupe(findings []report.Finding) []report.Finding {
var retFindings []report.Finding
for _, f := range findings {
include := true
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
for _, fPrime := range findings {
if f.StartLine == fPrime.StartLine &&
f.EndLine == fPrime.EndLine &&
f.Commit == fPrime.Commit &&
f.RuleID != fPrime.RuleID &&
strings.Contains(fPrime.Secret, f.Secret) &&
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false
break
// check entropy
entropy := shannonEntropy(finding.Secret)
finding.Entropy = float32(entropy)
if rule.Entropy != 0.0 {
if entropy <= rule.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(rule.RuleID, "generic") {
if !containsDigit(secret) {
continue
}
}
}
if include {
retFindings = append(retFindings, f)
findings = append(findings, finding)
}
return findings
}
// GitScan accepts a *gitdiff.File channel which contents a git history generated from
// the output of `git log -p ...`. startGitScan will look at each file (patch) in the history
// and determine if the patch contains any findings.
func (d *Detector) DetectGit(source string, logOpts string, gitScanType GitScanType) ([]report.Finding, error) {
var (
gitdiffFiles <-chan *gitdiff.File
err error
)
switch gitScanType {
case DetectType:
gitdiffFiles, err = git.GitLog(source, logOpts)
if err != nil {
return d.findings, err
}
case ProtectType:
gitdiffFiles, err = git.GitDiff(source, false)
if err != nil {
return d.findings, err
}
case ProtectStagedType:
gitdiffFiles, err = git.GitDiff(source, true)
if err != nil {
return d.findings, err
}
}
return retFindings
s := semgroup.NewGroup(context.Background(), 4)
for gitdiffFile := range gitdiffFiles {
gitdiffFile := gitdiffFile
// skip binary files
if gitdiffFile.IsBinary || gitdiffFile.IsDelete {
continue
}
// Check if commit is allowed
commitSHA := ""
if gitdiffFile.PatchHeader != nil {
commitSHA = gitdiffFile.PatchHeader.SHA
if d.Config.Allowlist.CommitAllowed(gitdiffFile.PatchHeader.SHA) {
continue
}
}
d.addCommit(commitSHA)
s.Go(func() error {
for _, textFragment := range gitdiffFile.TextFragments {
if textFragment == nil {
return nil
}
fragment := Fragment{
Raw: textFragment.Raw(gitdiff.OpAdd),
CommitSHA: commitSHA,
FilePath: gitdiffFile.NewName,
}
for _, finding := range d.Detect(fragment) {
d.addFinding(augmentGitFinding(finding, textFragment, gitdiffFile))
}
}
return nil
})
}
if err := s.Wait(); err != nil {
return d.findings, err
}
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(d.commitMap))
return d.findings, nil
}
// DetectFiles accepts a path to a source directory or file and begins a scan of the
// file or directory.
func (d *Detector) DetectFiles(source string) ([]report.Finding, error) {
s := semgroup.NewGroup(context.Background(), 4)
paths := make(chan string)
s.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fInfo.Name() == ".git" {
return filepath.SkipDir
}
if fInfo.Mode().IsRegular() {
paths <- path
}
return nil
})
})
for pa := range paths {
p := pa
s.Go(func() error {
b, err := os.ReadFile(p)
if err != nil {
return err
}
mimetype, err := filetype.Match(b)
if err != nil {
return err
}
if mimetype.MIME.Type == "application" {
return nil // skip binary files
}
fragment := Fragment{
Raw: string(b),
FilePath: p,
}
for _, finding := range d.Detect(fragment) {
// need to add 1 since line counting starts at 1
finding.EndLine++
finding.StartLine++
d.addFinding(finding)
}
return nil
})
}
if err := s.Wait(); err != nil {
return d.findings, err
}
return d.findings, nil
}
// Detect scans the given fragment and returns a list of findings
func (d *Detector) Detect(fragment Fragment) []report.Finding {
var findings []report.Finding
// initiate fragment keywords
fragment.keywords = make(map[string]bool)
// check if filepath is allowed
if fragment.FilePath != "" && (d.Config.Allowlist.PathAllowed(fragment.FilePath) ||
fragment.FilePath == d.Config.Path) {
return findings
}
// add newline indices for location calculation in detectRule
fragment.newlineIndices = regexp.MustCompile("\n").FindAllStringIndex(fragment.Raw, -1)
// build keyword map for prefiltering rules
normalizedRaw := strings.ToLower(fragment.Raw)
matches := d.prefilter.FindAll(normalizedRaw)
for _, m := range matches {
fragment.keywords[normalizedRaw[m.Start():m.End()]] = true
}
for _, rule := range d.Config.Rules {
if len(rule.Keywords) == 0 {
// if not keywords are associated with the rule always scan the
// fragment using the rule
findings = append(findings, d.detectRule(fragment, rule)...)
continue
}
fragmentContainsKeyword := false
// check if keywords are in the fragment
for _, k := range rule.Keywords {
if _, ok := fragment.keywords[strings.ToLower(k)]; ok {
fragmentContainsKeyword = true
}
}
if fragmentContainsKeyword {
findings = append(findings, d.detectRule(fragment, rule)...)
}
}
return filter(findings, d.Redact)
}
// addFinding synchronously adds a finding to the findings slice
func (d *Detector) addFinding(finding report.Finding) {
d.findingMutex.Lock()
d.findings = append(d.findings, finding)
if d.Verbose {
printFinding(finding)
}
d.findingMutex.Unlock()
}
// addCommit synchronously adds a commit to the commit slice
func (d *Detector) addCommit(commit string) {
d.commitMap[commit] = true
}
+368 -41
View File
@@ -2,6 +2,7 @@ package detect
import (
"fmt"
"os"
"path/filepath"
"testing"
@@ -12,20 +13,91 @@ import (
"github.com/zricethezav/gitleaks/v8/report"
)
func TestDetectFindings(t *testing.T) {
const configPath = "../testdata/config/"
const repoBasePath = "../testdata/repos/"
func TestDetect(t *testing.T) {
tests := []struct {
cfgName string
opts Options
filePath string
bytes []byte
commit string
fragment Fragment
expectedFindings []report.Finding
wantError error
}{
{
cfgName: "simple",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\ // gitleaks:allow"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \
\"AKIALALEMEL33243OKIA\ // gitleaks:allow"
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OKIA\"
// gitleaks:allow"
`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
Secret: "AKIALALEMEL33243OKIA",
Match: "AKIALALEMEL33243OKIA",
File: "tmp.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
StartLine: 0,
EndLine: 0,
StartColumn: 15,
EndColumn: 34,
Entropy: 3.1464393,
},
},
},
{
cfgName: "escaped_character_group",
fragment: Fragment{
Raw: `pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "PyPI upload token",
Secret: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
Match: "pypi-AgEIcHlwaS5vcmcAAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAB",
File: "tmp.go",
RuleID: "pypi-upload-token",
Tags: []string{"key", "pypi"},
StartLine: 1,
EndLine: 1,
StartColumn: 1,
EndColumn: 86,
Entropy: 1.9606875,
},
},
},
{
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
@@ -38,32 +110,41 @@ func TestDetectFindings(t *testing.T) {
EndLine: 1,
StartColumn: 15,
EndColumn: 34,
Entropy: 3.0841837,
},
},
},
{
cfgName: "allow_aws_re",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
cfgName: "allow_aws_re",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_path",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
cfgName: "allow_path",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_commit",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
cfgName: "allow_commit",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
CommitSHA: "allowthiscommit",
},
expectedFindings: []report.Finding{},
commit: "allowthiscommit",
},
{
cfgName: "entropy_group",
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.go",
cfgName: "entropy_group",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{
{
Description: "Discord API key",
@@ -81,15 +162,19 @@ func TestDetectFindings(t *testing.T) {
},
},
{
cfgName: "generic_with_py_path",
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.go",
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.py",
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{
{
Description: "Generic API Key",
@@ -107,9 +192,11 @@ func TestDetectFindings(t *testing.T) {
},
},
{
cfgName: "path_only",
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.py",
cfgName: "path_only",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{
{
Description: "Python Files",
@@ -121,22 +208,36 @@ func TestDetectFindings(t *testing.T) {
},
},
{
cfgName: "bad_entropy_group",
bytes: []byte(`const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`),
filePath: "tmp.go",
cfgName: "bad_entropy_group",
fragment: Fragment{
Raw: `const Discord_Public_Key = "e7322523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
wantError: fmt.Errorf("Discord API key invalid regex secret group 5, max regex secret group 3"),
},
{
cfgName: "simple",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: filepath.Join(configPath, "simple.toml"),
cfgName: "simple",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: filepath.Join(configPath, "simple.toml"),
},
expectedFindings: []report.Finding{},
},
{
cfgName: "allow_global_aws_re",
bytes: []byte(`awsToken := \"AKIALALEMEL33243OLIA\"`),
filePath: "tmp.go",
cfgName: "allow_global_aws_re",
fragment: Fragment{
Raw: `awsToken := \"AKIALALEMEL33243OLIA\"`,
FilePath: "tmp.go",
},
expectedFindings: []report.Finding{},
},
{
cfgName: "generic_with_py_path",
fragment: Fragment{
Raw: `const Discord_Public_Key = "load2523fb86ed64c836a979cf8465fbd436378c653c1db38f9ae87bc62a6fd5"`,
FilePath: "tmp.py",
},
expectedFindings: []report.Finding{},
},
}
@@ -152,7 +253,10 @@ func TestDetectFindings(t *testing.T) {
}
var vc config.ViperConfig
viper.Unmarshal(&vc)
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
cfg.Path = filepath.Join(configPath, tt.cfgName+".toml")
if tt.wantError != nil {
@@ -161,8 +265,231 @@ func TestDetectFindings(t *testing.T) {
}
assert.Equal(t, tt.wantError, err)
}
d := NewDetector(cfg)
findings := DetectFindings(cfg, tt.bytes, tt.filePath, tt.commit)
findings := d.Detect(tt.fragment)
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
// TestFromGit tests the FromGit function
func TestFromGit(t *testing.T) {
tests := []struct {
cfgName string
source string
logOpts string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "small"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 19,
EndColumn: 38,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "main.go",
Date: "2021-11-02T23:37:53Z",
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
Author: "Zachary Rice",
Email: "zricer@protonmail.com",
Message: "Accidentally add a secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "foo/foo.go",
Date: "2021-11-02T23:48:06Z",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
{
source: filepath.Join(repoBasePath, "small"),
logOpts: "--all foo...",
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
Date: "2021-11-02T23:48:06Z",
File: "foo/foo.go",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
}
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer func() {
if err := moveDotGit(".git", "dotGit"); err != nil {
t.Error(err)
}
}()
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err = viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if err != nil {
t.Error(err)
}
detector := NewDetector(cfg)
findings, err := detector.DetectGit(tt.source, tt.logOpts, DetectType)
if err != nil {
t.Error(err)
}
for _, f := range findings {
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
// TestFromGit tests the FromGit function
func TestFromFiles(t *testing.T) {
tests := []struct {
cfgName string
source string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "nogit"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
{
source: filepath.Join(repoBasePath, "nogit", "main.go"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
Entropy: 3.0841837,
},
},
},
}
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, _ := vc.Translate()
detector := NewDetector(cfg)
findings, err := detector.DetectFiles(tt.source)
if err != nil {
t.Error(err)
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
func moveDotGit(from, to string) error {
repoDirs, err := os.ReadDir("../testdata/repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if to == ".git" {
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
if os.IsNotExist(err) {
// dont want to delete the only copy of .git accidentally
continue
}
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
}
if !dir.IsDir() {
continue
}
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
if os.IsNotExist(err) {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
if err != nil {
return err
}
}
return nil
}
-77
View File
@@ -1,77 +0,0 @@
package detect
import (
"context"
"os"
"path/filepath"
"sync"
"golang.org/x/sync/errgroup"
godocutil "golang.org/x/tools/godoc/util"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
)
// FromFiles opens the directory or file specified in source and checks each file against the rules
// from the configuration. If any secrets are found, they are added to the list of findings.
func FromFiles(source string, cfg config.Config, outputOptions Options) ([]report.Finding, error) {
var (
findings []report.Finding
mu sync.Mutex
)
g, _ := errgroup.WithContext(context.Background())
paths := make(chan string)
g.Go(func() error {
defer close(paths)
return filepath.Walk(source,
func(path string, fInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fInfo.Name() == ".git" {
return filepath.SkipDir
}
if fInfo.Mode().IsRegular() {
paths <- path
}
return nil
})
})
for pa := range paths {
p := pa
g.Go(func() error {
b, err := os.ReadFile(p)
if err != nil {
return err
}
if !godocutil.IsText(b) {
return nil
}
fis := DetectFindings(cfg, b, p, "")
for _, fi := range fis {
// need to add 1 since line counting starts at 1
fi.StartLine++
fi.EndLine++
if outputOptions.Redact {
fi.Redact()
}
if outputOptions.Verbose {
printFinding(fi)
}
mu.Lock()
findings = append(findings, fi)
mu.Unlock()
}
return nil
})
}
if err := g.Wait(); err != nil {
return findings, err
}
return findings, nil
}
-80
View File
@@ -1,80 +0,0 @@
package detect
import (
"path/filepath"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
)
// TestFromGit tests the FromGit function
func TestFromFiles(t *testing.T) {
tests := []struct {
cfgName string
opts Options
source string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "nogit"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
},
},
{
source: filepath.Join(repoBasePath, "nogit", "main.go"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 16,
EndColumn: 35,
Match: "AKIALALEMEL33243OLIA",
Secret: "AKIALALEMEL33243OLIA",
File: "../testdata/repos/nogit/main.go",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
},
},
}
for _, tt := range tests {
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err := viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
viper.Unmarshal(&vc)
cfg, _ := vc.Translate()
findings, err := FromFiles(tt.source, cfg, tt.opts)
if err != nil {
t.Error(err)
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
-96
View File
@@ -1,96 +0,0 @@
package detect
import (
"strings"
"sync"
"time"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/rs/zerolog/log"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/report"
godocutil "golang.org/x/tools/godoc/util"
)
// FromGit accepts a gitdiff.File channel (structure output from `git log -p`) and a configuration
// struct. Files from the gitdiff.File channel are then checked against each rule in the configuration to
// check for secrets. If any secrets are found, they are added to the list of findings.
func FromGit(files <-chan *gitdiff.File, cfg config.Config, outputOptions Options) []report.Finding {
var findings []report.Finding
mu := sync.Mutex{}
wg := sync.WaitGroup{}
commitMap := make(map[string]bool)
for f := range files {
// keep track of commits for logging
if f.PatchHeader != nil {
commitMap[f.PatchHeader.SHA] = true
}
wg.Add(1)
go func(f *gitdiff.File) {
defer wg.Done()
if f.IsBinary {
return
}
if f.IsDelete {
return
}
commitSHA := ""
// Check if commit is allowed
if f.PatchHeader != nil {
commitSHA = f.PatchHeader.SHA
if cfg.Allowlist.CommitAllowed(f.PatchHeader.SHA) {
return
}
}
for _, tf := range f.TextFragments {
if f.TextFragments == nil {
// TODO fix this in gitleaks gitdiff fork
// https://github.com/gitleaks/gitleaks/issues/11
continue
}
if !godocutil.IsText([]byte(tf.Raw(gitdiff.OpAdd))) {
continue
}
for _, fi := range DetectFindings(cfg, []byte(tf.Raw(gitdiff.OpAdd)), f.NewName, commitSHA) {
// don't add to start/end lines if finding is from a file only rule
if !strings.HasPrefix(fi.Match, "file detected") {
fi.StartLine += int(tf.NewPosition)
fi.EndLine += int(tf.NewPosition)
}
if f.PatchHeader != nil {
fi.Commit = f.PatchHeader.SHA
fi.Message = f.PatchHeader.Message()
if f.PatchHeader.Author != nil {
fi.Author = f.PatchHeader.Author.Name
fi.Email = f.PatchHeader.Author.Email
}
fi.Date = f.PatchHeader.AuthorDate.UTC().Format(time.RFC3339)
}
if outputOptions.Redact {
fi.Redact()
}
if outputOptions.Verbose {
printFinding(fi)
}
mu.Lock()
findings = append(findings, fi)
mu.Unlock()
}
}
}(f)
}
wg.Wait()
log.Debug().Msgf("%d commits scanned. Note: this number might be smaller than expected due to commits with no additions", len(commitMap))
return findings
}
View File
File renamed without changes.
+158
View File
@@ -0,0 +1,158 @@
package git_test
// TODO: commenting out this test for now because it's flaky. Alternatives to consider to get this working:
// -- use `git stash` instead of `restore()`
// const repoBasePath = "../../testdata/repos/"
// const expectPath = "../../testdata/expected/"
// func TestGitLog(t *testing.T) {
// tests := []struct {
// source string
// logOpts string
// expected string
// }{
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: filepath.Join(expectPath, "git", "small.txt"),
// },
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
// logOpts: "--all foo...",
// },
// }
// err := moveDotGit("dotGit", ".git")
// if err != nil {
// t.Fatal(err)
// }
// defer func() {
// if err = moveDotGit(".git", "dotGit"); err != nil {
// t.Fatal(err)
// }
// }()
// for _, tt := range tests {
// files, err := git.GitLog(tt.source, tt.logOpts)
// if err != nil {
// t.Error(err)
// }
// var diffSb strings.Builder
// for f := range files {
// for _, tf := range f.TextFragments {
// diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
// }
// }
// expectedBytes, err := os.ReadFile(tt.expected)
// if err != nil {
// t.Error(err)
// }
// expected := string(expectedBytes)
// if expected != diffSb.String() {
// // write string builder to .got file using os.Create
// err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
// if err != nil {
// t.Error(err)
// }
// t.Error("expected: ", expected, "got: ", diffSb.String())
// }
// }
// }
// func TestGitDiff(t *testing.T) {
// tests := []struct {
// source string
// expected string
// additions string
// target string
// }{
// {
// source: filepath.Join(repoBasePath, "small"),
// expected: "this line is added\nand another one",
// additions: "this line is added\nand another one",
// target: filepath.Join(repoBasePath, "small", "main.go"),
// },
// }
// err := moveDotGit("dotGit", ".git")
// if err != nil {
// t.Fatal(err)
// }
// defer func() {
// if err = moveDotGit(".git", "dotGit"); err != nil {
// t.Fatal(err)
// }
// }()
// for _, tt := range tests {
// noChanges, err := os.ReadFile(tt.target)
// if err != nil {
// t.Error(err)
// }
// err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
// if err != nil {
// restore(tt.target, noChanges, t)
// t.Error(err)
// }
// files, err := git.GitDiff(tt.source, false)
// if err != nil {
// restore(tt.target, noChanges, t)
// t.Error(err)
// }
// for f := range files {
// sb := strings.Builder{}
// for _, tf := range f.TextFragments {
// sb.WriteString(tf.Raw(gitdiff.OpAdd))
// }
// if sb.String() != tt.expected {
// restore(tt.target, noChanges, t)
// t.Error("expected: ", tt.expected, "got: ", sb.String())
// }
// }
// restore(tt.target, noChanges, t)
// }
// }
// func restore(path string, data []byte, t *testing.T) {
// err := os.WriteFile(path, data, 0644)
// if err != nil {
// t.Fatal(err)
// }
// }
// func moveDotGit(from, to string) error {
// repoDirs, err := os.ReadDir("../../testdata/repos")
// if err != nil {
// return err
// }
// for _, dir := range repoDirs {
// if to == ".git" {
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
// if os.IsNotExist(err) {
// // dont want to delete the only copy of .git accidentally
// continue
// }
// os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
// }
// if !dir.IsDir() {
// continue
// }
// _, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
// if os.IsNotExist(err) {
// continue
// }
// err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
// fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
// if err != nil {
// return err
// }
// }
// return nil
// }
-160
View File
@@ -1,160 +0,0 @@
package detect
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/zricethezav/gitleaks/v8/config"
"github.com/zricethezav/gitleaks/v8/git"
"github.com/zricethezav/gitleaks/v8/report"
)
const repoBasePath = "../testdata/repos/"
const expectPath = "../testdata/expected/"
const configPath = "../testdata/config/"
// TestFromGit tests the FromGit function
func TestFromGit(t *testing.T) {
tests := []struct {
cfgName string
opts Options
source string
logOpts string
expected string
expectedFindings []report.Finding
}{
{
source: filepath.Join(repoBasePath, "small"),
expected: filepath.Join(expectPath, "git", "small.txt"),
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 20,
EndLine: 20,
StartColumn: 19,
EndColumn: 38,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "main.go",
Date: "2021-11-02T23:37:53Z",
Commit: "1b6da43b82b22e4eaa10bcf8ee591e91abbfc587",
Author: "Zachary Rice",
Email: "zricer@protonmail.com",
Message: "Accidentally add a secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
File: "foo/foo.go",
Date: "2021-11-02T23:48:06Z",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
},
},
{
source: filepath.Join(repoBasePath, "small"),
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
logOpts: "--all foo...",
cfgName: "simple",
expectedFindings: []report.Finding{
{
Description: "AWS Access Key",
StartLine: 9,
EndLine: 9,
StartColumn: 17,
EndColumn: 36,
Secret: "AKIALALEMEL33243OLIA",
Match: "AKIALALEMEL33243OLIA",
Date: "2021-11-02T23:48:06Z",
File: "foo/foo.go",
Commit: "491504d5a31946ce75e22554cc34203d8e5ff3ca",
Author: "Zach Rice",
Email: "zricer@protonmail.com",
Message: "adding foo package with secret",
RuleID: "aws-access-key",
Tags: []string{"key", "AWS"},
},
},
},
}
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer moveDotGit(".git", "dotGit")
for _, tt := range tests {
files, err := git.GitLog(tt.source, tt.logOpts)
if err != nil {
t.Error(err)
}
viper.AddConfigPath(configPath)
viper.SetConfigName("simple")
viper.SetConfigType("toml")
err = viper.ReadInConfig()
if err != nil {
t.Error(err)
}
var vc config.ViperConfig
viper.Unmarshal(&vc)
cfg, _ := vc.Translate()
findings := FromGit(files, cfg, tt.opts)
for _, f := range findings {
f.Match = "" // remove lines cause copying and pasting them has some wack formatting
}
assert.ElementsMatch(t, tt.expectedFindings, findings)
}
}
func moveDotGit(from, to string) error {
repoDirs, err := os.ReadDir("../testdata/repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if to == ".git" {
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
if os.IsNotExist(err) {
// dont want to delete the only copy of .git accidentally
continue
}
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
}
if !dir.IsDir() {
continue
}
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
if os.IsNotExist(err) {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
if err != nil {
return err
}
}
return nil
}
+19 -3
View File
@@ -10,7 +10,7 @@ type Location struct {
endLineIndex int
}
func getLocation(linePairs [][]int, start int, end int) Location {
func location(fragment Fragment, matchIndex []int) Location {
var (
prevNewLine int
location Location
@@ -18,8 +18,10 @@ func getLocation(linePairs [][]int, start int, end int) Location {
_lineNum int
)
for lineNum, pair := range linePairs {
_lineNum = lineNum
start := matchIndex[0]
end := matchIndex[1]
for lineNum, pair := range fragment.newlineIndices {
newLineByteIndex := pair[0]
if prevNewLine <= start && start < newLineByteIndex {
lineSet = true
@@ -45,6 +47,20 @@ func getLocation(linePairs [][]int, start int, end int) Location {
location.endColumn = (end - prevNewLine)
location.startLine = _lineNum + 1
location.endLine = _lineNum + 1
location.startLineIndex = start
// search for new line byte index
i := 0
for end+i < len(fragment.Raw) {
if fragment.Raw[end+i] == '\n' {
break
}
if fragment.Raw[end+i] == '\r' {
break
}
i++
}
location.endLineIndex = end + i
}
return location
}
+1 -1
View File
@@ -49,7 +49,7 @@ func TestGetLocation(t *testing.T) {
}
for _, test := range tests {
loc := getLocation(test.linePairs, test.start, test.end)
loc := location(Fragment{newlineIndices: test.linePairs}, []int{test.start, test.end})
if loc != test.wantLocation {
t.Errorf("\nstartLine %d\nstartColumn: %d\nendLine: %d\nendColumn: %d\nstartLineIndex: %d\nendlineIndex %d",
loc.startLine, loc.startColumn, loc.endLine, loc.endColumn, loc.startLineIndex, loc.endLineIndex)
+108
View File
@@ -0,0 +1,108 @@
package detect
import (
"encoding/json"
"fmt"
"math"
"strings"
"time"
"github.com/zricethezav/gitleaks/v8/report"
"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 {
if !strings.HasPrefix(finding.Match, "file detected") {
finding.StartLine += int(textFragment.NewPosition)
finding.EndLine += int(textFragment.NewPosition)
}
if f.PatchHeader != nil {
finding.Commit = f.PatchHeader.SHA
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)
}
return finding
}
// 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
// needed to on average encode the data. So, the higher the entropy, the more random the data, the
// more bits needed to encode that data.
func shannonEntropy(data string) (entropy float64) {
if data == "" {
return 0
}
charCounts := make(map[rune]int)
for _, char := range data {
charCounts[char]++
}
invLength := 1.0 / float64(len(data))
for _, count := range charCounts {
freq := float64(count) * invLength
entropy -= freq * math.Log2(freq)
}
return entropy
}
// filter will dedupe and redact findings
func filter(findings []report.Finding, redact bool) []report.Finding {
var retFindings []report.Finding
for _, f := range findings {
include := true
if strings.Contains(strings.ToLower(f.RuleID), "generic") {
for _, fPrime := range findings {
if f.StartLine == fPrime.StartLine &&
f.EndLine == fPrime.EndLine &&
f.Commit == fPrime.Commit &&
f.RuleID != fPrime.RuleID &&
strings.Contains(fPrime.Secret, f.Secret) &&
!strings.Contains(strings.ToLower(fPrime.RuleID), "generic") {
genericMatch := strings.Replace(f.Match, f.Secret, "REDACTED", -1)
betterMatch := strings.Replace(fPrime.Match, fPrime.Secret, "REDACTED", -1)
log.Debug().Msgf("skipping %s finding (%s), %s rule takes precendence (%s)", f.RuleID, genericMatch, fPrime.RuleID, betterMatch)
include = false
break
}
}
}
if redact {
f.Redact()
}
if include {
retFindings = append(retFindings, f)
}
}
return retFindings
}
func printFinding(f report.Finding) {
var b []byte
b, _ = json.MarshalIndent(f, "", " ")
fmt.Println(string(b))
}
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
}
-157
View File
@@ -1,157 +0,0 @@
package git_test
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gitleaks/go-gitdiff/gitdiff"
"github.com/zricethezav/gitleaks/v8/git"
)
const repoBasePath = "../testdata/repos/"
const expectPath = "../testdata/expected/"
func TestGitLog(t *testing.T) {
tests := []struct {
source string
logOpts string
expected string
}{
{
source: filepath.Join(repoBasePath, "small"),
expected: filepath.Join(expectPath, "git", "small.txt"),
},
{
source: filepath.Join(repoBasePath, "small"),
expected: filepath.Join(expectPath, "git", "small-branch-foo.txt"),
logOpts: "--all foo...",
},
}
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer moveDotGit(".git", "dotGit")
for _, tt := range tests {
files, err := git.GitLog(tt.source, tt.logOpts)
if err != nil {
t.Error(err)
}
var diffSb strings.Builder
for f := range files {
for _, tf := range f.TextFragments {
diffSb.WriteString(tf.Raw(gitdiff.OpAdd))
}
}
expectedBytes, err := os.ReadFile(tt.expected)
if err != nil {
t.Error(err)
}
expected := string(expectedBytes)
if expected != diffSb.String() {
// write string builder to .got file using os.Create
err = os.WriteFile(strings.Replace(tt.expected, ".txt", ".got.txt", 1), []byte(diffSb.String()), 0644)
if err != nil {
t.Error(err)
}
t.Error("expected: ", expected, "got: ", diffSb.String())
}
}
}
func TestGitDiff(t *testing.T) {
tests := []struct {
source string
expected string
additions string
target string
}{
{
source: filepath.Join(repoBasePath, "small"),
expected: "this line is added\nand another one",
additions: "this line is added\nand another one",
target: filepath.Join(repoBasePath, "small", "main.go"),
},
}
err := moveDotGit("dotGit", ".git")
if err != nil {
t.Fatal(err)
}
defer moveDotGit(".git", "dotGit")
for _, tt := range tests {
noChanges, err := os.ReadFile(tt.target)
if err != nil {
t.Error(err)
}
err = os.WriteFile(tt.target, []byte(tt.additions), 0644)
if err != nil {
restore(tt.target, noChanges, t)
t.Error(err)
}
files, err := git.GitDiff(tt.source, false)
if err != nil {
restore(tt.target, noChanges, t)
t.Error(err)
}
for f := range files {
sb := strings.Builder{}
for _, tf := range f.TextFragments {
sb.WriteString(tf.Raw(gitdiff.OpAdd))
}
if sb.String() != tt.expected {
restore(tt.target, noChanges, t)
t.Error("expected: ", tt.expected, "got: ", sb.String())
}
}
restore(tt.target, noChanges, t)
}
}
func restore(path string, data []byte, t *testing.T) {
err := os.WriteFile(path, data, 0644)
if err != nil {
t.Fatal(err)
}
}
func moveDotGit(from, to string) error {
repoDirs, err := os.ReadDir("../testdata/repos")
if err != nil {
return err
}
for _, dir := range repoDirs {
if to == ".git" {
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), "dotGit"))
if os.IsNotExist(err) {
// dont want to delete the only copy of .git accidentally
continue
}
os.RemoveAll(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), ".git"))
}
if !dir.IsDir() {
continue
}
_, err := os.Stat(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from))
if os.IsNotExist(err) {
continue
}
err = os.Rename(fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), from),
fmt.Sprintf("%s/%s/%s", repoBasePath, dir.Name(), to))
if err != nil {
return err
}
}
return nil
}
+28 -6
View File
@@ -1,15 +1,37 @@
module github.com/zricethezav/gitleaks/v8
go 1.16
go 1.17
require (
github.com/gitleaks/go-gitdiff v0.7.4
github.com/rs/zerolog v1.25.0
github.com/fatih/semgroup v1.2.0
github.com/gitleaks/go-gitdiff v0.7.6
github.com/rs/zerolog v1.26.1
github.com/spf13/cobra v1.2.1
github.com/spf13/viper v1.8.1
github.com/stretchr/testify v1.7.0
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/h2non/filetype v1.1.3
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb
github.com/magiconair/properties v1.8.5 // indirect
github.com/mitchellh/mapstructure v1.4.1 // indirect
github.com/pelletier/go-toml v1.9.3 // indirect
github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9
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/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 // indirect
golang.org/x/tools v0.1.5
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
golang.org/x/text v0.3.6 // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
+21 -9
View File
@@ -67,11 +67,13 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m
github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
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/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=
github.com/gitleaks/go-gitdiff v0.7.4 h1:8vICc4moyRR2poklblThdQ0ckMet22mEvFJSxPsiDlk=
github.com/gitleaks/go-gitdiff v0.7.4/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/gitleaks/go-gitdiff v0.7.6 h1:atcfoNPD9erzPs9C89a+i2Y+EUmR2QKB5QHJTfB4n60=
github.com/gitleaks/go-gitdiff v0.7.6/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -141,6 +143,8 @@ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5m
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg=
github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -179,6 +183,8 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
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/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb h1:w1g9wNDIE/pHSTmAaUhv4TZQuPBS6GV3mMz5hkgziIU=
github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4=
github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
@@ -199,6 +205,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ=
github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9 h1:lL+y4Xv20pVlCGyLzNHRC0I0rIHhIL1lTvHizoS/dU8=
github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9/go.mod h1:EHPiTAKtiFmrMldLUNswFwfZ2eJIYBHktdaUTZxYWRw=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
@@ -209,8 +217,8 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:
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/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.25.0 h1:Rj7XygbUHKUlDPcVdoLyR91fJBsduXj5fRxyqIQj/II=
github.com/rs/zerolog v1.25.0/go.mod h1:7KHcEGe0QZPOm2IE4Kpb5rTh6n1h2hIgS5OOnu1rUaI=
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=
@@ -246,6 +254,7 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g=
go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ=
@@ -266,6 +275,7 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -337,6 +347,7 @@ golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -401,7 +412,9 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 h1:WecRHqgE09JBkh/584XIE6PMz5KKE/vER4izNUi30AQ=
golang.org/x/sys v0.0.0-20211110154304-99a53858aa08/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -411,8 +424,9 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -467,8 +481,7 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -576,9 +589,8 @@ google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlba
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
-1
View File
@@ -2,4 +2,3 @@ package report
const version = "v8.0.0"
const driver = "gitleaks"
const driverURL = "https://github.com/zricethezav/gitleaks"
-8
View File
@@ -1,7 +1,6 @@
package report
import (
"strconv"
"strings"
)
@@ -43,10 +42,3 @@ func (f *Finding) Redact() {
f.Match = strings.Replace(f.Match, f.Secret, "REDACTED", -1)
f.Secret = "REDACT"
}
func (f *Finding) Hash() string {
return f.Secret + f.Commit +
strconv.Itoa(f.EndLine) +
strconv.Itoa(f.StartLine)
}
+1 -1
View File
@@ -7,7 +7,7 @@ import (
func writeJson(findings []Finding, w io.WriteCloser) error {
if len(findings) == 0 {
return nil
findings = []Finding{}
}
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
+1 -2
View File
@@ -39,9 +39,8 @@ func TestWriteJSON(t *testing.T) {
}},
{
wantEmpty: true,
testReportName: "empty",
expected: filepath.Join(expectPath, "report", "this_should_not_exist.json"),
expected: filepath.Join(expectPath, "report", "empty.json"),
findings: []Finding{}},
}
+4 -8
View File
@@ -14,9 +14,6 @@ const (
)
func Write(findings []Finding, cfg config.Config, ext string, reportPath string) error {
if len(findings) == 0 {
return nil
}
file, err := os.Create(reportPath)
if err != nil {
return err
@@ -24,13 +21,12 @@ func Write(findings []Finding, cfg config.Config, ext string, reportPath string)
ext = strings.ToLower(ext)
switch ext {
case ".json", "json":
writeJson(findings, file)
err = writeJson(findings, file)
case ".csv", "csv":
writeCsv(findings, file)
err = writeCsv(findings, file)
case ".sarif", "sarif":
writeSarif(cfg, findings, file)
err = writeSarif(cfg, findings, file)
}
return nil
return err
}
+28 -18
View File
@@ -30,25 +30,46 @@ func getRuns(cfg config.Config, findings []Finding) []Runs {
}
func getTool(cfg config.Config) Tool {
return Tool{
tool := Tool{
Driver: Driver{
Name: driver,
SemanticVersion: version,
Rules: getRules(cfg),
},
}
// if this tool has no rules, ensure that it is represented as [] instead of null/nil
if hasEmptyRules(tool) {
tool.Driver.Rules = make([]Rules, 0)
}
return tool
}
func hasEmptyRules(tool Tool) bool {
return len(tool.Driver.Rules) == 0
}
func getRules(cfg config.Config) []Rules {
// TODO for _, rule := range cfg.Rules {
var rules []Rules
for _, rule := range cfg.Rules {
rules = append(rules, Rules{
ID: rule.RuleID,
Name: rule.Description,
Description: ShortDescription{
shortDescription := ShortDescription{
Text: rule.Description,
}
if rule.Regex != nil {
shortDescription = ShortDescription{
Text: rule.Regex.String(),
},
}
} else if rule.Path != nil {
shortDescription = ShortDescription{
Text: rule.Path.String(),
}
}
rules = append(rules, Rules{
ID: rule.RuleID,
Name: rule.Description,
Description: shortDescription,
})
}
return rules
@@ -64,7 +85,7 @@ func messageText(f Finding) string {
}
func getResults(findings []Finding) []Results {
var results []Results
results := []Results{}
for _, f := range findings {
r := Results{
Message: Message{
@@ -186,14 +207,3 @@ type Runs struct {
Tool Tool `json:"tool"`
Results []Results `json:"results"`
}
func configToRules(cfg config.Config) []Rules {
var rules []Rules
for _, rule := range cfg.Rules {
rules = append(rules, Rules{
ID: rule.RuleID,
Name: rule.Description,
})
}
return rules
}
+5 -1
View File
@@ -63,7 +63,11 @@ func TestWriteSarif(t *testing.T) {
}
var vc config.ViperConfig
viper.Unmarshal(&vc)
err = viper.Unmarshal(&vc)
if err != nil {
t.Error(err)
}
cfg, err := vc.Translate()
if err != nil {
t.Error(err)
+8
View File
@@ -0,0 +1,8 @@
title = "gitleaks config"
# https://learnxinyminutes.com/docs/toml/ for toml reference
[[rules]]
id = "pypi-upload-token"
description = "PyPI upload token"
regex = '''pypi-AgEIcHlwaS5vcmc[A-Za-z0-9\-_]{50,1000}'''
tags = ["key", "pypi"]
+27
View File
@@ -7,3 +7,30 @@ regex = '''(?i)((key|api|token|secret|password)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|
path = '''.py'''
entropy = 3.7
secretGroup = 4
[allowlist]
description = "global allow lists"
regexes = [
'''219-09-9999''',
'''078-05-1120''',
'''(9[0-9]{2}|666)-\d{2}-\d{4}''',
'''process''',
'''getenv''',
'''\.env''',
'''env\(''',
'''env\.''',
'''setting''',
'''load''',
'''token''',
'''password''',
'''secret''',
'''api\_key''',
'''apikey''',
'''api\-key''',
]
paths = [
'''gitleaks.toml''',
'''(.*?)(jpg|gif|doc|pdf|bin|svg|socket)$''',
'''(go.mod|go.sum)$'''
]
+1
View File
@@ -0,0 +1 @@
[]
Binary file not shown.